GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / cosmic / tools/explore/bigbang/rules

Feeder 47 and 1 more file

A Python module in the rules folder of Cosmic that works with cables, battery storage (BESS) and transformers, using IEC 60287 and IEC 60853.

697 lines of Python from cosmic, in 2 files. Topic: Grid network and substations. Section 313 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. Feeder 47 electrical · cosmic / tools/explore/bigbang/rules/FEEDER-47.py lines 1–656
  2. Test Feeder 47 test · cosmic / tools/explore/bigbang/rules/test_FEEDER-47.py lines 1–41

Feeder 47

A Python module in the rules folder of Cosmic that works with cables, battery storage (BESS) and transformers, using IEC 60287 and IEC 60853.

electricalcosmic / tools/explore/bigbang/rules/FEEDER-47.py · lines 1–656 of 656 · Not reached from any entry point (candidate for review) · pattern _main_functions (shared by 2 files)

What it does
It calculates cables, battery storage (BESS), transformers and the REPD register. Defines 23 functions or classes, including _words, _in_src, _main_functions, _code_only, _gloss_generic. Uses libraries json, os, re, sys.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'grid-network'): 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: cables, battery storage (BESS), transformers, the REPD register, 525kV, 400kV.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89 / EPSG:4258. Voltage levels named: 525kV, 400kV, 320kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It is built from the translate step (`translate`). Big Bang player: ENGINEERING DOMAIN rules (owner: FEEDER-47, rule-set player). Its code works with 400 kV, 1 kV and 1.1 kV.
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), json, os, re, sys
Used by
none found
Produces
translate
Defines here
_words, _in_src, _main_functions, _code_only, _gloss_generic, _gloss_engineering, _detect, _voltages, kv, _units, _term, _without_missing_term, _join, _folder_words, _repo_name, _evidence, _bad, _cap, _dedupe, _clean_sentence, _readme_sentence, _header_sentence, 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/FEEDER-47.py:1-656 · blob c9847176382ee2f75239343ae46b9e444b446531 · 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: unreached_review
"""FEEDER-47 - Big Bang player: ENGINEERING DOMAIN rules (owner: FEEDER-47, rule-set player).

translate(rec, src) -> {'title', 'synopsis', 'achieves'}

Reads the code the way a grid or energy engineer would. A vocabulary table (VOCAB) maps patterns that truly occur
in the source (formulas such as haversine or voltage drop, standards such as IEC 60287, coordinate systems such as
OSGB36 or WGS84, data sources such as REPD or NESO, assets such as substations, cables or BESS) to plain meanings;
voltages (400V-400kV) and units (MW, MVA, kA, kWp, mm2) are read from the source with their numbers. Defined
functions are explained in file order, each with an engineering gloss when its own name carries one, else with a
plain verb gloss built from its name words. Everything said is evidence: a term is used only when its pattern is
found in the source, a data source only when the file itself names it, and a final guard drops any sentence that
describe.invented() would flag against the arena's evidence text. Deterministic, stdlib only.
"""
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)))
try:
    import describe  # read-only: invented(), evidence_text(), ident_words(), polish_title()
except Exception:  # pragma: no cover - the player still runs without it (no guard)
    describe = None

NAME = 'FEEDER-47 (engineering domain)'
STRATEGY = ('Reads grid and energy engineering in the code (formulas, standards, voltages, units, coordinate '
            'systems, named data sources, assets) and says what it computes as an engineer would.')

