In this section
- TRUSS 47 render · cosmic / tools/explore/bigbang/rules/TRUSS-47.py lines 701–790
- Baseline transform · cosmic / tools/explore/bigbang/rules/baseline.py lines 1–22
- Test Cadastre 27 test · cosmic / tools/explore/bigbang/rules/test_CADASTRE-27.py lines 1–135
- Test Primer 48 test · cosmic / tools/explore/bigbang/rules/test_PRIMER-48.py lines 1–105
- Test TRUSS 47 test · cosmic / tools/explore/bigbang/rules/test_TRUSS-47.py lines 1–127
- Test Arena test · cosmic / tools/explore/bigbang/test_arena.py lines 1–118
- Test Describe Bigbang test · cosmic / tools/explore/bigbang/test_describe_bigbang.py lines 1–55
TRUSS 47
A Python module in the rules folder of Cosmic that cleans name (`clean_name`) and groups steps (`group_steps`) (units: mm², MVA, MW), using haversine and Vincenty.
rendercosmic / tools/explore/bigbang/rules/TRUSS-47.py · lines 701–790 of 790 (continued from section 1078) · Not reached from any entry point (candidate for review) · pattern main_functions (shared by 3 files)
- What it does
- It draws its content. Defines 30 functions or classes, including words, clean_name, ext_of, defined_functions, call_counts. Uses libraries re. Side effects: changes the web page (DOM); makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: form fields (user input). Out: SVG drawing. Coordinate systems named: WGS84 / EPSG:4326, Web Mercator / EPSG:3857.
- What it achieves
- It joins list (`join_list`) and is built from the words step (`words`) and the ext of helper (`ext_of`). TRUSS-47 rule set (Big Bang tournament player): STRUCTURE strategy.
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/bigbang/rules · Python module
- Uses
- re
- Used by
- none found
- Produces
- words, clean_name, ext_of, defined_functions, call_counts, entry_order, phrase_for, join_list, structure, code_terms, main_functions, q
- Defines here
- _role_groups, _role_clause, role_phrase, role_sentences, function_bodies
- 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/rules/TRUSS-47.py:701-790 · blob 51438344c1a66f9a294f5a82538e18d587acb43b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network, process, storage · domain stage: unknown · users: none · canonical: unreached_review
if re.match(r'\s*class\b', b):
out[n] = 'class definition'
continue
for role, rx in ROLE_RX[1:]:
if rx.search(b):
out[n] = role
break
return out
PLURAL = {'class definition': 'class definitions', 'canvas drawing': 'canvas drawing routines',
'vector drawing': 'vector drawing routines', 'page update': 'page updates', 'data loading': 'data loaders',
'file output': 'file writers', 'event wiring': 'event wiring routines', 'hash calculation': 'hash calculations',
'geometry maths': 'geometry maths routines', 'numeric calculation': 'numeric calculations',
'number formatting': 'number formatters', 'input check': 'input checks', 'text processing': 'text processing routines',
'list building': 'list builders', 'object lookup': 'lookups', 'utility routine': 'utility routines'}
def _role_groups(src, lang, names):
roles = function_roles(src, lang, names)
groups, order = {}, []
for d in names:
r = roles.get(d, 'utility routine')
if r not in groups:
groups[r] = []
order.append(r)
groups[r].append(d)
return [(r, groups[r]) for r in order]
def _role_clause(role, names):
"""One clause per role. Multi-word names are explained by their plain words; single words by the role noun."""
multi = [d for d in names if len(words(d)) > 1 and re.fullmatch(r'[A-Za-z_$][\w$]*', d) and
not STATUSY.search(' '.join(words(d))) and not re.match(r'[a-z]\d', d)]
single = [d for d in names if d not in multi]
out = []
if len(multi) >= 2:
out.append('%s for %s (%s)' % (PLURAL.get(role, role + 's'), join_list([' '.join(words(d)) for d in multi]),
', '.join(q(d) for d in multi)))
elif multi:
out.append('the %s for %s (%s)' % (role, ' '.join(words(multi[0])), q(multi[0])))
for d in single:
out.append('the %s %s' % (role, q(d)))
return out
def role_phrase(src, lang, names, lead):
cl = []
for r, ns in _role_groups(src, lang, names):
cl.extend(_role_clause(r, ns))
return lead + join_list(cl)
def role_sentences(src, lang, names):
cl = []
for r, ns in _role_groups(src, lang, names):
cl.extend(_role_clause(r, ns))
out, cur = [], []
for c in cl:
if cur and nwords(' '.join(cur + [c])) > 20:
out.append(cur)
cur = []
cur.append(c)
if cur:
out.append(cur)
return [('It also has ' if k == 0 else 'It has ') + join_list(c) + '.' for k, c in enumerate(out)]
ANY_DEF_PY = re.compile(r'(?m)^[ \t]*(?:async\s+)?(?:def|class)\s+([A-Za-z_]\w*)')
ANY_DEF_JS = re.compile(r'(?m)(?:^|[;{}\s])(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(|'
r'(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=|class\s+([A-Za-z_$][\w$]*))')
def function_bodies(src, lang, names):
"""[(name, body)] for each wanted name: from its definition to the next definition of any name."""
rx = ANY_DEF_PY if lang == 'py' else ANY_DEF_JS
starts = []
for m in rx.finditer(src):
n = next((g for g in m.groups() if g), None)
if n:
starts.append((m.start(), n))
out, want = [], set(names)
for k, (p, n) in enumerate(starts):
if n in want and n not in dict(out):
end = starts[k + 1][0] if k + 1 < len(starts) else len(src)
out.append((n, src[p:end]))
found = dict(out)
for n, b in defined_functions(src, lang, [x for x in names if x not in found]):
out.append((n, b[:1500]))
return outBaseline
A Python module in the rules folder of Cosmic. It is built from the translate step (`translate`).
transformcosmic / tools/explore/bigbang/rules/baseline.py · lines 1–22 of 22 · Not reached from any entry point (candidate for review) · pattern translate (shared by 7 files)
- What it does
- It calculates its inputs. Defines translate. Uses libraries os, sys.
- What it achieves
- The current `tools/explore/describe.py` output, as a Big Bang player (owned by TALLY-58, arbiter).
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/bigbang/rules · Python module
- Uses
- Describe (sys.path import), os, sys
- Used by
- none found
- Produces
- translate
- Defines here
- 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/rules/baseline.py:1-22 · blob e7116fb567027c590c7e345db27931995a3b9698 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""baseline - the current tools/explore/describe.py output, as a Big Bang player (owned by TALLY-58, arbiter).
translate(rec, src) returns describe.describe(evidence) for the evidence the arena passes in rec['ctx'], so the
baseline is exactly what describe.py would publish today for that file.
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import describe # noqa: E402
NAME = 'baseline (describe.py)'
STRATEGY = 'Current describe.describe() output from the same evidence; the reference every writer must beat.'
def translate(rec, src):
ev = dict((rec.get('ctx') or {}).get('evidence') or {})
if not ev:
ev = {'title': rec.get('title', ''), 'kind': rec.get('kind', ''), 'role': rec.get('role', ''),
'repo': rec.get('repo', ''), 'path': rec.get('path', ''), 'defines': rec.get('defines', [])}
d = describe.describe(ev)
return {'title': d['title'], 'synopsis': d['synopsis'], 'achieves': d['achieves']}Test Cadastre 27
A test in the rules folder of Cosmic that checks Describe. It builds tables (`build_tables`) and is built from the run step (`run`) and the rec step (`rec`).
testcosmic / tools/explore/bigbang/rules/test_CADASTRE-27.py · lines 1–135 of 135 · Entry point · pattern test_shape_and_determinism (shared by 2 files)
- What it does
- It tests solar and substations. Defines 15 functions or classes, including build_tables, run, rec, test_shape_and_determinism, test_synopsis_leads_with_estate_context. Uses libraries importlib.util, json, os, re, sys. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain terms in the code: solar, substations.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for `bigbang/rules/CADASTRE-27.py` (ESTATE CONTEXT player).
- Why it matters
- Guards the behaviour of Describe.
- Application
- cosmic · tools/explore/bigbang/rules · test
- Uses
- Describe (sys.path import), importlib.util, json, os, re, sys, pytest
- Used by
- none found
- Produces
- build_tables, run, rec, test_shape_and_determinism, test_synopsis_leads_with_estate_context, test_quoted_identifiers_occur_in_source, test_function_explained_from_doc_comment, test_function_explained_from_params, test_no_timestamp_or_date_in_text, test_area_strips_stamps_and_generic_folders, test_long_descriptor_repo_title_replaced, test_context_sentence_filters
- Defines here
- build_tables, run, rec, test_shape_and_determinism, test_synopsis_leads_with_estate_context, test_quoted_identifiers_occur_in_source, test_function_explained_from_doc_comment, test_function_explained_from_params, test_no_timestamp_or_date_in_text, test_area_strips_stamps_and_generic_folders, test_long_descriptor_repo_title_replaced, test_context_sentence_filters, test_no_religious_words_in_own_phrasing, test_never_invents_on_graph_sample, _readmes
- 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/rules/test_CADASTRE-27.py:1-135 · blob c4178825b9e0d125a0d10a2d17615686420b9809 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for bigbang/rules/CADASTRE-27.py (ESTATE CONTEXT player). Run: python3 -m pytest test_CADASTRE-27.py"""
import importlib.util
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
import describe # noqa: E402
spec = importlib.util.spec_from_file_location('cadastre27', os.path.join(HERE, 'CADASTRE-27.py'))
P = importlib.util.module_from_spec(spec)
spec.loader.exec_module(P)
PY = '''"""Tool."""
def build_tables(config, data_dir):
"""Build the summary tables from local sources."""
return 1
def run(cmd, args):
return 2
'''
JS = '''// Distance helpers.
/** Distance in km between two points. */
export function distanceKm(a, b) { return 0; }
// Initial bearing in degrees.
export function initialBearingDeg(a, b) { return 0; }
export const snapLines = (lines, tol) => lines;
'''
def rec(**kw):
r = {'id': -1, 'repo': 'gridatlas', 'path': 'atlas/places/202609111007/geodesy.mjs', 'title': 'Geodesy',
'kind': 'JavaScript module', 'defines': ['distanceKm', 'initialBearingDeg', 'snapLines'], 'signatures': [],
'dependents': [], 'imports': [], 'published': '', 'ctx': {'repo_title': 'GridAtlas', 'readme': []}}
r.update(kw)
return r
def test_shape_and_determinism():
a = P.translate(rec(), JS)
b = P.translate(rec(), JS)
assert a == b
assert set(a) == {'title', 'synopsis', 'achieves'} and all(isinstance(v, str) for v in a.values())
def test_synopsis_leads_with_estate_context():
out = P.translate(rec(), JS)
assert out['synopsis'].startswith("Part of GridAtlas's")
assert 12 <= len(out['synopsis'].split()) <= 40
def test_quoted_identifiers_occur_in_source():
out = P.translate(rec(), JS)
for q in re.findall(r'`([^`]+)`', ' '.join(out.values())):
assert q in JS
def test_function_explained_from_doc_comment():
s = P._explain('build_tables', rec(path='x/tool.py', defines=['build_tables', 'run']), PY)
assert s == 'It builds the summary tables from local sources (`build_tables`).'
def test_function_explained_from_params():
s = P._explain('run', rec(path='x/tool.py'), PY)
assert s == 'It takes cmd and args in `run`.'
def test_no_timestamp_or_date_in_text():
out = P.translate(rec(), JS)
assert not re.search(r'20\d{6,}', out['synopsis'] + out['achieves'])
def test_area_strips_stamps_and_generic_folders():
assert P._area('solar-design-studio/202609271853-site-world/world/module-view.mjs') == 'solar design studio'
assert P._area('src/js/x.js') == ''
def test_long_descriptor_repo_title_replaced():
r = rec(ctx={'repo_title': 'This platform is deployed via GitHub Pages as a static site.', 'readme': []})
assert P.translate(r, JS)['synopsis'].startswith("Part of GridAtlas")
def test_context_sentence_filters():
assert P._context_sentence('Open Grid maps substations and lines across Great Britain. More text here.') == \
'Open Grid maps substations and lines across Great Britain'
assert P._context_sentence('Built on 20260901 with hash abcdef1234567.') == ''
assert P._context_sentence('uses fooBar to load things in the browser now') == ''
def test_no_religious_words_in_own_phrasing():
src = open(os.path.join(HERE, 'CADASTRE-27.py'), encoding='utf-8').read()
phrases = re.findall(r"'([A-Z][^']{8,})'", src)
for p in phrases:
assert not P.RELIGIOUS.search(p.replace('vedic-', '')), p
def test_never_invents_on_graph_sample():
st = P._graph()
F = st['F']
if not F:
return
for i in range(0, len(F), max(1, len(F) // 40)):
r = json.loads(json.dumps(F[i]))
try:
src = open(os.path.join(P.SRC, r['repo'], r['path']), encoding='utf-8', errors='replace').read(400000)
except OSError:
continue
r['ctx'] = {'repo_title': '', 'readme': []}
out = P.translate(r, src)
ev = json.dumps(F[i]) + '\n' + src + '\n' + ' '.join(F[j]['title'] for j in F[i]['dependents'] + F[i]['imports'])
for k in ('README',):
pass
bad = [w for w in describe.invented(out['synopsis'], ev + _readmes(r)) if w not in ('Part',)]
assert not bad, (i, bad, out['synopsis'])
def _readmes(r):
out, d = [], os.path.dirname(r['path'])
while True:
for n in ('README.md', 'readme.md', 'README'):
p = os.path.join(P.SRC, r['repo'], d, n)
if os.path.isfile(p):
out.append(open(p, encoding='utf-8', errors='replace').read())
if not d:
break
d = os.path.dirname(d)
return '\n'.join(out) + ' ' + P.build.repo_title(r['repo'])
if __name__ == '__main__':
import pytest
sys.exit(pytest.main([__file__, '-q']))Test Primer 48
A test in the rules folder of Cosmic that checks Arena.
testcosmic / tools/explore/bigbang/rules/test_PRIMER-48.py · lines 1–105 of 105 · Not reached from any entry point (candidate for review) · pattern test_shape_and_determinism (shared by 2 files)
- What it does
- It tests cables, battery storage (BESS) and 33kV. Defines 10 functions or classes, including _rec, test_shape_and_determinism, test_never_invents_and_quotes_only_source, test_functions_explained_in_plain_verbs, test_units_get_plain_meaning. Uses libraries importlib.util, json, os, re, sys. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, battery storage (BESS), 33kV.
- Inputs & outputs
- In: JSON file build_graph.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 33kV.
- What it achieves
- Tests for PRIMER-48 (plain learner). Its code works with 33 kV and 20 MW.
- Why it matters
- Guards the behaviour of Arena.
- Application
- cosmic · tools/explore/bigbang/rules · test
- Uses
- Arena (sys.path import), importlib.util, json, os, re, sys
- Used by
- none found
- Produces
- test_shape_and_determinism, test_never_invents_and_quotes_only_source, test_functions_explained_in_plain_verbs, test_units_get_plain_meaning, test_why_it_matters_only_with_dependents, test_glossary_meanings_are_lower_case_and_used_once, test_imperative_comment_becomes_third_person, test_no_religious_terms, test_real_graph_sample_no_invented
- Defines here
- _rec, test_shape_and_determinism, test_never_invents_and_quotes_only_source, test_functions_explained_in_plain_verbs, test_units_get_plain_meaning, test_why_it_matters_only_with_dependents, test_glossary_meanings_are_lower_case_and_used_once, test_imperative_comment_becomes_third_person, test_no_religious_terms, test_real_graph_sample_no_invented
- 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/rules/test_PRIMER-48.py:1-105 · blob e81a58af25e377b1c8488d03afceae4f4dbfeb12 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Tests for PRIMER-48 (plain learner). Run: python3 -m pytest bigbang/rules/test_PRIMER-48.py -q"""
import importlib.util
import json
import os
import re
HERE = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location('primer48', os.path.join(HERE, 'PRIMER-48.py'))
P = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(P)
SRC = '''// Cable helpers
function computeLayout(a) { return a; }
function getInputs() { return byId('x'); }
function byId(id) { return document.getElementById(id); }
function osgb_to_wgs84(e, n) { return [e, n]; }
const rating = "33kV feeder, 33kV cable, 20 MW";
'''
def _rec(**kw):
r = {'repo': 'cable-trench-or-drill', 'path': 'tools/cable-geometry-visualiser/calculations.js',
'title': 'Calculations', 'kind': 'script', 'role': 'render',
'defines': ['computeLayout', 'getInputs', 'byId', 'osgb_to_wgs84'],
'folder_hierarchy': ['cable-trench-or-drill', 'tools', 'cable-geometry-visualiser'],
'ctx': {'readme': ['Owner of the standalone Cable Geometry Visualiser and future civil-route assessment '
'cartridges.'], 'repo_title': 'Cable Trench or Drill',
'dependents': ['Solar BESS Topology V7 — Cable Geometry Visualiser Page'], 'imports': [],
'evidence': {}}}
r.update(kw)
r['ctx']['evidence'] = {'title': r['title'], 'kind': r['kind'], 'role': r['role'], 'repo': r['repo'],
'path': r['path'], 'defines': r['defines'], 'comment': '// Cable helpers',
'readme': r['ctx']['readme'],
'dependents': [{'title': t} for t in r['ctx']['dependents']]}
return r
def test_shape_and_determinism():
a = P.translate(_rec(), SRC)
b = P.translate(_rec(), SRC)
assert a == b
assert set(a) == {'title', 'synopsis', 'achieves'} and all(isinstance(v, str) for v in a.values())
assert 12 <= len(a['synopsis'].split()) <= 40
def test_never_invents_and_quotes_only_source():
r = _rec()
out = P.translate(r, SRC)
ev = P.describe.evidence_text(r['ctx']['evidence']) + '\n' + SRC
for v in out.values():
assert P._invented(v, ev) == []
for q in re.findall(r'`([^`]+)`', ' '.join(out.values())):
assert q in SRC
def test_functions_explained_in_plain_verbs():
out = P.translate(_rec(), SRC)
assert 'computes layout (`computeLayout`)' in out['achieves']
assert 'gets inputs (`getInputs`)' in out['achieves']
assert 'converts OSGB to WGS84 (`osgb_to_wgs84`)' in out['achieves']
def test_units_get_plain_meaning():
out = P.translate(_rec(), SRC)
assert 'kV (kilovolts, a measure of voltage)' in out['achieves']
def test_why_it_matters_only_with_dependents():
assert 'Why it matters' in P.translate(_rec(), SRC)['synopsis']
r = _rec()
r['ctx']['dependents'] = []
assert 'Why it matters' not in P.translate(r, SRC)['synopsis']
def test_glossary_meanings_are_lower_case_and_used_once():
for k, v in P.GLOSSARY.items():
assert v == v.lower() or re.search(r'Python', v), k
seen = set()
t = P._gloss('A BESS page; the BESS again.', seen)
assert t.count('(a large battery') == 1 and 'BESS' in seen
def test_imperative_comment_becomes_third_person():
s, ok = P._verbify('Extract an approved star definition and write its stable path')
assert ok and s.startswith('extracts') and 'and writes' in s
def test_no_religious_terms():
text = open(os.path.join(HERE, 'PRIMER-48.py')).read().lower()
for w in ('god', 'divine', 'holy', 'sacred', 'prayer', 'church', 'temple', 'scripture'):
assert not re.search(r'\b%s\b' % w, text), w
def test_real_graph_sample_no_invented():
g = '/tmp/site8/explore-code/build_graph.json'
if not os.path.exists(g):
return
import sys
sys.path.insert(0, os.path.dirname(HERE))
import arena
c = arena.Corpus(g)
for i in c.sample(12345, 25):
rec, src, evt = c.prep(i)
out = P.translate(json.loads(json.dumps(rec)), src)
assert all(P._invented(v, evt) == [] for v in out.values()), (c.key(i), out)Test TRUSS 47
A test in the rules folder of Cosmic that checks Describe. It loads cables (`load_cables`) and writes table (`write_table`).
testcosmic / tools/explore/bigbang/rules/test_TRUSS-47.py · lines 1–127 of 127 · Entry point · pattern test_workflow (shared by 2 files)
- What it does
- It tests cables. Defines 12 functions or classes, including load_cables, voltage_drop, write_table, main, _check. Uses libraries importlib.util, os, re, sys, argparse. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- In: JSON file prices.json; JSON file cables.json; CSV file table.csv; command-line arguments. Out: CSV file table.csv; canvas drawing.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for the TRUSS-47 Big Bang player (STRUCTURE strategy). It reads `data/prices.json` and writes `table.csv`. It accepts `--input`.
- Why it matters
- Guards the behaviour of Describe.
- Application
- cosmic · tools/explore/bigbang/rules · test
- Uses
- Describe (sys.path import), importlib.util, os, re, sys, argparse, json
- Used by
- none found
- Produces
- load_cables, voltage_drop, write_table, main, test_js_structure_sentence, test_js_events_and_context, test_python_cli_reads_and_writes, test_role_from_body_for_noun_names, test_workflow, test_style_sheet_and_empty, test_deterministic_and_no_religious_terms
- Defines here
- load_cables, voltage_drop, write_table, main, _check, test_js_structure_sentence, test_js_events_and_context, test_python_cli_reads_and_writes, test_role_from_body_for_noun_names, test_workflow, test_style_sheet_and_empty, test_deterministic_and_no_religious_terms
- 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/rules/test_TRUSS-47.py:1-127 · blob 09af8d66e7b64b5cc10551c5d4d9cd430d601c41 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: unknown
"""Tests for the TRUSS-47 Big Bang player (STRUCTURE strategy). Run: python3 -m pytest test_TRUSS-47.py"""
import importlib.util
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
import describe # noqa: E402
_spec = importlib.util.spec_from_file_location('truss47', os.path.join(HERE, 'TRUSS-47.py'))
P = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(P)
JS = """
const ctx = document.getElementById('c').getContext('2d');
async function loadPrices() { const r = await fetch('data/prices.json'); return r.json(); }
function computeLayout(rows) { return rows.map(r => r.value * 2); }
function drawBars(rows) { rows.forEach((v, i) => ctx.fillRect(i * 10, 0, 8, v)); }
function formatMm(x) { return x.toFixed(1) + ' mm'; }
async function main() { const rows = await loadPrices(); drawBars(computeLayout(rows)); }
document.addEventListener('DOMContentLoaded', main);
"""
REC_JS = {'title': 'Price Bars', 'kind': 'script', 'path': 'web/prices/bars.js', 'lines': 8,
'defines': ['loadPrices', 'computeLayout', 'drawBars', 'formatMm', 'main'],
'folder_hierarchy': ['repo', 'web', 'prices'],
'ctx': {'readme': ['The prices page shows daily wholesale electricity prices as bars.']}}
PY = '''"""Build the cable table."""
import argparse, json
def load_cables(path):
with open(path) as fh:
return json.load(fh)
def voltage_drop(i, r):
return i * r
def write_table(rows):
with open('table.csv', 'w') as fh:
fh.write('x')
def main():
ap = argparse.ArgumentParser(); ap.add_argument('--input')
rows = load_cables('cables.json'); write_table([voltage_drop(1, 2) for _ in rows])
if __name__ == '__main__':
main()
'''
REC_PY = {'title': 'Cable Table', 'kind': 'Python CLI', 'path': 'tools/cable_table.py', 'lines': 20,
'defines': ['load_cables', 'voltage_drop', 'write_table', 'main'], 'folder_hierarchy': ['repo', 'tools']}
def _check(out, src, rec):
for k in ('title', 'synopsis', 'achieves'):
assert isinstance(out[k], str)
for q in re.findall(r'`([^`]+)`', out['synopsis'] + out['achieves']):
assert q in src, q
ev = ' '.join([rec['title'], rec['path'], ' '.join(rec['defines'])] + (rec.get('ctx') or {}).get('readme', [])) + src
assert describe.invented(out['synopsis'] + ' ' + out['achieves'], ev) == []
n = len(out['synopsis'].split())
assert 12 <= n <= 40, out['synopsis']
assert out['achieves'].strip() and out['achieves'] != out['synopsis']
def test_js_structure_sentence():
out = P.translate(dict(REC_JS), JS)
_check(out, JS, REC_JS)
s = out['synopsis']
assert s.startswith('It reads `prices.json`')
assert 'computes layout (`computeLayout`)' in s
assert 'draws on a canvas' in s
# call order from main(): load before compute before draw
assert s.index('loadPrices') < s.index('computeLayout') < s.index('drawBars')
def test_js_events_and_context():
out = P.translate(dict(REC_JS), JS)
assert 'starts when the page loads' in out['achieves']
assert 'daily wholesale electricity prices' in out['achieves']
def test_python_cli_reads_and_writes():
out = P.translate(dict(REC_PY), PY)
_check(out, PY, REC_PY)
s = out['synopsis']
assert s.startswith('From the command line, it reads `cables.json`')
assert '`table.csv`' in s or '`table.csv`' in out['achieves']
assert 'voltage drop' in (s + out['achieves'])
assert '`--input`' in out['achieves']
def test_role_from_body_for_noun_names():
src = 'function geometry(a, b) { return Math.hypot(a, b); }\nfunction hatch(el) { el.innerHTML = "x"; }\n'
rec = {'title': 'Shapes', 'kind': 'JavaScript module', 'path': 'lib/shapes.mjs', 'defines': ['geometry', 'hatch'],
'folder_hierarchy': ['repo', 'lib']}
out = P.translate(rec, src)
text = out['synopsis'] + ' ' + out['achieves']
assert 'geometry maths `geometry`' in text
assert 'page update `hatch`' in text
def test_workflow():
src = 'name: Refresh\non:\n push:\n workflow_dispatch:\njobs:\n build:\n steps:\n - run: python3 tools/refresh.py\n - run: git commit -am x && git push\n'
rec = {'title': 'Refresh Workflow', 'kind': 'workflow', 'path': '.github/workflows/refresh.yml',
'defines': ['Refresh'], 'folder_hierarchy': ['.github', 'workflows']}
out = P.translate(rec, src)
s = out['synopsis']
assert '`Refresh`' in s and 'on push' in s and 'by hand' in s and '`tools/refresh.py`' in s
assert 'commits the results back' in s
def test_style_sheet_and_empty():
out = P.translate({'title': 'Site', 'kind': 'style sheet', 'path': 'site.css', 'defines': []},
':root{--ink:#000}\nbody{color:var(--ink)}\n@media (max-width:600px){body{margin:0}}\n')
assert 'rule blocks' in out['synopsis'] and 'screen widths' in out['synopsis']
out = P.translate({}, '')
assert out['synopsis'] and isinstance(out['achieves'], str)
def test_deterministic_and_no_religious_terms():
a = P.translate(dict(REC_JS), JS)
b = P.translate(dict(REC_JS), JS)
assert a == b
src = open(os.path.join(HERE, 'TRUSS-47.py')).read().lower()
for w in ('vedic', 'holy', 'sacred', 'divine', 'god'):
assert not re.search(r'\b' + w + r'\b', src), wTest Arena
A test in the bigbang folder of Cosmic that checks Arena and Judge, using IEC 60287. It is built from the good step (`good`).
testcosmic / tools/explore/bigbang/test_arena.py · lines 1–118 of 118 · Not reached from any entry point (candidate for review)
- What it does
- It tests cables. Defines 13 functions or classes, including good, test_good_scores_and_counts_specifics, test_bare_define_list_counts_half, test_invented_proper_noun_is_hard_fail, test_quoted_identifier_not_in_source_is_hard_fail. Uses libraries os, sys, types.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- What it achieves
- Tests for the Big Bang arena and judge (TALLY-58).
- Why it matters
- Guards the behaviour of Arena and Judge.
- Application
- cosmic · tools/explore/bigbang · test
- Uses
- Arena (import), Judge (import), os, sys, types
- Used by
- none found
- Produces
- good, test_good_scores_and_counts_specifics, test_bare_define_list_counts_half, test_invented_proper_noun_is_hard_fail, test_quoted_identifier_not_in_source_is_hard_fail, test_malformed_and_empty, test_plainness_penalises_dumps_and_status, test_move_rules, test_bt_elo_orders_players, test_crosstable_points, test_sample_is_seeded_stratified_and_baseline_clean, test_player_error_is_contained
- Defines here
- good, test_good_scores_and_counts_specifics, test_bare_define_list_counts_half, test_invented_proper_noun_is_hard_fail, test_quoted_identifier_not_in_source_is_hard_fail, test_malformed_and_empty, test_plainness_penalises_dumps_and_status, test_move_rules, test_bt_elo_orders_players, test_crosstable_points, test_sample_is_seeded_stratified_and_baseline_clean, test_player_error_is_contained, test_backtick_list_is_a_dump
- 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/test_arena.py:1-118 · blob e0e7a37d905f3f02f2c07182454d7dc8d8462e66 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for the Big Bang arena and judge (TALLY-58). Run: python3 -m pytest -q test_arena.py"""
import os
import sys
import types
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import arena # noqa: E402
import judge # noqa: E402
SRC = 'def cable_rating(i, r):\n """Ampacity per IEC 60287 at 90 °C."""\n return i * i * r\n\ndef voltage_drop(x):\n return x\n'
REC = {'title': 'Cable Rating', 'kind': 'Python module', 'defines': ['cable_rating', 'voltage_drop', '_h'],
'folder_hierarchy': ['repo', 'cables'], 'ctx': {'readme': ['Cable rating tools for buried cables.'],
'repo_title': 'Repo'}}
EVID = 'Cable Rating cable_rating voltage_drop ' + SRC
def good():
return {'title': 'Cable rating', 'synopsis': 'Works out the current a buried cable can carry with '
'`cable_rating`, following IEC 60287, and estimates the voltage drop along it.',
'achieves': 'Gives a quick cable rating check for buried cables.'}
def test_good_scores_and_counts_specifics():
s = judge.score(good(), REC, SRC, EVID)
assert not s['fail']
assert 'cable_rating' in s['detail']['quoted']
assert any('IEC' in t for t in s['detail']['terms'])
assert s['parts']['cov'] == 4.0 # cable_rating as code, voltage_drop as plain words
assert s['parts']['brief'] == 2.0
def test_bare_define_list_counts_half():
o = good()
o['synopsis'] = 'Defines `cable_rating` and `voltage_drop` for buried cables, with a short check on each.'
o['achieves'] = 'A quick check for buried cables.'
s = judge.score(o, REC, SRC, EVID)
assert s['parts']['cov'] == 2.0 and s['detail']['named_only'] == ['cable_rating', 'voltage_drop']
assert judge.explained('cable_rating', 'Works out the current with `cable_rating`.')
def test_invented_proper_noun_is_hard_fail():
o = good()
o['achieves'] = 'Used by National Grid planners.'
assert judge.score(o, REC, SRC, EVID)['fail'].startswith('invented')
def test_quoted_identifier_not_in_source_is_hard_fail():
o = good()
o['synopsis'] = o['synopsis'].replace('`cable_rating`', '`cable_ratings_v2`')
assert 'not in source' in judge.score(o, REC, SRC, EVID + ' cable_ratings_v2x')['fail'] or \
judge.score(o, REC, SRC, EVID)['fail']
def test_malformed_and_empty():
assert judge.score(None, REC, SRC, EVID)['fail']
assert judge.score({'title': 'x', 'synopsis': '', 'achieves': ''}, REC, SRC, EVID)['fail']
def test_plainness_penalises_dumps_and_status():
o = good()
o['synopsis'] = 'Candidate: defines cableRating, voltageDrop and cable_temp_max for the draft model 20261205.'
s = judge.score(o, REC, SRC, EVID + ' cableRating voltageDrop cable_temp_max draft model')
assert not s['fail'] and s['parts']['plain'] < 2
def test_move_rules():
a = judge.score(good(), REC, SRC, EVID)
b = dict(a, total=a['total'] - 1, parts=dict(a['parts'], spec=a['parts']['spec'] - 1))
assert judge.move(a, b)[0] == '1-0'
assert judge.move(b, a)[0] == '0-1'
assert judge.move(a, dict(a))[0] == '1/2-1/2'
f = {'total': 0, 'fail': 'invented: X', 'parts': {}, 'detail': {}}
assert judge.move(f, a)[0] == '0-1' and judge.move(f, f)[0] == '1/2-1/2'
def test_bt_elo_orders_players():
games = [{'white': 'a', 'black': 'b', 'moves': [{'result': '1-0'}] * 8 + [{'result': '0-1'}] * 2},
{'white': 'b', 'black': 'c', 'moves': [{'result': '1-0'}] * 7 + [{'result': '1/2-1/2'}] * 3}]
e = arena.bt_elo(['a', 'b', 'c'], games)
assert e['a'] > e['b'] > e['c']
def test_crosstable_points():
g = [{'white': 'a', 'black': 'b', 'score': '40-20', 'result': '1-0'},
{'white': 'c', 'black': 'a', 'score': '30-30', 'result': '1/2-1/2'}]
ct, t = arena.crosstable(['a', 'b', 'c'], g)
assert ct['a']['b'] == 1 and ct['b']['a'] == 0 and ct['a']['c'] == 0.5
assert t['a']['points'] == 1.5 and t['a']['won'] == 1 and t['a']['drawn'] == 1
def test_sample_is_seeded_stratified_and_baseline_clean():
if not os.path.exists(arena.GRAPH):
return
c = arena.Corpus()
s1, s2 = c.sample(7, 24), c.sample(7, 24)
assert s1 == s2 and len(s1) == 24 and len(set(s1)) == 24
roles = {c.F[i]['role'] for i in s1}
assert len(roles) == len({f['role'] for f in c.F}) # 24 >= 12 roles: every role represented
base = arena.load_players({'baseline'})['baseline']
for i in s1[:12]:
rec, src, evt = c.prep(i)
out, _ = arena.run_player(base, rec, src)
assert judge.score(out, rec, src, evt)['fail'] == '', c.key(i)
k = c.key(s1[0])
assert '@' in k and ':1-' in k
def test_player_error_is_contained():
bad = types.SimpleNamespace(translate=lambda r, s: 1 / 0)
out, _ = arena.run_player(bad, {'title': 't'}, '')
assert out['_error'].startswith('ZeroDivisionError')
def test_backtick_list_is_a_dump():
o = good()
o['achieves'] = 'It also defines `cable_rating`, `voltage_drop`, `i` and `r`.'
s = judge.score(o, REC, SRC, EVID)
assert any('4+' in f for f in s['detail']['plain_flags']) and s['parts']['plain'] == 2.0Test Describe Bigbang
A test in the explore folder of Cosmic that checks Describe Bigbang and Judge, using IEC 60287 and SHA-256. It is built from the out step (`out`).
testcosmic / tools/explore/bigbang/test_describe_bigbang.py · lines 1–55 of 55 · Not reached from any entry point (candidate for review) · pattern test_deterministic (shared by 11 files)
- What it does
- It tests cables and 33kV. Defines 7 functions or classes, including out, test_verb_clause_and_helper, test_specifics_use_source_spelling, test_io_facts, test_output_is_honest_and_scored_well. Uses libraries os, re, sys. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV.
- Inputs & outputs
- In: JSON file ratings.json; command-line arguments. Out: JSON file ratings.json. Voltage levels named: 33kV.
- What it achieves
- Tests for `describe_bigbang.py` (TALLY-58). Its code works with 33 kV. It writes `ratings.json`. It accepts `--cable`.
- Why it matters
- Guards the behaviour of Describe Bigbang and Judge.
- Application
- cosmic · tools/explore/bigbang · test
- Uses
- Describe Bigbang (import), Judge (import), os, re, sys
- Used by
- none found
- Produces
- out, test_verb_clause_and_helper, test_specifics_use_source_spelling, test_io_facts, test_output_is_honest_and_scored_well, test_guard_drops_invented_sentence, test_deterministic
- Defines here
- out, test_verb_clause_and_helper, test_specifics_use_source_spelling, test_io_facts, test_output_is_honest_and_scored_well, test_guard_drops_invented_sentence, test_deterministic
- 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/test_describe_bigbang.py:1-55 · blob 0061d1464ca8cf9d4d0afff112fb7b0ec475fec5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Tests for describe_bigbang.py (TALLY-58). Run: python3 -m pytest -q test_describe_bigbang.py"""
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import describe_bigbang as D # noqa: E402
import judge # noqa: E402
SRC = ('"""Rates buried cables per IEC 60287."""\nimport argparse\ndef compute_rating(i):\n return i\n'
'def segDist(a):\n return a\np = argparse.ArgumentParser()\np.add_argument("--cable")\n'
'open("ratings.json", "w")\n# 33 kV and 33 kV feeders\n')
EV = {'title': 'cable_rate', 'kind': 'Python CLI', 'path': 'tools/cable_rate.py', 'repo_title': 'Cable Tools',
'defines': ['compute_rating', 'segDist', '_x'], 'comment': 'Rates buried cables per IEC 60287.',
'readme': ['Cable Tools rate buried cables.']}
def out():
return D.describe_bigbang(EV, SRC, {'ctx': {}})
def test_verb_clause_and_helper():
assert D._verb_clause('compute_rating') == 'computes rating (`compute_rating`)'
assert D._verb_clause('kernel') == '' and D.helper_clause('segDist') == 'the seg dist helper (`segDist`)'
def test_specifics_use_source_spelling():
assert 'IEC 60287' in D.specifics(SRC)
assert D.specifics('h = hashlib.sha256(b)') == ['sha256']
assert D.units_with_numbers(SRC) == ['33 kV']
def test_io_facts():
f = D.io_facts(SRC)
assert f['writes'] == ['ratings.json'] and f['flags'] == ['--cable']
def test_output_is_honest_and_scored_well():
o = out()
text = o['synopsis'] + ' ' + o['achieves']
assert all(q in SRC for q in re.findall(r'`([^`]+)`', text))
evt = ' '.join(str(v) for v in EV.values()) + SRC
s = judge.score(o, {'defines': EV['defines'], 'ctx': {'readme': EV['readme']}}, SRC, evt)
assert not s['fail'], s
assert 12 <= len(o['synopsis'].split()) <= 40
assert s['parts']['cov'] == 4.0 and 'compute_rating' in s['detail']['covered']
def test_guard_drops_invented_sentence():
o = D._guard({'title': 't', 'synopsis': 'A tool. Used by National Grid.', 'achieves': ''}, EV, SRC, {})
assert 'National' not in o['synopsis'] and o['synopsis'] == 'A tool.'
def test_deterministic():
assert out() == out()