Numerical Solvers¶
Pulsim's transient kernel supports two fixed-step integrators
(Tustin / BDF1) baked into pulsim.simulate(...), plus two
adaptive Runge-Kutta integrators (DormandPrince5 and
RadauIIA3) usable standalone against any user-supplied
f(t, x) → dx/dt callback.
Quick decision table¶
| Need | Use |
|---|---|
| Default SMPS / converter sim | pulsim.simulate(...) (Tustin fixed-step) |
| Stiff circuit (RC ≪ dt) | pulsim.simulate(..., integrator="bdf1") (L-stable, fixed) |
| Non-stiff ODE outside pulsim | DormandPrince5(f=...).solve(...) |
| Stiff ODE outside pulsim | RadauIIA3(f=...).solve(...) |
| Variable step inside pulsim | shipped — engine='dsed' (event-driven RK45/BDF2 auto-dispatch) for LTI-per-mask circuits; in-kernel adaptive trap for the PWL engine still planned |
Fixed-step integrators (in-kernel)¶
Tustin (trapezoidal companion) — default¶
- 2nd-order, A-stable, NOT L-stable.
- Cheap: 1 sparse solve per step.
- Used for the bread-and-butter PWM-switched-mode workflow.
discontinuity_restart=True(off by default): the step containing a mask change, diode flip, source jump (or ab_extra_fnjump declared throughnext_jump_after(t)) or inconsistent start, and the next two, are Alexander SDIRK(2,2) steps (γ = 1 − 1/√2, L-stable). Each is two backward-Euler-like stages of γ·dt on one factor per mask at 2γ·dt. The result is order 2 across edges on the grid instead of 1, with no alternation after them, and resonant modes keep their energy. The gate is sampled at the step start, and a source reads its left limit at a jump on the step end.engine='trbdf2'and'dsed'refuse it. With it,enable_substep_state_correction=Truesplits a step at an event inside it (a gate edge of a schedule withnext_edge_after, a built-in source jump, a located diode crossing): trapezoid to the event, then the SDIRK window from it. Edges off the grid become second order (buck D = 0.4567,v_Cat T/50: 8.08e-2 V snapped, 1.07e-6 V split);res.n_split_stepscounts the split steps. A jump the restart finds (or an ideal element's) is reported byres.reinit_records; an in-loop recorder's lines start from the post-jump state, so a window integral is the regular part, as onengine='dsed'.- Resolution diagnostics (on by default, read-only): the trapezoid's
local error
(h/12)|f_{k+1} − 2f_k + f_{k−1}|per linear C/L (f = i/C,v/Lfrom the companion), over the variable's running peak, on three steps under one mask without restart, split, retry or source jump; plus a Nyquist-ringing detector (Δ_k·Δ_{k−1} < 0,|Δ_k|above 1 % of the local magnitude, four steps). Recorded inres.resolution;pulsim.ResolutionWarningabove 1e-2, on a run or when over half the steps are unestimated. Opt-in:resolution_diagnostics=True.
BDF1 (implicit Euler)¶
- 1st-order, L-stable.
- Used for stiff systems where Tustin would oscillate at large
dt. - Enabled by
opts.advanced.timestep.integrator = Bdf1.
Newton on nonlinear devices (pwl and trbdf2)¶
Circuits with Newton devices (Shockley diodes, MOSFET Level-1,
saturable magnetics) solve J_lin + J_nl each iteration. Each run keeps
one Newton workspace: the combined Jacobian is written in place on the
union pattern of the two operands, and one sparse-LU analysis is reused
for as long as that pattern holds (checked after every device refresh;
a switch state with another pattern, or the static dt = 0 system,
analyses again). Results are bit-identical to analysing every
iteration (update-newton-persistent-solver, stage A1). Since stage
A2 the factorisation is the in-house sparse LU, refactorised in place
with no allocation per iteration; the DC operating point keeps
Eigen::SparseLU. result.newton reports the run's counters
(iterations, analyses, factorizations, …) and the iteration count
of every Newton call (iterations_per_solve). The Levenberg-Marquardt
fallback still factorises from scratch.
Adaptive Runge-Kutta integrators (Phase 2.4, standalone)¶
Both integrators ship as pure-Python classes in
python/pulsim/integrators.py. They run against any
f(t, x) → dx/dt callback (numpy array in, numpy array out),
not yet coupled to the in-kernel pulsim.simulate solve —
that requires reformulating the cache to expose continuous
matrices, queued for v1.6.0.
DormandPrince5 — RK 5(4)¶
7-stage FSAL embedded pair (the "RK45" of MATLAB / SciPy fame).
- 5th-order solution + 4th-order embedded error estimate.
- FSAL → 6 effective
fevals per step (vs 7). - PI step controller with safety factor 0.9, growth ≤ 5×.
- Default
rtol=1e-5,atol=1e-8.
import pulsim as p
import numpy as np
def lorenz(t, x, sigma=10, rho=28, beta=8/3):
return np.array([sigma*(x[1]-x[0]),
x[0]*(rho-x[2]) - x[1],
x[0]*x[1] - beta*x[2]])
solver = p.DormandPrince5(f=lorenz, rtol=1e-8, atol=1e-10)
res = solver.solve(t_span=(0.0, 10.0), x0=np.array([1.0, 1.0, 1.0]))
print(f"{res.n_accepted} accepted, {res.n_rejected} rejected, "
f"{res.n_f_evals} f evals")
RadauIIA3 — implicit, L-stable¶
2-stage Radau IIA, order 3.
- L-stable — handles stiff ODEs that crash RK45.
- Newton inner solve on the 2n × 2n block system.
- Step-doubling error estimate (Richardson) — robust + simple.
- Optional analytical Jacobian via
jac=callable; defaults to central finite differences.
Speedup demo¶
examples/scripts/run_adaptive_rk_speedup.py — van der Pol stiff
oscillator (μ=100):
| Integrator | Steps | Wall-clock | vs Euler |
|---|---|---|---|
| Fixed-step Euler (dt=10 µs) | 49,999 | 86.3 ms | baseline |
| DormandPrince5 (rtol=1e-4) | 56 | 3.7 ms | 23× faster |
| RadauIIA3 (rtol=1e-4) | 18 | 7.0 ms | 12× faster |
DOPRI5 vs Radau final states agree to 1.49e-7. DOPRI5 wins wall-clock because each step is cheap (explicit). Radau wins step count because L-stability lets dt grow several orders of magnitude through the stiff transitions, at the cost of a Newton solve per step.
Variable-step transient engine (engine='trbdf2')¶
TR-BDF2 (γ = 2 − √2) with an embedded error estimate over capacitor voltages and inductor currents, gate edges landed exactly and diode crossings localised by Illinois on trial solves. Two restart rules after a gate edge:
- Derivative refresh. The zero-time diode cascade at an edge
solves a short trapezoidal probe (
h_probe) under the post-edge mask; that probe is committed as a recorded step, so the history's inductor voltages, capacitor currents and stateful-device slots are post-edge values and the probe sample carries the post-edge switch state for loss post-processing. At an edge settled at a step boundary only the slots are replaced (the states are kept). The first post-edge step is then sized by a true error estimate. Each edge adds one recorded sampleh_probeafter it, sonp.diff(res.times).min()is the probe length, not a controller step. Not done at diode events or at the initial settle (a diode turn-off leaves an inductor on a g_off-only path whose probe derivative is a picosecond mode). - Post-edge memory. Per edge parity (rising/falling), the step the
controller proposes after the first accepted post-edge step,
capped at
h_max, is where the next edge of that parity restarts. It can grow as well as shrink. Diode events have no memory.
Error control:
- Estimate. The local error estimate carries the factor 2 of
Bank et al. (1985), so it is the true local error to leading order;
before, it was half of it and
rtolmeant twice itself. The Python defaults (rtol=1e-5,atol=1e-8) are unchanged; doubled values give the previous step density. - Ceiling and floors. The default ceiling is
min(span/1000, period/20 of a periodic source, pulse width/3);dtoverrides it. The step floor, probe floor, probe cap, chatter floor and gate-pulse floor are fixed fractions of1000·h_max(exactly the old span fractions while the ceiling isspan/1000), so with a ceiling set bydtor a source the steps up to a time do not depend ont_end.h_max_basis: 0 span, 1 source, 2 user. - Source breakpoints. Every corner of a pulse source (start, end
of rise, start and end of fall, per period) and every edge of a PWM
voltage source is landed like a gate edge; the landing step reads
the source's left limit and the engine restarts as after a gate
edge (
n_source_breakpoints).
res._trbdf2_stats reports n_derivative_refreshes,
n_refresh_probes and h_post_event_min (smallest accepted first
step after a refreshed edge).
Tuning guide¶
| Knob | DormandPrince5 | RadauIIA3 | Effect |
|---|---|---|---|
rtol |
1e-5 | 1e-5 | Larger → fewer steps, lower accuracy. |
atol |
1e-8 | 1e-8 | Floor on the error scale (for states near zero). |
dt_min |
1e-12 | 1e-12 | Raises if controller wants smaller (typically means tolerances too tight). |
dt_max |
∞ | ∞ | Cap for non-stiff regions to avoid skipping events. |
safety |
0.9 | 0.9 | Multiplier on optimal step estimate. |
growth_max |
5.0 | 5.0 | Max single-step growth factor. |
newton_max_iter |
n/a | 8 | Radau: max Newton iterations per step. |
newton_tol |
n/a | 1e-8 | Radau: Newton convergence threshold. |
jac |
n/a | None | Radau: analytical Jacobian callable, else finite diff. |
What's NOT here (v1.5)¶
- In-kernel coupling — replace Tustin / BDF1 inside
pulsim.simulatewithDormandPrince5/RadauIIA3. NeedsPwlStateSpaceCacheto expose continuousA, bmatrices (currently Tustin-discretized). Scope: 3-4 weeks kernel refactor. Queued for v1.6.0. - Dense-output interpolants — needed for precise switching-event localisation. Both algorithms support them (Hermite for DOPRI5, Lagrange for Radau); not exposed in this release.
- DOPRI8(7) higher-order — only added on demand.
- Rosenbrock / Rodas semi-implicit (no Newton, one linear solve) — DOPRI5 + Radau cover the common cases.
See also¶
python/pulsim/integrators.py— source.python/pulsim/adaptive.py— coarse-grain Python-level adaptive driver wrapping fixed-stepsimulate()segments. Useful when you need adaptive stepping today without waiting for v1.6.0.openspec/changes/add-adaptive-runge-kutta-solvers/— proposal + design + delta spec.