Skip to content

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 a b_extra_fn jump declared through next_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=True splits a step at an event inside it (a gate edge of a schedule with next_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_C at T/50: 8.08e-2 V snapped, 1.07e-6 V split); res.n_split_steps counts the split steps. split_snap (a fraction of dt, default 1e-6; 2.1.0's was 0.01) is the split's snap band: an event that close to a grid point is taken at it instead of cutting a sliver, and events that close merge. Pass split_snap=0.01 for 2.1.0's behaviour; it must lie in [1e-12, 0.25] and needs the split on (OptionsError otherwise). A jump the restart finds (or an ideal element's) is reported by res.reinit_records; an in-loop recorder's lines start from the post-jump state, so a window integral is the regular part, as on engine='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/L from 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 in res.resolution; pulsim.ResolutionWarning above 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 f evals 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 sample h_probe after it, so np.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 rtol meant twice itself. The Python defaults (rtol=1e-5, atol=1e-8) are unchanged; doubled values give the previous step density.
  • What rtol bounds. The error of each step, not of the run. On a lightly damped oscillation the steps' errors are mostly phase and add up, so the global error grows with the number of periods. Measured (2026-12-03) on the series RLC of high_q_rlc_ringdown (Q = 316, ~125 steps per period at the default) against its closed form: each step's local error, in the controller's own norm (RMS over the states, each scaled by atol + rtol·|y|), is 0.71 / 0.73 / 0.73 of its tolerance (median; at most 1.00 / 0.95 / 0.79) at rtol 1e-5 / 1e-6 / 1e-7, and the phase error grows by 8.1e-4 / 1.8e-4 / 4.6e-5 rad per period (×4.5 and ×3.9 per decade, near the ×4.6 of rtol^(2/3) that a second-order method with a per-step error control gives); after 50 periods the worst error is 1.3 % / 0.28 % / 0.071 % of the swing. (integrator='esdirk43' at 1e-5 reads 5.1e-5 rad per period and 0.079 %, but there its steps sit at the span/1000 ceiling, so that is not a tolerance figure.) For N periods of an oscillation expect a phase error of about N × 8e-4 rad × (rtol/1e-5)^(2/3).
  • Ceiling and floors. The default ceiling is min(span/1000, period/20 of a periodic source, pulse width/3); dt overrides it. The step floor, probe floor, probe cap, chatter floor and gate-pulse floor are fixed fractions of 1000·h_max (exactly the old span fractions while the ceiling is span/1000), so with a ceiling set by dt or a source the steps up to a time do not depend on t_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).

For developers: where the stepper lives

Both transient engines (pwl, fixed step, in solver/run_transient.hpp; trbdf2, variable step, in solver/trbdf2_transient.hpp) run on one step driver. The shared pieces are in core/include/pulsim/solver/step/:

