File size: 4,895 Bytes
e1dc886
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reference solutions (protocol documented in REPRODUCE.md).

stiff problems  : y_T = BDF(1e-12)  verified against Radau(1e-12), gate 1e-10.
non-stiff        : y_T = DOP853(1e-12) verified against DOP853(1e-11)
                   (Richardson-style self-consistency), gate 1e-10.
kepler           : y_T = DOP853(1e-13) vs DOP853(1e-12), gate 1e-10
                   (e=0.1 periapse still degrades error by ~10x per tol decade).

Rationale: on oscillatory/periodic problems scipy's implicit multi-step solvers
saturate near roundoff at ~1e-7..1e-8 global error, so cross-method agreement
is unattainable; explicit high-order DOP853 reaches 1e-11..1e-12. On stiff
problems explicit methods fail outright, so the implicit pair is used. Any
problem failing its gate is excluded from scoring (fail-closed).
"""
import json, os, sys, time
import numpy as np
from scipy.integrate import solve_ivp
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from problems import PROBLEMS

OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "benchmarks", "refs.json")
PROTOCOL = {
    # problem -> (methodA, tolA, methodB, tolB, gate)
    "vdp5":    ("DOP853", 1e-12, "DOP853", 1e-11, 1e-10),
    "bruss":   ("DOP853", 1e-12, "DOP853", 1e-11, 1e-10),
    "lotka":   ("DOP853", 1e-12, "DOP853", 1e-11, 1e-10),
    "kepler":  ("DOP853", 1e-13, "DOP853", 1e-12, 1e-10),
    "rossler": ("DOP853", 1e-12, "DOP853", 1e-11, 1e-10),
    "vdp100":  ("DOP853", 1e-12, "Radau", 1e-12, 1e-10),
    "rober":   ("BDF", 1e-12, "Radau", 1e-12, 1e-10),
    "orego":   ("BDF", 1e-12, "Radau", 1e-12, 1e-10),
    "hires":   ("BDF", 1e-12, "Radau", 1e-12, 1e-10),
    # 392-dim PDE: BDF/Radau@1e-12 agree to 7.9e-10; gate relaxed to 1% of the
    # tightest success threshold (SLACK*tol = 1e-7), i.e. 1e-9.
    "bruss2d": ("BDF", 1e-12, "Radau", 1e-12, 1e-9),
    # pollu: excluded - no solver family yields a verifiable reference
    # (BDF/Radau/LSODA overflow or underflow step at rtol<=5e-12).
}
EXCLUDED = {"pollu"}
GATE_NOTE = "gates: default 1e-10; bruss2d 1e-9 (<=1% of SLACK*tol_min=1e-7)"

def run_solver(p, method, tol, budget=2_000_000):
    n_calls = [0]
    def fun(t, y):
        n_calls[0] += 1
        if n_calls[0] > budget:
            raise RuntimeError(f"f-eval budget exceeded")
        return p.f(t, y)
    t0 = time.time()
    try:
        sol = solve_ivp(fun, (p.t0, p.t1), p.y0(), method=method,
                        rtol=tol, atol=tol, dense_output=False, max_step=np.inf)
        ok = bool(sol.success) and sol.t.size and sol.t[-1] >= p.t1 - 1e-12 * max(1.0, abs(p.t1))
        return {"ok": ok, "yT": sol.y[:, -1].tolist() if sol.t.size else None,
                "nfev": int(sol.nfev), "njev": int(sol.njev),
                "msg": str(sol.message), "wall_s": time.time() - t0}
    except Exception as e:
        return {"ok": False, "yT": None, "nfev": n_calls[0], "njev": 0,
                "msg": repr(e)[:100], "wall_s": time.time() - t0}

def rel(a, b):
    a = np.asarray(a); b = np.asarray(b)
    return float(np.max(np.abs(a - b)) / (1.0 + np.max(np.abs(a))))

def main():
    out = {"_meta": {"gate_note": GATE_NOTE, "excluded": sorted(EXCLUDED)},
           "problems": {}}
    # resume: keep already-verified problems from a previous run
    if os.path.exists(OUT):
        try:
            prev = json.load(open(OUT))
            out["problems"] = {n: v for n, v in prev.get("problems", {}).items() if v.get("ok")}
            print(f"resuming with {len(out['problems'])} verified problems", flush=True)
        except Exception:
            pass
    for name, cls in PROBLEMS.items():
        p = cls()
        if name in out["problems"]:
            print(f"{name:8s} already verified - skipping", flush=True)
            continue
        if name in EXCLUDED:
            print(f"{name:8s} EXCLUDED (no verifiable reference)", flush=True)
            continue
        mA, tA, mB, tB, gate = PROTOCOL[name]
        rA = run_solver(p, mA, tA)
        rB = run_solver(p, mB, tB)
        agree = rel(rA["yT"], rB["yT"]) if (rA["ok"] and rB["ok"]) else None
        entry = {"protocol": f"{mA}@{tA:g}-vs-{mB}@{tB:g}", "res": {f"{mA}@{tA:g}": rA, f"{mB}@{tB:g}": rB},
                 "agree": agree, "yT": rA["yT"], "ok": agree is not None and agree <= gate}
        out["problems"][name] = entry
        print(f"{name:8s} {mA}@{tA:g}/{mB}@{tB:g} agree={agree if agree is None else f'{agree:.2e}'} OK={entry['ok']} "
              f"nfev={rA['nfev']},{rB['nfev']}", flush=True)
    with open(OUT, "w") as f:
        json.dump(out, f, indent=2, default=lambda o: bool(o) if isinstance(o, (bool,)) else str(o))
    nok = sum(1 for v in out["problems"].values() if v["ok"])
    print(f"\n{nok}/{len(PROBLEMS) - len(EXCLUDED)} problems have verified references -> {OUT}")
    sys.exit(0 if nok == len(out) else 1)

if __name__ == "__main__":
    main()