# ---------------------------------------------------------------- vocabulary table
# Each entry: key, class, detection regex (on the source), plain phrase, optional verb phrase for the synopsis,
# optional term (a literal checked again in the source before it is written), and optional name regex (matches a
# defined function name, used to gloss that function). Order is priority within a class.
_I = re.I
VOCAB = [
    # formulas and methods
    dict(key='haversine', cls='formula', rx=r'haversine', struct=(r'\b(?:6371|6378137|6371008|6371000|6371\.0088|EARTH_R\w*|R_EARTH\w*)\b', r'\bsin\b', r'\b(?:atan2|asin)\b'),
         proof=r'\b(?:atan2|asin)\b', plain='great-circle distance by the haversine formula',
         verb='computes great-circle distances with the haversine formula', term='haversine',
         name=r'haversine|greatcircle|gcdist'),
    dict(key='vincenty', cls='formula', rx=r'vincenty', plain='ellipsoidal distance by the Vincenty method',
         verb='computes ellipsoidal distances by the Vincenty method', term='vincenty', name=r'vincenty'),
    dict(key='bearing', cls='formula', rx=r'bearing[\s\S]{0,400}atan2|atan2[\s\S]{0,400}bearing',
         plain='initial great-circle bearing between two points', verb='works out compass bearings between points',
         name=r'bearing'),
    dict(key='iec60287', cls='standard', rx=r'IEC\s?60287', plain='continuous cable current rating by IEC 60287',
         verb='rates cable current capacity by IEC 60287', term='IEC 60287', name=r'60287|ampacity|ratingmodule'),
    dict(key='iec60853', cls='standard', rx=r'IEC\s?60853', plain='cyclic cable rating by IEC 60853',
         verb='applies cyclic cable rating by IEC 60853', term='IEC 60853'),
    dict(key='iec60909', cls='standard', rx=r'IEC\s?60909', plain='short-circuit currents by IEC 60909',
         verb='calculates short-circuit currents by IEC 60909', term='IEC 60909'),
    dict(key='iec60228', cls='standard', rx=r'IEC\s?60228', plain='conductor sizes by IEC 60228',
         verb='uses conductor sizes from IEC 60228', term='IEC 60228'),
    dict(key='iec60364', cls='standard', rx=r'IEC\s?60364', plain='low-voltage installation rules of IEC 60364',
         verb='follows the IEC 60364 low-voltage installation rules', term='IEC 60364'),
    dict(key='bs7671', cls='standard', rx=r'BS\s?7671', plain='wiring rules of BS 7671',
         verb='checks against the BS 7671 wiring rules', term='BS 7671'),
    dict(key='iec62446', cls='standard', rx=r'IEC\s?62446', plain='PV system test records by IEC 62446',
         verb='follows IEC 62446 PV test records', term='IEC 62446'),
    dict(key='iec60076', cls='standard', rx=r'IEC\s?60076', plain='power transformer rules of IEC 60076',
         verb='uses IEC 60076 power transformer rules', term='IEC 60076'),
    dict(key='iec61936', cls='standard', rx=r'IEC\s?61936', plain='high-voltage installation rules of IEC 61936',
         verb='follows IEC 61936 high-voltage installation rules', term='IEC 61936'),
    dict(key='g99', cls='standard', rx=r'\bG99\b', plain='G99 generator connection rules',
         verb='applies the G99 generator connection rules', term='G99'),
    dict(key='g98', cls='standard', rx=r'\bG98\b', plain='G98 micro-generator connection rules',
         verb='applies the G98 micro-generator rules', term='G98'),
    dict(key='g100', cls='standard', rx=r'\bG100\b', plain='G100 export limitation rules',
         verb='applies G100 export limitation', term='G100'),
    dict(key='p27', cls='standard', rx=r'P2/[678]\b', plain='security of supply rules (P2)',
         verb='checks security of supply', term=None),
    dict(key='vdrop', cls='formula', proof=r'(?:mV|mv)[\s_/]*(?:A|a)[\s_/]*(?:m|km)|sqrt\(\s*3\s*\)|SQRT3|1\.732|\* ?length|cos\(|resistance', rx=r'voltage[\s_-]?drop|voltageDrop|\bv_?drop', plain='voltage drop along a circuit',
         verb='works out voltage drop along circuits', term='voltage drop', name=r'v(oltage)?_?drop'),
    dict(key='fault', cls='formula', proof=r'\bkA\b|sqrt\(\s*3\s*\)|SQRT3|1\.732|impedance|\bmva\b|MVA', rx=r'fault[\s_-]?level|faultLevel|short[\s-]circuit|shortCircuit',
         plain='fault level (short-circuit current)', verb='estimates fault level (short-circuit current)',
         term=('fault level', 'short-circuit'), name=r'fault|shortcircuit|short_circuit'),
    dict(key='loadflow', cls='formula', rx=r'load[\s_-]?flow|power[\s_-]?flow|newton[\s-]raphson|gauss[\s-]seidel|pandapower',
         proof=r'jacobian|admittance|ybus|y_bus|newton|gauss[\s-]seidel|pp\.runpp|runpp',
         plain='load flow (power flow) solution', verb='solves load flow across the network',
         term=('load flow', 'power flow', 'newton-raphson', 'gauss-seidel'), name=r'loadflow|powerflow|load_flow|power_flow'),
    dict(key='derate', cls='formula', proof=r'derat\w*\s*\*|\*\s*derat|factor', rx=r'\bderat(e|ed|es|ing|ion)', plain='derating factors for installed conditions',
         verb='applies derating factors', term='derating', name=r'derat'),
    dict(key='thermal', cls='formula', rx=r'thermal[\s_-]?resistiv|thermal[\s_-]?resistance',
         plain='soil and insulation thermal resistance', verb='models thermal resistance around buried cables',
         term='thermal resistance'),
    dict(key='pf', cls='formula', rx=r'power[\s_-]?factor|powerFactor', plain='power factor',
         verb='accounts for power factor', term='power factor', name=r'power_?factor'),
    dict(key='impedance', cls='formula', rx=r'impedance|reactance', plain='circuit impedance and reactance',
         verb='uses circuit impedance', term=('impedance', 'reactance'), name=r'impedance|reactance'),
    dict(key='perunit', cls='formula', rx=r'per[\s_-]unit|\bp\.u\.', plain='per-unit quantities',
         verb='works in per-unit quantities', term='per-unit'),
    dict(key='i2r', cls='formula', rx=r'I²R|I\^2\s?R|i2r|copper[\s_-]?loss|ohmic[\s_-]?loss', plain='resistive (I²R) losses',
         verb='estimates resistive losses', term=('i²r', 'i2r')),
    dict(key='skin', cls='formula', rx=r'skin[\s_-]?effect', plain='conductor skin effect', verb='allows for skin effect',
         term='skin effect'),
    dict(key='irradiance', cls='formula', rx=r'irradiance', plain='solar irradiance on the panels',
         verb='uses solar irradiance', term='irradiance', name=r'irradiance|poa'),
    dict(key='mppt', cls='asset', rx=r'\bMPPT', plain='inverter MPPT inputs', verb='allocates PV strings to MPPT inputs',
         term='mppt', name=r'mppt'),
    dict(key='stringsize', cls='formula', rx=r'\bV_?oc\b|\bVoc[A-Z_]|\bVmpp?\b|open[\s_-]?circuit[\s_-]?voltage',
         plain='PV string voltage limits (open-circuit and maximum-power voltage)',
         verb='checks PV string voltages against limits', name=r'string_?siz|stringsiz|voc'),
    dict(key='tm', cls='formula', rx=r'transverse[\s_-]?mercator', plain='transverse Mercator projection',
         verb='projects coordinates by transverse Mercator', term='transverse mercator'),
    dict(key='helmert', cls='formula', rx=r'helmert', plain='Helmert datum transformation',
         verb='shifts datum with a Helmert transformation', term='helmert', name=r'helmert'),
    dict(key='ostn15', cls='coord', rx=r'OSTN15', plain='OSTN15 grid shift', verb='applies the OSTN15 grid shift',
         term='ostn15'),
    dict(key='webmerc', cls='formula', rx=r'web[\s_-]?mercator|EPSG:3857', plain='Web Mercator tiles',
         verb='works in Web Mercator', term=('web mercator', 'EPSG:3857')),
    dict(key='npv', cls='formula', rx=r'\bNPV\b|net[\s_-]present[\s_-]value', plain='net present value',
         verb='computes net present value', term='npv', name=r'npv'),
    dict(key='lcoe', cls='formula', rx=r'\bLCOE\b|levelised[\s_-]cost', plain='levelised cost of energy',
         verb='computes levelised cost of energy', term=('lcoe', 'levelised cost'), name=r'lcoe'),
    dict(key='irr', cls='formula', rx=r'\bIRR\b', plain='internal rate of return', verb='computes internal rate of return',
         term='irr', name=r'\birr'),
    dict(key='dijkstra', cls='algo', rx=r'dijkstra', plain='shortest paths by Dijkstra',
         verb='finds shortest paths with Dijkstra', term='dijkstra', name=r'dijkstra|shortest'),
    dict(key='douglas', cls='algo', rx=r'douglas[\s_-]?peucker|ramer', plain='line simplification by Douglas-Peucker',
         verb='simplifies lines by Douglas-Peucker', term='douglas-peucker', name=r'simplif'),
    dict(key='pip', cls='algo', rx=r'point[\s_-]?in[\s_-]?polygon|pointInPolygon|ray[\s_-]?cast',
         plain='point-in-polygon test', verb='tests whether points fall inside polygons',
         term=('point in polygon', 'ray casting', 'raycast'), name=r'pointinpoly|inpolygon|point_in_poly'),
    dict(key='interp', cls='algo', rx=r'interpolat', plain='interpolation between table values',
         verb='interpolates between table values', term='interpolation', name=r'interp|lerp'),
    dict(key='sha256', cls='algo', rx=r'sha-?256', plain='SHA-256 hashes', verb='hashes content with SHA-256',
         term=('sha256', 'sha-256'), name=r'sha256|hash'),
    dict(key='threephase', cls='formula', rx=r'(?:Math\.)?sqrt\(\s*3(?:\.0)?\s*\)|\bSQRT_?3\b|\b1\.732\d*\b',
         proof=r'(?:Math\.)?sqrt\(\s*3(?:\.0)?\s*\)|\bSQRT_?3\b|\b1\.732',
         plain='three-phase power from line voltage and current (the square root of 3 factor)',
         verb='converts between three-phase power, voltage and current'),
    dict(key='planar', cls='algo', rx=r'(?:Math\.)?hypot\(|sqrt\(\s*d[xX]\s*\*\s*d[xX]|sqrt\(\s*d[xX]\s*\*\*\s*2',
         proof=r'.', plain='straight-line (planar) distances', verb='measures straight-line distances',
         name=r'dist'),
    # coordinate systems
    dict(key='bng', cls='coord', rx=r'OSGB36|EPSG:27700|British National Grid|\bBNG\b',
         plain='British National Grid eastings and northings', verb='works in British National Grid coordinates',
         term=('EPSG:27700', 'osgb36'), name=r'bng|osgb|easting|northing'),
    dict(key='wgs84', cls='coord', rx=r'WGS[\s-]?84|EPSG:4326', plain='WGS84 latitude and longitude',
         verb='works in WGS84 latitude and longitude', term=('wgs84', 'EPSG:4326'), name=r'wgs|latlon|lnglat'),
    dict(key='etrs89', cls='coord', rx=r'ETRS89', plain='ETRS89 coordinates', verb='uses ETRS89 coordinates', term='etrs89'),
    dict(key='utm', cls='coord', rx=r'\bUTM\b', plain='UTM grid coordinates', verb='uses UTM grid coordinates', term=None),
    # data sources (only when the file names them)
    dict(key='repd', cls='source', rx=r'\bREPD\b|repd[_\-.]', plain='REPD'),
    dict(key='neso', cls='source', rx=r'\bNESO\b', plain='NESO'),
    dict(key='etys', cls='source', rx=r'\bETYS\b', plain='ETYS'),
    dict(key='bmrs', cls='source', rx=r'\bBMRS\b', plain='BMRS'),
    dict(key='elexon', cls='source', rx=r'\bElexon\b', plain='Elexon'),
    dict(key='entsoe', cls='source', rx=r'ENTSO-?E', plain='ENTSO-E'),
    dict(key='ukpn', cls='source', rx=r'\bUKPN\b', plain='UKPN'),
    dict(key='ssen', cls='source', rx=r'\bSSEN\b', plain='SSEN'),
    dict(key='nged', cls='source', rx=r'\bNGED\b', plain='NGED'),
    dict(key='ofgem', cls='source', rx=r'\bOfgem\b', plain='Ofgem'),
    dict(key='desnz', cls='source', rx=r'\bDESNZ\b', plain='DESNZ'),
    dict(key='osm', cls='source', rx=r'OpenStreetMap|overpass-api|\bOSM\b', plain='OpenStreetMap'),
    dict(key='os', cls='source', rx=r'Ordnance Survey', plain='Ordnance Survey'),
    dict(key='pvgis', cls='source', rx=r'\bPVGIS\b', plain='PVGIS'),
    dict(key='era5', cls='source', rx=r'\bERA5\b', plain='ERA5'),
    dict(key='dno', cls='source', rx=r'\bDNOs?\b', plain='DNO'),
    dict(key='tec', cls='source', rx=r'TEC[\s_-]?register', plain='TEC register'),
    dict(key='ecr', cls='source', rx=r'Embedded Capacity Register', plain='Embedded Capacity Register'),
    # assets (plain noun, regex)
    dict(key='substation', cls='asset', rx=r'substation', plain='substations', name=r'substation|\bsubs?\b'),
    dict(key='ohl', cls='asset', rx=r'overhead[\s_-]?line|\bOHL\b', plain='overhead lines', name=r'ohl|overhead'),
    dict(key='cable', cls='asset', rx=r'\bcables?\b|cable[A-Z_]', plain='cables', name=r'cable'),
    dict(key='transformer', cls='asset', rx=r'transformer', plain='transformers', name=r'transformer|trafo'),
    dict(key='busbar', cls='asset', rx=r'busbar', plain='busbars', name=r'busbar'),
    dict(key='switchgear', cls='asset', rx=r'switchgear|circuit[\s_-]?breaker', plain='switchgear and circuit breakers'),
    dict(key='feeder', cls='asset', rx=r'\bfeeders?\b', plain='feeders'),
    dict(key='inverter', cls='asset', rx=r'\binverters?\b', plain='inverters', name=r'inverter'),
    dict(key='pvstring', cls='asset', rx=r'\bPV\b[\s\S]{0,200}\bstrings?\b|\bstrings?\b[\s\S]{0,200}\bmodules?\b[\s\S]{0,200}\bPV\b',
         plain='PV strings'),
    dict(key='bess', cls='asset', rx=r'\bBESS\b|battery[\s_-]?storage', plain='battery storage (BESS)', name=r'bess|battery'),
    dict(key='wind', cls='asset', rx=r'wind[\s_-]?turbine|wind[\s_-]?farm', plain='wind turbines'),
    dict(key='interconnector', cls='asset', rx=r'interconnector', plain='interconnectors', name=r'interconnector'),
    dict(key='gsp', cls='asset', rx=r'grid[\s_-]?supply[\s_-]?point|\bGSPs?\b', plain='grid supply points'),
    dict(key='trench', cls='asset', rx=r'\btrench', plain='cable trenches', name=r'trench'),
    dict(key='pylon', cls='asset', rx=r'\bpylons?\b', plain='pylons'),
]
for _v in VOCAB:
    _v['crx'] = re.compile(_v['rx'], _I if _v['cls'] not in ('source',) or _v['key'] in ('repd',) else 0)
    _v['nrx'] = re.compile(_v['name'], _I) if _v.get('name') else None
    _v.setdefault('proof', None)

