In this section
- Test Grid Finder test · faraday / apparatus/test_grid_finder.py lines 1–127
- Backup storage · faraday / bench/backup.py lines 1–73
- Commands Build storage · faraday / bench/commands_build.py lines 1–227
- Commands Check ingest · faraday / bench/commands_check.mjs lines 1–74
- Energy Cases transform · faraday / bench/energy_cases.py lines 1–64
- Fire ingest · faraday / bench/fire.js lines 1–63
- Fire Check ingest · faraday / bench/fire_check.mjs lines 1–24
Test Grid Finder
A test in the apparatus folder of Faraday that checks Grid Finder, using SHA-256. It is built from the grid finder tests class (`GridFinderTests`).
testfaraday / apparatus/test_grid_finder.py · lines 1–127 of 127 · Entry point
- What it does
- It tests transformers. Defines 10 functions or classes, including GridFinderTests, test_source_counts_and_hashes, test_actual_js_distance_source_parity, test_distance_degenerate_and_antipodal, test_all_site_paths_against_reverse_multi_target_distances. Uses libraries collections, hashlib, json, math, pathlib. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: transformers, 400kV.
- Inputs & outputs
- In: JSON file grid-finder-fixtures.json. Out: JSON file grid-finder-example-result.json; JSON file grid-finder-test-results.json. Voltage levels named: 400kV.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Behavioral fixtures, actual source parity and independent reverse-distance audit. Its code works with 400 kV.
- Why it matters
- Guards the behaviour of Grid Finder.
- Application
- faraday · apparatus · test
- Uses
- Grid Finder (import), collections, hashlib, json, math, pathlib, subprocess, time, unittest
- Used by
- none found
- Produces
- GridFinderTests
- Defines here
- GridFinderTests, test_source_counts_and_hashes, test_actual_js_distance_source_parity, test_distance_degenerate_and_antipodal, test_all_site_paths_against_reverse_multi_target_distances, test_unknown_capacity_and_user_entered_scenario, test_published_nameplate_is_not_spare_capacity, test_no_assumed_voltage, test_input_refusals, test_unknown_voltage_and_no_invented_same_site_ties
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 apparatus/test_grid_finder.py:1-127 · blob 770c4d27f7fa9be4f1e16b1cad57a128a00e4a05 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
"""Behavioral fixtures, actual source parity and independent reverse-distance audit."""
from collections import deque, defaultdict
import hashlib
import json
import math
from pathlib import Path
import subprocess
import time
import unittest
from grid_finder import GridFinder, distance_km, DATA_PATH, EARTH_RADIUS_KM, compare_published_path_ratings
HERE = Path(__file__).resolve().parent
FINDER = GridFinder()
AUDIT = {}
class GridFinderTests(unittest.TestCase):
def test_source_counts_and_hashes(self):
self.assertEqual(FINDER.data['counts']['sites'], 886)
self.assertEqual(FINDER.data['counts']['located_sites'], 489)
self.assertEqual(FINDER.data['counts']['unknown_voltage_nodes'], 726)
self.assertEqual(hashlib.sha256(DATA_PATH.read_bytes()).hexdigest(), 'cf977c3cff6f6929e3b5edb530be5012b966311bdc449c79318019bf52fa9592')
def test_actual_js_distance_source_parity(self):
fixture = json.loads((HERE/'grid-finder-fixtures.json').read_text())
errors = [abs(distance_km(*p)-v) for p,v in zip(fixture['pairs'], fixture['distance_km'])]
self.assertLess(max(errors), 1e-9)
AUDIT['js_source_parity'] = {'samples': len(errors), 'max_error_km': max(errors),
'source': fixture['source'], 'sha256': fixture['source_sha256']}
def test_distance_degenerate_and_antipodal(self):
self.assertEqual(distance_km(0, 0, 0, 0), 0)
self.assertAlmostEqual(distance_km(0, 0, 180, 0), math.pi*EARTH_RADIUS_KM, places=9)
self.assertAlmostEqual(distance_km(179.9, 20, -179.9, 20), distance_km(-179.9, 20, 179.9, 20), places=9)
def test_all_site_paths_against_reverse_multi_target_distances(self):
# Independently build legal adjacency from packaged rows, then search FROM ALL 400kV nodes.
nodes = {n['id']: n for n in FINDER.data['nodes']}
graph = defaultdict(set)
for e in FINDER.data['edges']:
a, b = nodes.get(e['from']), nodes.get(e['to'])
if not a or not b or a['voltage_kv'] is None or b['voltage_kv'] is None:
continue
if e['kind'] != 'transformer' and a['voltage_kv'] != b['voltage_kv']:
continue
graph[a['id']].add(b['id']); graph[b['id']].add(a['id'])
dist = {n['id']: 0 for n in nodes.values() if n['voltage_kv'] is not None and n['voltage_kv'] >= 400}
queue = deque(dist)
while queue:
n = queue.popleft()
for neighbor in graph[n]:
if neighbor not in dist:
dist[neighbor] = dist[n]+1
queue.append(neighbor)
checked = found = 0
for site in FINDER.sites.values():
for kv in site['voltages_kv']:
starts = [n['id'] for n in nodes.values() if n['site_code'] == site['code'] and n['voltage_kv'] == kv]
expected = min([dist[n] for n in starts if n in dist], default=None)
if expected is not None and expected > 12:
expected = None
result = FINDER.path_to_voltage(site['code'], kv, 400, 12)
self.assertEqual(result['hops'], expected, (site['code'], kv))
checked += 1; found += expected is not None
AUDIT['reverse_graph_audit'] = {'site_voltage_queries': checked, 'paths_within_12_edges': found}
def test_unknown_capacity_and_user_entered_scenario(self):
normal = FINDER.query(53.3, -.8, 100, 132, limit=3)
first = normal['candidates'][0]
self.assertEqual(first['site_code'], 'WBUR')
self.assertEqual(first['capacity']['status'], 'UNKNOWN')
self.assertEqual(first['topology']['hops'], 1)
entered = FINDER.query(53.3, -.8, 100, 132, headroom_mw_by_site={'WBUR': 80}, limit=3)
self.assertEqual(entered['candidates'][0]['capacity']['margin_mw'], -20)
self.assertFalse(entered['candidates'][0]['capacity']['within_entered_headroom'])
self.assertEqual([c['site_code'] for c in normal['candidates']], [c['site_code'] for c in entered['candidates']])
(HERE/'grid-finder-example-result.json').write_text(json.dumps(normal, indent=2), encoding='utf-8')
def test_published_nameplate_is_not_spare_capacity(self):
path = FINDER.path_to_voltage('WBUR', 132)['path']
self.assertEqual(path[0]['source_row'], 'transformers[1262]')
self.assertEqual(path[0]['published_ratings_mva']['rating_mva'], 274)
below = compare_published_path_ratings(path, 100, .95)
above = compare_published_path_ratings(path, 300, .95)
self.assertFalse(below['edges'][0]['exceeds_nameplate'])
self.assertTrue(above['edges'][0]['exceeds_nameplate'])
self.assertIsNone(below['available_headroom_mw'])
self.assertIsNone(above['available_headroom_mw'])
self.assertAlmostEqual(below['edges'][0]['entered_apparent_mva'], 100/.95)
self.assertAlmostEqual(above['edges'][0]['entered_apparent_mva'], 300/.95)
AUDIT['published_rating_experiment'] = {'site_code':'WBUR', 'below': below, 'above': above}
def test_no_assumed_voltage(self):
result = FINDER.query(53.3, -.8, 100, limit=4)
self.assertTrue(all(c['topology']['status'] == 'CONNECTION_VOLTAGE_NOT_ENTERED' and c['pareto_tier'] is None for c in result['candidates']))
def test_input_refusals(self):
for change in [{'latitude': 91}, {'longitude': float('nan')}, {'mw': -1},
{'headroom_mw_by_site': []}, {'headroom_mw_by_site': {'MISSING': 10}}, {'max_hops': 1.5}]:
args = dict(latitude=53.3, longitude=-.8, mw=100, voltage_kv=132)
args.update(change)
with self.assertRaises(ValueError): FINDER.query(**args)
def test_unknown_voltage_and_no_invented_same_site_ties(self):
data = {'schema': 'globalgrid.grid-finder-data.v1', 'sites': [{'code': 'A'}, {'code': 'B'}],
'nodes': [{'id': 'a1', 'site_code': 'A', 'voltage_kv': 132}, {'id': 'a2', 'site_code': 'A', 'voltage_kv': 400},
{'id': 'b', 'site_code': 'B', 'voltage_kv': 400}, {'id': 'u', 'site_code': 'B', 'voltage_kv': None}],
'edges': [{'id': 'bad', 'from': 'a1', 'to': 'b', 'kind': 'circuit', 'source_row': 'synthetic'},
{'id': 'unknown', 'from': 'a1', 'to': 'u', 'kind': 'transformer', 'source_row': 'synthetic'}]}
f = GridFinder(data=data)
result = f.path_to_voltage('A', 132)
self.assertIsNone(result['hops'])
self.assertEqual(result['refused_edge_count'], 2)
data['edges'].append({'id': 'valid', 'from': 'a1', 'to': 'b', 'kind': 'transformer', 'source_row': 'synthetic'})
self.assertEqual(GridFinder(data=data).path_to_voltage('A', 132)['hops'], 1)
if __name__ == '__main__':
began = time.perf_counter()
suite = unittest.defaultTestLoader.loadTestsFromTestCase(GridFinderTests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
AUDIT.update(status='passed' if result.wasSuccessful() else 'failed', tests=result.testsRun,
failures=len(result.failures), errors=len(result.errors), elapsed_seconds=time.perf_counter()-began,
data_sha256=hashlib.sha256(DATA_PATH.read_bytes()).hexdigest(), counts=FINDER.data['counts'],
implementation_sha256=hashlib.sha256((HERE/'grid_finder.py').read_bytes()).hexdigest())
(HERE/'grid-finder-test-results.json').write_text(json.dumps(AUDIT, indent=2), encoding='utf-8')
raise SystemExit(0 if result.wasSuccessful() else 1)Backup
A Python command-line tool in the bench folder of Faraday that reads summary and top. It is built from the merge step (`merge`).
storagefaraday / bench/backup.py · lines 1–73 of 73 · Entry point · pattern merge (shared by 12 files)
- What it does
- It loads summary and top. Defines merge, main. Uses libraries glob, heapq, json, os, sys. Side effects: reads or writes files; starts processes.
- 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.
- Inputs & outputs
- In: JSON file top.json; JSON file SUMMARY.json; command-line arguments. Out: JSON file SUMMARY.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Run by hand, or every N minutes by `nightshift.py`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- faraday · bench · Python CLI
- Uses
- glob, heapq, json, os, sys, time, run100
- Used by
- none found
- Produces
- merge, main
- Defines here
- merge, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/backup.py:1-73 · blob fa941f7be12de235587ec99b8e4db24cd74b79cc · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""bench/backup.py - THE METHOD AND THE DATA, KEPT ON GITHUB. Run by hand, or every N minutes by nightshift.py.
What goes to the repository (public): the scripts (they are the method), each run's STATUS.md, a merged summary
(results/<run>/SUMMARY.json: counts, the second opinion's counts, by shape), and the MOST TELLING cases merged across shards
(results/<run>/top.json, at most 1,000 a kind). What never goes: the row by row shards (they stay on E:, and any shard can be
rebuilt from its seeds alone, which is the point of a seeded generator). Everything staged is passed through the runner's guard
against private strings first; if the guard finds anything, NOTHING is committed and the finding is printed.
python bench/backup.py commit and push
python bench/backup.py --dry show what would be committed
"""
import glob, heapq, json, os, sys, time
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
import run100 as R
RUNS = {'million': r'E:\faraday-bench\million', 'topo': r'E:\faraday-bench\topo'}
METHOD = ['bench/million.py', 'bench/million_check.mjs', 'bench/topo.py', 'bench/topo_check.mjs', 'bench/fire_topo.js', 'bench/fire_site.js', 'bench/backup.py', 'bench/nightshift.py',
'bench/topo_top.py', 'experiments']
def merge(run, src):
out = os.path.join(R.REPO, 'bench', 'results', run); os.makedirs(out, exist_ok=True)
st = os.path.join(src, 'STATUS.md')
if os.path.exists(st): open(os.path.join(out, 'STATUS.md'), 'w', encoding='utf8').write(open(st, encoding='utf8').read())
tot = {}; tops = {}; n = 0
for f in glob.glob(os.path.join(src, 'shards', '*.json')):
try: d = json.load(open(f))
except Exception: continue # a shard being written this second
n += 1
for k, v in d.items():
if isinstance(v, (int, float)) and k not in ('shard', 'seconds'): tot[k] = tot.get(k, 0) + v
for k, v in (d.get('check') or {}).items():
if isinstance(v, (int, float)): tot['check_' + k] = tot.get('check_' + k, 0) + v
for k, v in (d.get('by_shape') or {}).items():
s = tot.setdefault('by_shape', {}).setdefault(k, [0, 0]); s[0] += v[0]; s[1] += v[1]
for kind, items in (d.get('tops') or {}).items():
h = tops.setdefault(kind, [])
for it in items:
it = tuple(it)
if len(h) < 1000: heapq.heappush(h, it)
elif it > h[0]: heapq.heapreplace(h, it)
tot['shards'] = n; tot['written_utc'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
json.dump(tot, open(os.path.join(out, 'SUMMARY.json'), 'w'), indent=1, sort_keys=True)
if tops: json.dump({'columns': ['score', 'seed', 'case', 'p_kw', 'vmax_pu', 'vmin_pu', 'worst_tx_pct', 'flags'], 'kinds': {k: sorted(v, reverse=True) for k, v in tops.items()}},
open(os.path.join(out, 'top.json'), 'w'), separators=(',', ':'))
return n
def main():
dry = '--dry' in sys.argv
for run, src in RUNS.items():
if os.path.isdir(src): print(run, merge(run, src), 'shards merged')
paths = [p for p in METHOD if os.path.exists(os.path.join(R.REPO, p))] + ['bench/results/million', 'bench/results/topo']
paths = [p for p in paths if os.path.exists(os.path.join(R.REPO, p))]
texts = {}
for p in paths:
full = os.path.join(R.REPO, p)
files = [full] if os.path.isfile(full) else [os.path.join(dp, f) for dp, _, fs in os.walk(full) for f in fs]
for f in files:
if os.path.getsize(f) < 5_000_000: texts[os.path.relpath(f, R.REPO)] = open(f, encoding='utf8', errors='replace').read()
found = R.guard(texts)
if found: print('THE GUARD REFUSES, nothing committed:\n ' + '\n '.join(found)); sys.exit(2)
if dry: print('would commit', len(texts), 'files'); return
R.git('add', '--', *paths)
if R.git('diff', '--cached', '--quiet', check=False).returncode == 0: print('nothing new to commit'); return
s = json.load(open(os.path.join(R.REPO, 'bench', 'results', 'topo', 'SUMMARY.json'))) if os.path.exists(os.path.join(R.REPO, 'bench', 'results', 'topo', 'SUMMARY.json')) else {}
msg = 'night shift backup: the method and the summaries; networks solved twice so far: %s, differing: %s' % (format(int(s.get('cases', 0)), ','), format(int(s.get('check_differed', 0)), ','))
who = 'Co-Authored-By: Claude Fable 5.1 <noreply' + chr(64) + 'anthropic.com>' # built here so the guard above stays strict about addresses in files
R.git('commit', '-m', msg + '\n\n' + who)
r = R.git('push', check=False)
print(msg); print('pushed' if r.returncode == 0 else 'COMMITTED BUT NOT PUSHED: ' + (r.stderr or '')[-300:])
if __name__ == '__main__':
main()Commands Build
A Python command-line tool in the bench folder of Faraday that reads top, solar and transformers, using SHA-256.
storagefaraday / bench/commands_build.py · lines 1–227 of 227 · Entry point · pattern sha256_of (shared by 2 files)
- What it does
- It loads top, solar and transformers. Defines 10 functions or classes, including when, kw, sentence, command, build_network_commands. Uses libraries hashlib, io, json, os, sys. Side effects: reads or writes files.
- 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: solar, transformers.
- Inputs & outputs
- In: JSON file top.json; JSON file commands.json; JSON file current.json; command-line arguments. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It builds network commands (`build_network_commands`) and is built from the when step (`when`) and the sentence step (`sentence`). The page's "choose an example sentence" list is not written into the page: the page fetches it.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- faraday · bench · Python CLI
- Uses
- Topo (import), hashlib, io, json, os, sys, time
- Used by
- none found
- Produces
- when, kw, sentence, command, build_network_commands, curate, site_pulse_commands, sha256_of, check, main
- Defines here
- when, kw, sentence, command, build_network_commands, curate, site_pulse_commands, sha256_of, check, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/commands_build.py:1-227 · blob 18e60a32c11c952e31991e4a19b502e8ef443169 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""bench/commands_build.py - THE COMMAND LIST, BUILT LIKE A GRIDATLAS RELEASE.
The page's "choose an example sentence" list is not written into the page: the page fetches it. This builds that list from
the networks the bench has already solved, and publishes it the way the Atlas publishes a composition:
a POINTER bench/results/commands/current.json - which generation is live, which file it is, its sha256 and its length
a FILE bench/results/commands/commands-<generation>.json - the list itself, named after its generation, never edited
so a reader can fetch the pointer with no cache, fetch the file it names, re-hash the bytes it received and refuse anything
that does not match. The previous generation is kept in the pointer, so a roll back is one line.
WHAT IS IN THE LIST. bench/results/topo/top.json holds the most telling cases found so far, by kind, merged across every
shard of the billion-case run. The best 200 of each of the five kinds make up to 1,000 commands. Nothing is padded: a kind
with fewer cases contributes fewer. Nothing is run here - every number in a sentence is read from the row that was solved
twice (once in Python, once in JavaScript) and the sentence only describes it. No claim words: a sentence says what was
computed, never that it is good, safe or best. bench/commands_check.mjs then fires every command and checks the numbers.
python bench/commands_build.py build a new generation
python bench/commands_build.py --check re-read the pointer, re-hash the file it names, and fail on any mismatch
"""
import hashlib, io, json, os, sys, time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import topo
TOP = os.path.join(HERE, 'results', 'topo', 'top.json')
OLD_LIST = os.path.join(HERE, 'results', 'commands.json')
OUT = os.path.join(HERE, 'results', 'commands')
PER_KIND = 200
LIST_SCHEMA = 'faraday.commands.v2'
POINTER_SCHEMA = 'faraday.commands.current.v1'
SOLAR = {0.0: 'no solar', 0.5: 'half solar', 1.0: 'full solar'}
LOAD = {1.0: 'full load', 0.6: 'load at 60 per cent', 0.3: 'load at 30 per cent'}
# the four shapes as a reader would say them: "a sub-boards of 8 substations" is not English
SHAPE = {'star': 'A star', 'chain': 'A chain', 'tree': 'A tree', 'sub-boards': 'A sub-board network'}
def when(case):
"""The operating case in words, in the order topo.CASES holds it."""
ps, g, ls = topo.CASES[case]
return '%s, generator %s, %s' % (SOLAR[ps], 'running' if g else 'off', LOAD[ls])
def kw(x):
return '%d kW' % round(x)
def sentence(kind, net, case, p_kw, vmax, vmin, tx):
"""A description of one solved case, from the row and the network. Nothing here is computed again."""
head = '%s of %d substations: ' % (SHAPE.get(net['shape'], 'A ' + net['shape']), len(net['subs']))
tail = ', at ' + when(case)
if kind == 'export on the line':
export = max(0.0, -p_kw)
limit = net['export_limit_kw']
gap = export - limit
if gap > 0:
body = 'export %s, %s over its %s limit' % (kw(export), kw(gap), kw(limit))
elif round(-gap) == 0:
body = 'export %s, on its %s limit' % (kw(export), kw(limit))
else:
body = 'export %s, within %s of its %s limit' % (kw(export), kw(-gap), kw(limit))
elif kind == 'volts high on the line':
body = 'highest voltage %.4f against the %s line' % (vmax, topo.C['volts_high_pu'])
elif kind == 'volts low on the line':
body = 'lowest voltage %.4f against the %s line' % (vmin, topo.C['volts_low_pu'])
elif kind == 'transformer on the line':
body = 'busiest transformer at %.1f per cent of its rating' % tx
elif kind == 'most solar inside every limit':
ps, _g, ls = topo.CASES[case]
pv = sum(s['pv_kw'] for s in net['subs']) * ps
load = sum(s['load_kw'] for s in net['subs']) * ls
body = '%s of solar against %s of load, every figure inside its limit' % (kw(pv), kw(load))
else:
body = 'connection point %s, volts %.4f to %.4f, busiest transformer %.1f per cent' % (kw(p_kw), vmin, vmax, tx)
return head + body + tail
def command(seed, case):
ps, g, ls = topo.CASES[case]
return 'fire network {"seed":%d,"solar":%s,"generator":%d,"load":%s}' % (seed, repr(ps), g, repr(ls))
def build_network_commands():
top = json.load(io.open(TOP, encoding='utf-8'))
cols = top['columns']
want = ['score', 'seed', 'case', 'p_kw', 'vmax_pu', 'vmin_pu', 'worst_tx_pct', 'flags']
if cols != want:
raise SystemExit('top.json does not have the columns this reads: %r' % (cols,))
out = []
for kind in sorted(top['kinds']):
rows = top['kinds'][kind]
rows = sorted(rows, reverse=True)[:PER_KIND] # already sorted; sorted again so the choice never depends on that
for _score, seed, case, p_kw, vmax, vmin, tx, flags in rows:
net = topo.network(seed)
out.append(dict(family='NETWORKS', kind=kind, sentence=sentence(kind, net, case, p_kw, vmax, vmin, tx),
command=command(seed, case), seed=seed, case=case,
row=dict(p_kw=p_kw, vmax_pu=vmax, vmin_pu=vmin, worst_tx_pct=tx, flags=flags)))
return out
PINNED = 100
SIZE = lambda n: 'small' if n <= 4 else 'middling' if n <= 8 else 'large'
SHORT = {'export on the line': 'right on its export limit', 'volts high on the line': 'voltage at the top of its band',
'volts low on the line': 'voltage at the bottom of its band', 'transformer on the line': 'a transformer at its rating',
'most solar inside every limit': 'the most solar that still fits'}
def curate(cmds):
"""THE PINNED HUNDRED. The thousand read alike (200 of a kind, the same sentence with other numbers), so a reader is shown
a hundred that DIFFER and searches the rest. Two commands are the same picture to a reader when they share the shape, the
size band (2 to 4, 5 to 8, 9 to 12 substations), the kind, the solar level and whether the generator runs: one of each at
most, the best scored first, taken in turn across kinds and shapes so no kind or shape crowds the top. Pinned commands
carry pin (1 is first) and a short name; the list is reordered pinned first; nothing is removed and no number changes."""
groups = {}
for c in cmds:
if c['family'] != 'NETWORKS':
continue
net = topo.network(c['seed']); ps, g, _ls = topo.CASES[c['case']]
sig = (c['kind'], net['shape'], SIZE(len(net['subs'])), ps, g)
if sig not in groups: # cmds arrive best scored first within a kind
groups[sig] = (c, net)
lanes = {}
for sig in sorted(groups):
lanes.setdefault((sig[0], sig[1]), []).append(groups[sig])
picked = []
while len(picked) < PINNED and any(lanes.values()):
for lane in sorted(lanes):
if lanes[lane] and len(picked) < PINNED:
picked.append(lanes[lane].pop(0))
for i, (c, net) in enumerate(picked, 1):
ps, g, _ls = topo.CASES[c['case']]
extras = [SOLAR[ps]] + (['generator running'] if g else [])
c['pin'] = i
c['name'] = '%s of %d, %s (%s)' % (SHAPE.get(net['shape'], 'A ' + net['shape']), len(net['subs']), SHORT.get(c['kind'], c['kind']), ', '.join(extras))
pinned = [c for c, _ in picked]
ids = set(id(c) for c in pinned)
return pinned + [c for c in cmds if id(c) not in ids]
def site_pulse_commands():
"""The sentences that already draw a reader in, carried forward unchanged from the list the page fetches today."""
if not os.path.exists(OLD_LIST):
return []
old = json.load(io.open(OLD_LIST, encoding='utf-8'))
return [dict(family='SITE PULSE', kind='site pulse', sentence=e['sentence'], command=e['command'], seed=None, case=None)
for e in old.get('commands', []) if e.get('family') == 'SITE PULSE']
def sha256_of(path):
h = hashlib.sha256()
with io.open(path, 'rb') as fh:
for chunk in iter(lambda: fh.read(1 << 20), b''):
h.update(chunk)
return h.hexdigest()
def check():
"""Read the pointer as a stranger would, re-hash the file it names, and say exactly what is wrong if anything is."""
p = os.path.join(OUT, 'current.json')
if not os.path.exists(p):
raise SystemExit('CHECK FAILED: there is no pointer at ' + os.path.relpath(p, HERE))
cur = json.load(io.open(p, encoding='utf-8'))
bad = []
if cur.get('schema') != POINTER_SCHEMA:
bad.append('the pointer says schema %r, not %r' % (cur.get('schema'), POINTER_SCHEMA))
f = os.path.join(OUT, cur.get('file', ''))
if not cur.get('file') or not os.path.exists(f):
bad.append('the pointer names %r and there is no such file beside it' % (cur.get('file'),))
else:
got = sha256_of(f)
size = os.path.getsize(f)
if got != cur.get('sha256'):
bad.append('the file hashes to %s and the pointer says %s' % (got[:16], str(cur.get('sha256'))[:16]))
if size != cur.get('bytes'):
bad.append('the file is %d bytes and the pointer says %s' % (size, cur.get('bytes')))
lst = json.load(io.open(f, encoding='utf-8'))
if lst.get('schema') != LIST_SCHEMA:
bad.append('the list says schema %r, not %r' % (lst.get('schema'), LIST_SCHEMA))
if lst.get('generation') != cur.get('generation'):
bad.append('the list is generation %r and the pointer says %r' % (lst.get('generation'), cur.get('generation')))
if len(lst.get('commands', [])) != cur.get('count') or lst.get('count') != cur.get('count'):
bad.append('the pointer counts %s and the list holds %d' % (cur.get('count'), len(lst.get('commands', []))))
if bad:
raise SystemExit('CHECK FAILED:\n ' + '\n '.join(bad))
print('check ok: generation %s, %d commands, sha256 %s, %d bytes'
% (cur['generation'], cur['count'], cur['sha256'][:12], cur['bytes']))
def main():
if '--check' in sys.argv:
return check()
os.makedirs(OUT, exist_ok=True)
cmds = curate(build_network_commands() + site_pulse_commands())
gen =time.strftime('%Y%m%d%H%M', time.gmtime())
name = 'commands-%s.json' % gen
doc = dict(schema=LIST_SCHEMA, generation=gen, generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
count=len(cmds), commands=cmds)
path = os.path.join(OUT, name)
with io.open(path, 'w', encoding='utf-8', newline='\n') as fh:
json.dump(doc, fh, separators=(',', ':'))
prev = None
p = os.path.join(OUT, 'current.json')
if os.path.exists(p):
try:
prev = json.load(io.open(p, encoding='utf-8')).get('generation')
except Exception:
prev = None
pointer = dict(schema=POINTER_SCHEMA, generation=gen, previous_generation=prev, file=name,
sha256=sha256_of(path), bytes=os.path.getsize(path), count=len(cmds))
with io.open(p, 'w', encoding='utf-8', newline='\n') as fh:
json.dump(pointer, fh, indent=1)
fh.write('\n')
by = {}
for c in cmds:
by[c['kind']] = by.get(c['kind'], 0) + 1
print('generation %s: %d commands (%s)' % (gen, len(cmds), '; '.join('%s %d' % kv for kv in sorted(by.items()))))
print(' ' + name + ' sha256 ' + pointer['sha256'][:12] + ' ' + format(pointer['bytes'], ',') + ' bytes')
if prev:
print(' previous generation ' + prev)
check()
if __name__ == '__main__':
main()Commands Check
A JavaScript module in the bench folder of Faraday that reads transformers, using SHA-256. It is built from the stop step (`stop`) and the near step (`near`).
ingestfaraday / bench/commands_check.mjs · lines 1–74 of 74 · Not reached from any entry point (candidate for review)
- What it does
- It loads transformers. Defines stop, near. Uses libraries node:module, node:fs, node:crypto, node:path, node:url. Side effects: reads or writes files; starts processes.
- 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: transformers.
- Inputs & outputs
- In: JSON file current.json; command-line arguments.
- What it achieves
- Reads the pointer the way a browser will, re-hashes the file it names, and then FIRES EVERY COMMAND in the list through FIRE - the same code a visitor's browser runs. Its code works with 0.1 kW.
- Why it matters
- No other file in the estate was found to import it.
- Application
- faraday · bench · JavaScript module
- Uses
- Fire (require), Fire Site (require), Fire Topo (require), node:module, node:fs, node:crypto, node:path, node:url
- Used by
- none found
- Produces
- stop, near
- Defines here
- stop, near
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/commands_check.mjs:1-74 · blob 512be3e5c714b5aa3e057413f2c02281c863c956 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// bench/commands_check.mjs - THE SECOND OPINION ON THE LIST ITSELF. Reads the pointer the way a browser will, re-hashes the
// file it names, and then FIRES EVERY COMMAND in the list through FIRE - the same code a visitor's browser runs. A sentence
// that describes a number nobody can reproduce is a sentence that should not be published, so every network command's answer
// is compared with the row it was written from: power to 0.1 kW, volts to 1e-4 per unit, transformer loading to 0.1 per cent.
// The last line printed is one JSON object; exit 1 if anything at all is wrong.
//
// node bench/commands_check.mjs check bench/results/commands/
// node bench/commands_check.mjs <dir> check another folder of the same shape
import { createRequire } from 'node:module';
import { readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const HERE = dirname(fileURLToPath(import.meta.url));
const DIR = resolve(process.argv[2] || join(HERE, 'results', 'commands'));
const LIST_SCHEMA = 'faraday.commands.v2', POINTER_SCHEMA = 'faraday.commands.current.v1';
const FIRE = require('./fire.js');
require('./fire_site.js');
require('./fire_topo.js');
const faults = [];
const stop = (why) => { console.log(JSON.stringify({ ok: false, reason: why })); process.exit(1); };
const pointerPath = join(DIR, 'current.json');
if (!existsSync(pointerPath)) stop('there is no current.json in ' + DIR);
const pointer = JSON.parse(readFileSync(pointerPath, 'utf8'));
if (pointer.schema !== POINTER_SCHEMA) stop('the pointer says schema ' + JSON.stringify(pointer.schema) + ', not ' + POINTER_SCHEMA);
if (typeof pointer.file !== 'string' || !pointer.file) stop('the pointer names no file');
const listPath = join(DIR, pointer.file);
if (!existsSync(listPath)) stop('the pointer names ' + pointer.file + ' and there is no such file beside it');
const bytes = readFileSync(listPath);
const sha = createHash('sha256').update(bytes).digest('hex');
if (sha !== pointer.sha256) stop('the file hashes to ' + sha + ' and the pointer says ' + pointer.sha256);
if (bytes.length !== pointer.bytes) stop('the file is ' + bytes.length + ' bytes and the pointer says ' + pointer.bytes);
const list = JSON.parse(bytes.toString('utf8'));
if (list.schema !== LIST_SCHEMA) stop('the list says schema ' + JSON.stringify(list.schema) + ', not ' + LIST_SCHEMA);
if (list.generation !== pointer.generation) stop('the list is generation ' + list.generation + ' and the pointer says ' + pointer.generation);
if (!Array.isArray(list.commands)) stop('the list carries no commands array');
if (list.commands.length !== pointer.count || list.count !== pointer.count) stop('the pointer counts ' + pointer.count + ' and the list holds ' + list.commands.length);
// power to 0.1 kW, volts to 1e-4 per unit, transformer loading to 0.1 per cent: the row was rounded to exactly these places
const near = (got, want, tol) => Math.abs(got - want) <= tol + 1e-12;
let fired = 0, compared = 0;
const byFamily = {};
for (const c of list.commands) {
for (const k of ['family', 'kind', 'sentence', 'command']) if (typeof c[k] !== 'string' || !c[k]) faults.push({ command: c.command, why: k + ' is missing or not text' });
if (/\b(optimal|optimum|safe|safest|best|ideal|recommended|guaranteed)\b/i.test(c.sentence)) faults.push({ command: c.command, why: 'the sentence makes a claim: ' + c.sentence });
let r;
try { r = FIRE.fire(c.command); } catch (e) { faults.push({ command: c.command, why: 'threw: ' + e.message }); continue; }
if (!r || !r.ran) { faults.push({ command: c.command, why: 'did not run: no such command' }); continue; }
fired++;
byFamily[c.family] = (byFamily[c.family] || 0) + 1;
if (!c.row) continue; // a site pulse sentence has no solved row to be checked against
const n = r.numbers, row = c.row;
const checks = [['connection point kW', n.connection_point_kw, row.p_kw, 0.1],
['highest volts', n.highest_volts_pu, row.vmax_pu, 1e-4],
['lowest volts', n.lowest_volts_pu, row.vmin_pu, 1e-4],
['busiest transformer per cent', n.worst_transformer_pct, row.worst_tx_pct, 0.1]];
for (const [what, got, want, tol] of checks) {
if (typeof got !== 'number' || !near(got, want, tol)) faults.push({ command: c.command, why: what + ': fired ' + got + ', the row says ' + want });
}
compared++;
}
const out = { ok: faults.length === 0, generation: list.generation, file: pointer.file, sha256: sha.slice(0, 12), bytes: bytes.length,
commands: list.commands.length, fired, compared_against_a_solved_row: compared, by_family: byFamily,
faults: faults.length, first_faults: faults.slice(0, 5) };
console.log(JSON.stringify(out, null, 1));
process.exit(faults.length ? 1 : 0);Energy Cases
A Python module in the bench folder of Faraday that works with solar.
transformfaraday / bench/energy_cases.py · lines 1–64 of 64 · Entry point · pattern t_known (shared by 3 files)
- What it does
- It calculates solar. Defines year, t_energy, t_known, registry. Uses libraries json, math, random.
- 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: solar.
- Downstream impact
- Used directly by 1 file: Tests (faraday). Reached from 1 other entry point, including One (faraday).
- What it achieves
- It is built from the year step (`year`), the t energy helper (`t_energy`) and the t known helper (`t_known`). SITE ENERGY: a very large private network (the scale of a major airport) hour by hour for a year. Its code works with 62 MW, 100 MW and 271 GWh.
- Why it matters
- Checked by Tests.
- Application
- faraday · bench · Python module
- Uses
- json, math, random
- Used by
- imported by Tests (import)
- Produces
- year, t_energy, t_known, registry
- Defines here
- year, t_energy, t_known, registry
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/energy_cases.py:1-64 · blob a77da997fb0677ca9a1316744270d0633b492ab7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""bench/energy_cases.py - SITE ENERGY: a very large private network (the scale of a major airport) hour by hour for a year.
The question an owner asks before any electrical study: if we put this much solar and this much battery behind our meter, how much of
our own electricity do we make, what is the most we still pull from the grid, and how much solar is thrown away?
GENERIC: the round figures of a published article on a major airport, which cites the operator's public sustainability report:
about 271 GWh a year, peak about 100 MW; an option of 150 MWp of solar (about 135 GWh a year) and 600 MWh of battery.
Every hour: solar first, then the battery, then the grid. Load and solar shapes are simple stated curves (CANDIDATE), seeded, not data.
THE CHECK THAT CAN FAIL: energy in = energy out, to a part in a billion, every case.
"""
import json
import math
import random
def year(annual_gwh=271.0, peak_mw=100.0, pv_mwp=150.0, pv_gwh_per_150=135.0, batt_mwh=600.0, batt_mw=100.0, eff=0.90, seed=1):
g = random.Random(seed); load = []; sun = []
for h in range(8760):
d, hr = divmod(h, 24)
shape = 0.55 + 0.45 * max(0.0, math.sin(math.pi * (hr - 4) / 18)) if 4 <= hr <= 22 else 0.55 # busy by day, never off
load.append(shape * (1 + 0.08 * math.cos(2 * math.pi * (d - 15) / 365))) # a little more in winter
elev = max(0.0, math.sin(math.pi * (hr - 6) / 12)) if 6 <= hr <= 18 else 0.0
season = 0.55 + 0.45 * math.cos(2 * math.pi * (d - 172) / 365) # long days in June
sun.append(elev * season * g.uniform(0.25, 1.0)) # cloud, seeded
k = annual_gwh * 1000 / sum(load); load = [min(x * k, peak_mw) for x in load]
k = annual_gwh * 1000 / sum(load); load = [x * k for x in load]
ks = (pv_gwh_per_150 * 1000 * pv_mwp / 150.0) / max(sum(sun), 1e-9); sun = [x * ks for x in sun]
soc = 0.0; imp = 0.0; spill = 0.0; charged = 0.0; discharged = 0.0; peak_import = 0.0; own = 0.0; rt = math.sqrt(eff)
for L, S in zip(load, sun):
direct = min(L, S); own += direct; need = L - direct; spare = S - direct
c = min(spare, batt_mw, (batt_mwh - soc) / rt); soc += c * rt; charged += c; spill += spare - c
dch = min(need, batt_mw, soc * rt); soc -= dch / rt; discharged += dch; own += dch
g_in = need - dch; imp += g_in; peak_import = max(peak_import, g_in)
total_load = sum(load); total_sun = sum(sun)
# energy in = energy out: solar + grid = load + thrown away + (what went into the battery - what came out: its losses and what is left in it)
balance = abs(total_sun + imp - total_load - spill - (charged - discharged)) / total_load
return dict(load_gwh=total_load / 1000, solar_gwh=total_sun / 1000, import_gwh=imp / 1000, spilled_gwh=spill / 1000, own_share=own / total_load,
peak_import_mw=peak_import, battery_full_cycles=discharged / batt_mwh if batt_mwh else 0.0, average_mw=total_load / 8760, balance=balance, soc_end=soc)
def t_energy(pv_mwp, batt_mwh):
r = year(pv_mwp=pv_mwp, batt_mwh=batt_mwh, batt_mw=max(1.0, batt_mwh / 6.0) if batt_mwh else 0.0)
inputs = dict(annual_gwh=271, peak_mw=100, pv_mwp=pv_mwp, battery_mwh=batt_mwh)
return dict(question='A site using 271 GWh a year, peak 100 MW, with %g MWp of solar and %g MWh of battery: how much of its own electricity does it make?' % (pv_mwp, batt_mwh),
sentence='Site energy: %g MWp solar, %g MWh battery' % (pv_mwp, batt_mwh), command='fire site-energy ' + json.dumps(inputs, sort_keys=True),
did='8,760 hours: solar first, then the battery, then the grid; then energy in against energy out',
numbers=dict(own_share_pct=round(r['own_share'] * 100, 1), solar_gwh=round(r['solar_gwh'], 1), grid_import_gwh=round(r['import_gwh'], 1), solar_thrown_away_gwh=round(r['spilled_gwh'], 1),
peak_grid_import_mw=round(r['peak_import_mw'], 1), battery_full_cycles_a_year=round(r['battery_full_cycles']), energy_balance_error=float('%.1e' % r['balance'])),
observed='makes %.0f%% of its own electricity; still pulls up to %.0f MW from the grid; throws away %.1f GWh of solar' % (r['own_share'] * 100, r['peak_import_mw'], r['spilled_gwh']),
assumed='load and solar shapes are simple stated curves with seeded cloud, not measured data; round trip efficiency 90%; battery power = a sixth of its energy',
result='CONFIRMED' if r['balance'] < 1e-9 else 'REFUTED')
def t_known():
"""Two sums from the published article, checked: 600 MWh lasts 9.7 hours at 62 MW and 6 hours at 100 MW; and what 62 MW means."""
a, b = 600 / 62, 600 / 100; avg_all_hours = 271000 / 8760; avg_12h_day = 271000 / (365 * 12)
ok = abs(a - 9.7) < 0.05 and abs(b - 6.0) < 1e-9 and abs(avg_12h_day - 61.9) < 0.1
return dict(question='Do the published sums hold: 600 MWh = 9.7 hours at 62 MW and 6 hours at 100 MW; and is 62 MW the average demand?', sentence='Site energy: the known answers',
command='fire site-energy-known {}', did='divided', numbers=dict(hours_at_62_mw=round(a, 2), hours_at_100_mw=round(b, 2), average_over_all_hours_mw=round(avg_all_hours, 1), average_over_a_12_hour_day_mw=round(avg_12h_day, 1)),
observed='both durations hold. 62 MW is the average if the 271 GWh falls in a 12 hour day; spread over all 8,760 hours the average is %.1f MW. A model must say which it uses.' % avg_all_hours,
assumed='none', result='CONFIRMED' if ok else 'REFUTED')
def registry():
R = [('SITE ENERGY', 'the known answers', (t_known, ()))]
for pv in (0, 50, 100, 150, 200, 300):
for batt in (0, 150, 300, 600, 1200): R.append(('SITE ENERGY', '%g MWp, %g MWh' % (pv, batt), (t_energy, (pv, batt))))
return RFire
A JavaScript module in the bench folder of Faraday that calculates three-phase power (units: mm², kV, kW), covering cables, solar and transformers.
ingestfaraday / bench/fire.js · lines 1–63 of 63 · Entry point · pattern register (shared by 59 files)
- What it does
- Defines 6 functions or classes, including rate, r, need, parse, fire.
- 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, solar, transformers.
- Downstream impact
- Used directly by 6 files: Commands Check (faraday); Fire Site (faraday); Fire Topo (faraday); Million Check (faraday); and 2 more.
- What it achieves
- It is built from the rate step (`rate`), the need step (`need`) and the parse step (`parse`). The pop commands that RUN IN THE VISITOR'S BROWSER. Its code works with 604 GWh.
- Why it matters
- Loaded by the Results page. Also imported by 5 files, including Commands Check, Fire Site and Fire Topo.
- Application
- faraday · bench · JavaScript module
- Uses
- none found
- Used by
- required by Commands Check (require), required by Fire Site (require), required by Fire Topo (require), required by Million Check (require), loaded by Bench — Results Page (script src), required by Topo Check (require), mentioned in Standalone (comment link)
- Produces
- rate, r, need, parse, fire, register
- Defines here
- rate, r, need, parse, fire, register
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/fire.js:1-63 · blob 20a67e9c717d2af2a8ec586a862dbc9880db8a44 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
// bench/fire.js - the pop commands that RUN IN THE VISITOR'S BROWSER. Plain JavaScript, no library, nothing leaves the device.
// Each function is a port of the Python in bench/*_cases.py and is checked against the saved records by bench/fire_check.mjs:
// same inputs, same numbers, or the port is wrong. A command is: fire <name> {inputs as JSON}
(function (root) {
const R20 = { al: { 50: 0.641, 70: 0.443, 95: 0.320, 120: 0.253, 150: 0.206, 185: 0.164, 240: 0.125, 300: 0.100, 400: 0.0778, 500: 0.0605, 630: 0.0469 },
cu: { 50: 0.387, 70: 0.268, 95: 0.193, 120: 0.153, 150: 0.124, 185: 0.0991, 240: 0.0754, 300: 0.0601, 400: 0.0470, 500: 0.0366, 630: 0.0283 } };
const K = { al: 94.0, cu: 143.0 }, ALPHA = { al: 0.00403, cu: 0.00393 };
const RATE_AL = { 50: 150, 70: 185, 95: 220, 120: 250, 150: 280, 185: 320, 240: 370, 300: 420, 400: 480, 500: 545, 630: 615 };
const rate = (m, s) => m === 'al' ? RATE_AL[s] : Math.round(RATE_AL[s] * 1.28);
// as Python's round(): the number as it is actually held decides; only an EXACT half goes to the even side
const r = (x, d) => { const up = Number(x.toFixed(d)), t = Math.abs(x).toFixed(d + 25), tail = t.slice(t.indexOf('.') + 1 + d);
if (!/^50*$/.test(tail)) return up;
const k = Math.pow(10, d), n = Math.round(Math.abs(up) * k); return n % 2 === 0 ? up : Number((up - Math.sign(x) / k).toFixed(d)); };
const need = (o, keys) => { for (const k of keys) if (o[k] === undefined) throw new Error('this command needs "' + k + '"'); };
const RUN = {
'cable-withstand': { family: 'CABLE CHECK', run(i) { need(i, ['metal', 'size_mm2', 'seconds', 'fault_ka']);
if (!K[i.metal]) throw new Error('metal is "al" or "cu"');
const limit = K[i.metal] * i.size_mm2 / Math.sqrt(i.seconds) / 1000, ok = i.fault_ka <= limit;
return { numbers: { withstand_ka: r(limit, 2), fault_ka: i.fault_ka, margin_pct: r((limit / i.fault_ka - 1) * 100, 1) },
said: 'withstands ' + limit.toFixed(2) + ' kA; asked for ' + i.fault_ka + ' kA: ' + (ok ? 'survives' : 'DOES NOT SURVIVE: a larger conductor or faster protection'),
how: 'adiabatic rule: k x area / square root of time, k = ' + K[i.metal] }; } },
'cable-run': { family: 'CABLE CHECK', run(i) { need(i, ['metal', 'size_mm2', 'amps', 'metres', 'kv', 'derate']);
if (!R20[i.metal] || !R20[i.metal][i.size_mm2]) throw new Error('sizes: ' + Object.keys(R20.al).join(', ') + ' mm2; metal "al" or "cu"');
const rh = R20[i.metal][i.size_mm2] * (1 + ALPHA[i.metal] * 70), x = 0.08;
const vd = Math.sqrt(3) * i.amps * (rh * 0.95 + x * Math.sqrt(1 - 0.95 * 0.95)) * i.metres / 1000, pct = vd / (i.kv * 1000) * 100;
const use = i.amps / (rate(i.metal, i.size_mm2) * i.derate) * 100, flags = [];
if (use > 100) flags.push('over its derated rating'); else if (use > 85) flags.push('within 15 per cent of its derated rating: commission a buried cable thermal study');
if (pct > 1.5) flags.push('voltage drop ' + pct.toFixed(2) + '% is over 1.5%');
return { numbers: { volt_drop_pct: r(pct, 3), loading_pct: r(use, 1), loss_kw: r(3 * i.amps * i.amps * rh * i.metres / 1000 / 1000, 2) },
said: 'drop ' + pct.toFixed(2) + '%, loaded to ' + use.toFixed(0) + '% of its derated rating; ' + (flags.length ? flags.join('; ') : 'inside both limits'),
how: 'resistance at 20 C raised to 90 C; drop = root three x amps x (r cos + x sin) x length; rating x derating (ratings are CANDIDATE round figures)' }; } },
'national-day': { family: 'NATIONAL DAY', run(i) { need(i, ['firm_gw', 'round_trip']);
const raw = []; for (let h = 0; h < 48; h++) raw.push(24.25 + 6.25 * Math.sin(Math.PI * (h / 2 - 7) / 12));
const k = 604 / (raw.reduce((a, b) => a + b, 0) / 2), d = raw.map(v => v * k);
const short = d.reduce((a, v) => a + Math.max(0, v - i.firm_gw), 0) / 2, spare = d.reduce((a, v) => a + Math.max(0, i.firm_gw - v), 0) / 2, inp = short / i.round_trip;
return { numbers: { storage_delivers_gwh: r(short, 1), must_be_put_in_gwh: r(inp, 1), spare_generation_that_day_gwh: r(spare, 1), day_low_gw: r(Math.min(...d), 1), day_high_gw: r(Math.max(...d), 1) },
said: 'storage delivers ' + short.toFixed(0) + ' GWh and needs ' + inp.toFixed(0) + ' GWh put in; the steady generation has ' + spare.toFixed(0) + ' GWh to spare that day: ' + (spare >= inp ? 'enough to refill it' : 'NOT enough to refill it'),
how: '48 half hours of a 604 GWh spring day; demand above the steady generation comes from storage' }; } },
'dc-traction-chain': { family: 'DC TRACTION', run(i) { need(i, ['inverter', 'transformer', 'rectifier', 'dc_converter']);
const ac = i.inverter * i.transformer * i.rectifier, s = i.dc_converter - ac;
return { numbers: { reaches_rail_by_ac_route_pct: r(ac * 100, 2), reaches_rail_by_dc_route_pct: r(i.dc_converter * 100, 2), saved_pct_of_the_solar: r(s * 100, 2) },
said: (ac * 100).toFixed(1) + '% arrives by the usual route, ' + (i.dc_converter * 100).toFixed(1) + '% by the direct route: ' + (s * 100).toFixed(1) + '% of the SOLAR is saved',
how: 'multiplied the efficiencies along each route' }; } },
'dc-traction-scale': { family: 'DC TRACTION', run(i) { need(i, ['solar_gwh', 'saving_share']);
const traction = 1216 * 0.825, saved = i.solar_gwh * i.saving_share;
return { numbers: { traction_gwh: r(traction, 1), saved_gwh: r(saved, 2), solar_share_of_traction_pct: r(i.solar_gwh / traction * 100, 1), average_kw_per_substation: Math.round(traction * 1e6 / 300 / 8760) },
said: 'saves ' + saved.toFixed(1) + ' GWh a year; the solar is ' + (i.solar_gwh / traction * 100).toFixed(1) + '% of traction energy',
how: 'traction = total x 82.5%; saving = solar x share saved' }; } },
};
function parse(text) {
const m = String(text).trim().match(/^fire\s+([a-z0-9-]+)\s*(\{[\s\S]*\})?\s*$/i);
if (!m) throw new Error('a command looks like: fire cable-withstand {"metal":"al","size_mm2":185,"seconds":1,"fault_ka":16}');
let inputs = {}; if (m[2]) { try { inputs = JSON.parse(m[2]); } catch (e) { throw new Error('the part in { } is not valid: ' + e.message); } }
return { name: m[1].toLowerCase(), inputs };
}
function fire(text) { const c = parse(text), f = RUN[c.name]; if (!f) return { name: c.name, inputs: c.inputs, ran: false }; const o = f.run(c.inputs); return Object.assign({ name: c.name, inputs: c.inputs, ran: true, family: f.family }, o); }
// another file may add commands: FIRE.register('site-pulse', 'SITE PULSE', inputs => ({ numbers, said, how }))
function register(name, family, run) { RUN[name] = { family, run }; }
root.FIRE = { fire, parse, register, get names() { return Object.keys(RUN); } };
if (typeof module !== 'undefined') module.exports = root.FIRE;
})(typeof window !== 'undefined' ? window : globalThis);Fire Check
A JavaScript module in the bench folder of Faraday. It is built from the same step (`same`).
ingestfaraday / bench/fire_check.mjs · lines 1–24 of 24 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Defines same. Uses libraries node:fs, node:module, node:url, node:path. Side effects: reads or writes files; starts processes.
- 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.
- What it achieves
- The browser's commands against the saved records: same inputs, same numbers, or the port is wrong.
- Why it matters
- No other file in the estate was found to import it.
- Application
- faraday · bench · JavaScript module
- Uses
- node:fs, node:module, node:url, node:path
- Used by
- none found
- Produces
- same
- Defines here
- same
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- faraday@e439b450f37a8c124fa4a0cb38159ae0dc337062 bench/fire_check.mjs:1-24 · blob ce97fb38a848577601a00ab60e8dec18bfc25044 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// bench/fire_check.mjs - the browser's commands against the saved records: same inputs, same numbers, or the port is wrong.
// node bench/fire_check.mjs exits 1 on any difference
import { readFileSync, existsSync } from 'node:fs';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const here = dirname(fileURLToPath(import.meta.url)), require = createRequire(import.meta.url);
const FIRE = require(join(here, 'fire.js'));
if (existsSync(join(here, 'fire_site.js'))) { globalThis.FIRE = FIRE; require(join(here, 'fire_site.js')); }
const rows = readFileSync(join(here, 'results', 'ledger.jsonl'), 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
const same = (a, b) => (a === null || b === null || typeof a !== 'number' || typeof b !== 'number') ? JSON.stringify(a) === JSON.stringify(b) : Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(a), Math.abs(b));
const tally = {}; let bad = 0;
for (const r of rows) {
if (!r.command) continue;
let c; try { c = FIRE.parse(r.command); } catch { continue; }
if (!FIRE.names.includes(c.name)) continue;
const o = FIRE.fire(r.command); tally[c.name] = tally[c.name] || { matched: 0, differed: 0 };
const diffs = Object.keys(r.numbers).filter(k => k in o.numbers && !same(o.numbers[k], r.numbers[k]));
const missing = Object.keys(r.numbers).filter(k => !(k in o.numbers) && !/error|rounds/.test(k));
if (diffs.length || missing.length) { tally[c.name].differed++; if (bad++ < 5) console.log('DIFFERS record', r.n, c.name, diffs.map(k => k + ': js ' + o.numbers[k] + ' py ' + r.numbers[k]).join('; '), missing.length ? 'missing ' + missing.join(',') : ''); }
else tally[c.name].matched++;
}
for (const [k, v] of Object.entries(tally)) console.log(k.padEnd(20), 'matched', v.matched, 'differed', v.differed);
console.log(bad ? 'FIRE CHECK FAIL' : 'FIRE CHECK PASS'); process.exit(bad ? 1 : 0);