File size: 7,045 Bytes
e85b663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Procedure-fidelity gates for kcnuX4xEpL reproduction.

Usage:
    python3 gates.py exp01 --toy      # structural checks, relaxed params
    python3 gates.py exp01 --full     # structural checks + exact full-scale params
    python3 gates.py exp01 --full --report

Gates verify STRUCTURE / SHAPES / SCHEMA / RANGES / (synthetic) PROVENANCE only.
They NEVER encode expected paper outcomes (no beta==1/(d+2) assertions).
"""
import json, os, sys, math

RESULTS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "results", "exp01.json")

FULL = {
    "N": 2000, "M": 2000, "R": 10, "d_grid": [100, 200, 500, 1000],
    "eps_multipliers": [1e-8, 5e-8, 1e-7, 5e-7, 1e-6, 5e-6, 1e-5, 5e-5, 1e-4, 5e-4],
    "initTol": 0.01, "tau": 1e-12, "base": 1.00005, "a": 0,
    "solvers": ["nonlinear_gauss_seidel", "semismooth_newton"],
}
K = 10


def _num(x):
    return isinstance(x, (int, float)) and not isinstance(x, bool)


def check(results, toy, report):
    C = []  # (name, ok, detail)

    def add(name, ok, detail=""):
        C.append((name, bool(ok), detail))

    m = results.get("meta", {})
    add("meta present", isinstance(m, dict) and len(m) > 0)

    # ---- synthetic provenance (this paper uses a SYNTHETIC family, no real dataset) ----
    add("provenance: base==1.00005", m.get("base") == 1.00005, str(m.get("base")))
    add("provenance: a==0", m.get("a") == 0)
    add("provenance: tau==1e-12", m.get("tau") == 1e-12)
    add("provenance: initTol==0.01", m.get("initTol") == 0.01)
    add("provenance: solvers set",
        m.get("solvers") == FULL["solvers"], str(m.get("solvers")))
    em = m.get("eps_multipliers", [])
    add("eps_multipliers length 10", isinstance(em, list) and len(em) == K)
    if isinstance(em, list) and len(em) == K:
        okm = all(abs(a - b) <= 1e-9 * max(1, abs(b)) for a, b in zip(em, FULL["eps_multipliers"]))
        add("eps_multipliers match spec grid", okm, str(em))

    if not toy:
        add("full: N==2000", m.get("N") == 2000)
        add("full: M==2000", m.get("M") == 2000)
        add("full: R==10", m.get("R") == 10)
        add("full: d_grid exact", m.get("d_grid") == FULL["d_grid"], str(m.get("d_grid")))
    else:
        add("toy: N present int", _num(m.get("N")))
        add("toy: d_grid nonempty", isinstance(m.get("d_grid"), list) and len(m.get("d_grid")) >= 1)

    d_grid = m.get("d_grid", []) if isinstance(m.get("d_grid"), list) else []
    solvers = m.get("solvers", []) if isinstance(m.get("solvers"), list) else []
    R = m.get("R", 0)

    # ---- records ----
    recs = results.get("records", [])
    add("records is list nonempty", isinstance(recs, list) and len(recs) > 0)
    if not isinstance(recs, list):
        recs = []

    if not toy and d_grid and solvers and _num(R):
        add("full: record count == len(d_grid)*R*len(solvers)",
            len(recs) == len(d_grid) * R * len(solvers),
            f"{len(recs)} vs {len(d_grid) * R * len(solvers)}")

    fields = ["d", "seed", "solver", "c_med", "eps_actual", "dbias", "converged",
              "n_active", "beta_hat", "alpha_hat", "rel_err"]
    all_shape_ok = True
    all_range_ok = True
    seen = set()
    for r in recs:
        if not isinstance(r, dict):
            all_shape_ok = False
            continue
        if not all(f in r for f in fields):
            all_shape_ok = False
            continue
        seen.add((r.get("d"), r.get("seed"), r.get("solver")))
        for arr in ("eps_actual", "dbias", "converged", "n_active"):
            v = r.get(arr)
            if not (isinstance(v, list) and len(v) == K):
                all_shape_ok = False
        # ranges
        if not (_num(r.get("c_med")) and r["c_med"] > 0):
            all_range_ok = False
        ea = r.get("eps_actual", [])
        if isinstance(ea, list) and all(_num(x) and x > 0 for x in ea):
            pass
        else:
            all_range_ok = False
        db = r.get("dbias", [])
        if isinstance(db, list):
            for x in db:
                if x is None:
                    continue
                if not (_num(x) and x >= 0 and math.isfinite(x)):
                    all_range_ok = False
        if not (_num(r.get("beta_hat")) and math.isfinite(r["beta_hat"])):
            all_range_ok = False
        if r.get("solver") not in solvers:
            all_range_ok = False
        if r.get("d") not in d_grid:
            all_range_ok = False
    add("all records have required fields", all_shape_ok)
    add("all record arrays length 10", all_shape_ok)
    add("record ranges sane (c_med>0, eps>0, dbias>=0/null, beta finite)", all_range_ok)

    if not toy and d_grid and solvers and _num(R):
        expected = {(d, s, sv) for d in d_grid for s in range(R) for sv in solvers}
        add("full: (d,seed,solver) grid complete", seen == expected,
            f"missing {len(expected - seen)}")

    # ---- summary ----
    summ = results.get("summary", [])
    add("summary is list nonempty", isinstance(summ, list) and len(summ) > 0)
    if isinstance(summ, list):
        sok = True
        for s in summ:
            if not isinstance(s, dict):
                sok = False
                continue
            for f in ("d", "solver", "theory", "beta_mean", "beta_std",
                      "rel_err_mean", "rel_err_std"):
                if f not in s:
                    sok = False
            if _num(s.get("d")) and _num(s.get("theory")):
                if abs(s["theory"] - 1.0 / (s["d"] + 2)) > 1e-9:
                    sok = False  # theory column must equal 1/(d+2) (definition, not outcome)
        add("summary rows well-formed; theory==1/(d+2)", sok)
        if not toy and d_grid and solvers:
            add("full: summary has len(d_grid)*len(solvers) rows",
                len(summ) == len(d_grid) * len(solvers),
                f"{len(summ)} vs {len(d_grid) * len(solvers)}")

    ok = all(c[1] for c in C)
    if report:
        print(f"=== gates report exp01 ({'toy' if toy else 'full'}) ===")
        for name, cok, detail in C:
            print(f"  [{'PASS' if cok else 'FAIL'}] {name}" + (f"  ({detail})" if detail and not cok else ""))
        print(f"=== {'ALL PASS' if ok else 'FAILURES PRESENT'} ({sum(c[1] for c in C)}/{len(C)}) ===")
    return ok


def main():
    args = sys.argv[1:]
    if not args or args[0] != "exp01":
        print("usage: python3 gates.py exp01 --toy|--full [--report]")
        sys.exit(2)
    toy = "--toy" in args
    full = "--full" in args
    if toy == full:
        print("specify exactly one of --toy / --full")
        sys.exit(2)
    report = "--report" in args
    if not os.path.exists(RESULTS):
        print(f"[FAIL] results file missing: {RESULTS}")
        sys.exit(1)
    try:
        with open(RESULTS) as f:
            results = json.load(f)
    except Exception as e:
        print(f"[FAIL] cannot parse {RESULTS}: {e}")
        sys.exit(1)
    ok = check(results, toy=toy, report=report or True)
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()