In this section
- Plant500 ingest · worlds- / src/plant500.py lines 1–245
- Provenance Gate storage · worlds- / src/provenance_gate.py lines 1–455
Plant500
A Python command-line tool in Worlds. It is built from the decode step (`decode`), the plant step (`plant`) and the reference step (`reference`).
ingestworlds- / src/plant500.py · lines 1–245 of 245 · Entry point · pattern plant (shared by 3 files)
- What it does
- Defines decode, plant, reference, main. Uses libraries argparse, io, json, os, sys. Side effects: starts processes.
- Why it exists in the grid workflow
- Domain terms in the code: 400kV, 33kV, 0.8kV.
- Inputs & outputs
- In: JSON file plant500.json; command-line arguments. Voltage levels named: 400kV, 33kV, 0.8kV.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- A 500MW DC plant, anonymised, with the module rating as a swept axis. Its code works with 500 MW, 0.8 kV and 33 kV. It accepts `--run`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- worlds- · src · Python CLI
- Uses
- argparse, io, json, os, sys, time, numpy, cupy
- Used by
- none found
- Produces
- decode, plant, reference, main
- Defines here
- decode, plant, reference, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/plant500.py:1-245 · blob 46a63aa130f7340dd2cabb862a3719d776aa1503 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
"""A 500 MW DC plant, anonymised, with the module rating as a swept axis.
THE PROVENANCE, STATED PLAINLY
The ARCHITECTURE is taken from an operational project's single line diagram:
module -> string -> inverter at 0.8 kV -> collection at 33 kV -> grid at
400 kV, gathered into blocks of roughly 9.9 MW. That shape is ordinary
engineering practice and is what is reused here.
NOTHING IDENTIFYING IS REUSED. No project, client, consultant, site, drawing
number, equipment maker or model appears in this file, its output, or anything
derived from it. The plant modelled here is 500 MW DC, which is not the size of
the source, and every quantity is recomputed from the axes below rather than
copied. The source document does not leave this machine.
THE AXES - all of them the client's to change
module rating 250 to 800 Wp, which is the whole point: a plant designed
around 660 Wp modules is a different plant at 250 and at 800,
and nobody sees the difference because the number is chosen
once at the start and never revisited
modules in series, strings per inverter, site minimum temperature,
inverter class, module class
python plant500.py the space and what it costs
python plant500.py --run enumerate it on the card
"""
import argparse
import io
import json
import os
import sys
import time
import numpy as np
# ---- the anonymised architecture, from the SLD's structure only
TARGET_DC_MW = 500.0
AC_VOLTS = 800.0 # inverter terminal, 0.8 kV
COLLECT_KV = 33.0
GRID_KV = 400.0
BLOCK_MW = 9.856 # the repeated block size in the source topology
# ---- module classes we own, plus the swept rating
CLASSES = [(45.90, -0.25), (50.59, -0.22), (53.27, -0.25)] # Voc, beta %/K
WP_LO, WP_HI, WP_STEP = 250, 800, 10 # 56 values
TMIN = [-14.0, -12.0, -11.0, -10.0, -8.0, -6.0]
SERIES = list(range(20, 35)) # 15
STRINGS = list(range(16, 37)) # 21
# FROM THE DATASHEET, read 2026-09-21. The AC rating DERATES with ambient,
# which the band analysis must use: same array, different verdict.
INVERTER_KVA = [352.0, 320.0, 295.0] # @30C, @40C, @50C - one machine
AMBIENT = [30, 40, 50]
# variants: (MPPT count, max A per MPPT, connectors per MPPT) -> strings
VARIANTS = [(12, 40, 2), (14, 30, 2), (16, 30, 2)] # 24 / 28 / 32 strings
STRING_A_LIMIT = 20.0 # 20 A per string, datasheet
MPP_LO, MPP_HI = 500.0, 1500.0 # MPP window, datasheet
MAX_V = 1500.0
DCAC_LO, DCAC_HI = 1.15, 1.40
OK, DISPUTED, FAIL_COLD, OUT_OF_BAND = 0, 1, 2, 3
LABEL = ["buildable, both readings", "disputed: the clause decides it",
"fails cold voltage", "DC:AC outside the band"]
WP = list(range(WP_LO, WP_HI + 1, WP_STEP))
RAD = [len(CLASSES), len(WP), len(TMIN), len(SERIES), len(STRINGS),
len(INVERTER_KVA)]
SIZE = int(np.prod(RAD))
SRC = """
long long r = idx;
int ci = (int)(r %% %(A0)d); r /= %(A0)d;
int wi = (int)(r %% %(A1)d); r /= %(A1)d;
int ti = (int)(r %% %(A2)d); r /= %(A2)d;
int si = (int)(r %% %(A3)d); r /= %(A3)d;
int ni = (int)(r %% %(A4)d); r /= %(A4)d;
int ii = (int)(r %% %(A5)d);
double v = voc[ci], b = beta[ci];
double w = wp[wi], tm = tmin[ti], se = ser[si], sn = strs[ni], kva = inv[ii];
double nb = floor(%(MAXV).17g / (v * (1.0 + b / 100.0 * (tm - 25.0))));
double na = floor(%(MAXV).17g / (v * (1.0 + b / 100.0 * (tm - 15.0))));
double kw_inv = se * w / 1000.0 * sn;
double dcac = kw_inv / kva;
bool band = (dcac >= %(LO).17g) && (dcac <= %(HI).17g);
code = (se > na) ? %(FC)d : ((se > nb) ? %(DI)d : (band ? %(OK)d : %(OB)d));
""" % {"A0": RAD[0], "A1": RAD[1], "A2": RAD[2], "A3": RAD[3], "A4": RAD[4],
"A5": RAD[5], "MAXV": MAX_V, "LO": DCAC_LO, "HI": DCAC_HI,
"FC": FAIL_COLD, "DI": DISPUTED, "OK": OK, "OB": OUT_OF_BAND}
def decode(i):
out, r = [], int(i)
for q in RAD:
out.append(r % q)
r //= q
return out
def plant(ci, wi, ti, si, ni, ii):
"""Everything the client actually asks for, recomputed from the axes."""
w, se, sn, kva = WP[wi], SERIES[si], STRINGS[ni], INVERTER_KVA[ii]
kw_string = se * w / 1000.0
kw_inv = kw_string * sn
inverters = int(np.ceil(TARGET_DC_MW * 1000.0 / kw_inv))
return {
"module_wp": w, "series": se, "strings_per_inverter": sn,
"inverter_kva": kva,
"kw_dc_string": round(kw_string, 3),
"kw_dc_inverter": round(kw_inv, 2),
"dc_ac": round(kw_inv / kva, 4),
"inverters_for_500MW": inverters,
"modules_total": inverters * sn * se,
"strings_total": inverters * sn,
"mated_pairs_total": inverters * sn * 2,
"mva_ac_total": round(inverters * kva / 1000.0, 1),
"blocks_at_%.3f_MW" % BLOCK_MW: int(np.ceil(TARGET_DC_MW / BLOCK_MW)),
}
def reference(idx):
out = np.zeros(len(idx), np.int64)
for j, i in enumerate(idx):
ci, wi, ti, si, ni, ii = decode(i)
v, b = CLASSES[ci]
tm, se, sn, w, kva = TMIN[ti], SERIES[si], STRINGS[ni], WP[wi], INVERTER_KVA[ii]
nb = np.floor(MAX_V / (v * (1 + b / 100 * (tm - 25))))
na = np.floor(MAX_V / (v * (1 + b / 100 * (tm - 15))))
dcac = (se * w / 1000.0) * sn / kva
band = DCAC_LO <= dcac <= DCAC_HI
out[j] = (FAIL_COLD if se > na else
(DISPUTED if se > nb else (OK if band else OUT_OF_BAND)))
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--run", action="store_true")
a = ap.parse_args()
print("A 500 MW DC PLANT - anonymised architecture, swept design")
print(" topology reused module -> string -> inverter at %.1f kV -> "
"collection at %g kV -> grid at %g kV" % (AC_VOLTS / 1000, COLLECT_KV,
GRID_KV))
print(" blocks %g MW, as the source groups them" % BLOCK_MW)
print(" NOTHING IDENTIFYING is reused: no project, client, site, drawing,")
print(" maker or model, here or in any output.")
print()
print(" THE AXES, all of them the client's to change")
for nm, n, rng in (("module class", RAD[0], "3 owned classes"),
("module rating", RAD[1], "%d-%d Wp in %d Wp steps"
% (WP_LO, WP_HI, WP_STEP)),
("site min temp", RAD[2], "%g to %g C" % (TMIN[0], TMIN[-1])),
("modules in series", RAD[3], "%d-%d" % (SERIES[0], SERIES[-1])),
("strings per inverter", RAD[4], "%d-%d" % (STRINGS[0], STRINGS[-1])),
("inverter class", RAD[5], "352 / 465 / 500")):
print(" %-22s %5d %s" % (nm, n, rng))
print(" %-22s %5s" % ("", "-----"))
print(" %-22s %s cases" % ("", "{:,}".format(SIZE)))
# the reference design, at the source's own module rating
ref = plant(0, WP.index(660), 3, SERIES.index(30), STRINGS.index(24), 0)
print("\n AT 660 Wp, 30 IN SERIES, 24 STRINGS, 352 kVA CLASS")
for k, v in ref.items():
print(" %-24s %s" % (k, "{:,}".format(v) if isinstance(v, int) else v))
print("\n THE SAME PLANT AT OTHER MODULE RATINGS (30 series, 24 strings)")
print(" %5s %10s %12s %12s %10s" % ("Wp", "kW/string", "inverters",
"modules", "DC:AC"))
for w in (250, 400, 550, 660, 700, 800):
p = plant(0, WP.index(w), 3, SERIES.index(30), STRINGS.index(24), 0)
print(" %5d %10.2f %12s %12s %10.3f"
% (w, p["kw_dc_string"], "{:,}".format(p["inverters_for_500MW"]),
"{:,}".format(p["modules_total"]), p["dc_ac"]))
print(" -> the plant needs %s modules at 250 Wp and %s at 800 Wp for the"
% ("{:,}".format(plant(0, WP.index(250), 3, SERIES.index(30),
STRINGS.index(24), 0)["modules_total"]),
"{:,}".format(plant(0, WP.index(800), 3, SERIES.index(30),
STRINGS.index(24), 0)["modules_total"])))
print(" same 500 MW DC. That ratio is chosen once and never revisited.")
if not a.run:
print("\n --run to enumerate on the card.")
return 0
try:
import cupy as cp
except Exception as exc:
print("\nFAIL: cupy unavailable (%r). Not evaluated." % (exc,))
return 1
K = cp.ElementwiseKernel(
"int64 idx, raw float64 voc, raw float64 beta, raw float64 wp, "
"raw float64 tmin, raw float64 ser, raw float64 strs, raw float64 inv",
"int64 code", SRC, "ventus_plant500")
T = (cp.asarray([c[0] for c in CLASSES]), cp.asarray([c[1] for c in CLASSES]),
cp.asarray([float(x) for x in WP]), cp.asarray(TMIN),
cp.asarray([float(s) for s in SERIES]),
cp.asarray([float(s) for s in STRINGS]),
cp.asarray(INVERTER_KVA))
stride = 1000003
while np.gcd(stride, SIZE) != 1:
stride += 2
probe = (np.arange(min(200000, SIZE), dtype=np.int64) * stride) % SIZE
differ = int((cp.asnumpy(K(cp.asarray(probe), *T)) != reference(probe)).sum())
print("\n verified: processor vs card on %s cases, %d differ"
% ("{:,}".format(len(probe)), differ))
if differ:
print(" FAIL: refusing to report anything for arithmetic that differs.")
return 1
t0 = time.perf_counter()
totals = cp.bincount(K(cp.arange(SIZE, dtype=cp.int64), *T), minlength=4)[:4]
cp.cuda.Stream.null.synchronize()
sec = time.perf_counter() - t0
got = [int(x) for x in cp.asnumpy(totals)]
if sum(got) != SIZE:
print(" FAIL: reduction lost cases: %d of %d" % (sum(got), SIZE))
return 1
print(" ENUMERATED %s cases in %.4f s" % ("{:,}".format(SIZE), sec))
for k in range(4):
print(" %-32s %10s %6.2f%%"
% (LABEL[k], "{:,}".format(got[k]), 100.0 * got[k] / SIZE))
out = {"target_dc_mw": TARGET_DC_MW, "axes": dict(zip(
["module_class", "module_wp", "site_tmin", "series", "strings",
"inverter_kva"], RAD)), "cases": SIZE, "seconds": round(sec, 4),
"verified_differ": differ, "verdicts": dict(zip(LABEL, got)),
"reference_design_660wp": ref,
"anonymised": "Architecture only. No project, client, site, drawing, "
"maker or model is recorded. 500 MW DC is not the size "
"of the source.",
"what_this_is_not": "Not a design, not a study, not a connection "
"assessment. DC sizing arithmetic under both "
"readings of the cold-voltage clause."}
p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..",
"plant500.json")
io.open(p, "w", encoding="utf-8", newline="\n").write(
json.dumps(out, indent=1) + "\n")
print("\n wrote plant500.json")
return 0
if __name__ == "__main__":
sys.exit(main())Provenance Gate
A Python command-line tool in Worlds that loads evidence (`load_evidence`) and absent numbers (`load_absent_numbers`) and scans python (`scan_python`).
storageworlds- / src/provenance_gate.py · lines 1–455 of 498 · Entry point · pattern load_evidence (shared by 2 files)
- What it does
- It loads data. Defines 11 functions or classes, including load_evidence, walk, load_absent_numbers, lookup, classify. Uses libraries __future__, ast, json, os, re. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: JSON file MODULES.json; JSON file provenance.json. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the walk step (`walk`), the lookup step (`lookup`) and the classify step (`classify`). The gate that asks WHERE A NUMBER CAME FROM.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- worlds- · src · Python CLI
- Uses
- Paths (import), __future__, ast, json, os, re, sys
- Used by
- none found
- Produces
- load_evidence, load_absent_numbers, lookup, classify, const_value, scan_python, scan_json, scan_markdown, main
- Defines here
- load_evidence, walk, load_absent_numbers, lookup, classify, const_value, scan_python, scan_json, walk, scan_markdown, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/provenance_gate.py:1-455 · blob a215fdfc55dd588dacf1957e49d6f209b6e56994 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: supporting_data
"""
provenance_gate.py - the gate that asks WHERE A NUMBER CAME FROM.
Every other gate in this tree checks that two things we wrote agree with each
other. Agreement is not provenance. A limit invented once and copied into
twelve modules agrees with itself perfectly, and that is exactly how a 20 A
string limit that appears nowhere in the evidence base, and a 40 A machine
limit recorded ABSENT from both source documents, ended up underneath every
published verdict.
THE RULE ENFORCED HERE
A number may not be published unless something beside it says where it
came from.
WHAT COUNTS AS A DECLARED SOURCE
1. The value is present in the evidence base (the feed's MODULES.json)
in a field carrying a src tag of FROM-DATASHEET -> SOURCED.
2. The value is present there under a src tag of DERIVED (a value the
evidence base itself derives, with its formula printed beside it)
-> DERIVED-FROM-SOURCED.
3. A value READ from MODULES.json at runtime never appears here at all -
it is not a hardcoded constant, so there is nothing to flag. Note that
a module reading the feed elsewhere does NOT excuse the constants it
also hardcodes; that loophole is deliberately closed.
4. A note or field beside the number names a document AND the value can be
located in the evidence base. A note on its own is a CLAIM, not a
source; see below.
WHAT THIS GATE DOES **NOT** CHECK - read this before trusting a pass
* It cannot tell a CORRECT source from an INCORRECT one. It only tells a
PRESENT source from an ABSENT one. A number tagged to the wrong page of
the right document passes here, unflagged and wrong.
* It does not re-read the source documents. It trusts the src tags in
MODULES.json. If a FROM-DATASHEET tag is a lie, this gate repeats it.
* It does not check that a sourced number is USED correctly. A correctly
sourced 35 A fuse rating compared against the wrong current is still a
wrong verdict, and every gate here will pass it.
* A bare comment such as "# 20 A per string, datasheet" is deliberately NOT
accepted as a source. The word "datasheet" beside a number that appears
nowhere in the evidence base is an unverifiable claim; those are reported
as UNSOURCED with claim_unverifiable set, because that is the more
dangerous case, not the safer one.
* Numbers below 1000 that are not used as limits are not examined at all.
EXIT
1 if any number used as a LIMIT is UNSOURCED, 0 otherwise.
2 if the evidence base is absent: nothing examined, which is not a pass.
Writes night-results/provenance.json - sorted keys, no timestamps in body.
"""
from __future__ import annotations
import ast
import json
import os
import re
import sys
import paths
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(REPO, "src")
RESULTS = os.path.join(REPO, "night-results")
# Not written down here: this repository is public and an absolute path
# names a drive, a machine and an account. The root comes from GRID_DATA
# in the environment; see src/paths.py for the whole argument.
FEED = paths.FEED
MODULES_JSON = os.path.join(FEED, "MODULES.json")
DISTINCTIVE = 1000.0 # any number this big is distinctive
TOL = 1e-9
# a PYTHON module constant that is a boundary something is tested against
LIMIT_NAME = re.compile(
r"(LIMIT|CEIL|FLOOR|THRESH|RATING|RATED|FUSE|MAX_SYSTEM|"
r"_INPUT_A$|_A$|_V$|_KVA$)")
# a JSON / markdown key that names a PUBLISHED LIMIT, not a computed output
KEY_LIMIT = re.compile(
r"(^|[_.])(limit|limits|ceiling|cap|threshold|rating|rated|fuse|"
r"max_system_v|max_series_fuse_a|v_ceiling|string_input_a|mppt_input_a)"
r"([_.]|$)", re.I)
# computed per-row outputs: examined, but they are results, not limits
NOT_A_LIMIT = re.compile(
r"(pass|fail|margin|headroom|count|index|total|sum|mean|worst|size|"
r"table|order|actual|observed|result|verdict|region)", re.I)
# a feed field that is itself a boundary
LIMIT_FIELD = re.compile(
r"(max_|min_|_max|_min|limit|fuse|rating|rated|ceiling|withstand)", re.I)
# a feed field that is a nameplate electrical value - a published limit may
# legitimately BE one of these (a power bin, a Voc, an Isc)
# Deliberately NARROW: only the power bin, because a published "rating_w" may
# legitimately BE the bin. Operating values (Voc, Isc, Vmp, Imp) are NOT
# accepted as the source of a limit - a 20 A string limit that happens to equal
# some bin's Imp is a value collision, not a provenance.
NAMEPLATE_FIELD = re.compile(r"^(power_bin_w|wp)$", re.I)
# a note that names a document
NAMES_DOC = re.compile(
r"(DOC-A|DOC-B|datasheet|data sheet|MODULES\.json|STANDARDS|62548|62738|"
r"61730|60364|disclosure|nameplate|IEC\s*\d)", re.I)
# a note that admits there is no source
ADMITS_NONE = re.compile(r"(NO SOURCE|ABSENT|UNSOURCED|ASSUMED|OURS)", re.I)
# ---------------------------------------------------------------- evidence
def load_evidence():
"""Every numeric value in the feed, with its src tag and field path."""
sourced, derived, absent_fields = {}, {}, []
if not os.path.exists(MODULES_JSON):
return sourced, derived, absent_fields, False
with open(MODULES_JSON, "r", encoding="utf-8") as fh:
data = json.load(fh)
def walk(node, path):
if isinstance(node, dict):
src = node.get("src")
val = node.get("v")
if isinstance(src, str) and isinstance(val, (int, float)) and \
not isinstance(val, bool):
field = path.split(".")[-1] or path
tag = src.upper()
bucket = sourced if tag.startswith("FROM-") else (
derived if tag == "DERIVED" else None)
if bucket is not None:
bucket.setdefault(float(val), []).append(
{"field": field, "path": path, "src": src})
if isinstance(src, str) and src.upper() == "ABSENT":
absent_fields.append(path)
for k, v in node.items():
walk(v, "%s.%s" % (path, k) if path else str(k))
elif isinstance(node, list):
for i, v in enumerate(node):
walk(v, "%s[%d]" % (path, i))
walk(data, "")
return sourced, derived, absent_fields, True
def load_absent_numbers():
"""Numbers the standards note itself records ABSENT from both documents."""
out = {}
path = os.path.join(FEED, "STANDARDS.md")
if not os.path.exists(path):
return out
with open(path, "r", encoding="utf-8", errors="replace") as fh:
for n, line in enumerate(fh, 1):
if "ABSENT" not in line.upper():
continue
for m in re.finditer(
r"(?<![\w.])(\d+(?:[.,]\d+)?)\s*(A|V|kV|kW|W)\b", line):
try:
val = float(m.group(1).replace(",", "."))
except ValueError:
continue
out.setdefault(val, "STANDARDS.md:%d records this ABSENT: %s"
% (n, line.strip()[:160]))
return out
def lookup(value, table):
for known, entries in table.items():
if abs(known - value) <= TOL * max(1.0, abs(known)):
return entries
return None
# ---------------------------------------------------------------- classify
def classify(value, is_limit, ev, runtime_read, note):
"""Return (verdict, evidence string, claim_unverifiable)."""
hits = lookup(value, ev["sourced"])
if hits:
fields = [h for h in hits
if not is_limit or LIMIT_FIELD.search(h["field"])
or NAMEPLATE_FIELD.search(h["field"])]
if fields:
names = sorted({h["field"] for h in fields})
return ("SOURCED",
"MODULES.json %s, src %s, %d field(s)"
% ("/".join(names[:3]), fields[0]["src"], len(fields)),
False)
hits = lookup(value, ev["derived"])
if hits:
fields = [h for h in hits
if not is_limit or LIMIT_FIELD.search(h["field"])]
if fields:
names = sorted({h["field"] for h in fields})
return ("DERIVED-FROM-SOURCED",
"MODULES.json %s, src DERIVED" % "/".join(names[:3]), False)
if runtime_read:
return ("SOURCED", "read at runtime from MODULES.json", False)
if note and ADMITS_NONE.search(note):
return ("UNSOURCED",
"note admits no source: %s" % note.strip()[:120], False)
for known, why in ev["absent"].items():
if abs(known - value) <= TOL * max(1.0, abs(known)):
return ("UNSOURCED", why, False)
if note and NAMES_DOC.search(note):
# a claim, but the value is nowhere in the evidence base
return ("UNSOURCED",
"note claims a source but the value is not in the evidence "
"base: %s" % note.strip()[:100], True)
return ("UNSOURCED", "not found anywhere in the evidence base", False)
# ---------------------------------------------------------------- scanning
def const_value(node):
if isinstance(node, ast.Constant) and \
isinstance(node.value, (int, float)) and \
not isinstance(node.value, bool):
return float(node.value)
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
inner = const_value(node.operand)
return None if inner is None else -inner
return None
def scan_python(ev, findings):
here = os.path.basename(os.path.abspath(__file__))
for fname in sorted(os.listdir(SRC)):
if not fname.endswith(".py") or fname == here:
continue
path = os.path.join(SRC, fname)
with open(path, "r", encoding="utf-8", errors="replace") as fh:
text = fh.read()
lines = text.splitlines()
try:
tree = ast.parse(text)
except SyntaxError:
continue
# A file that reads the feed somewhere does NOT thereby source the
# constants it hardcodes elsewhere. Hardcoded is hardcoded, and that
# loophole is closed deliberately: a value genuinely read at runtime is
# not a module-level constant and never reaches this scan at all.
runtime_read = False
# names that appear on either side of a comparison anywhere in the file
compared = set()
for node in ast.walk(tree):
if isinstance(node, ast.Compare):
for part in [node.left] + list(node.comparators):
for sub in ast.walk(part):
if isinstance(sub, ast.Name):
compared.add(sub.id)
for node in tree.body:
if not isinstance(node, (ast.Assign, ast.AnnAssign)):
continue
targets = node.targets if isinstance(node, ast.Assign) \
else [node.target]
pairs = []
for tgt in targets:
if isinstance(tgt, ast.Name):
v = const_value(node.value)
if v is not None:
pairs.append((tgt.id, v))
elif isinstance(tgt, ast.Tuple) and \
isinstance(node.value, ast.Tuple):
for t, val in zip(tgt.elts, node.value.elts):
v = const_value(val)
if isinstance(t, ast.Name) and v is not None:
pairs.append((t.id, v))
for name, value in pairs:
named = bool(LIMIT_NAME.search(name))
# a bare 0 or 1 that merely appears in a comparison is an
# index or a flag, not a published limit
is_limit = named or (name in compared and abs(value) > 1.0001)
if not is_limit and abs(value) < DISTINCTIVE:
continue
line = node.lineno
raw = lines[line - 1] if line <= len(lines) else ""
note = raw.split("#", 1)[1] if "#" in raw else ""
verdict, why, claim = classify(value, is_limit, ev,
runtime_read, note)
findings.append({
"artefact": "src/" + fname,
"claim_unverifiable": claim,
"evidence": why,
"is_limit": is_limit,
"line": line,
"name": name,
"value": value,
"verdict": verdict,
})
def scan_json(ev, findings):
for fname in sorted(os.listdir(RESULTS)):
if not fname.endswith(".json") or fname == "provenance.json":
continue
path = os.path.join(RESULTS, fname)
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
data = json.load(fh)
except Exception:
continue
def walk(node, trail, parent):
if isinstance(node, dict):
for k, v in node.items():
walk(v, trail + [str(k)], node)
elif isinstance(node, list):
for i, v in enumerate(node[:200]):
walk(v, trail + ["[]"], parent)
elif isinstance(node, (int, float)) and not isinstance(node, bool):
value = float(node)
key = trail[-1] if trail else ""
path_txt = ".".join(trail)
is_limit = bool(KEY_LIMIT.search(key)) and not NOT_A_LIMIT.search(path_txt)
if not is_limit and abs(value) < DISTINCTIVE:
return
declared = ""
if isinstance(parent, dict):
for f in ("src", "provenance", "source", "note", "from"):
if isinstance(parent.get(f), str):
declared += " " + parent[f]
if re.search(r"FROM-(DATASHEET|STANDARD)", declared, re.I):
findings.append({
"artefact": "night-results/" + fname,
"claim_unverifiable": False,
"evidence": "declared src%s" % declared[:60],
"is_limit": is_limit,
"line": 0,
"name": ".".join(trail),
"value": value,
"verdict": "SOURCED",
})
return
verdict, why, claim = classify(value, is_limit, ev, False,
declared)
findings.append({
"artefact": "night-results/" + fname,
"claim_unverifiable": claim,
"evidence": why,
"is_limit": is_limit,
"line": 0,
"name": ".".join(trail),
"value": value,
"verdict": verdict,
})
before = len(findings)
walk(data, [], None)
seen, kept = set(), []
for f in findings[before:]:
key = (f["name"], f["value"])
if key in seen:
continue
seen.add(key)
kept.append(f)
findings[before:] = kept
NUM_UNIT = re.compile(r"(?<![\w.])(\d[\d,]*(?:\.\d+)?)\s*(A|V|kV|kW|kVA|W)\b")
LIMIT_WORD = re.compile(r"(limit|maximum|ceiling|rating|rated|threshold|"
r"must not exceed|over the)", re.I)
def scan_markdown(ev, findings):
for fname in sorted(os.listdir(RESULTS)):
if not fname.endswith(".md"):
continue
path = os.path.join(RESULTS, fname)
with open(path, "r", encoding="utf-8", errors="replace") as fh:
lines = fh.read().splitlines()
for n, line in enumerate(lines, 1):
limitish = bool(LIMIT_WORD.search(line))
for m in NUM_UNIT.finditer(line):
try:
value = float(m.group(1).replace(",", ""))
except ValueError:
continue
if not limitish and value < DISTINCTIVE:
continue
verdict, why, claim = classify(value, limitish, ev, False, line)
findings.append({
"artefact": "night-results/" + fname,
"claim_unverifiable": claim,
"evidence": why,
"is_limit": limitish,
"line": n,
"name": "%s %s" % (m.group(1), m.group(2)),
"value": value,
"verdict": verdict,
})
# ---------------------------------------------------------------- main
def main():
sourced, derived, absent_fields, have_feed = load_evidence()
if not have_feed:
# A gate that reads no evidence must not answer. Without the feed
# every number is UNSOURCED and the exit is 1 for a reason nobody
# asked about: the input was missing, not the source. That is a
# gate getting louder when blind, which is the same fault as one
# getting quieter. Refuse, distinctly.
print("PROVENANCE GATE - where did the number come from?")
print(" COULD NOT CHECK: the evidence base is not present at")
print(" the configured root (set GRID_DATA to the directory that")
print(" holds feed/MODULES.json). Nothing was examined, nothing")
print(" was written. This is not a pass and not a finding.")
return 2
ev = {"sourced": sourced, "derived": derived,
"absent": load_absent_numbers()}
findings = []
if os.path.isdir(SRC):
scan_python(ev, findings)
if os.path.isdir(RESULTS):
scan_json(ev, findings)
scan_markdown(ev, findings)
findings.sort(key=lambda f: (f["artefact"], f["line"], f["name"],
f["value"]))
unsourced_limits = [f for f in findings
if f["is_limit"] and f["verdict"] == "UNSOURCED"]
# one row per distinct limit value, so a limit copied into twelve modules
# is reported as one fault with twelve sites
by_value = {}
for f in unsourced_limits:
by_value.setdefault(repr(f["value"]), []).append(
"%s:%d %s" % (f["artefact"], f["line"], f["name"]))
report = {
"evidence_base": {
"absent_fields_in_feed": len(absent_fields),
"derived_values": len(derived),
"modules_json_present": have_feed,
"numbers_recorded_absent_in_standards": sorted(ev["absent"]),
"sourced_values": len(sourced),
},
"findings": findings,
"rule": "A number may not be published unless something beside it says "
"where it came from.",
"summary": {
"derived_from_sourced": sum(
1 for f in findings if f["verdict"] == "DERIVED-FROM-SOURCED"),
"distinct_unsourced_limit_values": sorted(by_value),
"limits_examined": sum(1 for f in findings if f["is_limit"]),
"numbers_examined": len(findings),
"sourced": sum(1 for f in findings if f["verdict"] == "SOURCED"),
"unsourced": sum(1 for f in findings
if f["verdict"] == "UNSOURCED"),
"unsourced_limit_sites": len(unsourced_limits),
},
"what_this_gate_cannot_check": [
"It cannot tell a correct source from an incorrect one - only a "
"present one from an absent one.",
"It trusts the src tags in MODULES.json; it does not re-read the "
"source documents.",
"It does not check that a sourced number is USED correctly.",
"A note naming a document is a claim, not a source; claims whose "
"value is absent from the evidence base are reported UNSOURCED "
"with claim_unverifiable true.",