VOLT_RX = re.compile(r'(?<![\w.])(\d{1,3}(?:\.\d+)?)\s?(kV|V)\b')
UNIT_NUM_RX = re.compile(r'(?<![\w.])(\d+(?:\.\d+)?)\s?(MVA|MW|MWh|kA|kWp|GW|mm²)(?![\w²])')
OK_VOLTS = {'400V', '230V', '415V', '690V', '1.5kV', '3.3kV', '6.6kV', '11kV', '20kV', '22kV', '33kV', '66kV', '110kV',
            '132kV', '220kV', '275kV', '400kV', '1kV', '1.1kV', '6.35kV', '19kV', '525kV', '320kV'}

# Plain verbs for names that start with a verb word.
VERB3 = {
    'get': 'gets', 'set': 'sets', 'compute': 'computes', 'calc': 'calculates', 'calculate': 'calculates',
    'build': 'builds', 'make': 'makes', 'create': 'creates', 'render': 'renders', 'draw': 'draws', 'paint': 'paints',
    'parse': 'parses', 'load': 'loads', 'fetch': 'fetches', 'format': 'formats', 'fmt': 'formats',
    'normalise': 'normalises', 'normalize': 'normalizes', 'norm': 'normalises', 'clamp': 'clamps',
    'validate': 'validates', 'check': 'checks', 'verify': 'verifies', 'update': 'updates', 'init': 'sets up',
    'setup': 'sets up', 'handle': 'handles', 'apply': 'applies', 'export': 'exports', 'import': 'imports',
    'read': 'reads', 'write': 'writes', 'save': 'saves', 'filter': 'filters', 'sort': 'sorts', 'find': 'finds',
    'add': 'adds', 'remove': 'removes', 'delete': 'deletes', 'toggle': 'toggles', 'show': 'shows', 'hide': 'hides',
    'escape': 'escapes', 'esc': 'escapes', 'sum': 'sums', 'count': 'counts', 'merge': 'merges', 'convert': 'converts',
    'estimate': 'estimates', 'select': 'selects', 'open': 'opens', 'close': 'closes', 'resolve': 'resolves',
    'collect': 'collects', 'extract': 'extracts', 'generate': 'generates', 'gen': 'generates', 'emit': 'emits',
    'scan': 'scans', 'list': 'lists', 'search': 'searches', 'match': 'matches', 'detect': 'detects',
    'measure': 'measures', 'plot': 'plots', 'fit': 'fits', 'score': 'scores', 'rank': 'ranks', 'run': 'runs',
    'start': 'starts', 'stop': 'stops', 'reset': 'resets', 'clear': 'clears', 'refresh': 'refreshes',
    'download': 'downloads', 'upload': 'uploads', 'send': 'sends', 'post': 'posts', 'store': 'stores',
    'cache': 'caches', 'attach': 'attaches', 'bind': 'binds', 'wire': 'wires', 'register': 'registers',
    'populate': 'populates', 'fill': 'fills', 'append': 'appends', 'insert': 'inserts', 'replace': 'replaces',
    'split': 'splits', 'join': 'joins', 'group': 'groups', 'classify': 'classifies', 'assign': 'assigns',
    'allocate': 'allocates', 'size': 'sizes', 'route': 'routes', 'snap': 'snaps', 'project': 'projects',
    'transform': 'transforms', 'scale': 'scales', 'rotate': 'rotates', 'move': 'moves', 'zoom': 'zooms',
    'fly': 'flies to', 'pan': 'pans', 'highlight': 'highlights', 'mark': 'marks', 'label': 'labels', 'print': 'prints',
    'log': 'logs', 'warn': 'warns about', 'summarise': 'summarises', 'summarize': 'summarizes', 'describe': 'describes',
    'explain': 'explains', 'translate': 'translates', 'encode': 'encodes', 'decode': 'decodes', 'hash': 'hashes',
    'sign': 'signs', 'compare': 'compares', 'diff': 'compares', 'test': 'tests', 'assert': 'asserts', 'ensure': 'ensures',
    'require': 'requires', 'track': 'tracks', 'watch': 'watches', 'poll': 'polls', 'schedule': 'schedules',
    'wrap': 'wraps', 'pick': 'picks', 'choose': 'chooses', 'evaluate': 'evaluates', 'eval': 'evaluates',
    'solve': 'solves', 'derive': 'derives', 'infer': 'infers', 'guess': 'guesses', 'clean': 'cleans',
    'strip': 'strips', 'trim': 'trims', 'pad': 'pads', 'round': 'rounds', 'snapshot': 'snapshots', 'publish': 'publishes',
    'deploy': 'deploys', 'serve': 'serves', 'mount': 'mounts', 'animate': 'animates', 'tick': 'advances',
    'step': 'steps', 'advance': 'advances', 'connect': 'connects', 'link': 'links', 'lookup': 'looks up',
}
ON_WORDS = {'on', 'handle'}
BOOL_LEAD = {'is': 'tells whether it is', 'has': 'tells whether it has', 'can': 'tells whether it can',
             'should': 'decides whether to'}
