screening-ceiling / export.py
nickh007's picture
Give every text read an explicit encoding
3c9b419 verified
Raw
History Blame Contribute Delete
10 kB
#!/usr/bin/env python3
"""Export the screening-ceiling dataset from committed source artifacts.
Two very different kinds of row come out of this, and keeping them straight is
the whole point of the dataset:
certified_regions.jsonl -- a UNIVERSAL claim. 256 sub-boxes of a 4-parameter
family, each certified by outward-rounded interval branch-and-bound to
contain NO layout whose screening factor exceeds k_bar. Exported from a
committed proof witness; provenance recorded by digest.
counterexamples.jsonl -- an EXISTENTIAL refutation. Concrete layouts where
a second-order Born extractor predicts k > 1, which no passive
arrangement of conductors can do. Generated here by running the
open-source `maxwell-lint` reference models, so every row is reproducible
from published code alone.
Run:
python3 export.py # writes data/
python3 export.py --check # verify existing data, write nothing
"""
from __future__ import annotations
import argparse
import hashlib
import json
import pathlib
import sys
HERE = pathlib.Path(__file__).resolve().parent
DATA = HERE / "data"
REPO = HERE.parents[2]
WITNESS = REPO / "benchmarks" / "impossibility" / \
"family_two_tight_pairs_k10pct_parallel_2026_07.json"
DIM_NAMES = ["d0_um", "pt_mult", "sep_mult", "jog_mult"]
# Reproduced verbatim from the source witness so the published scope statement
# cannot drift from the one the proof was run under.
HONEST_SCOPE = (
"A complete interval theorem about the frozen MONOPOLE-CLOSURE model only. "
"The closure-vs-BEM/PDE model gap remains additive and unresolved. This "
"witness does not establish Maxwell, BEM, driven-S, fabrication, or "
"measured-silicon truth."
)
def sha256(path: pathlib.Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
# --------------------------------------------------------------- certified regions
def export_certified_regions(w: dict) -> list[dict]:
"""One row per certified root region of the branch-and-bound partition.
The witness stores the 256-region partition with per-region certification
rather than all 237,490 leaves. That is what gets published, and the
distinction is stated rather than glossed: each row is a region the prover
certified, together with how many leaves it took and the largest screening
factor the interval enclosure admitted anywhere inside it.
"""
rows = []
for r in w["root_results"]:
rows.append({
"region_id": r["root_id"],
"bounds": {n: {"lo": lo, "hi": hi}
for n, (lo, hi) in zip(DIM_NAMES, r["box"])},
"status": r["status"],
"certified_leaves": r["certified_boxes"],
"processed_leaves": r["processed_boxes"],
"sup_certified_k_hi": r["sup_certified_k_hi"],
"volume_fraction_of_region": r["certified_volume_frac_of_root"],
"unresolved_leaves": r["unresolved_count"],
})
return rows
# ----------------------------------------------------------------- counterexamples
def export_counterexamples() -> list[dict]:
"""Concrete layouts where a plausible cheap extractor predicts k > 1.
Generated by running the published `maxwell-lint` reference models, so a
reader can regenerate every row without this repository. Full coordinates
are emitted -- a counterexample you cannot rebuild is an anecdote.
"""
try:
import numpy as np
from maxwell_lint.models import (
born_second_order,
isolated_pair_matrix,
random_layout,
)
except ImportError as exc: # pragma: no cover - exercised by the CLI path
raise SystemExit(
f"counterexample export needs maxwell-lint installed: {exc}\n"
" pip install ../../maxwell-lint") from exc
rows = []
for n in (6, 8, 12):
for pitch in (60.0, 80.0, 100.0):
for seed in range(4):
lay = random_layout(n, seed=seed, pitch_um=pitch)
full = born_second_order(lay)
iso = isolated_pair_matrix(lay)
with np.errstate(divide="ignore", invalid="ignore"):
k = np.where(iso > 0, full / iso, 0.0)
np.fill_diagonal(k, 0.0)
i, j = np.unravel_index(int(np.argmax(k)), k.shape)
kmax = float(k[i, j])
if kmax <= 1.0:
continue
rows.append({
"case_id": f"born2_n{n}_p{int(pitch)}_s{seed}",
"model": "born_second_order",
"n_conductors": int(n),
"nominal_pitch_um": pitch,
"seed": int(seed),
"worst_pair": [int(i), int(j)],
"k_predicted": kmax,
"violates_ceiling": True,
"n_pairs_violating": int((k > 1.0).sum()),
"n_pairs_total": int(n * (n - 1)),
"xy_um": [[float(x * 1e6), float(y * 1e6)] for x, y in lay.xy],
"radius_um": [float(r * 1e6) for r in lay.radius],
"eps_r": float(lay.eps_r),
})
return rows
# ------------------------------------------------------------------------ theorem
def export_theorem(w: dict) -> dict:
return {
"family": w["family"],
"parameters": DIM_NAMES,
# the top-level box is keyed by name; the per-region boxes are positional
"family_box": {n: {"lo": w["box"][n][0], "hi": w["box"][n][1]}
for n in DIM_NAMES},
"k_bar": w["k_bar"],
"statement": (
"For every layout in the family box, the monopole-closure many-body "
f"screening factor satisfies k <= {w['k_bar']:.12f}. A pairwise-"
"superposition extractor assumes k == 1, so it over-predicts the worst "
f"coupling by at least {100.0 / w['k_bar'] - 100.0:.4f}% on every "
"member of the family."
),
# Derived from the supremum the proof actually certified, not from the
# target bound -- so it is very slightly STRONGER than 100/k_bar - 100
# (10.000002% vs 10.000000%). Recorded explicitly because a reader who
# divides by k_bar and gets a different last digit deserves an answer.
"forced_pairwise_overprediction_pct": w["forced_pairwise_overprediction_pct"],
"forced_pairwise_overprediction_basis": "sup_certified_k_hi",
"certified_leaves_total": w["certified_boxes"],
"processed_leaves_total": w["processed_boxes"],
"certified_volume_fraction": w["certified_volume_frac"],
"failure_regions": w["n_failure_regions"],
"open_boxes": w["open_boxes"],
"sup_certified_k_hi": w["sup_certified_k_hi"],
"enclosure_mode": w["enclosure_mode"],
"status": w["status"],
"honest_scope": HONEST_SCOPE,
"geometry": {
"description": (
"Four parallel circular conductors forming two tight pairs. "
"pitch = 1.6 * d0 * pt_mult; separation = pitch * sep_mult; "
"jog = jog_mult * separation. Conductor centres at (0,0), "
"(pitch,0), (separation,jog), (separation+pitch,jog); every "
"conductor has diameter d0."
),
"units": "d0_um in micrometres; the multipliers are dimensionless",
"self_term_radius_scale": 1.0,
},
"provenance": {
"source_witness": WITNESS.name,
"source_sha256": sha256(WITNESS),
"witness_content_sha256": w["content_sha256"],
"schema": w["schema"],
"prover_wall_seconds": w["wall_s"],
"partition_regions": w["root_count"],
},
}
def write_jsonl(path: pathlib.Path, rows: list[dict]) -> None:
with path.open("w", encoding="utf-8", newline="\n") as fh:
for r in rows:
fh.write(json.dumps(r, sort_keys=True) + "\n")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--check", action="store_true",
help="verify the committed data instead of rewriting it")
args = ap.parse_args()
if not WITNESS.exists():
print(f"source witness not found: {WITNESS}", file=sys.stderr)
print("(export requires the source repository; the published data files "
"stand alone)", file=sys.stderr)
return 2
w = json.loads(WITNESS.read_text(encoding="utf-8"))
regions = export_certified_regions(w)
theorem = export_theorem(w)
counters = export_counterexamples()
if args.check:
old_r = [json.loads(x) for x in
(DATA / "certified_regions.jsonl").read_text(encoding="utf-8").splitlines()]
old_c = [json.loads(x) for x in
(DATA / "counterexamples.jsonl").read_text(encoding="utf-8").splitlines()]
old_t = json.loads((DATA / "theorem.json").read_text(encoding="utf-8"))
ok = (old_r == regions and old_c == counters and old_t == theorem)
print("data matches a fresh export" if ok else "DATA DRIFT")
return 0 if ok else 1
DATA.mkdir(parents=True, exist_ok=True)
write_jsonl(DATA / "certified_regions.jsonl", regions)
write_jsonl(DATA / "counterexamples.jsonl", counters)
(DATA / "theorem.json").write_text(
json.dumps(theorem, indent=2, sort_keys=True) + "\n",
encoding="utf-8", newline="\n")
n_viol = sum(r["n_pairs_violating"] for r in counters)
print(f"certified_regions.jsonl {len(regions)} regions "
f"({theorem['certified_leaves_total']} leaves)")
print(f"counterexamples.jsonl {len(counters)} layouts "
f"({n_viol} violating pairs)")
print(f"theorem.json k_bar = {theorem['k_bar']:.12f}")
return 0
if __name__ == "__main__":
raise SystemExit(main())