Skip to main content

dae_runtime/
step_control.rs

1//! How a transient run's timestep is chosen: a fixed, caller-given `dt` throughout (simple,
2//! deterministic, exactly reproducible — what every function in this crate did until this
3//! module existed), or local-truncation-error-driven adaptive step-size control (small steps
4//! automatically where the solution is changing fast, large steps where it's settled or
5//! between switching events — what every real SPICE-family tool does by default, because a
6//! circuit's dynamics are rarely uniform in speed across a whole run: see [`AdaptiveConfig`]
7//! and [`lte_attempt`] for the actual algorithm).
8//!
9//! [`TimeStep::Fixed`] keeps exactly the original behavior (used directly, no LTE machinery
10//! touched at all) — this module doesn't change anything about the fixed-step path beyond
11//! giving it a name in this enum.
12
13use std::collections::BTreeMap;
14
15use general_mna::MnaSystem;
16use general_spice_core::ast::Statement;
17use pwl_devices::IdealDiode;
18
19use crate::{
20    classify_segments, fold_and_solve, is_ringing, DaeError, OperatingPoint, Scheme, Segment,
21};
22
23/// How a transient run picks its step size.
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub enum TimeStep {
26    /// The same `dt` every step, exactly as before this module existed.
27    Fixed(f64),
28    /// Local-truncation-error-driven: see [`AdaptiveConfig`].
29    Adaptive(AdaptiveConfig),
30}
31
32/// Parameters for [`lte_attempt`]'s local-truncation-error step-size control.
33///
34/// `reltol`/`abstol` together form the per-unknown error scale `abstol + reltol *
35/// max(|x_trapezoidal|, |x_backward_euler|)` a step's estimated error is normalized against
36/// (the same `RELTOL`/`ABSTOL` idea every SPICE-family tool exposes) — `reltol` alone isn't
37/// enough because it degenerates to zero right where many circuit unknowns spend a lot of
38/// their time (an AC-coupled voltage or an inductor current crossing zero), so `abstol` is the
39/// floor that keeps step control meaningful there. This crate uses one scalar `abstol` for
40/// every unknown regardless of whether it's a voltage or a current — a real simplification
41/// relative to SPICE's own separate voltage/current tolerances (`VNTOL`/`ABSTOL`), noted
42/// directly rather than silently: pick `abstol` relative to the smaller-magnitude unknowns in
43/// your own circuit if the defaults reject too aggressively.
44#[derive(Debug, Clone, Copy, PartialEq)]
45pub struct AdaptiveConfig {
46    /// The very first trial step size.
47    pub dt_init: f64,
48    /// Never shrink below this, no matter how large the estimated error — accept whatever
49    /// result comes out instead of looping forever (a run that only converges below `dt_min`
50    /// needs a smaller `dt_min` or looser tolerances, not an infinite retry loop).
51    pub dt_min: f64,
52    /// Never grow above this, even if the estimated error says a step could be much larger —
53    /// the same role `TSTEP`/a `.tran` step ceiling plays in a real SPICE deck: without it, a
54    /// long quiet stretch could grow the step past the resolution needed to catch the *next*
55    /// fast event at all.
56    pub dt_max: f64,
57    /// Relative error tolerance (dimensionless, e.g. `1e-3` for 0.1%).
58    pub reltol: f64,
59    /// Absolute error tolerance (same units as the circuit's own unknowns — volts/amps).
60    pub abstol: f64,
61}
62
63impl AdaptiveConfig {
64    /// A reasonable default derived from `t_final` alone, for when the caller hasn't measured
65    /// their own circuit's time constants — the same situation a real SPICE `.tran` line is
66    /// in when only `TSTOP` is meaningfully chosen by the user and the internal step is left to
67    /// the tool. `dt_max = t_final/1000` (a 1000-point default resolution, comparable to a
68    /// typical SPICE run's point count), `dt_init = dt_max/100` (start conservatively, like
69    /// every real tool's own small first step, then grow once the solution's behavior is
70    /// actually known), `dt_min = dt_max*1e-9`.
71    pub fn from_t_final(t_final: f64) -> Self {
72        let dt_max = t_final / 1000.0;
73        AdaptiveConfig {
74            dt_init: dt_max / 100.0,
75            dt_min: dt_max * 1e-9,
76            dt_max,
77            reltol: 1e-3,
78            abstol: 1e-9,
79        }
80    }
81}
82
83/// The result of one [`lte_attempt`] at one candidate `dt` — the caller decides accept/reject
84/// (`accept`) and the next `dt` to try (`suggested_dt_next`, already the right value for
85/// *either* outcome: use it as-is on accept, or as the next attempt's `dt` on reject).
86pub(crate) struct LteAttempt {
87    pub point: OperatingPoint,
88    pub used_backward_euler: bool,
89    pub accept: bool,
90    pub suggested_dt_next: f64,
91}
92
93/// One local-truncation-error attempt at a candidate `dt`, against an already-built `system`
94/// (the caller is responsible for rebuilding `system` at this `dt`/gate-state combination
95/// first, when that matters — e.g. an ideal switch circuit whose gate states are themselves a
96/// function of `dt` through a block graph; see `block_graph`'s own adaptive loop).
97///
98/// **The error estimate**: backward Euler (order 1, `O(h^2)` local error) and trapezoidal
99/// (order 2, `O(h^3)` local error) are both solved at the *same* trial `dt`; their difference
100/// is dominated by backward Euler's own larger error term, giving a cheap, history-free proxy
101/// for trapezoidal's actual error — the same idea an embedded Runge-Kutta pair (e.g. Runge-
102/// Kutta-Fehlberg) uses two different-order formulas for, adapted here to the two schemes this
103/// crate already implements rather than introducing new ones. The accepted result is always
104/// the (more accurate) trapezoidal one, never backward Euler, except when a segment/gate
105/// change or ringing is detected (same as [`crate::step_with_fallback`]) or when the caller
106/// already knows this step must be backward Euler (`force_backward_euler` — the first step of
107/// a run, right after a gate change, or during a ringing cooldown; see
108/// [`crate::step_with_fallback`]'s own doc comment for why those specific cases need it).
109///
110/// Step-size update, on acceptance: `dt_next = dt * clamp(sqrt(1/err), 0.2, 5.0) * 0.9`, the
111/// `0.9` a standard safety margin so a step doesn't repeatedly land right at the tolerance
112/// boundary and oscillate between barely-accepted and rejected. On rejection: `dt_next = dt *
113/// clamp(sqrt(1/err), 0.1, 0.5)` (always shrinks). After a forced/discontinuity step,
114/// `suggested_dt_next` is conservatively halved rather than left to the error estimate — the
115/// same reason [`crate::step_with_fallback`]'s ringing-cooldown exists: trust the solution
116/// less immediately after a mode change, not more.
117#[allow(clippy::too_many_arguments)]
118pub(crate) fn lte_attempt(
119    system: &MnaSystem,
120    statements: &[Statement],
121    diodes: &BTreeMap<String, IdealDiode>,
122    x_prev_prev: Option<&[f64]>,
123    x_prev: &[f64],
124    dt: f64,
125    prev_diode_raw_ioff: &BTreeMap<String, f64>,
126    prev_segments: &Option<Vec<Segment>>,
127    force_backward_euler: bool,
128    config: &AdaptiveConfig,
129    t_start: f64,
130    extra_values: &BTreeMap<String, f64>,
131    extra_values_prev: &BTreeMap<String, f64>,
132) -> Result<LteAttempt, DaeError> {
133    let t = t_start + dt;
134    if force_backward_euler {
135        let point = fold_and_solve(
136            system,
137            statements,
138            diodes,
139            &Scheme::BackwardEuler { x_prev, dt },
140            t,
141            extra_values,
142            extra_values_prev,
143        )?;
144        let suggested_dt_next = (dt * 0.5).clamp(config.dt_min, config.dt_max);
145        return Ok(LteAttempt {
146            point,
147            used_backward_euler: true,
148            accept: true,
149            suggested_dt_next,
150        });
151    }
152
153    let be = fold_and_solve(
154        system,
155        statements,
156        diodes,
157        &Scheme::BackwardEuler { x_prev, dt },
158        t,
159        extra_values,
160        extra_values_prev,
161    )?;
162    let trap = fold_and_solve(
163        system,
164        statements,
165        diodes,
166        &Scheme::Trapezoidal {
167            x_prev,
168            dt,
169            prev_diode_raw_ioff,
170        },
171        t,
172        extra_values,
173        extra_values_prev,
174    )?;
175
176    let trial_segments = classify_segments(&trap);
177    let segments_changed = Some(&trial_segments) != prev_segments.as_ref();
178    let ringing = x_prev_prev.is_some_and(|xpp| is_ringing(xpp, x_prev, &trap.x));
179    if segments_changed || ringing {
180        // Same policy as step_with_fallback: don't trust trapezoidal across a resolved mode
181        // change or detected ringing -- take backward Euler outright, and restart the growth
182        // ramp conservatively rather than trusting an error estimate computed against a
183        // trapezoidal result that's being discarded anyway.
184        let suggested_dt_next = (dt * 0.5).clamp(config.dt_min, config.dt_max);
185        return Ok(LteAttempt {
186            point: be,
187            used_backward_euler: true,
188            accept: true,
189            suggested_dt_next,
190        });
191    }
192
193    let err = trap.x.iter().zip(&be.x).fold(0.0_f64, |acc, (&xt, &xb)| {
194        let scale = config.abstol + config.reltol * xt.abs().max(xb.abs());
195        acc.max((xt - xb).abs() / scale)
196    });
197
198    let at_floor = dt <= config.dt_min * (1.0 + 1e-9);
199    if err <= 1.0 || at_floor {
200        let growth = if err > 1e-12 { (1.0 / err).sqrt() } else { 5.0 };
201        let suggested_dt_next =
202            (dt * (growth.clamp(0.2, 5.0)) * 0.9).clamp(config.dt_min, config.dt_max);
203        Ok(LteAttempt {
204            point: trap,
205            used_backward_euler: false,
206            accept: true,
207            suggested_dt_next,
208        })
209    } else {
210        let shrink = (1.0 / err).sqrt().clamp(0.1, 0.5);
211        let suggested_dt_next = (dt * shrink).max(config.dt_min);
212        Ok(LteAttempt {
213            point: trap,
214            used_backward_euler: false,
215            accept: false,
216            suggested_dt_next,
217        })
218    }
219}
220
221/// The common case built on [`lte_attempt`]: `system` is fixed for the whole run (no ideal switchs,
222/// or any other reason gate/topology doesn't depend on `dt`), so this owns the retry loop
223/// directly. `block_graph`'s adaptive loop can't use this — its `system` is rebuilt from block
224/// outputs that are themselves a function of `dt`, so it drives [`lte_attempt`] with its own
225/// retry loop instead (see that module).
226#[allow(clippy::too_many_arguments)]
227pub(crate) fn adaptive_step(
228    system: &MnaSystem,
229    statements: &[Statement],
230    diodes: &BTreeMap<String, IdealDiode>,
231    x_prev_prev: Option<&[f64]>,
232    x_prev: &[f64],
233    dt_trial: f64,
234    prev_diode_raw_ioff: &BTreeMap<String, f64>,
235    prev_segments: &Option<Vec<Segment>>,
236    force_backward_euler: bool,
237    config: &AdaptiveConfig,
238    t_start: f64,
239) -> Result<(OperatingPoint, bool, f64, f64), DaeError> {
240    let mut dt = dt_trial.clamp(config.dt_min, config.dt_max);
241    let empty = BTreeMap::new();
242    loop {
243        let attempt = lte_attempt(
244            system,
245            statements,
246            diodes,
247            x_prev_prev,
248            x_prev,
249            dt,
250            prev_diode_raw_ioff,
251            prev_segments,
252            force_backward_euler,
253            config,
254            t_start,
255            &empty,
256            &empty,
257        )?;
258        if attempt.accept {
259            return Ok((
260                attempt.point,
261                attempt.used_backward_euler,
262                dt,
263                attempt.suggested_dt_next,
264            ));
265        }
266        dt = attempt.suggested_dt_next;
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn from_t_final_orders_the_three_step_sizes_sensibly() {
276        let config = AdaptiveConfig::from_t_final(1e-3);
277        assert!(config.dt_min < config.dt_init);
278        assert!(config.dt_init < config.dt_max);
279        assert_eq!(config.dt_max, 1e-6);
280    }
281}