"""Stiffness detectors: cheap solver-native signals vs Jacobian-based reference. All cheap signals use only telemetry that any explicit RK solver emits for free (stage vectors are available because we own the integrator): S_rej : rolling rejection rate over the last W step attempts S_decay : current step size / max step size in the last W accepted steps S_slope : least-squares slope of log10(h) over the last W accepted steps S_shamp : Shampine-Biehn (1991) proxy T = h*max|k2-k1| / (2*a21), a21=1/5 S_eig : kappa = rho(J)*h / L with rho via finite-difference Jacobian (SciML-AutoSwitch-style; expensive, needs J - the comparison arm) Labels (ground truth): kappa > 0.8 => stability-limited step (stiff regime). """ import numpy as np import scipy.linalg as la # ------------------------------------------------------------------ stability boundary def dopri5_stability_boundary(grid=np.linspace(-5.0, 0.0, 40001)): """L = sup{|z| <= 5 : |R(z)| <= 1} for the DOPRI5(4) stability polynomial. R(z) = 1 + z b^T (I - z A)^-1 e with the 7x7 Butcher A (b^T as last row). """ A = np.zeros((7, 7)) A[1, 0] = 1/5 A[2, 0], A[2, 1] = 3/40, 9/40 A[3, 0], A[3, 1], A[3, 2] = 44/45, -56/15, 32/9 A[4, 0], A[4, 1], A[4, 2], A[4, 3] = 19372/6561, -25360/2187, 64448/6561, -212/729 A[5, 0], A[5, 1], A[5, 2], A[5, 3], A[5, 4] = 9017/3168, -355/33, 46732/5247, 49/176, -5103/18656 A[6, 0], A[6, 2], A[6, 3], A[6, 4], A[6, 5] = 35/384, 500/1113, 125/192, -2187/6784, 11/84 b = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84, 0.0]) e = np.ones(7) I = np.eye(7) stable = [] for z in grid: R = 1.0 + z * b @ la.solve(I - z * A, e) stable.append(abs(R) <= 1.0) stable = np.array(stable) # largest |z| in the connected stable region containing 0 zs = grid[stable] return float(np.max(np.abs(zs))) L = dopri5_stability_boundary() # ------------------------------------------------------------------ finite-difference Jacobian spectral radius def spectral_radius(f, t, y): """rho(J) via one-sided finite differences (analysis only, never used by cheap detectors).""" n = len(y) J = np.zeros((n, n)) f0 = np.asarray(f(t, y), float) for j in range(n): yj = np.array(y, float) delta = 1e-8 * (1.0 + abs(y[j])) yj[j] += delta J[:, j] = (np.asarray(f(t, yj), float) - f0) / delta return float(np.max(np.abs(la.eigvals(J))).real) # ------------------------------------------------------------------ detectors class Window: def __init__(self, w): self.w = w self.hs = [] # accepted step sizes self.rej = [] # 1/0 flags per attempt def push_accept(self, h): self.hs.append(h) self.rej.append(0) if len(self.hs) > self.w: self.hs.pop(0) if len(self.rej) > self.w: self.rej.pop(0) def push_reject(self): self.rej.append(1) if len(self.rej) > self.w: self.rej.pop(0) class Detector: name = "?" warmup = 10 # accepted steps before a signal is considered valid def __init__(self, w=20): self.win = Window(w) self.n_acc = 0 self.value = None def on_reject(self, rec): self.win.push_reject() def on_accept(self, rec): self.n_acc += 1 self.win.push_accept(rec.h) def signal(self): """None = not enough data yet.""" return None class RejRate(Detector): name = "S_rej" def signal(self): if self.n_acc < self.warmup: return None return float(np.mean(self.win.rej)) class StepDecay(Detector): name = "S_decay" def signal(self): if self.n_acc < self.warmup or not self.win.hs: return None return float(self.win.hs[-1] / max(self.win.hs)) class Slope(Detector): name = "S_slope" def signal(self): if self.n_acc < self.warmup or len(self.win.hs) < 3: return None hs = np.log10(np.array(self.win.hs) + 1e-300) x = np.arange(len(hs), dtype=float) x = x - x.mean() if np.allclose(x, 0): return 0.0 return float(np.dot(x, hs) / np.dot(x, x)) class Shampine(Detector): name = "S_shamp" def __init__(self, w=20): super().__init__(w) self._v = None def on_accept(self, rec): super().on_accept(rec) # T = h * max|k2 - k1| / (2*a21), a21 = 1/5 (Shampine-Biehn 1991) self._v = float(rec.h * np.max(np.abs(rec.k2 - rec.k1)) / (2.0 * (1.0 / 5.0))) def signal(self): return self._v if self.n_acc >= self.warmup else None class EigDetector(Detector): """kappa = rho(J)*h / L, updated every `every` accepted steps (FD Jacobian).""" name = "S_eig" def __init__(self, f, w=20, every=10): super().__init__(w) self.f = f self.every = every self._v = None self.n_jac = 0 self._last = -10**9 def on_accept(self, rec): super().on_accept(rec) if self.n_acc - self._last >= self.every or self._v is None: rho = spectral_radius(self.f, rec.t1, rec.y1) self._v = float(rho * rec.h / L) self.n_jac += 1 self._last = self.n_acc def signal(self): return self._v def make_detectors(f): return { "S_rej": RejRate(), "S_decay": StepDecay(), "S_slope": Slope(), "S_shamp": Shampine(), "S_eig": EigDetector(f), } if __name__ == "__main__": print(f"DOPRI5(4) real-axis stability boundary L = {L:.6f}")