blocksim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,432 @@
1
+ """Independent NumPy implementations of integration and event root finding.
2
+
3
+ :class:`ClaudeSolver` provides adaptive Dormand-Prince RK45, fixed-step
4
+ RK4 and Euler integration, with cubic-Hermite dense output.
5
+ :func:`brentq` locates event roots.
6
+ :class:`ClaudeAlgebraicSolver` is a damped-Newton algebraic solver.
7
+
8
+ :class:`SimulatorClaude` shares the base Simulator's region, clock and
9
+ event orchestration while replacing its integration backend. To also
10
+ replace algebraic-loop solving, supply ClaudeAlgebraicSolver to System.
11
+
12
+ Typical use::
13
+
14
+ sim = SimulatorClaude(system)
15
+ result = sim.run(0.0, 10.0, dt_max=0.01)
16
+ fixed = SimulatorClaude(system, method="RK4")
17
+
18
+ Adaptive tolerances apply to RK45. For fixed-step methods, `dt_max`
19
+ controls the integration step. These independent implementations are
20
+ useful for cross-checking the SciPy-backed simulation path.
21
+ """
22
+
23
+ import numpy as np
24
+
25
+ from .core import AlgebraicSolver, AlgebraicLoopError, Simulator, Solver, SolverResult
26
+
27
+ __all__ = [
28
+ "ClaudeAlgebraicSolver",
29
+ "ClaudeSolver",
30
+ "SimulatorClaude",
31
+ "brentq",
32
+ ]
33
+
34
+ _EPS = float(np.finfo(float).eps)
35
+
36
+
37
+ # ==============================================================================
38
+ # Brent's method (root finding for event location)
39
+ # ==============================================================================
40
+ def brentq(f, a, b, xtol=4 * _EPS, rtol=4 * _EPS, maxiter=100):
41
+ """Find a root of f in [a, b] by Brent's method (inverse-quadratic /
42
+ secant steps safeguarded by bisection). f(a) and f(b) must not have
43
+ the same strict sign."""
44
+ fa, fb = f(a), f(b)
45
+ if fa == 0.0:
46
+ return a
47
+ if fb == 0.0:
48
+ return b
49
+ if fa * fb > 0.0:
50
+ raise ValueError("f(a) and f(b) must have different signs")
51
+
52
+ c, fc = a, fa
53
+ d = e = b - a
54
+ for _ in range(maxiter):
55
+ if fb * fc > 0.0:
56
+ c, fc = a, fa
57
+ d = e = b - a
58
+ if abs(fc) < abs(fb):
59
+ a, b, c = b, c, b
60
+ fa, fb, fc = fb, fc, fb
61
+ tol1 = 0.5 * xtol + rtol * abs(b)
62
+ xm = 0.5 * (c - b)
63
+ if abs(xm) <= tol1 or fb == 0.0:
64
+ return b
65
+ if abs(e) >= tol1 and abs(fa) > abs(fb):
66
+ # try inverse quadratic interpolation / secant
67
+ s = fb / fa
68
+ if a == c:
69
+ p = 2.0 * xm * s
70
+ q = 1.0 - s
71
+ else:
72
+ q = fa / fc
73
+ r = fb / fc
74
+ p = s * (2.0 * xm * q * (q - r) - (b - a) * (r - 1.0))
75
+ q = (q - 1.0) * (r - 1.0) * (s - 1.0)
76
+ if p > 0.0:
77
+ q = -q
78
+ p = abs(p)
79
+ if 2.0 * p < min(3.0 * xm * q - abs(tol1 * q), abs(e * q)):
80
+ e = d
81
+ d = p / q
82
+ else:
83
+ d = xm
84
+ e = d
85
+ else:
86
+ d = xm
87
+ e = d
88
+ a, fa = b, fb
89
+ b += d if abs(d) > tol1 else (tol1 if xm > 0 else -tol1)
90
+ fb = f(b)
91
+ return b
92
+
93
+
94
+ # ==============================================================================
95
+ # Dense output: cubic Hermite interpolant over one accepted step
96
+ # ==============================================================================
97
+ def _hermite(t0, y0, f0, t1, y1, f1):
98
+ """C1 interpolant matching value and slope at both step ends. Its
99
+ interior error is O(h^4), far below event-location tolerances for
100
+ solver-sized steps."""
101
+ h = t1 - t0
102
+
103
+ def sol(t):
104
+ x = (t - t0) / h
105
+ x2 = x * x
106
+ x3 = x2 * x
107
+ return (
108
+ (2 * x3 - 3 * x2 + 1) * y0
109
+ + (x3 - 2 * x2 + x) * h * f0
110
+ + (-2 * x3 + 3 * x2) * y1
111
+ + (x3 - x2) * h * f1
112
+ )
113
+
114
+ return sol
115
+
116
+
117
+ # ==============================================================================
118
+ # Dormand-Prince 5(4) tableau (the classic RK45 pair, FSAL)
119
+ # ==============================================================================
120
+ _DP_C = (1 / 5, 3 / 10, 4 / 5, 8 / 9, 1.0)
121
+ _DP_A = (
122
+ (1 / 5,),
123
+ (3 / 40, 9 / 40),
124
+ (44 / 45, -56 / 15, 32 / 9),
125
+ (19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729),
126
+ (9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656),
127
+ )
128
+ _DP_B = np.array([35 / 384, 0.0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84])
129
+ #: 5th-order minus embedded 4th-order weights (error estimator)
130
+ _DP_E = np.array(
131
+ [71 / 57600, 0.0, -71 / 16695, 71 / 1920, -17253 / 339200, 22 / 525, -1 / 40]
132
+ )
133
+
134
+ _SAFETY = 0.9
135
+ _MIN_FACTOR = 0.2
136
+ _MAX_FACTOR = 10.0
137
+ _ERR_EXPONENT = -0.2 # -1 / (4 + 1)
138
+
139
+
140
+ def _rms_norm(v):
141
+ return float(np.sqrt(np.mean(v * v))) if v.size else 0.0
142
+
143
+
144
+ def _initial_step(fun, t0, y0, f0, t_bound, max_step, rtol, atol):
145
+ """Hairer's starting-step heuristic (as used by solve_ivp)."""
146
+ if y0.size == 0:
147
+ return t_bound - t0
148
+ scale = atol + np.abs(y0) * rtol
149
+ d0 = _rms_norm(y0 / scale)
150
+ d1 = _rms_norm(f0 / scale)
151
+ h0 = 1e-6 if (d0 < 1e-5 or d1 < 1e-5) else 0.01 * d0 / d1
152
+ y1 = y0 + h0 * f0
153
+ f1 = fun(t0 + h0, y1)
154
+ d2 = _rms_norm((f1 - f0) / scale) / h0
155
+ if d1 <= 1e-15 and d2 <= 1e-15:
156
+ h1 = max(1e-6, h0 * 1e-3)
157
+ else:
158
+ h1 = (0.01 / max(d1, d2)) ** 0.2
159
+ return min(100 * h0, h1, t_bound - t0, max_step)
160
+
161
+
162
+ # ==============================================================================
163
+ # The scipy-free Solver backend
164
+ # ==============================================================================
165
+ class ClaudeSolver(Solver):
166
+ """ODE integration backend implemented from scratch (numpy only).
167
+
168
+ method
169
+ "RK45" adaptive Dormand-Prince 5(4), FSAL, error-controlled
170
+ steps (rtol/atol) -- the default, equivalent in use
171
+ to ScipySolver's default;
172
+ "RK4" / "Euler" fixed-step methods; the step is max_step
173
+ (i.e. Simulator.run's dt_max) or (t1-t0)/1000 when
174
+ dt_max is not given.
175
+
176
+ rtol, atol
177
+ adaptive error control tolerances ("RK45" only).
178
+
179
+ Event handling mirrors scipy.solve_ivp exactly -- sign-change
180
+ detection between accepted steps (up = g0 <= 0 <= g1, down = g0 >= 0
181
+ >= g1, filtered by each event's .direction), root location on the
182
+ dense interpolant with Brent's method, stop at the earliest terminal
183
+ root -- because the engine's hybrid loop and the mode-gated blocks
184
+ were designed against those exact semantics.
185
+ """
186
+
187
+ def __init__(self, method="RK45", rtol=1e-8, atol=1e-10):
188
+ method = method.upper()
189
+ if method not in ("RK45", "RK4", "EULER"):
190
+ raise ValueError(f"unknown method {method!r} (choose RK45, RK4 or Euler)")
191
+ self.method = method
192
+ self.rtol = rtol
193
+ self.atol = atol
194
+
195
+ # ---- single steps -------------------------------------------------------
196
+ def _dp_step(self, fun, t, y, h, f0):
197
+ """One Dormand-Prince step: returns (y_new, f_new, error_estimate);
198
+ f_new is the FSAL stage, reusable as the next step's f0."""
199
+ K = np.empty((7, y.size))
200
+ K[0] = f0
201
+ for i, (c, a_row) in enumerate(zip(_DP_C, _DP_A), start=1):
202
+ K[i] = fun(t + c * h, y + h * (np.asarray(a_row) @ K[:i]))
203
+ y_new = y + h * (_DP_B @ K[:6])
204
+ K[6] = fun(t + h, y_new)
205
+ err = h * (_DP_E @ K)
206
+ return y_new, K[6], err
207
+
208
+ def _fixed_step(self, fun, t, y, h, f0):
209
+ if self.method == "EULER":
210
+ y_new = y + h * f0
211
+ else: # classic RK4
212
+ k1 = f0
213
+ k2 = fun(t + h / 2, y + h / 2 * k1)
214
+ k3 = fun(t + h / 2, y + h / 2 * k2)
215
+ k4 = fun(t + h, y + h * k3)
216
+ y_new = y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
217
+ return y_new, fun(t + h, y_new)
218
+
219
+ # ---- event helpers ------------------------------------------------------
220
+ @staticmethod
221
+ def _find_active(g_old, g_new, directions):
222
+ active = []
223
+ for i, (g0, g1) in enumerate(zip(g_old, g_new)):
224
+ up = g0 <= 0.0 <= g1
225
+ down = g0 >= 0.0 >= g1
226
+ d = directions[i]
227
+ if (up and d > 0) or (down and d < 0) or ((up or down) and d == 0):
228
+ active.append(i)
229
+ return active
230
+
231
+ # ---- main driver ---------------------------------------------------------
232
+ def integrate(self, fun, t_span, y0, events=None, max_step=np.inf) -> SolverResult:
233
+ t0, t_bound = t_span
234
+ y = np.array(y0, dtype=float).ravel()
235
+ events = list(events) if events else []
236
+ directions = [getattr(ev, "direction", 0) for ev in events]
237
+ terminals = [bool(getattr(ev, "terminal", False)) for ev in events]
238
+
239
+ ts = [t0]
240
+ ys = [y.copy()]
241
+ t_events = [[] for _ in events]
242
+ y_events = [[] for _ in events]
243
+
244
+ f = fun(t0, y)
245
+ g_old = [float(ev(t0, y)) for ev in events]
246
+
247
+ adaptive = self.method == "RK45"
248
+ if adaptive:
249
+ h = _initial_step(fun, t0, y, f, t_bound, max_step, self.rtol, self.atol)
250
+ else:
251
+ h = max_step if np.isfinite(max_step) else (t_bound - t0) / 1000.0
252
+
253
+ t = t0
254
+ status = 0
255
+ message = "The solver successfully reached the end of the "
256
+ message += "integration interval."
257
+
258
+ while t < t_bound:
259
+ min_h = 10.0 * _EPS * max(abs(t), 1.0)
260
+ if t_bound - t <= min_h:
261
+ # the final step rarely lands exactly on t_bound in float
262
+ # arithmetic; a sub-resolution leftover means we are DONE,
263
+ # not failing (genuine error-control collapse is caught
264
+ # inside the rejection loop below)
265
+ break
266
+ h = min(h, t_bound - t)
267
+
268
+ # ---- take one (possibly retried) step --------------------------
269
+ if adaptive:
270
+ while True:
271
+ y_new, f_new, err = self._dp_step(fun, t, y, h, f)
272
+ scale = self.atol + self.rtol * np.maximum(np.abs(y), np.abs(y_new))
273
+ err_norm = _rms_norm(err / scale)
274
+ if err_norm <= 1.0:
275
+ factor = (
276
+ _MAX_FACTOR
277
+ if err_norm == 0.0
278
+ else min(_MAX_FACTOR, _SAFETY * err_norm**_ERR_EXPONENT)
279
+ )
280
+ h_next = min(h * factor, max_step)
281
+ break
282
+ h *= max(_MIN_FACTOR, _SAFETY * err_norm**_ERR_EXPONENT)
283
+ if h < min_h:
284
+ return SolverResult(
285
+ t=np.array(ts),
286
+ y=np.array(ys).T,
287
+ status=-1,
288
+ success=False,
289
+ message=f"required step size fell below the "
290
+ f"resolvable minimum at t={t:.6g}",
291
+ t_events=[np.array(ev) for ev in t_events],
292
+ y_events=[np.array(ev) for ev in y_events],
293
+ )
294
+ else:
295
+ y_new, f_new = self._fixed_step(fun, t, y, h, f)
296
+ h_next = h
297
+
298
+ t_new = t + h
299
+
300
+ # ---- event detection on the accepted step -----------------------
301
+ if events:
302
+ dense = _hermite(t, y, f, t_new, y_new, f_new)
303
+ g_new = [float(ev(t_new, y_new)) for ev in events]
304
+ active = self._find_active(g_old, g_new, directions)
305
+ if active:
306
+ roots = []
307
+ for i in active:
308
+ gi = events[i]
309
+ root = brentq(lambda tt: float(gi(tt, dense(tt))), t, t_new)
310
+ roots.append((root, i))
311
+ term_roots = [r for r, i in roots if terminals[i]]
312
+ t_stop = min(term_roots) if term_roots else None
313
+ for root, i in sorted(roots):
314
+ if t_stop is None or root <= t_stop + 1e-15:
315
+ t_events[i].append(root)
316
+ y_events[i].append(np.array(dense(root)))
317
+ if t_stop is not None:
318
+ y_stop = np.array(dense(t_stop))
319
+ ts.append(t_stop)
320
+ ys.append(y_stop)
321
+ status = 1
322
+ message = "A termination event occurred."
323
+ break
324
+ g_old = g_new
325
+
326
+ ts.append(t_new)
327
+ ys.append(y_new.copy())
328
+ t, y, f = t_new, y_new, f_new
329
+ h = h_next
330
+
331
+ return SolverResult(
332
+ t=np.array(ts),
333
+ y=np.array(ys).T,
334
+ status=status,
335
+ success=True,
336
+ message=message,
337
+ t_events=[np.array(ev) for ev in t_events],
338
+ y_events=[np.array(ev) for ev in y_events],
339
+ )
340
+
341
+
342
+ # ==============================================================================
343
+ # scipy-free algebraic-loop resolver (optional; System uses fsolve by default)
344
+ # ==============================================================================
345
+ class ClaudeAlgebraicSolver(AlgebraicSolver):
346
+ """
347
+ Damped Newton iteration with a forward-difference Jacobian (numpy's
348
+ linear solver only). Drop-in for the default fsolve-based resolver:
349
+
350
+ sys = System(algebraic_solver=ClaudeAlgebraicSolver())
351
+ """
352
+
353
+ def __init__(self, tol=1e-10, maxiter=50, fd_eps=1e-8):
354
+ self.tol = tol
355
+ self.maxiter = maxiter
356
+ self.fd_eps = fd_eps
357
+
358
+ def solve(self, residual, y0):
359
+ y = np.atleast_1d(np.array(y0, dtype=float))
360
+ n = y.size
361
+ for _ in range(self.maxiter):
362
+ r = np.atleast_1d(np.asarray(residual(y), dtype=float))
363
+ if np.max(np.abs(r)) < self.tol:
364
+ return y
365
+ J = np.empty((n, n))
366
+ for j in range(n):
367
+ step = self.fd_eps * max(1.0, abs(y[j]))
368
+ yp = y.copy()
369
+ yp[j] += step
370
+ J[:, j] = (np.atleast_1d(residual(yp)) - r) / step
371
+ try:
372
+ dy = np.linalg.solve(J, -r)
373
+ except np.linalg.LinAlgError:
374
+ raise AlgebraicLoopError("algebraic loop Jacobian is singular")
375
+ # damped line search: halve until the residual improves
376
+ r_norm = np.max(np.abs(r))
377
+ alpha = 1.0
378
+ for _ in range(30):
379
+ y_try = y + alpha * dy
380
+ r_try = np.max(np.abs(np.atleast_1d(residual(y_try))))
381
+ if r_try < r_norm:
382
+ break
383
+ alpha *= 0.5
384
+ else:
385
+ raise AlgebraicLoopError(
386
+ "algebraic loop failed to converge "
387
+ "(Newton step cannot reduce the residual)"
388
+ )
389
+ y = y + alpha * dy
390
+ r = np.max(np.abs(np.atleast_1d(residual(y))))
391
+ if r < self.tol * 1e3: # accept near-converged
392
+ return y
393
+ raise AlgebraicLoopError(
394
+ f"algebraic loop failed to converge "
395
+ f"(max|residual|={r:.3g} after {self.maxiter} iterations)"
396
+ )
397
+
398
+
399
+ # ==============================================================================
400
+ # The Simulator
401
+ # ==============================================================================
402
+ class SimulatorClaude(Simulator):
403
+ """Drop-in replacement for Simulator whose integration path uses NO scipy:
404
+ the adaptive RK45 integrator, dense output, event root finding and
405
+ (optionally, via ClaudeAlgebraicSolver on the System) algebraic-loop
406
+ resolution are all implemented in this module.
407
+
408
+ Configuration
409
+ -------------
410
+ system : System (compiled or not -- run() compiles if needed)
411
+ solver : a Solver instance; defaults to ClaudeSolver(method, rtol, atol)
412
+ method : "RK45" (adaptive, default), "RK4" or "Euler" (fixed step)
413
+ rtol, atol : forwarded to the default ClaudeSolver
414
+
415
+ Everything else -- run(), record=..., SimulationResult, the hybrid
416
+ region/clock/event loop, the no-states sampled path -- is inherited
417
+ unchanged from Simulator (that machinery is scipy-free; scipy enters
418
+ Simulator only through its default ScipySolver backend, which this
419
+ class swaps out).
420
+ """
421
+
422
+ def __init__(
423
+ self,
424
+ system,
425
+ solver=None,
426
+ method: str = "RK45",
427
+ rtol: float = 1e-8,
428
+ atol: float = 1e-10,
429
+ ):
430
+ super().__init__(
431
+ system, solver=solver or ClaudeSolver(method=method, rtol=rtol, atol=atol)
432
+ )