nickh007 commited on
Commit
c5d65f1
·
verified ·
1 Parent(s): bee60af

Add verify.py — the README's first command referenced a file the dataset did not ship

Browse files
Files changed (1) hide show
  1. verify.py +180 -0
verify.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Independent check of the corpus, using nothing but the standard library.
3
+
4
+ `score.py` grades *your* checker, so it cannot be run until you have one. This
5
+ script needs nothing: it checks that the corpus you have is internally
6
+ consistent -- every file matching the digest recorded for it, and no label
7
+ contradicting itself.
8
+
9
+ python3 verify.py
10
+
11
+ What it checks
12
+ --------------
13
+ 1. Every case named in the index has its Touchstone file present.
14
+ 2. Every file's SHA-256 matches the digest recorded in the index, so a corrupt
15
+ or truncated download is caught rather than silently scored against.
16
+ 3. The index and `manifest.json` agree on the set of cases.
17
+ 4. Every label is self-consistent: a case that is expected to fail a law must
18
+ name which laws, a case expected to pass all of them must name none, and
19
+ every law named must be one of the five the corpus defines.
20
+ 5. Every Touchstone file parses as a real N-port network with the port count
21
+ and reference impedance the index claims.
22
+
23
+ What it does NOT check
24
+ ----------------------
25
+ It does not re-derive the physics. Deciding whether `active_gain.s2p` really
26
+ violates passivity is the job of a checker, and re-implementing that here would
27
+ give the corpus a second, unvalidated opinion about its own ground truth --
28
+ exactly the circularity a conformance corpus exists to avoid. This verifies
29
+ integrity and label consistency. `score.py` is where physics gets graded.
30
+
31
+ It is also **not** a proof of authenticity. The digests live in `index.jsonl`,
32
+ inside the same download, so anyone who can rewrite a data file can rewrite its
33
+ digest to match. This detects corruption, truncation and inconsistent editing;
34
+ it does not detect deliberate substitution. Compare against the published
35
+ commit on the Hub if that is what you need.
36
+
37
+ Exit status is 0 if everything holds and 1 otherwise, so it is usable in CI.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import hashlib
43
+ import json
44
+ import pathlib
45
+ import re
46
+ import sys
47
+
48
+ HERE = pathlib.Path(__file__).resolve().parent
49
+ DATA = HERE / "data"
50
+
51
+ LAWS = {
52
+ "passivity",
53
+ "reciprocity",
54
+ "energy_conservation",
55
+ "positive_real_z0",
56
+ "group_delay_nonneg",
57
+ }
58
+
59
+
60
+ def parse_touchstone(path: pathlib.Path) -> tuple[int, float, int]:
61
+ """Return (n_ports, z0_ohm, n_points) from a Touchstone 1.x file.
62
+
63
+ In Touchstone 1.x the port count lives in the extension (`.s2p`, `.s4p`) --
64
+ it is not derivable from the payload, because a 2-port's row stride of 9
65
+ numbers is divisible by a 1-port's stride of 3, so counting alone would
66
+ happily mis-read every 2-port file as a 1-port. The extension is the
67
+ authority; the payload is then checked for consistency with it.
68
+ """
69
+ m = re.fullmatch(r"\.s(\d+)p", path.suffix, re.I)
70
+ if not m:
71
+ raise ValueError(f"{path.name}: not a Touchstone .sNp filename")
72
+ n_ports = int(m.group(1))
73
+
74
+ z0 = 50.0
75
+ values: list[float] = []
76
+ for raw in path.read_text(encoding="utf-8").splitlines():
77
+ line = raw.split("!", 1)[0].strip()
78
+ if not line:
79
+ continue
80
+ if line.startswith("#"):
81
+ opt = re.search(r"\bR\s*([0-9.eE+-]+)", line, re.I)
82
+ if opt:
83
+ z0 = float(opt.group(1))
84
+ continue
85
+ values.extend(float(tok) for tok in line.split())
86
+
87
+ # One row is: frequency, then a real/imag pair per S-parameter.
88
+ stride = 1 + 2 * n_ports * n_ports
89
+ if not values or len(values) % stride:
90
+ raise ValueError(
91
+ f"{path.name}: {len(values)} numbers is not a whole number of "
92
+ f"{n_ports}-port rows (stride {stride})"
93
+ )
94
+ return n_ports, z0, len(values) // stride
95
+
96
+
97
+ def main() -> int:
98
+ problems: list[str] = []
99
+
100
+ index_path = DATA / "index.jsonl"
101
+ if not index_path.exists():
102
+ print(f"FATAL: {index_path} is missing", file=sys.stderr)
103
+ return 1
104
+ rows = [json.loads(line) for line in index_path.read_text(encoding="utf-8").splitlines() if line.strip()]
105
+
106
+ for row in rows:
107
+ name = row["name"]
108
+ f = DATA / row["file"]
109
+
110
+ if not f.exists():
111
+ problems.append(f"{name}: file {row['file']} is missing")
112
+ continue
113
+
114
+ digest = hashlib.sha256(f.read_bytes()).hexdigest()
115
+ if digest != row["sha256"]:
116
+ problems.append(f"{name}: sha256 mismatch (file has been altered)")
117
+
118
+ fails = row["expected_failures"]
119
+ unknown = set(fails) - LAWS
120
+ if unknown:
121
+ problems.append(f"{name}: names laws that do not exist: {sorted(unknown)}")
122
+ if row["expected_to_pass_all_laws"] and fails:
123
+ problems.append(f"{name}: labelled as passing all laws but lists failures {fails}")
124
+ if not row["expected_to_pass_all_laws"] and not fails:
125
+ problems.append(f"{name}: labelled as failing but names no law")
126
+
127
+ try:
128
+ n_ports, z0, n_points = parse_touchstone(f)
129
+ except ValueError as exc:
130
+ problems.append(f"{name}: {exc}")
131
+ continue
132
+ if n_ports != row["n_ports"]:
133
+ problems.append(f"{name}: index says {row['n_ports']}-port, file parses as {n_ports}-port")
134
+ if abs(z0 - row["z0_ohm"]) > 1e-9:
135
+ problems.append(f"{name}: index says z0={row['z0_ohm']}, file declares {z0}")
136
+
137
+ manifest_path = DATA / "manifest.json"
138
+ if not manifest_path.exists():
139
+ problems.append("data/manifest.json is missing")
140
+ else:
141
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
142
+ in_manifest = {c["name"] for c in manifest.get("cases", [])}
143
+ in_index = {r["name"] for r in rows}
144
+ if in_manifest != in_index:
145
+ only_m = sorted(in_manifest - in_index)
146
+ only_i = sorted(in_index - in_manifest)
147
+ problems.append(f"manifest/index disagree (manifest-only={only_m}, index-only={only_i})")
148
+
149
+ realizable = sum(1 for r in rows if r["physically_realizable"])
150
+ print("sparam-conformance corpus verification (stdlib only)\n")
151
+ print(f" cases {len(rows)}")
152
+ print(f" physically valid {realizable}")
153
+ print(f" physically invalid {len(rows) - realizable}")
154
+ print(f" laws {len(LAWS)}")
155
+ matched = sum(
156
+ 1
157
+ for r in rows
158
+ if (DATA / r["file"]).exists()
159
+ and hashlib.sha256((DATA / r["file"]).read_bytes()).hexdigest() == r["sha256"]
160
+ )
161
+ print(f" sha256 matched {matched}/{len(rows)}")
162
+ print()
163
+
164
+ if problems:
165
+ print(f" INCONSISTENT -- {len(problems)} problem(s):\n")
166
+ for p in problems:
167
+ print(f" - {p}")
168
+ return 1
169
+
170
+ print(" self-consistent: every file matches its recorded digest, and every")
171
+ print(" label agrees with itself")
172
+ print()
173
+ print(" scope: internal consistency only. The digests ship in this download,")
174
+ print(" so this detects corruption, not substitution. It does not re-derive")
175
+ print(" the physics -- run score.py against a checker for that.")
176
+ return 0
177
+
178
+
179
+ if __name__ == "__main__":
180
+ raise SystemExit(main())