File size: 6,227 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
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
"""The scoring contract (single source of truth for self-eval and official eval).

Harness-compatible: `score.py eval --solver NAME` reads KEA_SEED to pick the
tolerance and prints exactly one `METRIC work_log=<value>` line (plus
human-readable `#` comment lines). Kea's define_evaluator/evaluate_solution
parse this format; direction = minimize.

Scoring rule (frozen in contract.py):
  success = solver reached t1 AND final err <= slack * tol
  work    = nfev + gamma * njev            (success)
          = budget + gamma * njev          (failure/over-budget)
  metric  = mean over all 11 problems of log10(work)
"""
import argparse, json, os, sys
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import contract
from problems import PROBLEMS
from dopri5 import Dopri5
from scipy.integrate import solve_ivp

P = contract.PARAMS
TOLS = P["tols"]
GAMMA = P["jacobian_weight"]
BUDGET = P["budget_nfe"]
SLACK = P["error_slack"]

REFS_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "benchmarks", "refs.json")

_REFS = None
def load_refs():
    global _REFS
    if _REFS is None:
        if not os.path.exists(REFS_FILE):
            raise RuntimeError("references missing - run reference.py first")
        raw = json.load(open(REFS_FILE))
        _REFS = raw["problems"] if "problems" in raw else raw  # tolerate both layouts
    return _REFS

_REF_Y = None
def get_ref_y(name):
    global _REF_Y
    if _REF_Y is None:
        _REF_Y = {n: v["yT"] for n, v in load_refs().items() if v.get("ok")}
    return np.asarray(_REF_Y[name], float)

def rel_err(y, yref):
    yref = np.asarray(yref, float)
    return float(np.max(np.abs(y - yref)) / (1.0 + np.max(np.abs(yref))))

def run_scipy_solver(p, method, tol):
    """Baseline via scipy solve_ivp; returns (success, err, nfev, njev, detail)."""
    method = {"rk45": "RK45", "lsoda": "LSODA", "radau": "Radau", "bdf": "BDF"}.get(method, method)
    n_calls = [0]
    def fun(t, y):
        n_calls[0] += 1
        if n_calls[0] > int(1.2 * BUDGET):
            raise RuntimeError(f"nfev budget {BUDGET} exceeded")
        return p.f(t, y)
    _mm = {"rk45": "RK45", "lsoda": "LSODA", "radau": "Radau", "bdf": "BDF"}
    try:
        sol = solve_ivp(fun, (p.t0, p.t1), p.y0(),
                        method=_mm.get(method, method), rtol=tol, atol=tol, dense_output=False,
                        max_step=np.inf)
        nfev, njev = int(sol.nfev), int(sol.njev)
        reached = bool(sol.success) and sol.t.size and sol.t[-1] >= p.t1 - 1e-12 * max(1.0, abs(p.t1))
        if not reached or nfev > BUDGET:
            return False, np.inf, nfev, njev, f"{sol.message} reached={reached}"
        err = rel_err(sol.y[:, -1], get_ref_y(p.name))
        return err <= SLACK * tol, err, nfev, njev, sol.message
    except Exception as e:
        return False, np.inf, 0, 0, repr(e)

def run_dopri5(p, tol):
    """My DOPRI5 (pure explicit, no switching)."""
    try:
        m = Dopri5(p.f, p.y0(), p.t0, p.t1, rtol=tol, atol=tol,
                   max_step=np.inf, max_steps=BUDGET).integrate()
        nfev = m.nfev
        if m.status != "finished" or m.t < p.t1 - 1e-12 * max(1.0, abs(p.t1)) or nfev > BUDGET:
            return False, np.inf, nfev, 0, f"status={m.status} t={m.t}"
        err = rel_err(m.y, get_ref_y(p.name))
        return err <= SLACK * tol, err, nfev, 0, m.status
    except Exception as e:
        return False, np.inf, 0, 0, repr(e)

def _switch_dispatch(p, tol, cfg_name):
    from switcher import SWITCH_CONFIGS, solve_switched
    cfg = SWITCH_CONFIGS[cfg_name]
    return solve_switched(p, tol, cfg, get_ref_y(p.name))

def eval_solver(solver, tol, verbose=True):
    """Evaluate one solver on all problems at one tolerance."""
    works = []
    details = {}
    for name, cls in PROBLEMS.items():
        if name not in load_refs():
            continue  # excluded problem (no verifiable reference)
        p = cls()
        if load_refs()[name].get("ok") is not True:
            raise RuntimeError(f"problem {name} has no verified reference")
        if solver in ("rk45", "lsoda", "radau", "bdf"):
            ok, err, nfev, njev, msg = run_scipy_solver(p, solver, tol)
        elif solver == "dopri5":
            ok, err, nfev, njev, msg = run_dopri5(p, tol)
        elif solver.startswith("switch_") or solver == "oracle_switch":
            ok, err, nfev, njev, msg = _switch_dispatch(p, tol, solver)
        else:
            raise ValueError(f"unknown solver {solver}")
        work = nfev + GAMMA * njev if ok else BUDGET + GAMMA * njev
        works.append(work)
        details[name] = {"ok": ok, "err": None if err == np.inf else float(err),
                         "nfev": nfev, "njev": njev, "work": work, "msg": str(msg)[:80]}
        if verbose:
            print(f"# {name:8s} ok={int(ok)} err={err if err==np.inf else f'{err:.2e}':>12} "
                  f"nfev={nfev:>9} njev={njev:>5} work={work:>10.1f}", flush=True)
    metric = float(np.mean(np.log10(works)))
    if verbose:
        print(f"METRIC {P['metric']['name']}={metric}")
    return {"tol": tol, "metric": metric, "per_problem": details, "works": works}

def main():
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)
    ev = sub.add_parser("eval")
    ev.add_argument("--solver", required=True)
    ev.add_argument("--tol", type=float, default=None)
    ev.add_argument("--quiet", action="store_true")
    ev.add_argument("--json", action="store_true")
    sub.add_parser("list")
    a = ap.parse_args()

    if a.cmd == "list":
        from switcher import SWITCH_CONFIGS
        print("baselines: rk45 lsoda radau bdf dopri5")
        print("candidates:", " ".join(sorted(SWITCH_CONFIGS)))
        return

    if not get_ref_y(next(iter(load_refs()))):
        pass  # populated lazily; existence of refs checked below

    seed = os.environ.get("KEA_SEED", "1")
    tol = a.tol if a.tol is not None else TOLS.get(seed, 1e-6)
    if a.json:
        out = eval_solver(a.solver, tol, verbose=not a.quiet)
        print(json.dumps(out, indent=2))
    else:
        eval_solver(a.solver, tol, verbose=not a.quiet)

if __name__ == "__main__":
    main()