FILLER = {'the', 'a', 'an', 'of', 'for', 'to', 'and', 'or', 'by', 'with', 'from', 'in', 'into', 'at'}

# Kind of file -> noun phrase starting with a stock-cased word, for "A ... that".
KIND = {
    'page': 'web page', 'test': 'test file', 'workflow': 'GitHub Actions workflow', 'style sheet': 'style sheet',
    'JavaScript module': 'JavaScript module', 'script': 'JavaScript file', 'TypeScript module': 'TypeScript module',
    'Python module': 'Python module', 'Python CLI': 'Python command-line tool', 'shell script': 'shell script',
    'PowerShell script': 'PowerShell script', 'batch script': 'batch script', 'configuration': 'configuration file',
    'SQL query': 'SQL query', 'component': 'UI component', 'shader': 'shader',
}
# never write these words (no religious terms anywhere in output)
BANNED = re.compile(r'\b(vedic|veda|holy|god|gods|goddess|divine|sacred|temple|prayer|pray|scripture|mahabharata|'
                    r'krishna|shiva|vishnu|brahma|bible|church|angel|heaven|karma|dharma|mantra|buddha|allah|jesus|'
                    r'christ|deity|worship|blessing|saint|soul|spirit|mother|psalm|gospel|devotion|guru)\b', _I)
