File size: 10,898 Bytes
4415131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c769d5a
4415131
c769d5a
 
4415131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env python3
"""Independently re-derive the screening-ceiling dataset. Zero dependencies.

Standard library only -- no numpy, no maxwell-lint, nothing from the repository
that produced the data. Point it at `data/` and it rebuilds the physics from the
published geometry and checks both claims:

  * the UNIVERSAL claim, by sampling inside every certified region and confirming
    no sampled layout exceeds k_bar;
  * the EXISTENTIAL claim, by recomputing each counterexample from its stored
    coordinates and confirming the extractor really does predict k > 1.

Sampling cannot prove the universal claim -- that is what the interval
branch-and-bound in the source proof is for, and no amount of sampling
substitutes for it. What sampling can do is REFUTE it, and that is the useful
thing an independent reader wants: a cheap, dependency-free way to try to catch
us being wrong.

Run:
    python3 verify.py                # check the committed data
    python3 verify.py --samples 200  # sample harder
    python3 verify.py --self-test    # prove the checker still discriminates
"""
from __future__ import annotations

import argparse
import json
import math
import pathlib
import random
import sys

HERE = pathlib.Path(__file__).resolve().parent
DATA = HERE / "data"


# ------------------------------------------------------------------ linear algebra

def inverse(m: list[list[float]]) -> list[list[float]]:
    """Gauss-Jordan inverse with partial pivoting. Small dense matrices only."""
    n = len(m)
    a = [row[:] + [1.0 if i == j else 0.0 for j in range(n)] for i, row in enumerate(m)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(a[r][col]))
        if abs(a[piv][col]) < 1e-300:
            raise ZeroDivisionError("singular potential matrix")
        a[col], a[piv] = a[piv], a[col]
        d = a[col][col]
        a[col] = [x / d for x in a[col]]
        for r in range(n):
            if r == col:
                continue
            f = a[r][col]
            if f:
                a[r] = [x - f * y for x, y in zip(a[r], a[col])]
    return [row[n:] for row in a]


# ---------------------------------------------------------------------- physics

def potential_matrix(xy: list[list[float]], radius: list[float]) -> list[list[float]]:
    """Maxwell potential coefficients, thin-wire/monopole form.

    The 1/(2*pi*eps0*eps_r) prefactor is omitted deliberately: k is a ratio of
    two capacitances computed from the same medium, so the prefactor cancels
    exactly. Carrying it would only add rounding.
    """
    n = len(xy)
    p = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if i == j:
                p[i][j] = -math.log(radius[i])
            else:
                dx = xy[i][0] - xy[j][0]
                dy = xy[i][1] - xy[j][1]
                p[i][j] = -math.log(math.hypot(dx, dy))
    return p


def isolated_pair_coupling(ri: float, rj: float, r: float) -> float:
    """|C_ij| for the pair alone -- the denominator of k."""
    p = [[-math.log(ri), -math.log(r)], [-math.log(r), -math.log(rj)]]
    return abs(inverse(p)[0][1])


def screening_factors(xy: list[list[float]], radius: list[float]) -> list[list[float]]:
    """k_ij = |C_ij(full array)| / |C_ij(pair alone)| for every off-diagonal pair."""
    n = len(xy)
    c = inverse(potential_matrix(xy, radius))
    k = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if i == j:
                continue
            r = math.hypot(xy[i][0] - xy[j][0], xy[i][1] - xy[j][1])
            iso = isolated_pair_coupling(radius[i], radius[j], r)
            k[i][j] = abs(c[i][j]) / iso if iso > 0 else 0.0
    return k


def family_layout(d0_um: float, pt_mult: float, sep_mult: float, jog_mult: float):
    """The two-tight-pairs family geometry, in metres.

    pitch = 1.6 * d0 * pt_mult, separation = pitch * sep_mult, jog = jog_mult *
    separation; four equal conductors of diameter d0 at (0,0), (pitch,0),
    (separation,jog), (separation+pitch,jog).
    """
    pt = 1.6 * d0_um * pt_mult * 1e-6
    sep = pt * sep_mult
    jog = jog_mult * sep
    xy = [[0.0, 0.0], [pt, 0.0], [sep, jog], [sep + pt, jog]]
    return xy, [d0_um * 1e-6 / 2.0] * 4


def max_family_k(d0_um: float, pt_mult: float, sep_mult: float, jog_mult: float) -> float:
    xy, radius = family_layout(d0_um, pt_mult, sep_mult, jog_mult)
    k = screening_factors(xy, radius)
    return max(k[i][j] for i in range(4) for j in range(4) if i != j)


def born_second_order_k(xy, radius) -> list[list[float]]:
    """Re-derive the failing extractor: second-order truncation of the inverse."""
    n = len(xy)
    p = potential_matrix(xy, radius)
    dinv = [[1.0 / p[i][i] if i == j else 0.0 for j in range(n)] for i in range(n)]
    r = [[0.0 if i == j else p[i][j] for j in range(n)] for i in range(n)]
    a = [[sum(dinv[i][t] * r[t][j] for t in range(n)) for j in range(n)] for i in range(n)]
    a2 = [[sum(a[i][t] * a[t][j] for t in range(n)) for j in range(n)] for i in range(n)]
    mid = [[(1.0 if i == j else 0.0) - a[i][j] + a2[i][j] for j in range(n)]
           for i in range(n)]
    approx = [[sum(mid[i][t] * dinv[t][j] for t in range(n)) for j in range(n)]
              for i in range(n)]
    k = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if i == j:
                continue
            d = math.hypot(xy[i][0] - xy[j][0], xy[i][1] - xy[j][1])
            iso = isolated_pair_coupling(radius[i], radius[j], d)
            k[i][j] = abs(approx[i][j]) / iso if iso > 0 else 0.0
    return k


