sparam-conformance / verify.py
nickh007's picture
Add verify.py — the README's first command referenced a file the dataset did not ship
c5d65f1 verified
Raw History Blame Contribute Delete
7.05 kB
#!/usr/bin/env python3
"""Independent check of the corpus, using nothing but the standard library.
`score.py` grades *your* checker, so it cannot be run until you have one. This
script needs nothing: it checks that the corpus you have is internally
consistent -- every file matching the digest recorded for it, and no label
contradicting itself.
python3 verify.py
What it checks
--------------
1. Every case named in the index has its Touchstone file present.
2. Every file's SHA-256 matches the digest recorded in the index, so a corrupt
or truncated download is caught rather than silently scored against.
3. The index and `manifest.json` agree on the set of cases.
4. Every label is self-consistent: a case that is expected to fail a law must
name which laws, a case expected to pass all of them must name none, and
every law named must be one of the five the corpus defines.
5. Every Touchstone file parses as a real N-port network with the port count
and reference impedance the index claims.
What it does NOT check
----------------------
It does not re-derive the physics. Deciding whether `active_gain.s2p` really
violates passivity is the job of a checker, and re-implementing that here would
give the corpus a second, unvalidated opinion about its own ground truth --
exactly the circularity a conformance corpus exists to avoid. This verifies
integrity and label consistency. `score.py` is where physics gets graded.
It is also **not** a proof of authenticity. The digests live in `index.jsonl`,
inside the same download, so anyone who can rewrite a data file can rewrite its
digest to match. This detects corruption, truncation and inconsistent editing;
it does not detect deliberate substitution. Compare against the published
commit on the Hub if that is what you need.
Exit status is 0 if everything holds and 1 otherwise, so it is usable in CI.
"""
from __future__ import annotations
import hashlib
import json
import pathlib
import re
import sys
HERE = pathlib.Path(__file__).resolve().parent
DATA = HERE / "data"
LAWS = {
"passivity",
"reciprocity",
"energy_conservation",
"positive_real_z0",
"group_delay_nonneg",
}
def parse_touchstone(path: pathlib.Path) -> tuple[int, float, int]:
"""Return (n_ports, z0_ohm, n_points) from a Touchstone 1.x file.
In Touchstone 1.x the port count lives in the extension (`.s2p`, `.s4p`) --
it is not derivable from the payload, because a 2-port's row stride of 9
numbers is divisible by a 1-port's stride of 3, so counting alone would
happily mis-read every 2-port file as a 1-port. The extension is the
authority; the payload is then checked for consistency with it.
"""
m = re.fullmatch(r"\.s(\d+)p", path.suffix, re.I)
if not m:
raise ValueError(f"{path.name}: not a Touchstone .sNp filename")
n_ports = int(m.group(1))
z0 = 50.0
values: list[float] = []
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.split("!", 1)[0].strip()
if not line:
continue
if line.startswith("#"):
opt = re.search(r"\bR\s*([0-9.eE+-]+)", line, re.I)
if opt:
z0 = float(opt.group(1))
continue
values.extend(float(tok) for tok in line.split())
# One row is: frequency, then a real/imag pair per S-parameter.
stride = 1 + 2 * n_ports * n_ports
if not values or len(values) % stride:
raise ValueError(
f"{path.name}: {len(values)} numbers is not a whole number of "
f"{n_ports}-port rows (stride {stride})"
)
return n_ports, z0, len(values) // stride
def main() -> int:
problems: list[str] = []
index_path = DATA / "index.jsonl"
if not index_path.exists():
print(f"FATAL: {index_path} is missing", file=sys.stderr)
return 1
rows = [json.loads(line) for line in index_path.read_text(encoding="utf-8").splitlines() if line.strip()]
for row in rows:
name = row["name"]
f = DATA / row["file"]
if not f.exists():
problems.append(f"{name}: file {row['file']} is missing")
continue
digest = hashlib.sha256(f.read_bytes()).hexdigest()
if digest != row["sha256"]:
problems.append(f"{name}: sha256 mismatch (file has been altered)")
fails = row["expected_failures"]
unknown = set(fails) - LAWS
if unknown:
problems.append(f"{name}: names laws that do not exist: {sorted(unknown)}")
if row["expected_to_pass_all_laws"] and fails:
problems.append(f"{name}: labelled as passing all laws but lists failures {fails}")
if not row["expected_to_pass_all_laws"] and not fails:
problems.append(f"{name}: labelled as failing but names no law")
try:
n_ports, z0, n_points = parse_touchstone(f)
except ValueError as exc:
problems.append(f"{name}: {exc}")
continue
if n_ports != row["n_ports"]:
problems.append(f"{name}: index says {row['n_ports']}-port, file parses as {n_ports}-port")
if abs(z0 - row["z0_ohm"]) > 1e-9:
problems.append(f"{name}: index says z0={row['z0_ohm']}, file declares {z0}")
manifest_path = DATA / "manifest.json"
if not manifest_path.exists():
problems.append("data/manifest.json is missing")
else:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
in_manifest = {c["name"] for c in manifest.get("cases", [])}
in_index = {r["name"] for r in rows}
if in_manifest != in_index:
only_m = sorted(in_manifest - in_index)
only_i = sorted(in_index - in_manifest)
problems.append(f"manifest/index disagree (manifest-only={only_m}, index-only={only_i})")
realizable = sum(1 for r in rows if r["physically_realizable"])
print("sparam-conformance corpus verification (stdlib only)\n")
print(f" cases {len(rows)}")
print(f" physically valid {realizable}")
print(f" physically invalid {len(rows) - realizable}")
print(f" laws {len(LAWS)}")
matched = sum(
1
for r in rows
if (DATA / r["file"]).exists()
and hashlib.sha256((DATA / r["file"]).read_bytes()).hexdigest() == r["sha256"]
)
print(f" sha256 matched {matched}/{len(rows)}")
print()
if problems:
print(f" INCONSISTENT -- {len(problems)} problem(s):\n")
for p in problems:
print(f" - {p}")
return 1
print(" self-consistent: every file matches its recorded digest, and every")
print(" label agrees with itself")
print()
print(" scope: internal consistency only. The digests ship in this download,")
print(" so this detects corruption, not substitution. It does not re-derive")
print(" the physics -- run score.py against a checker for that.")
return 0
if __name__ == "__main__":
raise SystemExit(main())