SKIP_FOLDERS = re.compile(r'^(releases?|src|lib|dist|build|public|static|assets?|js|css|scripts?|tools?|docs?|tests?|'
                          r'data|v\d+|\d{6,}|node_modules|vendor|app|web|site|www|pages?|_\w+|\..*)$', _I)


# ---------------------------------------------------------------- helpers
def _words(name):
    if describe is not None:
        return describe.ident_words(name)
    n = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', name)
    n = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1 \2', n)
    return [w.lower() for w in re.split(r'[\s_\-.$]+', n) if w]


def _in_src(term, src_l_nospace):
    return term.lower().replace(' ', '') in src_l_nospace


def _main_functions(rec, src, 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 _code_only(src):
    """Source with comment lines and long string literals removed (formula evidence prefers real code)."""
    s = re.sub(r'/\*[\s\S]*?\*/', ' ', src)
    s = re.sub(r'(?m)^\s*(#|//).*$', ' ', s)
    return s


def _gloss_generic(name):
    """Plain verb gloss from a name's own words, or '' (then the name is only listed)."""
    if not re.match(r'^[A-Za-z_$][\w$]*$', name):
        return ''
    ws = [w for w in _words(name) if w and w != '$']
    if not ws:
        return ''
    if name[:1].isupper() and not name.isupper() and len(ws) >= 2:
        return 'is the %s class' % ' '.join(ws)
    first, rest = ws[0], ws[1:]
    obj = ' '.join(w for w in rest if w not in ('fn', 'func', 'impl'))
    if not obj:
        if first in VERB3:
            return VERB3[first] + ' its input'
        if len(first) >= 3 and first.isalpha():
            return 'defines the %s helper' % first
        return ''
    if first == 'on':
        return 'handles %s events' % obj
    if first == 'handle':
        return 'handles %s' % obj
    if first in BOOL_LEAD:
        return '%s %s' % (BOOL_LEAD[first], obj)
    if first == 'to':
        return 'converts to %s' % obj
    if first in VERB3:
        return '%s %s' % (VERB3[first], obj)
    if 2 <= len(ws) <= 5:
        return 'works with %s' % ' '.join(ws)
    return ''


def _gloss_engineering(name, hits):
    low = name.lower()
    for v in VOCAB:
        if v['nrx'] is not None and v['key'] in hits and v['nrx'].search(low):
            g = _gloss_generic(name)
            first = g.split(' ')[0] if g else ''
            verb = first if first in VERB3.values() and first not in ('handles', 'converts') else 'gives'
            return '%s the %s' % (verb, v['plain'])
    return ''


def _detect(src, defines):
    """-> dict key -> entry (with count and strong) for vocabulary patterns found in the source."""
    code = _code_only(src)
    names = ' '.join(d.lower() for d in defines or [])
    hits = {}
    for v in VOCAB:
        hay = src if v['cls'] in ('source', 'standard', 'coord') else code
        try:
            m = v['crx'].findall(hay[:200000])
        except Exception:
            m = []
        if not m and v.get('struct') and all(re.search(x, hay) for x in v['struct']):
            m = ['structure']
        if not m:
            continue
        if v['cls'] == 'asset' and len(m) < 2 and v['key'] not in ('bess', 'mppt'):
            continue
        strong = v['cls'] in ('standard', 'coord') or bool(v['nrx'] is not None and v['nrx'].search(names))
        if not strong and v.get('proof'):
            strong = bool(re.search(v['proof'], code[:200000]))
        hits[v['key']] = dict(v, count=len(m), strong=strong)
    return hits


def _voltages(src):
    seen, out = set(), []
    for num, u in VOLT_RX.findall(src):
        lit = num + u
        if lit in OK_VOLTS and lit not in seen:
            seen.add(lit)
            out.append(lit)

    def kv(x):
        return float(x[:-2]) * 1000 if x.endswith('kV') else float(x[:-1])
    return sorted(out, key=kv)


def _units(src):
    seen, out = set(), []
    for num, u in UNIT_NUM_RX.findall(src):
        if u not in seen:
            seen.add(u)
            out.append('%s %s' % (num, u))
    return out[:3]


def _term(v, src_ns):
    t = v.get('term')
    if not t:
        return ''
    for x in (t if isinstance(t, tuple) else (t,)):
        if _in_src(x, src_ns):
            return x
    return ''


def _without_missing_term(phrase, v, src_ns):
    """Drop a 'by X' / 'with the X formula' / 'of X' tail naming a term the source does not literally contain."""
    t = v.get('term')
    if not t:
        return phrase
    for x in (t if isinstance(t, tuple) else (t,)):
        if x.lower() in phrase.lower() and not _in_src(x, src_ns):
            if v['key'] == 'haversine':
                return 'computes great-circle distances' if phrase.startswith('computes') else 'great-circle distance'
            return re.split(r'\s(?:with|by|of)\s', phrase)[0]
    return phrase


def _join(xs):
    xs = [x for x in xs if x]
    if len(xs) <= 1:
        return ''.join(xs)
    return ', '.join(xs[:-1]) + ' and ' + xs[-1]


def _folder_words(rec):
    fh = [f for f in (rec.get('folder_hierarchy') or [])[1:] if not SKIP_FOLDERS.match(f)]
    for f in reversed(fh):
        w = ' '.join(x for x in _words(f) if not re.match(r'^(v?\d+[a-z]?|the|nl|a)$', x))
        w = re.sub(r'\s+', ' ', w).strip()
        if len(w) >= 4 and 1 <= len(w.split()) <= 5 and not BANNED.search(w) and re.match(r'^[a-z][a-z0-9 ]*$', w):
            return w
    return ''


def _repo_name(rec):
    rt = ((rec.get('ctx') or {}).get('repo_title') or '').strip().rstrip('.')
    raw = ((rec.get('ctx') or {}).get('repo_title') or '').strip()
    if rt and len(rt.split()) <= 6 and not BANNED.search(rt) and not re.search(r'[.:;]', rt) and \
            not raw.endswith('.') and not re.search(r'\b(is|are|this|that)\b', rt, re.I):
        return rt
    w = ' '.join(_words(rec.get('repo') or ''))
    return (w + ' repository') if w and not BANNED.search(w) else ''


def _evidence(rec, src):
    ctx = rec.get('ctx') or {}
    ev = ctx.get('evidence') or {}
    recj = json.dumps({k: v for k, v in rec.items() if k != 'ctx'}, ensure_ascii=False)
    et = ''
    if describe is not None and ev:
        try:
            et = describe.evidence_text(ev)
        except Exception:
            et = ''
    return et + '\n' + recj + '\n' + src


HOUSE = re.compile(r'\b(candidate|retired|deprecated|superseded|unreviewed|quarantined|example only|copied|placeholder|'
                   r'byte-identical|immutable|unchanged|draft|legacy|frozen|archived|v\d+(?:\.\d+)+|phase-?\d|'
                   r'proof|team|owner|session|issue|nl-\d+)\b|https?://|\b20\d{6,}\b|\b[0-9a-f]{10,}\b|[`"“”]', _I)


def _bad(text, evidence):
    if BANNED.search(text):
        return True
    if describe is None:
        return False
    return bool(describe.invented(_INITIAL.sub(lambda m: m.group(1) + m.group(2).lower(), text), evidence))


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


def _cap(s):
    return s[:1].upper() + s[1:] if s else s


def _dedupe(s):
    return re.sub(r'\b(\w+) \1\b', r'\1', s, flags=_I)


def _clean_sentence(c, evidence):
    c = (c or '').strip()
    if not c or HOUSE.search(c) or not re.match(r'^[A-Z]', c) or len(c.split()) < 5 or len(c.split()) > 26:
        return ''
    if re.search(r'(?<![\w`])(?:[a-z]+[A-Z]\w+|[a-z]+_\w+|\w+\.(?:py|js|mjs|html|json|md)\b)', c) or \
            re.search(r'[:;—–|<>{}\[\]()]|\b(\w+) \1\b|\b[A-Z]{4,}\b', c):
        return ''
    if not c.endswith(('.', '!', '?')):
        c += '.'
    return '' if _bad(c, evidence) else c


def _readme_sentence(rec, evidence):
    """A README sentence that names this file, when it is one plain sentence."""
    if describe is None:
        return ''
    rd = (rec.get('ctx') or {}).get('readme') or []
    try:
        m = describe.readme_match(rd, rec.get('path', ''))
    except Exception:
        return ''
    return _clean_sentence(m, evidence)


def _header_sentence(rec, evidence):
    """The file's own leading comment, cleaned by describe.py, when it is one plain sentence."""
    if describe is None:
        return ''
    ev = (rec.get('ctx') or {}).get('evidence') or {}
    raw = ev.get('comment') or ''
    if not raw:
        return ''
    try:
        c = describe.clean_comment(raw, os.path.basename(rec.get('path', '')), rec.get('defines') or [], 30,
                                   rec.get('title', ''))
    except Exception:
        return ''
    c = (c or '').strip()
    if not c or HOUSE.search(c) or not re.match(r'^[A-Z]', c) or len(c.split()) < 5 or len(c.split()) > 26:
        return ''
    if re.search(r'(?<![\w`])(?:[a-z]+[A-Z]\w+|[a-z]+_\w+)', c) or re.search(r'[:;—–]|\b(\w+) \1\b|\b[A-Z]{4,}\b', c):
        return ''
    if not c.endswith(('.', '!', '?')):
        c += '.'
    return '' if _bad(c, evidence) else c


# ---------------------------------------------------------------- translate
def translate(rec, src):
    src = src or ''
    src_ns = src.lower().replace(' ', '')
    kind = KIND.get(rec.get('kind', ''), 'file')
    article = 'An' if kind[:1].lower() in 'aeiou' else 'A'
    defines = rec.get('defines') or []
    hits = _detect(src, defines)
    volts = _voltages(src)
    units = _units(src)
    evidence = _evidence(rec, src)
    rec_title = (rec.get('title') or '').strip()
    if describe is not None:
        try:
            rec_title = describe.polish_title(rec_title) or rec_title
        except Exception:
            pass
    if BANNED.search(rec_title):
        rec_title = ''

    eng = [v for v in hits.values() if v['cls'] in ('formula', 'standard', 'coord')]
    strong = [v for v in eng if v['strong']]
    weak = [v for v in eng if not v['strong']]
    algos = [v for v in hits.values() if v['cls'] == 'algo' and v['strong']]
    sources = [v for v in hits.values() if v['cls'] == 'source']
    assets = sorted([v for v in hits.values() if v['cls'] == 'asset'], key=lambda v: -v['count'])

    # -- function glosses (main functions in file order)
    mains = [d for d in _main_functions(rec, src) if d in src]
    glosses = [(d, _dedupe(_gloss_engineering(d, hits) or _gloss_generic(d))) for d in mains]

    # -- synopsis lead: what it does, as an engineer would say it
    acts = []
    for v in strong[:2] or algos[:1]:
        vp = _without_missing_term(v.get('verb') or '', v, src_ns)
        if vp and vp not in acts:
            acts.append(vp)
    covering = [_without_missing_term(v['plain'], v, src_ns) for v in weak[:2]]
    asset_words = [a['plain'] for a in assets[:3]]
    lead = ''
    head0 = _header_sentence(rec, evidence)
    if acts:
        lead = '%s %s that %s' % (article, kind, _join(acts[:2]))
        if asset_words:
            lead += ' for %s' % _join(asset_words)
        lead += '.'
    elif covering or asset_words:
        lead = '%s %s covering %s.' % (article, kind, _join((covering + asset_words)[:3]))
    elif head0:
        lead = head0
    else:
        vg = [g for _, g in glosses if g and not g.startswith(('works with', 'is the', 'defines'))
              and not g.endswith('its input')][:2]
        if vg:
            lead = '%s %s that %s.' % (article, kind, _join(vg))
        else:
            lead = '%s %s.' % (article, kind)
    extra = []
    if volts:
        vv = volts[:4]
        extra.append('It names the %s voltage level%s.' % (_join(vv), 's' if len(vv) > 1 else ''))
    elif units:
        extra.append('It works in %s.' % _join([u.split(' ')[1] for u in units]))
    if sources:
        ss = [s['plain'] for s in sources[:3]]
        extra.append('It names %s as data source%s.' % (_join(ss), 's' if len(ss) > 1 else ''))
    fw = _folder_words(rec)
    rn = _repo_name(rec)
    if lead == head0 and head0:
        extra.insert(0, 'It is %s %s%s.' % (article.lower(), kind, (' in the %s folder' % fw) if fw else ''))
        fw = ''
    if fw and fw.lower() not in lead.lower():
        extra.append('It sits in the %s folder%s.' % (fw, (' of ' + rn) if rn and fw.lower() not in rn.lower() else ''))
    elif rn:
        extra.append('It is part of %s.' % rn)
    syn = ''
    for p in [lead] + extra:
        p = _dedupe(p)
        if _bad(p, evidence):
            continue
        cand = (syn + ' ' + p).strip()
        if len(cand.split()) <= 40:
            syn = cand
    if len(syn.split()) < 12 and rn and rn.lower() not in syn.lower():
        p = 'It is part of %s.' % rn
        if not _bad(p, evidence) and len((syn + ' ' + p).split()) <= 40:
            syn = (syn + ' ' + p).strip()
    if not syn:
        syn = (rec.get('synopsis') or '').strip()

    # -- achieves: header sentence, main functions explained, method terms
    sents = []
    head = head0
    if head and head.lower().rstrip('.') not in syn.lower():
        sents.append(head)
    rdm = _readme_sentence(rec, evidence)
    if rdm and rdm.lower().rstrip('.') not in (syn + ' ' + head).lower():
        sents.append(rdm)
    else:
        ctx = rec.get('ctx') or {}
        ctxs = [('From the README: ', c) for c in list(ctx.get('readme') or [])[:3]] + \
            [('From the repository summary: ', ctx.get('repo_title') or '')]
        for lab, c in ctxs:
            c = _clean_sentence(c, evidence)
            if c and c.lower().rstrip('.') not in (syn + ' ' + head).lower():
                sents.append(lab + c)
                break
    named = [(d, g) for d, g in glosses if g]
    bare = [d for d, g in glosses if not g]
    for k in range(0, len(named), 3):
        sents.append('It ' + _join(['%s (`%s`)' % (g, d) for d, g in named[k:k + 3]]) + '.')
    for k in range(0, len(bare), 3):
        sents.append('It %sdefines %s.' % ('also ' if named or k else '', _join(['`%s`' % d for d in bare[k:k + 3]])))
    terms_said = ' '.join(sents + [syn]).lower()
    meth = []
    for v in strong + weak + algos:
        ph = _without_missing_term(v['plain'], v, src_ns)
        t = _term(v, src_ns)
        if ph.lower() in terms_said:
            continue
        if t and t.lower() not in ph.lower() and t.lower() not in terms_said and v['cls'] != 'algo':
            ph = '%s (%s)' % (ph, t) if not t[:1].isupper() or t.isupper() or ':' in t else ph
        meth.append(ph)
    if meth:
        sents.append('It uses %s.' % _join(meth[:3]))
    elif units and not volts:
        pass
    elif units:
        sents.append('It works with %s.' % _join(units))
    sents = [_dedupe(s) for s in sents if not _bad(s, evidence)]
    ach = ' '.join(sents)
    if not ach:
        ach = (rec.get('achieves') or '').strip()
        if _bad(ach, evidence) or HOUSE.search(ach):
            ach = ''

    # -- title: lead with the engineering topic when there is one
    title = rec_title
    top = strong[:1]
    if top:
        topic = _without_missing_term(top[0]['plain'], top[0], src_ns)
        topic = re.sub(r'\s*\([^)]*\)', '', topic)
        cand = '%s: %s' % (rec_title, topic) if rec_title else _cap(topic)
        if len(cand.split()) > 8:
            cand = _cap(topic)
        if len(cand.split()) <= 8 and not _bad(cand, evidence):
            title = cand
    elif volts and rec_title and len(rec_title.split()) <= 6:
        cand = '%s (%s)' % (rec_title, volts[-1])
        if not _bad(cand, evidence):
            title = cand
    if not title or _bad(title, evidence):
        title = (rec.get('title') or '').strip()
    if len(title.split()) >= 2 and title.lower() in syn.lower():
        title = rec_title if rec_title and rec_title.lower() not in syn.lower() else title
    out = {'title': title, 'synopsis': syn, 'achieves': ach}
    if _bad(' '.join(out.values()), evidence):  # last resort: the record's own words
        out = {'title': (rec.get('title') or '').strip(), 'synopsis': (rec.get('synopsis') or '').strip(),
               'achieves': (rec.get('achieves') or '').strip()}
    return out

Test Feeder 47

A test in the rules folder of Cosmic covering 33kV and cables, using IEC 60287 and haversine.

testcosmic / tools/explore/bigbang/rules/test_FEEDER-47.py · lines 1–41 of 41 · Entry point

What it does
It tests 33kV and cables. Defines _rec, test_iec60287_and_voltage, test_haversine_structure_without_word, test_no_invented_source_or_banned_words. Uses libraries importlib.util, os.
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: 33kV, cables.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for the FEEDER-47 engineering-domain player. Its code works with 33 kV.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/bigbang/rules · test
Uses
importlib.util, os
Used by
none found
Produces
test_iec60287_and_voltage, test_haversine_structure_without_word, test_no_invented_source_or_banned_words
Defines here
_rec, test_iec60287_and_voltage, test_haversine_structure_without_word, test_no_invented_source_or_banned_words
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_FEEDER-47.py:1-41 · blob 60797b7bdd43cce47c963fc50f7ea6053a01a9a8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Tests for the FEEDER-47 engineering-domain player (run: python3 test_FEEDER-47.py)."""
import importlib.util
import os

_spec = importlib.util.spec_from_file_location('feeder47', os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                                      'FEEDER-47.py'))
F = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(F)


def _rec(**kw):
    r = {'title': 'Cable Rating', 'kind': 'Python module', 'repo': 'demo', 'path': 'tools/cable_rating.py',
         'folder_hierarchy': ['demo', 'tools'], 'defines': [], 'ctx': {}}
    r.update(kw)
    return r


def test_iec60287_and_voltage():
    src = '# IEC 60287 continuous rating for a 33kV cable\ndef cable_rating(r):\n    return r * derate\n'
    out = F.translate(_rec(defines=['cable_rating']), src)
    text = ' '.join(out.values())
    assert 'IEC 60287' in text and '33kV' in text and '`cable_rating`' in text


def test_haversine_structure_without_word():
    src = 'function dist(a,b){const R=6371;return 2*R*Math.asin(Math.sqrt(Math.sin(1)**2));}'
    out = F.translate(_rec(kind='script', defines=['dist']), src)
    assert 'great-circle' in out['synopsis'] and 'haversine' not in ' '.join(out.values()).lower()


def test_no_invented_source_or_banned_words():
    out = F.translate(_rec(title='Plain'), 'def add(a, b):\n    return a + b\n')
    text = ' '.join(out.values())
    assert 'REPD' not in text and 'NESO' not in text and not F.BANNED.search(text)


if __name__ == '__main__':
    for k, v in list(globals().items()):
        if k.startswith('test_'):
            v()
    print('ok')