header what it holds
stepper.hpp step::run<I>(clock, body): the loop over the engine's phases (poll, attempt, accept or reject, commit, end)
controllers.hpp FixedClock, LteController (step proposal, reject_factor) and ControllerState, the controller's part of a snapshot
integrators.hpp stage tables: Trapezoidal, BackwardEuler, TrBdf2, Sdirk22 (incl. the restart estimate restart_gamma / lte / lte_q)
esdirk43.hpp the Esdirk43 table
policies.hpp HalvingLadder (fixed-step sub-step retry), GuardPolicy (inductor freeze, then clamp), RestartPolicy (the fixed engine's SDIRK restart steps)
stepper_core.hpp commit, snapshot_into, restore, seed: accept, rollback and seeding over the history and the devices
source_accumulator.hpp the source vector of a step
sensitivity.hpp forward sensitivities along the stages

What each engine still owns, and why (the decisions are in openspec/changes/refactor-unified-transient-stepper/DECISIONS.md):

  • Its solve point (DECISIONS 22). The fixed engine writes its one Newton call per segment out in the event iteration, because a closure on its step path cost more than the 0.5 % budget; TR-BDF2 keeps solve_stage / dispatch_solve.
  • The step decisions (DECISIONS 15, 25): reject, forced accept, the chatter guard, the event iteration (run_event_iteration) and the TR-BDF2 probe / landing phases stay in the engine's body. As free functions they would take the engine's whole state; they move when the event-driven loop owns that state (task groups 14 and 15).
  • The W⁻¹ restart filter (DECISIONS 24): two solves on the step's factor, so it stays with the other solves in run_transient_trbdf2.

Changes here are behaviour-preserving by contract: results, counters included, are checked byte for byte against stored baselines (benchmarks/tools/pwl_identity.py, benchmarks/tools/trbdf2_identity.py).

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.simulate with DormandPrince5 / RadauIIA3. Needs PwlStateSpaceCache to expose continuous A, b matrices (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-step simulate() segments. Useful when you need adaptive stepping today without waiting for v1.6.0.
  • openspec/changes/archive/2026-11-30-add-adaptive-runge-kutta-solvers/ — proposal + design + delta spec.

The exact engine: when it is selected, when it refuses

Selected only when asked: engine='exact' (alias 'dsed'). engine='auto' never routes to it in this release; pulsim.exact_route and result.exact['segments'] report whether it would (report only).

Refused with UnsupportedError(engine='dsed', feature=<rule>), before or during the run, by the first rule a segment fails (design D11):

feature Rule Example
'device' a device with no linear / PWL law (device, kind name it) a Shockley diode, a level-1 MOSFET
'source' a source with no closed form a user b_extra_fn
'extraction' the per-mask state extraction fails the extractor rejects the circuit
'cost' the mask's propagator is outside its accuracy tiers a stiff, near-defective mode (tier 3)

allow_implicit_segments=True turns a 'source' or 'cost' segment, and an 'extraction' refusal of the native adapter, into numeric segments (counted in n_rk45_steps / n_bdf2_steps, listed in result.exact['segments']); a 'device' refusal stays, and so does an 'extraction' refusal when no adapter can take the circuit. Other refusals carry their own feature ('floating_island', ...), as do options the engine does not honour (feature='store_every', ...); see pulsim.engine_capabilities() and Known limitations.

The exact engine's output grid (dt_out)

With engine='exact' the stored rows are, by default, the exact steps' ends (dt is the step cap; without it 10 µs). dt_out stores a grid separate from the step: the run's start, every t_start + k*dt_out before t_end, every event instant, and t_end. Each grid row is the exact flow x(t_k) = e^{A(t_k - t_s)} x(t_s) from the start t_s of the step that holds t_k (the same propagator as the step; with sine sources the augmented one). It is not a step: the steps, the event instants and count, the control ticks and every state are those of the run without dt_out (python/tests/test_exact_output_samples.py: a DCM buck at dt_out = T/7 has the same events and its rows equal runs that end at those instants to round-off). A step end within rounding of a grid instant is that row, at the step end's own time. An event row is the run's own row without the grid: its left limit, the right limit in res.right_limit_states (res.events and the end-of-run diode-law check keep every event; that check reads the stored rows, so its peak normalisation reads the grid's). It composes with dt (the step cap) and with ticks. An explicit dt drops output_rtol before dt_out is read (the standing policy: an explicit dt keeps the step's own samples), so dt + dt_out + a valid output_rtol is the run dt + dt_out, row for row. It is refused by name with output_rtol or store_every (each chooses the rows), integrator='fixed', resume_from, sensitivities, a numeric segment, the junction temperature loop (its heat lands at each step's end), and a circuit that runs on another integrator than the event-driven one (pass integrator='rk45').

integrator='rk45' and 'bdf2' on the exact engine are deprecated (a DeprecationWarning) and removed in the next release; leave integrator unset. Until then 'rk45' remains the way to select the event-driven integrator on a diode-free circuit.

The exact engine's output rule (output_rtol)

A plain trapezoid over the stored rows reads a jump as a ramp

The row stored at an event is its left limit on every engine (the right limit is res.right_limit_states). Averaging or integrating res.states / res.i(...) / res.v(...) with a plain trapezoid across an event draws the jump as a ramp to the next stored row: −0.21 % on a bridge rectifier's window-average diode current with engine='exact' and the output rule off (the next row is 1 µs after the turn-on), +0.19 % on the fixed engine. Use the recorders, device_loss_summary, or a trapezoid over pulsim.with_event_limits(res) (with_right_limits(with_inner_events(res))). With output_rtol set the next row is 2 ps after the event, so the ramp is 2 ps long (4.3e-9 relative on the same average).

With engine='exact', no dt, store_every or recorders, output_rtol chooses the stored samples: every event instant (its left limit, and the solution 2 ps after it), and between events only the samples a tolerance needs. The promise: the straight line between two consecutive stored samples is within max(output_rtol * range, atol, floor) of the exact solution at every instant of the line, for every stored column (states, node voltages, branch currents). range is the column's range over the run so far (through the end of the exact step holding the line, at least 1e-3 of its peak); atol is the run's absolute tolerance (default 1e-9). No column is promised below its own rounding floor (floor, 16·eps times the sum of the magnitudes of the terms it is evaluated from): a column whose bound only fits through its floor is certified constant up to rounding at that floor and counted in res.diagnostics['output_grid'] (n_output_floored, output_floor_max, output_floor_by_column). A fast mode whose content does not decay between two instants of one flow as its own closed form says (the eigenbasis's error, not a transient) is taken out of the bound of a step it cuts; where that lengthens the step the bound with it is the column's floor there: counted in n_output_inconsistent, with one RuntimeWarning (output_inconsistent). A source corner (a pulse or PWM edge) is always a stored sample. The sample stored at an event is its left limit (the right limit is res.right_limit_states, pulsim.with_event_limits); after an event that changed the mode or a source's piece the solution 2 ps later is a stored sample as well, so plain interpolation of res.times draws a jump of a node voltage as a jump (over those 2 ps, the one line the promise does not cover) and not as a ramp to the next sample. The "exact solution" of the promise is the flow WITH the parasitic cluster projected at each event: modes whose time constant is below 1e-6 of the run's resolved time scale are settled at the event instant (the rule-off run lets them decay; a diode turn-off's ~1 ns mode read 0.31 V apart for a few ns). Every projection is recorded in diagnostics['output_grid'] (and, rule on or off, in diagnostics['event_projections'], the same keys; without the rule the cut is dt_max / 100): n_projections, capped (more projections than the 1000 records kept), projection_max_by_column (per stored column the largest amplitude a projection moved it by) and projections (the first 1000: instant t, largest amplitude, its column, the cluster's slowest time constant tau). Without the rule the record is read from the state alone (no recovery, so no extra source or b_extra_fn evaluation): amplitude is the largest state move, column is None and projection_max_by_column is zero. Recorders on such a run read a window's min / max inside each exact step from its closed form where one exists (a constant plus one damped sinusoid or at most two real exponentials); elsewhere the step ends are kept and counted (res.recorder_feed['closed_form']['n_extrema_ends']). Where the 4096-sample cap per interval, a mode without a diagonalising basis, or the run's 2e6-sample budget suspends the promise, the diagnostics say so and the run warns. benchmarks/tools/output_rule_referee.py checks the promise on the benchmark set. It reads each stored line against a rule-off reference run, and beside that the reference's own chord between the line's two instants (which a sub-fs offset of the two runs' events does not move); a unit passes only when both readings are within the promise, and one where they disagree is reported as inside_band, not as a pass. A unit that does not pass on the reference is decided on its own flow: the same run at output_rtol / 100 stores about ten points of the same exact steps inside each line, and the lines the reference flagged are read against them (ratio_dense_lower; ratio_dense_upper is an estimate, not a bound: a polynomial through the error at those points and the line's ends). A unit whose own flow cannot be read that way (the rule cuts the steps themselves, a state kick) is not decided by it. A declared observable that is not a stored column (a switch current, a node difference) is outside the promise: it is read and reported in outside_promise. A fixed linear combination of stored columns, such as a DC bus v(p) - v(n), is bounded by its terms: the line between two samples of Σ c_j y_j is Σ c_j times the lines of the y_j, so its distance to the flow is at most Σ |c_j| · bound_j (each bound_j on its own column's range), not output_rtol times the combination's own range; on the branch-form three-phase overlap bridge the bus reads 1.11 of its own-range bound and 0.96 of the sum of its two nodes'. A switch current recovered from the states AND the mode jumps at the mode's events and has no such bound. Two runs of one circuit (the rule on and off, or two output_rtol) can place one event a few ns apart (a diode turn-off inside its decision band is located on each run's own scan points: up to 5.8 ns on the conductance-form overlap bridge, 2.4 ns at 119 µs with its bus jumping 40.5 V there; in general within B/|ġ| of the true crossing, B the signal's significance band and ġ its rate: 25 µs on a single-phase bridge whose last ON diode carries only the OFF diodes' leakage, signal 1e-13 V at 5.2e-9 V/s, where runs at dt = 1e-5 and 1e-6 differ by 2 µs): read one run against the other away from the events, or against its own flow at output_rtol / 100. A unit whose stored columns pass while such a column reads above the bound gets the verdict outside_promise, not pass. A unit the tool cannot compare says why in not_comparable_reason. A cut step is never shorter than 128 ulps of t (a 0.4 ps mode after a commutation is resolved, not clamped at 1.4e-14 s).