In this section
- Primer 48 transform · cosmic / tools/explore/bigbang/rules/PRIMER-48.py lines 1–464
Primer 48
A Python module in the rules folder of Cosmic that maps cables, overhead lines (OHL) and solar, using haversine and Dijkstra.
transformcosmic / tools/explore/bigbang/rules/PRIMER-48.py · lines 1–464 of 464 · Not reached from any entry point (candidate for review) · pattern _first_sentence (shared by 2 files)
- What it does
- It maps cables, overhead lines (OHL) and solar. Defines 19 functions or classes, including _words, _short_title, _deraw, _sent, _gloss. Uses libraries os, re, sys.
- Why it exists in the grid workflow
- Domain terms in the code: cables, overhead lines (OHL), solar.
- Inputs & outputs
- In: DuckDB queries. Out: downloaded file downloads. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- What it achieves
- It is built from the main functions helper (`main_functions`) and the translate step (`translate`). Big Bang rule writer, strategy PLAIN LEARNER.
- 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, re, sys
- Used by
- none found
- Produces
- main_functions, translate
- Defines here
- _words, _short_title, _deraw, _sent, _gloss, _verb_phrase, main_functions, _verbify, _first_sentence, _what, _why, _helper_phrase, _steps, _terms, _readme_line, _evidence, _invented, _ok, 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/PRIMER-48.py:1-464 · blob c40e9a6a90816b84faff5aad641dd8e775e99695 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""PRIMER-48 - Big Bang rule writer, strategy PLAIN LEARNER.
Writes for a newcomer who might become an infrastructure engineer: short, friendly, concrete sentences,
jargon explained in a few words from one shared glossary, and a "Why it matters" line only when the
evidence (files that depend on this one) supports it.
translate(rec, src) -> {'title', 'synopsis', 'achieves'}
title the estate title (short form when it is long)
synopsis one plain sentence on what the file does (+ glossary meanings) and, when evidenced, why it matters
achieves its main functions as plain verb phrases with the `identifier` beside each, units and named
formulas found in the source with their plain meaning, and the nearest README sentence
Every capitalised word, number-with-unit and URL comes from the evidence (title, path, comment, README,
defines, dependents, source); glossary meanings are lower case explanations. A final self-check runs
describe.invented() on the output and drops any sentence it flags, so invented() stays 0.
Deterministic, stdlib only.
"""
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import describe # noqa: E402 (read-only)
NAME = 'PRIMER-48 (plain learner)'
STRATEGY = 'Newcomer-friendly: one strong plain sentence, shared jargon glossary, functions as plain verbs.'
# ---------------------------------------------------------------- glossary (estate jargon -> plain meaning)
# Key: the token as written in the estate (matched case-sensitively, whole word). Meanings are lower case and
# short; they explain a word, they never add a fact about the file.
GLOSSARY = {
'BESS': 'a large battery that stores electricity',
'SLD': 'single-line diagram, a simple drawing of an electrical circuit',
'DNO': 'distribution network operator, the company that runs local power lines',
'DNOs': 'the companies that run local power lines',
'TSO': 'transmission system operator, which runs the high-voltage grid',
'REPD': 'a public list of renewable energy projects going through planning',
'OHL': 'overhead line, power cables carried on pylons or poles',
'UGC': 'underground cable',
'ETYS': 'a yearly statement on how the high-voltage grid will grow',
'NAEI': 'a national record of air pollution sources',
'NESO': 'the national electricity system operator',
'BMRS': 'live public data on electricity supply and demand',
'UKPN': 'a company that runs local power lines',
'SSEN': 'an electricity network company',
'PV': 'solar panels',
'GIS': 'software for maps and location data',
'HV': 'high voltage',
'LV': 'low voltage',
'EHV': 'extra-high voltage',
'XLPE': 'a plastic insulation used on power cables',
'CRS': 'the coordinate system used for map positions',
'WGS84': 'the usual latitude and longitude system',
'OSGB': 'the national map grid',
'GeoJSON': 'a text format for map shapes',
'TopoJSON': 'a compact text format for map shapes',
'CSV': 'a table saved as plain text',
'JSON': 'a common text format for data',
'API': 'a way for programs to ask for data',
'DOM': 'the structure of the web page',
'SVG': 'a format for drawing shapes on web pages',
'WebGL': 'drawing with the graphics card in the browser',
'MPAN': 'the number that identifies an electricity meter',
'MPPT': 'a method solar inverters use to get the most power',
'PPA': 'a long-term deal to buy electricity',
'CfD': 'a government price guarantee for low-carbon power',
'LiDAR': 'laser scanning that measures ground height',
'DEM': 'a height map of the ground',
'DTM': 'a height map of the bare ground',
'DSM': 'a height map including buildings and trees',
'ICP': 'independent connection provider, a firm that builds grid connections',
'GSP': 'grid supply point, where the high-voltage grid feeds a local network',
'TEC': 'the agreed capacity a generator may export to the grid',
'LCOE': 'the lifetime cost of each unit of electricity',
'NPV': 'net present value, future money counted in today\'s terms',
'PMTiles': 'a single-file format for map tiles',
'MapLibre': 'a library for interactive web maps',
'Leaflet': 'a library for interactive web maps',
'Parquet': 'a compact file format for large tables',
'DuckDB': 'a small database that runs inside a program',
'OpenStreetMap': 'a free, community-made world map',
'pandapower': 'a Python library for power-network calculations',
'Playwright': 'a tool that drives a real browser for testing',
}
UNIT_PLAIN = {
'kV': 'kilovolts, a measure of voltage', 'kVA': 'kilovolt-amperes, a measure of equipment size',
'MVA': 'megavolt-amperes, a measure of equipment size', 'MVAr': 'megavars, a measure of reactive power',
'kW': 'kilowatts, a measure of power', 'MW': 'megawatts, a measure of power',
'GW': 'gigawatts, a measure of power', 'kWh': 'kilowatt-hours, a measure of energy',
'MWh': 'megawatt-hours, a measure of energy', 'GWh': 'gigawatt-hours, a measure of energy',
'TWh': 'terawatt-hours, a measure of energy', 'Hz': 'hertz, the grid frequency',
'mm²': 'square millimetres, the size of a cable core', '°C': 'degrees Celsius',
'km': 'kilometres',
}
FORMULA_PLAIN = {
'haversine': 'distance over the curved surface of the globe', 'dijkstra': 'shortest-path search',
'voltage drop': 'how much voltage is lost along a cable', 'power factor': 'how usefully current is used',
'derating': 'reducing a rating for real conditions', 'thermal resistance': 'how well heat escapes',
'short-circuit': 'the current in a fault', 'fault level': 'how much current flows in a fault',
'load flow': 'how power spreads through a network', 'power flow': 'how power spreads through a network',
'impedance': 'opposition to current flow', 'irradiance': 'sunlight power on a surface',
'interpolation': 'estimating values between known points', 'levelised cost': 'lifetime cost per unit',
'monte carlo': 'many random trials', 'least squares': 'best-fit line fitting', 'median': 'the middle value',
'percentile': 'rank within a range of values', 'mercator': 'a common flat map projection',
'sha256': 'a fingerprint of the data', 'sha-256': 'a fingerprint of the data', 'delaunay': 'a triangle mesh',
'convex hull': 'the outline around a set of points', 'douglas-peucker': 'simplifying lines',
'breadth-first': 'searching a network level by level', 'topological sort': 'putting steps in dependency order',
'point in polygon': 'testing whether a point is inside a shape', 'bilinear': 'smooth blending between grid points',
'reactance': 'opposition to changing current', 'capacitance': 'stored electric charge',
}
KIND_PHRASE = {
'page': 'A web page', 'test': 'An automated test', 'workflow': 'A GitHub Actions workflow (an automatic job GitHub runs)',
'style sheet': 'A style sheet (rules for how a web page looks)', 'JavaScript module': 'A JavaScript module',
'script': 'A JavaScript file', 'TypeScript module': 'A TypeScript module',
'Python module': 'A Python module (reusable code)', 'Python CLI': 'A Python program run from the command line',
'shell script': 'A shell script (a list of terminal commands)', 'PowerShell script': 'A PowerShell script',
'batch script': 'A batch script', 'configuration': 'A settings file', 'SQL query': 'An SQL query (a database question)',
'component': 'A UI component', 'shader': 'A shader (a small graphics program)',
}
VERB3 = dict(describe.CODE_VERBS, get='gets', set='sets', is_='checks', has='checks', handle='handles', on='handles',
init='sets up', setup='sets up', run='runs', open='opens', close='closes', send='sends', post='posts',
emit='emits', clamp='clamps', escape='escapes', esc='escapes', pick='picks', select='selects',
wire='wires up', bind='binds', attach='attaches', mount='mounts', parse='parses',
append='appends', insert='inserts', delete='deletes', copy='copies', hash='hashes',
fmt='formats', pad='pads', round='rounds', walk='walks', visit='visits', collect='collects',
describe='describes', explain='explains', summarize='summarises', classify='classifies',
require='requires', assert_='asserts', ensure='ensures', apply='applies', compare='compares',
diff='compares', join='joins', split='splits', strip='strips', trim='trims', wrap='wraps',
lookup='looks up', find='finds', fetch='fetches', download='downloads', upload='uploads',
reset='resets', start='starts', stop='stops', tick='advances', step='steps through', play='plays',
project='projects', layout='lays out', paint='paints', fill='fills', stroke='outlines', zoom='zooms',
pan='pans', fit='fits', enable='enables', disable='disables', mark='marks', label='labels')
VERB3['is'] = 'checks if'
VERB3['has'] = 'checks for'
VERB3['to'] = 'converts to'
VERB3['on'] = 'handles'
VERB3.pop('is_', None)
VERB3.pop('assert_', None)
VERB3['assert'] = 'asserts'
STATUS = re.compile(r'\b(candidate|not composed|not published|no production|retired|deprecated|superseded|'
r'unreviewed|quarantined|example only|copied|placeholder|draft|legacy|archived)\b|COPIED|run with|'
r'usage|Opus team|NL-\d{3}|Apache-2\.0|\b20\d{6,}\b|\b[0-9a-f]{10,}\b|generation \d', re.I)
RAW_IDENT = re.compile(r'(?<![`\w./-])(?:[a-z]+[A-Z]\w*|[A-Za-z]+_\w+|[\w\-]+\.(?:mjs|cjs|py|js|ts|json|html|css|sh))'
r'(?![`\w])')
UNIT_SRC = re.compile(r'(?<![\w.])\d+(?:\.\d+)?\s?(kV|kVA|MVA|MVAr|kW|MW|GW|kWh|MWh|GWh|TWh|Hz|km)\b|'
r'(?<![\w])(kV|kVA|MVA|MVAr|kW|MW|GW|kWh|MWh|GWh|TWh|Hz|mm²|°C)(?!\w)')
# ---------------------------------------------------------------- small helpers
def _words(s):
return len(s.split())
def _short_title(t):
t = t or 'Untitled'
if _words(t) > 8 and ' — ' in t:
t = t.split(' — ')[-1]
if _words(t) > 8:
t = ' '.join(t.split()[:8])
return t
def _deraw(text, evt):
"""Raw identifiers outside backticks: quote them when they occur in the evidence, else make them words."""
segs = re.split(r'(`[^`]*`|https?://\S+)', text)
out = []
for s in segs:
if s.startswith('`') or s.startswith('http'):
out.append(s)
continue
out.append(RAW_IDENT.sub(lambda m: '`%s`' % m.group(0) if m.group(0) in evt
else ' '.join(describe.ident_words(m.group(0))), s))
return ''.join(out)
def _sent(s):
s = re.sub(r'\s+', ' ', s or '').strip()
if not s:
return ''
if s[0].islower() and not s.startswith('`'):
s = s[0].upper() + s[1:]
if s[-1] not in '.!?':
s = s.rstrip('…,;:') + '.'
return s
def _gloss(text, seen, limit=2):
"""Add a plain meaning after the first use of up to `limit` glossary words not yet explained."""
n = 0
for k, v in GLOSSARY.items():
if n >= limit or k in seen:
continue
m = re.search(r'(?<![\w`(-])%s(?![\w`-])' % re.escape(k), text)
if not m:
continue
after = text[m.end():m.end() + 3]
seen.add(k)
if after.startswith(' (') or after.startswith(')'):
continue
text = text[:m.end()] + ' (%s)' % v + text[m.end():]
n += 1
return text
def _verb_phrase(name):
"""'computeLayout' -> 'computes layout'; '' when the name does not start with a verb."""
ws = describe.ident_words(name)
if len(ws) < 2:
return ''
v = VERB3.get(ws[0])
if not v:
return ''
rest = [describe._shown(w) for w in ws[1:] if not w.isdigit()]
if not rest or rest[0].lower() == v.split()[-1].lower():
return ''
return '%s %s' % (v, ' '.join(rest))
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]
IMPERATIVE = {k: v for k, v in describe.CODE_VERBS.items() if ' ' not in v}
IMPERATIVE.update(get='gets', show='shows', draw='draws', turn='turns', keep='keeps', give='gives', take='takes',
hold='holds', serve='serves', write='writes', read='reads', test='tests', run='runs', use='uses',
print='prints', emit='emits', add='adds', render='renders', record='records', report='reports',
provide='provides', expose='exposes', define='defines', join='joins', assemble='assembles',
answer='answers', pin='pins', guard='guards', enforce='enforces', prove='proves', mirror='mirrors')
THIRD = set(IMPERATIVE.values())
def _verbify(sentence):
"""'Extract X and write Y.' -> ('extracts X and writes Y.', True); third-person openings pass through."""
ws = sentence.split(' ')
if not ws:
return sentence, False
first = ws[0].lower()
if first in THIRD:
return first + sentence[len(ws[0]):], True
if first in IMPERATIVE and ws[0][:1].isupper() and not ws[0].isupper():
s = IMPERATIVE[first] + sentence[len(ws[0]):]
s = re.sub(r'\b(and|then) (\w+)\b', lambda m: '%s %s' % (m.group(1), IMPERATIVE.get(m.group(2), m.group(2)))
if m.group(2) in IMPERATIVE else m.group(0), s)
return s, True
return sentence, False
def _first_sentence(text, cap=26):
ss = describe._sentences(text)
s = ss[0] if ss else text
return describe._cap_words(s, cap)
# ---------------------------------------------------------------- the three texts
def _what(ev, rec, title):
kind = rec.get('kind') or ev.get('kind', '')
kp = KIND_PHRASE.get(kind, 'A file')
if kind == 'page' and ev.get('has_map'):
kp = 'A web page with an interactive map'
path = rec.get('path', '')
names = [ev.get('repo_title', ''), rec.get('repo', ''), title]
wf = ev.get('workflow') or {}
if kind == 'workflow' or wf.get('triggers'):
trig = [describe.TRIGGER_WORDS[t] for t in wf.get('triggers') or [] if t in describe.TRIGGER_WORDS][:3]
s = kp + (' that runs %s' % describe.join_words(trig) if trig else '')
return _sent(s)
c = ev.get('comment') or ev.get('config') or ''
cc = describe.clean_comment(c, path, names, max_words=30, title=title) if c else ''
if cc and not describe._restates(cc, title) and not STATUS.search(cc):
fs = LABEL.sub('', _first_sentence(cc)).rstrip('.…')
v, ok = _verbify(fs)
if ok:
return _sent('%s that %s' % (kp, v))
if _words(fs) >= 3:
return _sent('%s: %s' % (kp, fs))
code = (ev.get('code') or {}).get('phrase', '')
code = re.sub(r' \(units: [^)]*\)', '', code)
if kind == 'test':
imps = [i['title'] for i in ev.get('imports') or [] if i.get('title') and i['title'] != title][:2]
if imps:
return _sent('%s that checks %s works' % (kp, describe.join_words(imps)))
if code:
return _sent('%s that %s' % (kp, code))
verb, objs = ev.get('verb') or '', describe.clean_objects(ev.get('objects'), title, kind, ev.get('role', ''))
if verb and objs and verb in describe.VERBS:
return _sent('%s that %s %s' % (kp, describe.VERBS[verb][0], describe.join_words(objs[:3])))
said = describe._name_says(title, kind)
if said:
return _sent('%s whose name says it %s' % (kp, said[len('Its name says it '):].rstrip('.')))
folder = [p for p in (rec.get('folder_hierarchy') or [])[1:] if not re.match(r'^\d{6,}$', p)]
if folder:
return _sent('%s in the %s folder' % (kp, ' '.join(describe.ident_words(folder[-1]))))
return _sent(kp)
def _why(rec):
deps = [d for d in (rec.get('ctx') or {}).get('dependents') or [] if d]
if not deps:
return ''
first = deps[0].split(' — ')[-1]
if len(deps) == 1:
return 'Why it matters: “%s” depends on it.' % first
return 'Why it matters: %d other files depend on it, including “%s”.' % (len(deps), first)
def _helper_phrase(d):
"""Plain phrase for a define whose name does not start with a verb (always explained by its own words)."""
ws = describe.ident_words(d)
if 'to' in ws[1:-1] and len(ws) <= 5: # osgb_to_wgs84 -> converts osgb to wgs84
return 'converts %s (`%s`)' % (' '.join(describe._shown(w) for w in ws), d), True
if d[:1].isupper() and len(ws) >= 1 and not d.isupper():
return 'the %s class (`%s`)' % (' '.join(ws), d), False
if len(ws) == 1 and ws[0] in VERB3:
return 'the %s step (`%s`)' % (ws[0], d), False
return 'the %s helper (`%s`)' % (' '.join(ws), d), False
def _steps(rec, src):
items, helpers = [], []
if rec.get('kind') == 'workflow' or ' ' in ''.join(rec.get('defines') or []):
jobs = ['“%s”' % d for d in main_functions(rec) if d in src]
return ['Its jobs are %s.' % describe.join_words(jobs)] if jobs else []
for d in main_functions(rec):
if d not in src:
continue
vp = _verb_phrase(d)
if vp:
items.append('%s (`%s`)' % (vp, d))
continue
hp, verb = _helper_phrase(d)
(items if verb else helpers).append(hp)
out = []
for k in range(0, len(items), 3):
out.append('%s %s.' % ('Its main steps: it' if k == 0 else 'It also', describe.join_words(items[k:k + 3])))
for k in range(0, len(helpers), 3):
lead = 'It also has' if (items or k) else 'It is built from'
out.append('%s %s.' % (lead, describe.join_words(helpers[k:k + 3])))
return out
def _terms(src):
if not src:
return ''
found = []
for m in UNIT_SRC.finditer(src[:200000]):
u = m.group(1) or m.group(2)
if u not in found:
found.append(u)
found = [u for u in found if src.count(u) >= 2][:2]
low = src.lower()
forms = [w for w in FORMULA_PLAIN if re.search(r'(?<![\w])' + re.escape(w) + r'(?![\w])', low)][:2]
stds = []
for m in re_std.finditer(src[:200000]):
k = m.group(0)
if k not in stds:
stds.append(k)
bits = ['%s (%s)' % (u, UNIT_PLAIN[u]) for u in found]
seenm = set()
forms = [w for w in forms if not (FORMULA_PLAIN[w] in seenm or seenm.add(FORMULA_PLAIN[w]))]
bits += ['%s (%s)' % (w, FORMULA_PLAIN[w]) for w in forms]
bits += ['the standard %s' % s for s in stds[:1]]
if not bits:
return ''
return 'The code works with %s.' % describe.join_words(bits)
re_std = re.compile(r'\b(?:IEC|BS|EN|IEEE|ENA|IET)\s?[A-Z]?\s?\d{3,5}(?:[-:]\d+)*\b|\bG(?:59|83|98|99)\b|\bP2/[67]\b|'
r'\bEPSG:\d{4,5}\b')
BAD_README = re.compile(r'\b(status|version|v\d|todo|wip|january|february|march|april|may|june|july|august|'
r'september|october|november|december)\b|\d\d:\d\d|^\W*[A-Z]{1,5}-?\w*\d+\s*:', re.I)
LABEL = re.compile(r'^(?:[A-Z]{1,5}-?[A-Z]?\d+[a-z]?|\d{1,4}|[A-Z][\w-]{0,20} \d{1,3})\s*[:.—–-]\s+')
def _readme_line(rec, title):
path = rec.get('path', '')
names = [(rec.get('ctx') or {}).get('repo_title', ''), rec.get('repo', ''), title]
for s in ((rec.get('ctx') or {}).get('readme') or [])[:8]:
cc = describe.clean_comment(s, path, names, max_words=24)
if not cc or STATUS.search(cc) or BAD_README.search(cc) or _words(cc) < 6 or 'http' in cc:
continue
cc = _first_sentence(cc, 24)
return 'The README (project notes) says: %s' % _sent(cc[0].lower() + cc[1:] if cc[:2].istitle()
and not cc.split()[0].isupper() else cc)
return ''
def _evidence(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', [])}
return ev, describe.evidence_text(ev) + '\n' + (src or '')
INITIAL = re.compile(r'(^|[.!?:]\s+|\n)([A-Z][a-z]+)\b(?![\w\-])')
def _invented(text, evt):
return describe.invented(INITIAL.sub(lambda m: m.group(1) + m.group(2).lower(), text), evt)
def _ok(sentence, evt, src):
if _invented(sentence, evt):
return False
for q in re.findall(r'`([^`]+)`', sentence):
if q not in src and q not in evt:
return False
return True
def translate(rec, src):
src = src or ''
ev, evt = _evidence(rec, src)
title = _short_title(rec.get('title') or ev.get('title', ''))
if not _ok(title, evt, src):
title = _short_title(ev.get('title', '') or rec.get('path', 'file').rsplit('/', 1)[-1])
seen = set(k for k in GLOSSARY if re.search(r'\b%s\b' % re.escape(k), title) and '(' in title)
what = _deraw(_what(ev, rec, title), evt)
if not _ok(what, evt, src):
what = _sent(KIND_PHRASE.get(rec.get('kind', ''), 'A file'))
what_g = _gloss(what, seen)
if _words(what_g) > 30:
what_g = what
syn = [what_g]
why = _why(rec)
if why and _ok(why, evt, src) and _words(what_g) + _words(why) <= 40:
syn.append(why)
ach = []
for s in _steps(rec, src) + [_terms(src)]:
if s and _ok(s, evt, src):
ach.append(s)
rl = _readme_line(rec, title)
if rl:
rl = _deraw(rl, evt)
if rl and _ok(rl, evt, src):
if _words(' '.join(syn)) < 12 and _words(' '.join(syn)) + _words(rl) <= 40:
syn.append(rl)
else:
ach.append(rl)
if _words(' '.join(syn)) < 12: # pad with the folder it lives in (plain words, evidence path)
folder = [p for p in (rec.get('folder_hierarchy') or [])[1:] if not re.match(r'^\d{6,}$', p)]
if folder:
syn.append(_sent('It lives in the %s folder of %s' % (' '.join(describe.ident_words(folder[-1])),
rec.get('repo', ''))))
synopsis = ' '.join(syn)
if _words(synopsis) > 40:
synopsis = describe._cap_words(synopsis, 40)
achieves = ' '.join(_gloss(a, seen, 1) if a.startswith('The README') else a for a in ach)
out = {'title': title, 'synopsis': synopsis, 'achieves': achieves}
# final self-check: never ship a flagged word
if any(_invented(v, evt) for v in out.values()):
out['achieves'] = ' '.join(a for a in ach if _ok(a, evt, src))
if any(_invented(v, evt) for v in out.values()):
out = {'title': title, 'synopsis': what, 'achieves': ''}
return out