"""Adaptive solver: DOPRI5 probe + cheap stiffness detector -> switch to implicit. Work accounting is honest: probe nfev + implicit nfev + gamma*njev, with a cold start for the implicit solver (no warm-start tricks). If the detector never trips, the result is the pure explicit run. """ import sys, os import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from dopri5 import Dopri5 from detectors import make_detectors, spectral_radius, L from scipy.integrate import solve_ivp import contract P = contract.PARAMS GAMMA = P["jacobian_weight"] BUDGET = P["budget_nfe"] SLACK = P["error_slack"] class SwitchConfig: def __init__(self, name, detector, threshold, probe_steps=50, implicit="Radau", direction="above", dwell=1): self.name = name self.detector = detector # "S_rej" | "S_decay" | "S_slope" | "S_shamp" | "S_eig" self.threshold = threshold self.probe_steps = probe_steps # minimum accepted steps before switching allowed self.implicit = implicit self.direction = direction # "above" (signal > thr trips) or "below" (signal < thr trips) self.dwell = dwell # consecutive accepted steps that must satisfy the condition def default_threshold(det): """Starting thresholds; recalibrated in analyze_signals.py.""" return {"S_rej": 0.1, "S_decay": 0.3, "S_slope": 0.02, "S_shamp": 1.0, "S_eig": 0.8}[det] def solve_switched(p, tol, cfg, yref): """Returns (success, err, nfev, njev, detail_dict).""" detail = {} probe = Dopri5(p.f, p.y0(), p.t0, p.t1, rtol=tol, atol=tol, max_step=np.inf, max_steps=BUDGET) dets = make_detectors(p.f) det = dets[cfg.detector] trip_step = None run = 0 # consecutive accepted steps satisfying the trip condition (dwell) try: while probe.status == "running" and probe.n_steps < BUDGET: accepted = probe.step() rec = probe.records[-1] if accepted: det.on_accept(rec) else: det.on_reject(rec) if accepted and det.n_acc >= cfg.probe_steps: s = det.signal() ok = s is not None and ((cfg.direction == "above" and s > cfg.threshold) or (cfg.direction == "below" and s < cfg.threshold)) run = run + 1 if ok else 0 if run >= cfg.dwell: trip_step = det.n_acc break if probe.status == "failed" or (probe.status == "finished" and probe.t < p.t1 - 1e-12 * max(1.0, abs(p.t1))): return False, np.inf, probe.nfev, 0, {**detail, "status": f"probe {probe.status} t={probe.t:.3g}"} jac_extra = int(getattr(det, "n_jac", 0) * (len(probe.y) + 1)) if trip_step is None: err = np.inf ok = probe.t >= p.t1 - 1e-12 * max(1.0, abs(p.t1)) if ok: err = float(np.max(np.abs(probe.y - yref)) / (1.0 + np.max(np.abs(yref)))) # Contract budget rule applies to every arm uniformly (same as # run_dopri5 / run_scipy_solver in score.py): a run whose f-evals # exceed budget_nfe counts as a failure (work = budget + gamma*njev), # never as a success. over_budget = bool(probe.nfev + jac_extra > BUDGET) ok = bool(ok and err <= SLACK * tol and not over_budget) return ok, err, probe.nfev + jac_extra, 0, \ {**detail, "tripped": False, "probe_steps": probe.n_accepted, "trip_step": None, "jac_extra": jac_extra, "over_budget": over_budget} # ---- switch sol = solve_ivp(lambda t, y: p.f(t, y), (probe.t, p.t1), probe.y, method=cfg.implicit, rtol=tol, atol=tol, dense_output=False, max_step=np.inf) nfev2, njev2 = 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)) detail.update({"tripped": True, "probe_steps": probe.n_accepted, "trip_step": trip_step, "dwell": cfg.dwell, "t_switch": float(probe.t), "probe_nfev": probe.nfev, "implicit": cfg.implicit, "nfev2": nfev2, "njev2": njev2, "msg": str(sol.message)[:60]}) total = probe.nfev + nfev2 + jac_extra over_budget = bool(total > BUDGET) if not reached: return False, np.inf, total, njev2, {**detail, "jac_extra": jac_extra, "over_budget": over_budget} err = float(np.max(np.abs(sol.y[:, -1] - yref)) / (1.0 + np.max(np.abs(yref)))) ok = bool(err <= SLACK * tol and not over_budget) return ok, err, total, njev2, {**detail, "jac_extra": jac_extra, "over_budget": over_budget} except Exception as e: return False, np.inf, probe.nfev, 0, {**detail, "status": f"exception {e}"} def solve_oracle(p, tol, yref): """Upper-bound ablation: switch exactly when the ground-truth kappa > 0.8. Honest accounting: every FD-Jacobian spectral-radius check costs n+1 f-evaluations, charged to nfev via jac_extra (same convention as S_eig). """ probe = Dopri5(p.f, p.y0(), p.t0, p.t1, rtol=tol, atol=tol, max_step=np.inf, max_steps=BUDGET) detail = {} n_jac = 0 try: trip = False while probe.status == "running" and probe.n_steps < BUDGET: accepted = probe.step() if not accepted: continue rec = probe.records[-1] if probe.n_accepted >= 10 and probe.n_accepted % 10 == 0: rho = spectral_radius(p.f, rec.t1, rec.y1) n_jac += 1 if rho * rec.h / L > 0.8: trip = True break jac_extra = n_jac * (len(probe.y) + 1) if not trip: err = float(np.max(np.abs(probe.y - yref)) / (1.0 + np.max(np.abs(yref)))) \ if probe.t >= p.t1 - 1e-12 * max(1.0, abs(p.t1)) else np.inf over_budget = bool(probe.nfev + jac_extra > BUDGET) ok = bool(err <= SLACK * tol and np.isfinite(err) and not over_budget) return ok, err, probe.nfev + jac_extra, 0, \ {"tripped": False, "jac_extra": jac_extra, "over_budget": over_budget} sol = solve_ivp(lambda t, y: p.f(t, y), (probe.t, p.t1), probe.y, method="Radau", rtol=tol, atol=tol, dense_output=False, max_step=np.inf) nfev2, njev2 = 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)) detail.update({"jac_extra": jac_extra, "n_jac": n_jac, "t_switch": float(probe.t), "probe_steps": probe.n_accepted}) total = probe.nfev + nfev2 + jac_extra over_budget = bool(total > BUDGET) if not reached: return False, np.inf, total, njev2, {**detail, "tripped": True, "over_budget": over_budget} err = float(np.max(np.abs(sol.y[:, -1] - yref)) / (1.0 + np.max(np.abs(yref)))) ok = bool(err <= SLACK * tol and not over_budget) return ok, err, total, njev2, {**detail, "tripped": True, "over_budget": over_budget} except Exception as e: return False, np.inf, probe.nfev, 0, {**detail, "status": f"exception {e}"} # ------------- calibrated switch registry (managed by src/calibrate.py) --------- # ------------- calibrated switch registry (managed by src/calibrate.py) --------- # ------------- calibrated switch registry (managed by src/calibrate.py) --------- # ------------- calibrated switch registry (managed by src/calibrate.py) --------- # BEGIN CALIBRATED CONFIGS SWITCH_CONFIGS = { "switch_S_rej": SwitchConfig("switch_S_rej", "S_rej", 0.14999999999999997, probe_steps=50, implicit="Radau", direction='above', dwell=30), "switch_S_decay": SwitchConfig("switch_S_decay", "S_decay", 0.4123781244329604, probe_steps=50, implicit="Radau", direction='below', dwell=30), "switch_S_slope": SwitchConfig("switch_S_slope", "S_slope", -0.025427891117091178, probe_steps=50, implicit="Radau", direction='below', dwell=20), "switch_S_shamp": SwitchConfig("switch_S_shamp", "S_shamp", 7.911345755273942e-06, probe_steps=50, implicit="Radau", direction='below', dwell=1), "switch_S_eig": SwitchConfig("switch_S_eig", "S_eig", 0.8, probe_steps=50, implicit="Radau", direction="above", dwell=1), "oracle_switch": SwitchConfig("oracle_switch", "S_eig", 0.8, probe_steps=10, implicit="Radau", direction="above", dwell=1), } # END CALIBRATED CONFIGS