# ---------------------------------------------------------------------- checks

def check_regions(regions, k_bar, samples, rng, verbose=True):
    worst, worst_at, violations = 0.0, None, []
    for reg in regions:
        b = reg["bounds"]
        for _ in range(samples):
            pt = {n: rng.uniform(b[n]["lo"], b[n]["hi"]) for n in b}
            k = max_family_k(pt["d0_um"], pt["pt_mult"], pt["sep_mult"], pt["jog_mult"])
            if k > worst:
                worst, worst_at = k, (reg["region_id"], pt)
            if k > k_bar:
                violations.append({"region": reg["region_id"], "point": pt, "k": k})
    if verbose:
        print(f"  regions            {len(regions)} x {samples} samples "
              f"= {len(regions) * samples} layouts")
        print(f"  worst sampled k    {worst:.12f}   (bound {k_bar:.12f})")
        print(f"  margin to bound    {k_bar - worst:.12f}")
        print(f"  violations         {len(violations)}")
        if worst_at:
            rid, p = worst_at
            print(f"  worst at           region {rid}  "
                  + " ".join(f"{n}={v:.4f}" for n, v in sorted(p.items())))
    return worst, violations


def check_counterexamples(cases, verbose=True):
    confirmed, failed = 0, []
    for c in cases:
        xy = [[x * 1e-6, y * 1e-6] for x, y in c["xy_um"]]
        radius = [r * 1e-6 for r in c["radius_um"]]
        k = born_second_order_k(xy, radius)
        n = len(xy)
        kmax = max(k[i][j] for i in range(n) for j in range(n) if i != j)
        if kmax > 1.0 and abs(kmax - c["k_predicted"]) < 1e-6:
            confirmed += 1
        else:
            failed.append({"case_id": c["case_id"], "recomputed": kmax,
                           "published": c["k_predicted"]})
    if verbose:
        print(f"  counterexamples    {confirmed}/{len(cases)} re-derived "
              f"and confirmed above the ceiling")
        for f in failed[:5]:
            print(f"    MISMATCH {f['case_id']}: "
                  f"recomputed {f['recomputed']:.9f} vs published {f['published']:.9f}")
    return confirmed, failed


def load():
    regions = [json.loads(x) for x in
               (DATA / "certified_regions.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()]
    cases = [json.loads(x) for x in
             (DATA / "counterexamples.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()]
    theorem = json.loads((DATA / "theorem.json").read_text(encoding="utf-8"))
    return regions, cases, theorem


def self_test() -> int:
    """A checker that cannot fail is not a checker. Prove it still discriminates."""
    print("negative control")
    rng = random.Random(0)
    ok = True

    # 1. an impossible bound must be violated by sampling
    regions, _, _ = load()
    _, viol = check_regions(regions[:4], k_bar=0.5, samples=5, rng=rng, verbose=False)
    hit = len(viol) > 0
    print(f"  [{'REJECTED' if hit else 'MISSED  '}] fabricated bound k_bar=0.5")
    ok &= hit

    # 2. a tampered counterexample value must not re-derive
    _, cases, _ = load()
    bad = dict(cases[0], k_predicted=cases[0]["k_predicted"] * 1.5)
    _, failed = check_counterexamples([bad], verbose=False)
    print(f"  [{'REJECTED' if failed else 'MISSED  '}] tampered k_predicted")
    ok &= bool(failed)

    # 3. a layout with the pair alone must give k == 1 (no screening to find)
    xy, radius = [[0.0, 0.0], [1e-4, 0.0]], [2e-5, 2e-5]
    k = screening_factors(xy, radius)[0][1]
    near1 = abs(k - 1.0) < 1e-9
    print(f"  [{'PASSED  ' if near1 else 'FAILED  '}] isolated pair reproduces k = 1 "
          f"({k:.12f})")
    ok &= near1

    print(f"\n  checker discriminates: {ok}")
    return 0 if ok else 3


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--samples", type=int, default=25,
                    help="interior samples per certified region (default 25)")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--self-test", action="store_true")
    args = ap.parse_args()

    if args.self_test:
        return self_test()

    if not DATA.exists():
        print(f"no data directory at {DATA}", file=sys.stderr)
        return 2

    regions, cases, theorem = load()
    k_bar = theorem["k_bar"]
    print("screening-ceiling  independent re-derivation (stdlib only)\n")
    print(f"  claim              k <= {k_bar:.12f} for every layout in the family")
    print(f"  forced error       pairwise over-predicts by >= "
          f"{theorem['forced_pairwise_overprediction_pct']:.4f}%\n")

    rng = random.Random(args.seed)
    worst, violations = check_regions(regions, k_bar, args.samples, rng)
    print()
    confirmed, failed = check_counterexamples(cases)

    bad = bool(violations) or bool(failed)
    print()
    if bad:
        print("  REFUTED -- the published claim does not survive re-derivation")
    else:
        print("  consistent: no sampled layout exceeds the bound, and every "
              "counterexample re-derives")
    print(f"\n  scope: {theorem['honest_scope']}")
    return 1 if bad else 0


if __name__ == "__main__":
    raise SystemExit(main())