Skip to main content

dune_core/
ltra.rs

1//! Lossy transmission line, Roychowdhury's convolution model (the 3f5
2//! `LTRA` device: `dev/ltra/ltraset.c`, `ltratemp.c`, `ltraload.c`,
3//! `ltraacct.c`, `ltratrun.c`, `ltraacld.c`, `ltramisc.c`).
4//!
5//! Each port obeys a branch equation (`LTRAbrEq1/2`, created with
6//! `CKTmkVolt`, so the front end and the convergence test treat them
7//! as *voltage* unknowns even though they carry the port currents):
8//!
9//! ```text
10//! Y0·v1(t) − i1(t) = Y0·(h1' ∗ v1) + (h2 ∗ i2)(t−T) + Y0·(h3' ∗ v2)(t−T)
11//!                    + e^{−βT}·(Y0·v2(t−T) + i2(t−T))
12//! ```
13//!
14//! (and symmetrically for port 2), with `T = l·sqrt(LC)` the delay,
15//! `Y0 = sqrt(C/L)`, `α = β = R/2L` (G = 0). The impulse responses
16//! (`ltramisc.c`, tilde-functions of the paper):
17//!
18//! - `h1'(t) = α·e^{−βt}·(I1(αt) − I0(αt))`
19//! - `h2(t)  = α²T·e^{−βt}·I1(α·√(t²−T²))/(α·√(t²−T²))`, `t ≥ T`
20//! - `h3'(t) = α·e^{−βt}·(t/√(t²−T²)·I1(α√(t²−T²)) − I0(α√(t²−T²)))`
21//!
22//! are convolved with the piecewise-linear port histories: the
23//! coefficient lists (`LTRArlcCoeffsSetup`, `LTRArcCoeffsSetup`) are
24//! second differences of the analytic twice-integrated responses on
25//! the accepted-timepoint grid (`CKTtimePoints`), recomputed on the
26//! first Newton iteration of every timepoint. Delayed values come
27//! from quadratic/linear interpolation in that grid. Four regimes:
28//! LC (lossless), RLC, RC (`L = G = 0`, erfc kernels) and RG (a
29//! frequency-independent attenuator stamped like DC).
30//!
31//! The line keeps its own copy of the accepted-timepoint list (the
32//! C's global `CKTtimePoints`, which `DCtran` only maintains when an
33//! LTRA instance exists); each instance stores its port histories.
34//! `.options trytocompact` (`ltraacct.c`) is ported: after an accepted
35//! point where the last three samples of *every* line's port
36//! variables are straight (`LtraI::straight_tail`), the engine drops
37//! the middle sample of every line (`LtraI::drop_middle`) — the C's
38//! shared `CKTtimePoints` list, kept per instance here in lockstep.
39//! Not ported: `LTRAlteCalculate`: its LTE control needs
40//! `fullcontrol`/`halfcontrol`, which the 3f5 (and ngspice) parameter
41//! tables never accept, so it is unreachable.
42//!
43//! Dune's opt-in recursive mode (`Options::ltra_fit`, issue #8)
44//! replaces the RLC/RC coefficient walk with the exponential sums of
45//! [`crate::ltrafit`], advanced once per accepted point; off, every
46//! line of the faithful path runs unchanged.
47
48use crate::devices::Device;
49use crate::disto::DistoSetupCtx;
50use crate::integ::TerrCtx;
51use crate::ltrafit::{
52    ExpFit, RC_WINDOW_FRACTION, fit_rc, fit_rlc, i0e, i1e, i1e_over_x, rc_integrals, segment,
53};
54use crate::matrix::{
55    AcCtx, AcceptCtx, InitMode, LoadCtx, MatrixBuilder, PeriodicPast, Slot, TRASH, Var,
56};
57
58// Every transcendental in this file goes through the pure-Rust `libm`
59// crate (fdlibm lineage — what `f64::exp` already lowers to on wasm32),
60// not `f64::exp`/`cos`/…, which call the platform C library (Apple's
61// libm and glibc disagree in the last ulp). The line's own kernels
62// (`e^{−βt}·I0/I1`, erfc) then compute the same bits on every target;
63// `sqrt` and the arithmetic are IEEE-exact already. This does NOT make
64// the ringing decks (ltra_1/ltra_3) platform-independent: their
65// trajectory forks on ulps from anywhere (diode/BJT `exp`, the LU), and
66// once the dioload string rings period-2, `accept`'s slope test plants
67// a breakpoint at `t+T` on nearly every step, which forces tiny steps
68// at `t+T`, which ring and plant more — a cascade faithful to
69// ltraacct.c that never ends inside the output guard.
70use libm::{atan, cos, exp, expm1, sin};
71
72/// How the delayed port values `v(t−T)`, `i(t−T)` are interpolated
73/// from the accepted timepoints (`LININTERP`/`QUADINTERP`/
74/// `MIXEDINTERP`).
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum LtraInterp {
77    /// `LININTERP`: linear between the two bracketing points.
78    Linear,
79    /// `QUADINTERP` (the default): quadratic through three points.
80    Quadratic,
81    /// `MIXEDINTERP`: quadratic, falling back to linear when the
82    /// quadratic value leaves the range of the three samples.
83    Mixed,
84}
85
86/// `.model … ltra(…)` parameters, 3f5 names (`ltra.c` model table,
87/// `ltrampar.c`; `spice.txt` §Lossy Transmission Lines). Per-unit-
88/// length quantities are multiplied by `LEN`.
89#[derive(Clone, Debug)]
90pub struct LtraModel {
91    /// `R`: resistance per unit length (Ω); unset = 0 with a warning.
92    pub r: Option<f64>,
93    /// `L`: inductance per unit length (H); unset = 0 with a warning.
94    pub l: Option<f64>,
95    /// `G`: conductance per unit length (S); unset = 0.
96    pub g: Option<f64>,
97    /// `C`: capacitance per unit length (F); unset = 0 with a
98    /// warning.
99    pub c: Option<f64>,
100    /// `LEN`: length of the line; required.
101    pub len: Option<f64>,
102    /// `REL`: relative rate of change of the derivative for breakpoint
103    /// setting, default 1. (An output-only parameter in the 3f5
104    /// table; ngspice accepts it as input — corpus/KNOWN_DIFFS.md.)
105    pub rel: Option<f64>,
106    /// `ABS`: absolute rate of change of the derivative for
107    /// breakpoint setting, default 1 (same 3f5/ngspice note).
108    pub abs: Option<f64>,
109    /// `STEPLIMIT` (true, the default) / `NOSTEPLIMIT` (false): limit
110    /// the timestep to the line delay `T`. The last flag wins.
111    pub steplimit: bool,
112    /// `LININTERP`/`QUADINTERP`/`MIXEDINTERP`; `None` = quadratic
113    /// (linear under `.options trytocompact`).
114    pub interp: Option<LtraInterp>,
115    /// `TRUNCNR`: Newton iterations for the LTE step estimate (only
116    /// reachable with LTE control, which the parameter table never
117    /// enables; kept for completeness).
118    pub truncnr: bool,
119    /// `TRUNCDONTCUT`: do not limit the step by the impulse-response
120    /// safe step (`LTRAmaxSafeStep`) of RLC lines.
121    pub truncdontcut: bool,
122    /// `COMPACTREL`: reltol for the straight-line checks; 0 = the
123    /// circuit `RELTOL`.
124    pub compactrel: f64,
125    /// `COMPACTABS`: abstol for the straight-line checks; 0 = the
126    /// circuit `ABSTOL`.
127    pub compactabs: f64,
128}
129
130impl Default for LtraModel {
131    fn default() -> Self {
132        LtraModel {
133            r: None,
134            l: None,
135            g: None,
136            c: None,
137            len: None,
138            rel: None,
139            abs: None,
140            steplimit: true,
141            interp: None,
142            truncnr: false,
143            truncdontcut: false,
144            compactrel: 0.0,
145            compactabs: 0.0,
146        }
147    }
148}
149
150/// `LTRAspecialCase`.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub(crate) enum LtraCase {
153    Lc,
154    Rlc,
155    Rc,
156    Rg,
157}
158
159/// Model quantities after `LTRAsetup` + `LTRAtemp` (and the RG
160/// constants `LTRAload` computes in DC mode, which depend on nothing
161/// else).
162#[derive(Clone, Debug)]
163pub(crate) struct LtraParams {
164    /// The instance name, for notes.
165    pub name: String,
166    pub case: LtraCase,
167    resist: f64,
168    induct: f64,
169    capac: f64,
170    length: f64,
171    /// `LTRAtd`, the propagation delay.
172    pub td: f64,
173    imped: f64,
174    admit: f64,
175    alpha: f64,
176    beta: f64,
177    /// `e^{−βT}`; 1 for LC, unset (0) for RC/RG like the C.
178    attenuation: f64,
179    cbyr: f64,
180    rclsqr: f64,
181    int_h1dash: f64,
182    int_h2: f64,
183    int_h3dash: f64,
184    cosh_lroot_gr: f64,
185    r_rs_lr_gr_or_g: f64,
186    r_gs_lr_gr_or_r: f64,
187    reltol: f64,
188    abstol: f64,
189    /// `LTRAchopReltol`: never settable (`choprel` is `#ifdef
190    /// notdef` in the table), so always 0.
191    chop_reltol: f64,
192    step_limit: bool,
193    interp: LtraInterp,
194    trunc_dont_cut: bool,
195    max_safe_step: f64,
196    /// `LTRAstLineReltol`/`LTRAstLineAbstol` (`COMPACTREL`/
197    /// `COMPACTABS`, the circuit tolerances when 0): the straight-line
198    /// checks of the safe step and of `trytocompact`.
199    st_line_reltol: f64,
200    st_line_abstol: f64,
201    /// Whether the model card gave an interpolation flag (`LTRAsetup`
202    /// only picks the default when none was given).
203    interp_given: bool,
204    /// Setup warnings (`IFerror(ERR_WARNING, …)`).
205    pub notes: Vec<String>,
206}
207
208impl LtraParams {
209    /// `LTRAsetup` (validation, defaults, case classification) and
210    /// `LTRAtemp` (derived constants). `reltol`/`abstol` are the
211    /// circuit tolerances the straight-line checks default to.
212    pub fn new(name: &str, m: &LtraModel, reltol: f64, abstol: f64) -> Result<Self, String> {
213        let mut notes = Vec::new();
214        for (key, v) in [
215            ("r", m.r),
216            ("l", m.l),
217            ("g", m.g),
218            ("c", m.c),
219            ("len", m.len),
220            ("rel", m.rel),
221            ("abs", m.abs),
222        ] {
223            if let Some(v) = v
224                && !v.is_finite()
225            {
226                return Err(format!(
227                    "`{name}`: lossy line parameter {key} is not finite"
228                ));
229            }
230        }
231        let resist = match m.r {
232            Some(v) => v,
233            None => {
234                notes.push(format!(
235                    "`{name}`: lossy line series resistance not given, assumed zero"
236                ));
237                0.0
238            }
239        };
240        let st_line_reltol = if m.compactrel == 0.0 {
241            reltol
242        } else {
243            m.compactrel
244        };
245        let st_line_abstol = if m.compactabs == 0.0 {
246            abstol
247        } else {
248            m.compactabs
249        };
250        let interp = m.interp.unwrap_or(LtraInterp::Quadratic);
251        let conduct = m.g.unwrap_or(0.0);
252        let induct = match m.l {
253            Some(v) => v,
254            None => {
255                notes.push(format!(
256                    "`{name}`: lossy line series inductance not given, assumed zero"
257                ));
258                0.0
259            }
260        };
261        // The C reports a missing C as ERR_FATAL but carries on with
262        // zero (no `return`), so it is a warning in effect.
263        let capac = match m.c {
264            Some(v) => v,
265            None => {
266                notes.push(format!(
267                    "`{name}`: lossy line parallel capacitance not given, assumed zero"
268                ));
269                0.0
270            }
271        };
272        let Some(length) = m.len else {
273            return Err(format!("`{name}`: lossy line length must be given"));
274        };
275
276        // Classification, in the C's order (later tests win, errors
277        // return at once).
278        let (r, g, l, c) = (resist, conduct, induct, capac);
279        let mut case = None;
280        if r == 0.0 && g == 0.0 && c != 0.0 && l != 0.0 {
281            case = Some(LtraCase::Lc);
282        }
283        if r != 0.0 && g == 0.0 && c != 0.0 && l != 0.0 {
284            case = Some(LtraCase::Rlc);
285        }
286        if r != 0.0 && g == 0.0 && c != 0.0 && l == 0.0 {
287            case = Some(LtraCase::Rc);
288        }
289        if r != 0.0 && g == 0.0 && c == 0.0 && l != 0.0 {
290            return Err(format!("`{name}`: RL line not supported yet"));
291        }
292        if r != 0.0 && g != 0.0 && c == 0.0 && l == 0.0 {
293            case = Some(LtraCase::Rg);
294        }
295        if g != 0.0 && (c != 0.0 || l != 0.0) {
296            return Err(format!(
297                "`{name}`: Nonzero G (except RG) line not supported yet"
298            ));
299        }
300        let nonzero = [r, g, l, c].iter().filter(|v| **v != 0.0).count();
301        let Some(case) = case.filter(|_| nonzero > 1) else {
302            return Err(format!(
303                "`{name}`: At least two of R,L,G,C must be specified and nonzero"
304            ));
305        };
306
307        let mut p = LtraParams {
308            name: name.to_string(),
309            case,
310            resist,
311            induct,
312            capac,
313            length,
314            td: 0.0,
315            imped: 0.0,
316            admit: 0.0,
317            alpha: 0.0,
318            beta: 0.0,
319            attenuation: 0.0,
320            cbyr: 0.0,
321            rclsqr: 0.0,
322            int_h1dash: 0.0,
323            int_h2: 0.0,
324            int_h3dash: 0.0,
325            cosh_lroot_gr: 0.0,
326            r_rs_lr_gr_or_g: 0.0,
327            r_gs_lr_gr_or_r: 0.0,
328            reltol: m.rel.unwrap_or(1.0),
329            abstol: m.abs.unwrap_or(1.0),
330            chop_reltol: 0.0,
331            step_limit: m.steplimit,
332            interp,
333            trunc_dont_cut: m.truncdontcut,
334            max_safe_step: 0.0,
335            st_line_reltol,
336            st_line_abstol,
337            interp_given: m.interp.is_some(),
338            notes,
339        };
340
341        // `LTRAtemp`.
342        match case {
343            LtraCase::Lc => {
344                p.imped = (l / c).sqrt();
345                p.admit = 1.0 / p.imped;
346                p.td = (l * c).sqrt() * length;
347                p.attenuation = 1.0;
348            }
349            LtraCase::Rlc => {
350                p.imped = (l / c).sqrt();
351                p.admit = 1.0 / p.imped;
352                p.td = (l * c).sqrt() * length;
353                p.alpha = 0.5 * (r / l);
354                p.beta = p.alpha;
355                p.attenuation = exp(-p.beta * p.td);
356                if p.alpha > 0.0 {
357                    p.int_h1dash = -1.0;
358                    p.int_h2 = 1.0 - p.attenuation;
359                    p.int_h3dash = -p.attenuation;
360                }
361                // alpha == 0: all zero; alpha < 0: the C leaves them
362                // at their calloc'd zero too.
363                if !p.trunc_dont_cut {
364                    p.max_safe_step =
365                        max_safe_step(p.td, p.alpha, p.beta, st_line_reltol, st_line_abstol);
366                }
367            }
368            LtraCase::Rc => {
369                p.cbyr = c / r;
370                p.rclsqr = r * c * length * length;
371                p.int_h1dash = 0.0;
372                p.int_h2 = 1.0;
373                p.int_h3dash = 0.0;
374            }
375            LtraCase::Rg => {
376                // `LTRAload` under MODEDC.
377                let x = length * (r * g).sqrt();
378                let em = exp(-x);
379                let ep = exp(x); // "LTRA warning: may overflow!"
380                p.cosh_lroot_gr = 0.5 * (ep + em);
381                p.r_rs_lr_gr_or_g = if g <= 1.0e-10 {
382                    // hack!
383                    length * r
384                } else {
385                    0.5 * (ep - em) * (r / g).sqrt()
386                };
387                p.r_gs_lr_gr_or_r = if r <= 1.0e-10 {
388                    // hack!
389                    length * g
390                } else {
391                    0.5 * (ep - em) * (g / r).sqrt()
392                };
393            }
394        }
395        Ok(p)
396    }
397
398    /// The Dune profile's interpolation (D-0052): a model without an
399    /// interpolation flag takes linear interpolation instead of the
400    /// 3f5's quadratic. Through a corner on the uneven grid the step
401    /// control leaves there, the parabola overshoots the delayed
402    /// wave; measured against refined runs at the decks' own step,
403    /// `ltra_1` is 5.1 rulers off with it and 2.4 with the linear
404    /// rule, `ltra_3` 7.3 and 2.9. A flag on the model card wins.
405    pub fn default_linear(&mut self) {
406        if !self.interp_given {
407            self.interp = LtraInterp::Linear;
408        }
409    }
410
411    /// `.options trytocompact` in `LTRAsetup` (`ltraset.c:55-72`, the
412    /// same in the 3f5): a model without an interpolation flag takes
413    /// linear interpolation instead of quadratic, with the C's warning.
414    pub fn try_to_compact(&mut self) {
415        if !self.interp_given {
416            self.interp = LtraInterp::Linear;
417            self.notes.push(format!(
418                "{}: using linear interpolation because trytocompact option specified",
419                self.name
420            ));
421        }
422    }
423}
424
425/// The `LTRAmaxSafeStep` bisection of `LTRAtemp`: shrink
426/// `[T, 10T]` towards `T` until `h2` looks straight over it. The C
427/// evaluates `h3'` alongside but passes the `h2` triple to
428/// `LTRAstraightLineCheck` twice (so only `h2` decides); ported as
429/// is. The function evaluations are pure, so the unused `h3'` values
430/// are not computed here.
431fn max_safe_step(td: f64, alpha: f64, beta: f64, reltol: f64, abstol: f64) -> f64 {
432    let mut xbig = td + 9.0 * td; // "hack! ckt is not yet initialised..."
433    let xsmall = td;
434    let mut xmid = 0.5 * (xbig + xsmall);
435    let y1small = rlc_h2(xsmall, td, alpha, beta);
436    let maxiter = 50;
437    let mut iters = 0;
438    loop {
439        iters += 1;
440        let y1big = rlc_h2(xbig, td, alpha, beta);
441        let y1mid = rlc_h2(xmid, td, alpha, beta);
442        let one = straight_line_check(xbig, y1big, xmid, y1mid, xsmall, y1small, reltol, abstol);
443        let done = one as u32 + one as u32;
444        if done == 2 || iters > maxiter {
445            break;
446        }
447        xbig = xmid;
448        xmid = 0.5 * (xbig + xsmall);
449    }
450    xbig - td
451}
452
453// ---------------------------------------------------------------------
454// ltramisc.c
455// ---------------------------------------------------------------------
456
457/// `LTRAquadInterp`: coefficients of the quadratic through
458/// `(t1, t2, t3)` evaluated at `t`; `None` when two abscissae
459/// coincide (the C returns 1 and leaves them unset).
460fn quad_interp(t: f64, t1: f64, t2: f64, t3: f64) -> Option<(f64, f64, f64)> {
461    if t == t1 {
462        return Some((1.0, 0.0, 0.0));
463    }
464    if t == t2 {
465        return Some((0.0, 1.0, 0.0));
466    }
467    if t == t3 {
468        return Some((0.0, 0.0, 1.0));
469    }
470    if (t2 - t1) == 0.0 || (t3 - t2) == 0.0 || (t1 - t3) == 0.0 {
471        return None;
472    }
473    let mut f1 = (t - t2) * (t - t3);
474    let mut f2 = (t - t1) * (t - t3);
475    let mut f3 = (t - t1) * (t - t2);
476    f1 /= t1 - t2;
477    f2 /= t2 - t1;
478    f2 /= t2 - t3;
479    f3 /= t2 - t3;
480    f1 /= t1 - t3;
481    f3 /= t1 - t3;
482    Some((f1, f2, f3))
483}
484
485/// `LTRAlinInterp`.
486fn lin_interp(t: f64, t1: f64, t2: f64) -> Option<(f64, f64)> {
487    if t1 == t2 {
488        return None;
489    }
490    if t == t1 {
491        return Some((1.0, 0.0));
492    }
493    if t == t2 {
494        return Some((0.0, 1.0));
495    }
496    let temp = (t - t1) / (t2 - t1);
497    Some((1.0 - temp, temp))
498}
499
500/// `intlinfunc`: `∫_lo^hi h(τ)dτ` for `h` linear through
501/// `(t1, lovalue)`, `(t2, hivalue)`.
502fn intlinfunc(lolimit: f64, hilimit: f64, lovalue: f64, hivalue: f64, t1: f64, t2: f64) -> f64 {
503    let width = t2 - t1;
504    if width == 0.0 {
505        return 0.0;
506    }
507    let m = (hivalue - lovalue) / width;
508    (hilimit - lolimit) * lovalue
509        + 0.5 * m * ((hilimit - t1) * (hilimit - t1) - (lolimit - t1) * (lolimit - t1))
510}
511
512/// `twiceintlinfunc`: `∫_lo^hi ∫_otherlo^τ h(τ')dτ'dτ`, `h` linear as
513/// in [`intlinfunc`].
514fn twiceintlinfunc(
515    lolimit: f64,
516    hilimit: f64,
517    otherlolimit: f64,
518    lovalue: f64,
519    hivalue: f64,
520    t1: f64,
521    t2: f64,
522) -> f64 {
523    let width = t2 - t1;
524    if width == 0.0 {
525        return 0.0;
526    }
527    let m = (hivalue - lovalue) / width;
528    let temp1 = hilimit - t1;
529    let temp2 = lolimit - t1;
530    let temp3 = otherlolimit - t1;
531    let mut dummy = lovalue
532        * ((hilimit - otherlolimit) * (hilimit - otherlolimit)
533            - (lolimit - otherlolimit) * (lolimit - otherlolimit));
534    dummy += m
535        * ((temp1 * temp1 * temp1 - temp2 * temp2 * temp2) / 3.0
536            - temp3 * temp3 * (hilimit - lolimit));
537    dummy * 0.5
538}
539
540/// `bessI0` (Numerical Recipes polynomial fits).
541fn bess_i0(x: f64) -> f64 {
542    let ax = x.abs();
543    if ax < 3.75 {
544        let y = (x / 3.75) * (x / 3.75);
545        1.0 + y
546            * (3.5156229
547                + y * (3.0899424
548                    + y * (1.2067492 + y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2)))))
549    } else {
550        let y = 3.75 / ax;
551        (exp(ax) / ax.sqrt())
552            * (0.39894228
553                + y * (0.1328592e-1
554                    + y * (0.225319e-2
555                        + y * (-0.157565e-2
556                            + y * (0.916281e-2
557                                + y * (-0.2057706e-1
558                                    + y * (0.2635537e-1
559                                        + y * (-0.1647633e-1 + y * 0.392377e-2))))))))
560    }
561}
562
563/// `bessI1` (Numerical Recipes).
564fn bess_i1(x: f64) -> f64 {
565    let ax = x.abs();
566    let ans = if ax < 3.75 {
567        let y = (x / 3.75) * (x / 3.75);
568        ax * (0.5
569            + y * (0.87890594
570                + y * (0.51498869
571                    + y * (0.15084934 + y * (0.2658733e-1 + y * (0.301532e-2 + y * 0.32411e-3))))))
572    } else {
573        let y = 3.75 / ax;
574        let a = 0.2282967e-1 + y * (-0.2895312e-1 + y * (0.1787654e-1 - y * 0.420059e-2));
575        let a = 0.39894228
576            + y * (-0.3988024e-1
577                + y * (-0.362018e-2 + y * (0.163801e-2 + y * (-0.1031555e-1 + y * a))));
578        a * (exp(ax) / ax.sqrt())
579    };
580    if x < 0.0 { -ans } else { ans }
581}
582
583/// `bessI1xOverX`: `I1(x)/x`, finite at 0.
584fn bess_i1_x_over_x(x: f64) -> f64 {
585    let ax = x.abs();
586    if ax < 3.75 {
587        let y = (x / 3.75) * (x / 3.75);
588        0.5 + y
589            * (0.87890594
590                + y * (0.51498869
591                    + y * (0.15084934 + y * (0.2658733e-1 + y * (0.301532e-2 + y * 0.32411e-3)))))
592    } else {
593        let y = 3.75 / ax;
594        let a = 0.2282967e-1 + y * (-0.2895312e-1 + y * (0.1787654e-1 - y * 0.420059e-2));
595        let a = 0.39894228
596            + y * (-0.3988024e-1
597                + y * (-0.362018e-2 + y * (0.163801e-2 + y * (-0.1031555e-1 + y * a))));
598        a * (exp(ax) / (ax * ax.sqrt()))
599    }
600}
601
602/// `LTRArlcH2Func`: `h2(t) = α²T·e^{−βt}·I1(α√(t²−T²))/(α√(t²−T²))`
603/// for `t ≥ T`, else 0.
604fn rlc_h2(time: f64, t: f64, alpha: f64, beta: f64) -> f64 {
605    if alpha == 0.0 {
606        return 0.0;
607    }
608    if time < t {
609        return 0.0;
610    }
611    let besselarg = if time != t {
612        alpha * (time * time - t * t).sqrt()
613    } else {
614        0.0
615    };
616    let exparg = -beta * time;
617    alpha * alpha * t * exp(exparg) * bess_i1_x_over_x(besselarg)
618}
619
620/// `LTRAstraightLineCheck`: do the three points lie acceptably close
621/// to a straight line? Compares the triangle they enclose with the
622/// trapezoid areas under them (an integral-flavoured criterion).
623#[allow(clippy::too_many_arguments)]
624fn straight_line_check(
625    x1: f64,
626    y1: f64,
627    x2: f64,
628    y2: f64,
629    x3: f64,
630    y3: f64,
631    reltol: f64,
632    abstol: f64,
633) -> bool {
634    let quad1 = (y2.abs() + y1.abs()) * 0.5 * (x2 - x1).abs();
635    let quad2 = (y3.abs() + y2.abs()) * 0.5 * (x3 - x2).abs();
636    let quad3 = (y3.abs() + y1.abs()) * 0.5 * (x3 - x1).abs();
637    let tr_area = (quad3 - quad1 - quad2).abs();
638    let area = quad1 + quad2;
639    area * reltol + abstol > tr_area
640}
641
642/// First coefficients and convolution lists for one timepoint
643/// (`LTRAh*FirstCoeff`, `LTRAh*Coeffs`, `LTRAauxIndex`).
644#[derive(Clone, Debug, Default)]
645struct Coeffs {
646    h1_first: f64,
647    h2_first: f64,
648    h3_first: f64,
649    h1: Vec<f64>,
650    h2: Vec<f64>,
651    h3: Vec<f64>,
652    aux_index: usize,
653}
654
655impl Coeffs {
656    fn ensure(&mut self, n: usize) {
657        if self.h1.len() < n {
658            self.h1.resize(n, 0.0);
659            self.h2.resize(n, 0.0);
660            self.h3.resize(n, 0.0);
661        }
662    }
663}
664
665/// `LTRArlcCoeffsSetup`: the RLC coefficient lists for `curtime`,
666/// assuming piecewise-linear port waveforms between the accepted
667/// `timelist[0..=timeindex]`. `h1'` uses its closed-form twice
668/// integral; `h2` and `h3'` (which start at `T`) integrate a linear
669/// interpolation of the function between grid-aligned lags. The
670/// chop tests use `<=` (the RC version uses `<`); with the always-0
671/// chop reltol they only stop on an exactly zero coefficient.
672///
673/// The `i == auxindex` correction of the previous interval's
674/// `[lolimit2, hilimit2]` is commented out in the C (`/* if (i ==
675/// auxindex) { lolimit2 = T; … } */`); ported as is.
676#[allow(clippy::too_many_arguments)]
677fn rlc_coeffs(
678    co: &mut Coeffs,
679    t: f64,
680    alpha: f64,
681    beta: f64,
682    curtime: f64,
683    timelist: &[f64],
684    timeindex: usize,
685    reltol: f64,
686) {
687    co.ensure(timeindex + 1);
688
689    let auxindex: usize = if t == 0.0 {
690        timeindex
691    } else if curtime - t <= 0.0 {
692        0
693    } else {
694        let mut exact = false;
695        let mut found: isize = -1;
696        for i in (0..=timeindex).rev() {
697            if curtime - timelist[i] == t {
698                exact = true;
699                found = i as isize;
700                break;
701            }
702            if curtime - timelist[i] > t {
703                found = i as isize;
704                break;
705            }
706        }
707        // "LTRAcoeffSetup: i <= 0: some mistake!" — cannot happen
708        // (timelist[0] = 0 and curtime > T); clamp instead of
709        // indexing before the list like the C would.
710        let a = if exact { found - 1 } else { found };
711        a.max(0) as usize
712    };
713
714    let alphasq_t = alpha * alpha * t;
715    let expbeta_t = exp(-beta * t);
716
717    let (mut h2lovalue1, mut h2hivalue1, mut h2dummy1, mut h2relval) = (0.0, 0.0, 0.0, 0.0);
718    let (mut h3hivalue1, mut h3dummy1, mut h3relval) = (0.0, 0.0, 0.0);
719
720    // The first coefficient (the lag `curtime − T`).
721    if auxindex != 0 {
722        let lolimit1 = t;
723        let hilimit1 = curtime - timelist[auxindex];
724        let delta1 = hilimit1 - lolimit1;
725
726        h2lovalue1 = rlc_h2(t, t, alpha, beta);
727        let besselarg = if hilimit1 > t {
728            alpha * (hilimit1 * hilimit1 - t * t).sqrt()
729        } else {
730            0.0
731        };
732        let expterm = exp(-beta * hilimit1);
733        let bessi1overxterm = bess_i1_x_over_x(besselarg);
734        h2hivalue1 = if alpha == 0.0 || hilimit1 < t {
735            0.0
736        } else {
737            alphasq_t * expterm * bessi1overxterm
738        };
739        h2dummy1 = twiceintlinfunc(
740            lolimit1, hilimit1, lolimit1, h2lovalue1, h2hivalue1, lolimit1, hilimit1,
741        ) / delta1;
742        co.h2_first = h2dummy1;
743        h2relval = (reltol * h2dummy1).abs();
744
745        let h3lovalue1 = 0.0; // E3dash should be consistent with this
746        let bessi0term = bess_i0(besselarg);
747        h3hivalue1 = if hilimit1 <= t || beta == 0.0 {
748            0.0
749        } else {
750            expterm * bessi0term - expbeta_t
751        };
752        h3dummy1 = intlinfunc(
753            lolimit1, hilimit1, h3lovalue1, h3hivalue1, lolimit1, hilimit1,
754        ) / delta1;
755        co.h3_first = h3dummy1;
756        h3relval = (h3dummy1 * reltol).abs();
757    } else {
758        co.h2_first = 0.0;
759        co.h3_first = 0.0;
760    }
761
762    let mut lolimit1 = 0.0;
763    let mut hilimit1 = curtime - timelist[timeindex];
764    let mut delta1 = hilimit1 - lolimit1;
765    let mut exparg = -beta * hilimit1;
766    let mut expterm = exp(exparg);
767
768    let h1twice = |hilimit1: f64, exparg: f64, expterm: f64| -> f64 {
769        // LTRArlcH1dashTwiceIntFunc(hilimit1, beta), inlined.
770        if beta == 0.0 {
771            hilimit1
772        } else if hilimit1 == 0.0 {
773            0.0
774        } else {
775            (bess_i1(-exparg) + bess_i0(-exparg)) * hilimit1 * expterm - hilimit1
776        }
777    };
778    let mut h1hivalue1 = h1twice(hilimit1, exparg, expterm);
779    let mut h1dummy1 = h1hivalue1 / delta1;
780    co.h1_first = h1dummy1;
781    let h1relval = (h1dummy1 * reltol).abs();
782
783    let (mut doh1, mut doh2, mut doh3) = (true, true, true);
784    let (mut lolimit2, mut hilimit2) = (0.0, 0.0);
785
786    for i in (1..=timeindex).rev() {
787        if doh1 || doh2 || doh3 {
788            lolimit2 = lolimit1;
789            hilimit2 = hilimit1;
790            lolimit1 = hilimit2;
791            hilimit1 = curtime - timelist[i - 1];
792            delta1 = timelist[i] - timelist[i - 1];
793            exparg = -beta * hilimit1;
794            expterm = exp(exparg);
795        }
796
797        if doh1 {
798            let h1hivalue2 = h1hivalue1;
799            let h1dummy2 = h1dummy1;
800            let h1lovalue1 = h1hivalue2;
801            h1hivalue1 = h1twice(hilimit1, exparg, expterm);
802            h1dummy1 = (h1hivalue1 - h1lovalue1) / delta1;
803            co.h1[i] = h1dummy1 - h1dummy2;
804            if co.h1[i].abs() <= h1relval {
805                doh1 = false;
806            }
807        } else {
808            co.h1[i] = 0.0;
809        }
810
811        if i <= auxindex {
812            let mut besselarg = 0.0;
813            if doh2 || doh3 {
814                besselarg = if hilimit1 > t {
815                    alpha * (hilimit1 * hilimit1 - t * t).sqrt()
816                } else {
817                    0.0
818                };
819            }
820
821            if doh2 {
822                let h2lovalue2 = h2lovalue1;
823                let h2hivalue2 = h2hivalue1;
824                let h2dummy2 = h2dummy1;
825                h2lovalue1 = h2hivalue2;
826                let bessi1overxterm = bess_i1_x_over_x(besselarg);
827                h2hivalue1 = if alpha == 0.0 || hilimit1 < t {
828                    0.0
829                } else {
830                    alphasq_t * expterm * bessi1overxterm
831                };
832                h2dummy1 = twiceintlinfunc(
833                    lolimit1, hilimit1, lolimit1, h2lovalue1, h2hivalue1, lolimit1, hilimit1,
834                ) / delta1;
835                co.h2[i] = h2dummy1 - h2dummy2
836                    + intlinfunc(
837                        lolimit2, hilimit2, h2lovalue2, h2hivalue2, lolimit2, hilimit2,
838                    );
839                if co.h2[i].abs() <= h2relval {
840                    doh2 = false;
841                }
842            } else {
843                co.h2[i] = 0.0;
844            }
845
846            if doh3 {
847                let h3hivalue2 = h3hivalue1;
848                let h3dummy2 = h3dummy1;
849                let h3lovalue1 = h3hivalue2;
850                let bessi0term = bess_i0(besselarg);
851                h3hivalue1 = if hilimit1 <= t || beta == 0.0 {
852                    0.0
853                } else {
854                    expterm * bessi0term - expbeta_t
855                };
856                h3dummy1 = intlinfunc(
857                    lolimit1, hilimit1, h3lovalue1, h3hivalue1, lolimit1, hilimit1,
858                ) / delta1;
859                co.h3[i] = h3dummy1 - h3dummy2;
860                if co.h3[i].abs() <= h3relval {
861                    doh3 = false;
862                }
863            } else {
864                co.h3[i] = 0.0;
865            }
866        }
867    }
868    co.aux_index = auxindex;
869}
870
871/// `erfc`, the C library's (fdlibm lineage, via `libm` like every
872/// transcendental here — see the note at the top of the file).
873fn erfc(x: f64) -> f64 {
874    libm::erfc(x)
875}
876
877/// `LTRArcCoeffsSetup`: the RC (`L = G = 0`) coefficient lists, from
878/// the closed-form twice-integrated responses
879/// `H1''(t) = √(4·(C/R)·t/π)`,
880/// `H2''(t) = (t + RCl²/2)·erfc(√(RCl²/4t)) − √(t·RCl²/π)·e^{−RCl²/4t}`,
881/// `H3''(t) = √(C/R)·(2√(t/π)·e^{−RCl²/4t} − √(RCl²)·erfc(√(RCl²/4t)))`.
882/// Chop tests use `<` (never true with the 0 chop reltol).
883fn rc_coeffs(
884    co: &mut Coeffs,
885    cbyr: f64,
886    rclsqr: f64,
887    curtime: f64,
888    timelist: &[f64],
889    timeindex: usize,
890    reltol: f64,
891) {
892    use std::f64::consts::PI;
893    co.ensure(timeindex + 1);
894    let auxindex = timeindex;
895
896    let mut delta1 = curtime - timelist[auxindex];
897    let mut hilimit1 = delta1;
898
899    let mut h1hivalue1 = (4.0 * cbyr * hilimit1 / PI).sqrt();
900    let mut h1dummy1 = h1hivalue1 / delta1;
901    co.h1_first = h1dummy1;
902    let h1relval = (h1dummy1 * reltol).abs();
903
904    let mut temp = rclsqr / (4.0 * hilimit1);
905    let mut temp2 = if temp >= 100.0 {
906        0.0
907    } else {
908        erfc(temp.sqrt())
909    };
910    let mut temp3 = exp(-temp);
911    let temp4 = rclsqr.sqrt();
912    let temp5 = cbyr.sqrt();
913
914    let mut h2hivalue1 = if hilimit1 != 0.0 {
915        (hilimit1 + rclsqr * 0.5) * temp2 - (hilimit1 * rclsqr / PI).sqrt() * temp3
916    } else {
917        0.0
918    };
919    let mut h2dummy1 = h2hivalue1 / delta1;
920    co.h2_first = h2dummy1;
921    let h2relval = (h2dummy1 * reltol).abs();
922
923    let h3of = |hilimit1: f64, temp2: f64, temp3: f64| -> f64 {
924        if hilimit1 != 0.0 {
925            let temp = 2.0 * (hilimit1 / PI).sqrt() * temp3 - temp4 * temp2;
926            temp5 * temp
927        } else {
928            0.0
929        }
930    };
931    let mut h3hivalue1 = h3of(hilimit1, temp2, temp3);
932    let mut h3dummy1 = h3hivalue1 / delta1;
933    co.h3_first = h3dummy1;
934    let h3relval = (h3dummy1 * reltol).abs();
935
936    let (mut doh1, mut doh2, mut doh3) = (true, true, true);
937    for i in (1..=auxindex).rev() {
938        delta1 = timelist[i] - timelist[i - 1];
939        hilimit1 = curtime - timelist[i - 1];
940
941        if doh1 {
942            let h1hivalue2 = h1hivalue1;
943            let h1dummy2 = h1dummy1;
944            let h1lovalue1 = h1hivalue2;
945            h1hivalue1 = (4.0 * cbyr * hilimit1 / PI).sqrt();
946            h1dummy1 = (h1hivalue1 - h1lovalue1) / delta1;
947            co.h1[i] = h1dummy1 - h1dummy2;
948            if co.h1[i].abs() < h1relval {
949                doh1 = false;
950            }
951        } else {
952            co.h1[i] = 0.0;
953        }
954
955        if doh2 || doh3 {
956            temp = rclsqr / (4.0 * hilimit1);
957            temp2 = if temp >= 100.0 {
958                0.0
959            } else {
960                erfc(temp.sqrt())
961            };
962            temp3 = exp(-temp);
963        }
964
965        if doh2 {
966            let h2hivalue2 = h2hivalue1;
967            let h2dummy2 = h2dummy1;
968            let h2lovalue1 = h2hivalue2;
969            h2hivalue1 = if hilimit1 != 0.0 {
970                (hilimit1 + rclsqr * 0.5) * temp2 - (hilimit1 * rclsqr / PI).sqrt() * temp3
971            } else {
972                0.0
973            };
974            h2dummy1 = (h2hivalue1 - h2lovalue1) / delta1;
975            co.h2[i] = h2dummy1 - h2dummy2;
976            if co.h2[i].abs() < h2relval {
977                doh2 = false;
978            }
979        } else {
980            co.h2[i] = 0.0;
981        }
982
983        if doh3 {
984            let h3hivalue2 = h3hivalue1;
985            let h3dummy2 = h3dummy1;
986            let h3lovalue1 = h3hivalue2;
987            h3hivalue1 = h3of(hilimit1, temp2, temp3);
988            h3dummy1 = (h3hivalue1 - h3lovalue1) / delta1;
989            co.h3[i] = h3dummy1 - h3dummy2;
990            if co.h3[i].abs() < h3relval {
991                doh3 = false;
992            }
993        } else {
994            co.h3[i] = 0.0;
995        }
996    }
997    co.aux_index = auxindex;
998}
999
1000// ---------------------------------------------------------------------
1001// The instance
1002// ---------------------------------------------------------------------
1003
1004/// Matrix positions of `LTRAsetup` (`TSTALLOC` list, in order).
1005#[derive(Clone, Copy)]
1006struct Slots {
1007    ibr1_pos1: Slot,
1008    ibr1_neg1: Slot,
1009    ibr1_pos2: Slot,
1010    ibr1_neg2: Slot,
1011    ibr1_ibr1: Slot,
1012    ibr1_ibr2: Slot,
1013    ibr2_pos1: Slot,
1014    ibr2_neg1: Slot,
1015    ibr2_pos2: Slot,
1016    ibr2_neg2: Slot,
1017    ibr2_ibr1: Slot,
1018    ibr2_ibr2: Slot,
1019    pos1_ibr1: Slot,
1020    neg1_ibr1: Slot,
1021    pos2_ibr2: Slot,
1022    neg2_ibr2: Slot,
1023}
1024
1025const NO_SLOTS: Slots = Slots {
1026    ibr1_pos1: TRASH,
1027    ibr1_neg1: TRASH,
1028    ibr1_pos2: TRASH,
1029    ibr1_neg2: TRASH,
1030    ibr1_ibr1: TRASH,
1031    ibr1_ibr2: TRASH,
1032    ibr2_pos1: TRASH,
1033    ibr2_neg1: TRASH,
1034    ibr2_pos2: TRASH,
1035    ibr2_neg2: TRASH,
1036    ibr2_ibr1: TRASH,
1037    ibr2_ibr2: TRASH,
1038    pos1_ibr1: TRASH,
1039    neg1_ibr1: TRASH,
1040    pos2_ibr2: TRASH,
1041    neg2_ibr2: TRASH,
1042};
1043
1044/// Delayed port values `v1(t−T)`, `i1(t−T)`, `v2(t−T)`, `i2(t−T)`.
1045#[derive(Clone, Copy, Default)]
1046struct Delayed {
1047    v1: f64,
1048    i1: f64,
1049    v2: f64,
1050    i2: f64,
1051}
1052
1053/// One `O` line.
1054pub(crate) struct LtraI {
1055    p: LtraParams,
1056    pos1: Var,
1057    neg1: Var,
1058    pos2: Var,
1059    neg2: Var,
1060    br1: Var,
1061    br2: Var,
1062    slots: Slots,
1063    /// `LTRAinput1/2`: the history part of each branch equation.
1064    input1: f64,
1065    input2: f64,
1066    /// `LTRAinitVolt1/2`, `LTRAinitCur1/2`: the operating point.
1067    init_v1: f64,
1068    init_i1: f64,
1069    init_v2: f64,
1070    init_i2: f64,
1071    /// `CKTtimePoints[0..=CKTtimeIndex]` and the port histories
1072    /// `LTRAv1/i1/v2/i2` on it.
1073    times: Vec<f64>,
1074    v1: Vec<f64>,
1075    i1: Vec<f64>,
1076    v2: Vec<f64>,
1077    i2: Vec<f64>,
1078    co: Coeffs,
1079    /// `CKTgmin` of the last DC load, for the RG stamps in `.ac`.
1080    gmin: f64,
1081    /// Dune's opt-in recursive convolution (`Options::ltra_fit`,
1082    /// issue #8); off = the C's coefficient walk, untouched.
1083    fit_on: bool,
1084    /// Dune's floor on the slope rule (D-0052; with the breakpoint
1085    /// hygiene): a slope change plants a breakpoint only when the
1086    /// wave moved by more than `RELTOL` of the largest either wave
1087    /// has been.
1088    slope_floor: bool,
1089    /// The largest magnitude each incident wave has had (the scale
1090    /// of [`LtraI::slope_floor`]).
1091    wave_peak: [f64; 2],
1092    /// The recursive-mode model and states of the current run (built
1093    /// at the operating-point accept, when TSTOP is known).
1094    fit: Option<FitState>,
1095    /// Why the recursive mode does not apply to this line, if it was
1096    /// asked for (LC/RG have no history convolution).
1097    fit_skip: Option<&'static str>,
1098    /// `.pss` (issue #20): the history of this run is the periodic
1099    /// past of a shooting interval (see [`LtraI::seed_periodic`]).
1100    periodic: bool,
1101    /// Why the periodic past could not be set up, reported at the
1102    /// first load.
1103    periodic_fault: Option<&'static str>,
1104}
1105
1106/// The recursive model's horizon in a periodic run, in periods: the
1107/// infinite periodic past is summed in closed form, and lags beyond
1108/// the horizon (where the fit stops tracking the `τ^{−3/2}` tails) see
1109/// a zero-mean deviation, so what they miss cancels over each period.
1110const PERIODIC_HORIZON_PERIODS: f64 = 1000.0;
1111
1112/// Wave blocks of a state snapshot.
1113const V1: usize = 0;
1114const V2: usize = 1;
1115const I1: usize = 2;
1116const I2: usize = 3;
1117
1118/// The recursive-mode state of one line (issue #8).
1119///
1120/// For every pole `−x_j` of the [`ExpFit`] and every port wave `w`
1121/// (`v1`, `v2`, `i1`, `i2`), `S_j[w](t_k) = ∫₀^∞ e^{−x_j σ}·d_w(t_k − σ)dσ`
1122/// with `d_w = w − w_init` piecewise linear on the accepted points
1123/// (and `d_w(t_0) = 0`, the C's convention of leaving index 0 out of
1124/// the sums). It advances once per accepted point, in `accept` — never
1125/// per Newton iteration or per TR-BDF2 stage. A load at time `t`
1126/// needs it at the newest point (`h1'`, RC kernels) and at the point
1127/// just older than `t − T` (`h2`, `h3'`), so a snapshot per accepted
1128/// point is kept from the oldest one a later load can still reach.
1129struct FitState {
1130    fit: ExpFit,
1131    /// Snapshots, `4·N` values per accepted point from `base` on.
1132    snaps: Vec<f64>,
1133    base: usize,
1134    /// Scratch for `e^{−x_j·lag}`.
1135    ew: Vec<f64>,
1136}
1137
1138impl FitState {
1139    fn new(fit: ExpFit) -> Self {
1140        let n = fit.rates.len();
1141        FitState {
1142            fit,
1143            snaps: vec![0.0; 4 * n],
1144            base: 0,
1145            ew: vec![0.0; n],
1146        }
1147    }
1148
1149    fn n(&self) -> usize {
1150        self.fit.rates.len()
1151    }
1152
1153    /// The snapshot of history point `k`; `None` if pruned (a bug).
1154    fn snap(&self, k: usize) -> Option<&[f64]> {
1155        let n4 = 4 * self.n();
1156        let off = k.checked_sub(self.base)? * n4;
1157        self.snaps.get(off..off + n4)
1158    }
1159
1160    /// `e^{−x_j·lag}` into the scratch.
1161    fn exps(&mut self, lag: f64) {
1162        for (e, x) in self.ew.iter_mut().zip(&self.fit.rates) {
1163            *e = exp(-x * lag);
1164        }
1165    }
1166
1167    /// `Σ_j r_j[kernel]·e^{−x_j·lag}·S_j[wave]` at snapshot `k`, with
1168    /// the exponentials already in the scratch.
1169    fn tail(&self, kernel: usize, k: usize, wave: usize) -> Option<f64> {
1170        let n = self.n();
1171        let s = &self.snap(k)?[wave * n..(wave + 1) * n];
1172        Some(
1173            self.fit.res[kernel]
1174                .iter()
1175                .zip(&self.ew)
1176                .zip(s)
1177                .map(|((r, e), s)| r * e * s)
1178                .sum(),
1179        )
1180    }
1181
1182    /// `.pss`: the states at a period boundary under the infinite
1183    /// periodic past. With `P` the states one period of the deviation
1184    /// builds from zero (`segs` = that period's segments), periodicity
1185    /// `S = e^{−xT}·S + P` gives `S = P/(1 − e^{−xT})` exactly — the
1186    /// geometric sum over every earlier period. Replaces the snapshots
1187    /// by that single one.
1188    fn periodic_start(&mut self, period: f64, segs: &[(f64, [f64; 4], [f64; 4])]) {
1189        let n = self.n();
1190        let mut s = vec![0.0; 4 * n];
1191        for &(h, dn, dp) in segs {
1192            for j in 0..n {
1193                let (e, a, b) = segment(self.fit.rates[j] * h);
1194                for w in 0..4 {
1195                    let v = &mut s[w * n + j];
1196                    *v = e * *v + h * (a * dn[w] + b * dp[w]);
1197                }
1198            }
1199        }
1200        for j in 0..n {
1201            let g = -expm1(-self.fit.rates[j] * period);
1202            for w in 0..4 {
1203                s[w * n + j] /= g;
1204            }
1205        }
1206        self.snaps = s;
1207        self.base = 0;
1208    }
1209
1210    /// Advance one accepted segment of length `h`: `dn`/`dp` are the
1211    /// four wave deviations at the new and the previous point.
1212    fn advance(&mut self, h: f64, dn: [f64; 4], dp: [f64; 4]) {
1213        let n = self.n();
1214        let start = self.snaps.len() - 4 * n;
1215        self.snaps.extend_from_within(start..);
1216        let new = start + 4 * n;
1217        for j in 0..n {
1218            let (e, a, b) = segment(self.fit.rates[j] * h);
1219            for w in 0..4 {
1220                let s = &mut self.snaps[new + w * n + j];
1221                *s = e * *s + h * (a * dn[w] + b * dp[w]);
1222            }
1223        }
1224    }
1225
1226    /// Drop the snapshots older than history point `keep`, in chunks.
1227    fn prune(&mut self, keep: usize) {
1228        let dead = keep.saturating_sub(self.base);
1229        if dead >= 1024 {
1230            self.snaps.drain(..dead * 4 * self.n());
1231            self.base += dead;
1232        }
1233    }
1234}
1235
1236impl LtraI {
1237    /// `nodes` = (P1+, P1−, P2+, P2−); `br` = the `#i1`/`#i2`
1238    /// equations.
1239    pub fn new(p: LtraParams, nodes: [Var; 4], br: [Var; 2]) -> Self {
1240        LtraI {
1241            p,
1242            pos1: nodes[0],
1243            neg1: nodes[1],
1244            pos2: nodes[2],
1245            neg2: nodes[3],
1246            br1: br[0],
1247            br2: br[1],
1248            slots: NO_SLOTS,
1249            input1: 0.0,
1250            input2: 0.0,
1251            init_v1: 0.0,
1252            init_i1: 0.0,
1253            init_v2: 0.0,
1254            init_i2: 0.0,
1255            times: Vec::new(),
1256            v1: Vec::new(),
1257            i1: Vec::new(),
1258            v2: Vec::new(),
1259            i2: Vec::new(),
1260            co: Coeffs::default(),
1261            gmin: 0.0,
1262            fit_on: false,
1263            slope_floor: false,
1264            wave_peak: [0.0; 2],
1265            fit: None,
1266            fit_skip: None,
1267            periodic: false,
1268            periodic_fault: None,
1269        }
1270    }
1271
1272    /// Turn on the floor of the slope rule (the Dune profile).
1273    pub fn with_slope_floor(mut self, on: bool) -> Self {
1274        self.slope_floor = on;
1275        self
1276    }
1277
1278    /// Opt into the recursive convolution (`Options::ltra_fit`).
1279    pub fn with_fit(mut self, on: bool) -> Self {
1280        self.fit_on = on;
1281        self
1282    }
1283
1284    /// Build the recursive model for a run to `final_time` (at the
1285    /// operating-point accept). Lines without a history convolution,
1286    /// or whose kernels live entirely inside the exact window, keep
1287    /// the exact path and say why.
1288    fn start_fit(&mut self, final_time: f64) {
1289        self.build_fit(final_time.max(f64::MIN_POSITIVE));
1290    }
1291
1292    /// The recursive model for lags up to `horizon` (see `start_fit`).
1293    fn build_fit(&mut self, horizon: f64) {
1294        self.fit = None;
1295        self.fit_skip = None;
1296        let p = &self.p;
1297        match p.case {
1298            LtraCase::Lc | LtraCase::Rg => {
1299                self.fit_skip = Some("no history convolution in this regime");
1300            }
1301            LtraCase::Rlc if !(p.alpha > 0.0 && p.alpha.is_finite()) => {
1302                self.fit_skip = Some("needs R/L > 0");
1303            }
1304            LtraCase::Rlc => {
1305                self.fit = Some(FitState::new(fit_rlc(p.alpha, p.td, horizon)));
1306            }
1307            LtraCase::Rc => {
1308                let w = RC_WINDOW_FRACTION * p.rclsqr;
1309                if !(w > 0.0 && w.is_finite() && p.cbyr > 0.0 && p.cbyr.is_finite()) {
1310                    self.fit_skip = Some("needs R, C > 0");
1311                } else if w >= horizon {
1312                    self.fit_skip =
1313                        Some("the diffusion time exceeds the run: exact window covers it");
1314                } else {
1315                    self.fit = Some(FitState::new(fit_rc(p.cbyr, p.rclsqr, w, horizon)));
1316                }
1317            }
1318        }
1319    }
1320
1321    /// The deviation `w − w_init` of history point `k` (0 at `k = 0`,
1322    /// the operating point, outside a periodic run).
1323    fn dev(&self, wave: usize, k: usize) -> f64 {
1324        if k == 0 && !self.periodic {
1325            return 0.0;
1326        }
1327        match wave {
1328            V1 => self.v1[k] - self.init_v1,
1329            V2 => self.v2[k] - self.init_v2,
1330            I1 => self.i1[k] - self.init_i1,
1331            _ => self.i2[k] - self.init_i2,
1332        }
1333    }
1334
1335    /// `LTRArlcCoeffsSetup`'s `auxindex` by bisection: the newest
1336    /// point with `t − t_i ≥ T`, one older if the lag is exactly `T`.
1337    fn aux_index(&self, time: f64) -> usize {
1338        let td = self.p.td;
1339        if td == 0.0 {
1340            return self.times.len() - 1;
1341        }
1342        if time - td <= 0.0 {
1343            return 0;
1344        }
1345        let n = self.times.partition_point(|&t| time - t >= td);
1346        let Some(found) = n.checked_sub(1) else {
1347            return 0;
1348        };
1349        if time - self.times[found] == td {
1350            found.saturating_sub(1)
1351        } else {
1352            found
1353        }
1354    }
1355
1356    /// The oldest history point whose snapshot a load after the newest
1357    /// accepted point can still need.
1358    fn oldest_needed(&self) -> usize {
1359        let n = self.times.len() - 1;
1360        let t = self.times[n];
1361        let k = match self.p.case {
1362            LtraCase::Rc => {
1363                let w = self.fit.as_ref().map_or(0.0, |f| f.fit.window);
1364                self.times
1365                    .partition_point(|&ti| t - ti >= w)
1366                    .saturating_sub(1)
1367            }
1368            _ => self.aux_index(t),
1369        };
1370        k.saturating_sub(1).min(n)
1371    }
1372
1373    /// Recursive mode, LC/RLC: the first coefficients (for the matrix)
1374    /// and the history inputs of `LTRAload` in one pass. `h1'` is the
1375    /// exact first segment (lags `[0, Δ]`, the C's closed forms) plus
1376    /// the recursion for older lags; `h2`/`h3'` likewise at `t − T`,
1377    /// whose first segment keeps the C's linear-in-lag rule.
1378    fn fit_inputs_lc_rlc(&mut self, time: f64, del: Option<Delayed>) -> Result<(), &'static str> {
1379        const PRUNED: &str = "LTRA: recursive history state pruned";
1380        let n = self.times.len() - 1;
1381        let (mut in1, mut in2) = (0.0, 0.0);
1382        if self.p.case == LtraCase::Rlc {
1383            let (alpha, beta, td, admit) = (self.p.alpha, self.p.beta, self.p.td, self.p.admit);
1384            let fs = self.fit.as_mut().ok_or(PRUNED)?;
1385            // h1': H''(Δ)/Δ (LTRArlcH1dashTwiceIntFunc, scaled Bessel)
1386            // and the x_n share H'(Δ) − H''(Δ)/Δ, H'(Δ) = e^{−βΔ}I0(βΔ) − 1.
1387            let dlt = time - self.times[n];
1388            let bd = beta * dlt;
1389            let h1_first = if dlt == 0.0 {
1390                0.0
1391            } else {
1392                (i1e(bd) + i0e(bd)) - 1.0
1393            };
1394            let c_n = (i0e(bd) - 1.0) - h1_first;
1395            fs.exps(dlt);
1396            let t1 = fs.tail(0, n, V1).ok_or(PRUNED)?;
1397            let t2 = fs.tail(0, n, V2).ok_or(PRUNED)?;
1398            self.co.h1_first = h1_first;
1399            let p = &self.p;
1400            let mut d1 = c_n * self.dev(V1, n) + t1;
1401            let mut d2 = c_n * self.dev(V2, n) + t2;
1402            d1 += self.init_v1 * p.int_h1dash - self.init_v1 * h1_first;
1403            d2 += self.init_v2 * p.int_h1dash - self.init_v2 * h1_first;
1404            in1 -= d1 * admit;
1405            in2 -= d2 * admit;
1406
1407            let (mut e1, mut e2, mut f1, mut f2) = (0.0, 0.0, 0.0, 0.0);
1408            if let Some(dl) = del {
1409                let aux = self.aux_index(time);
1410                let hi = time - self.times[aux];
1411                let dp = hi - td;
1412                let h2lo = rlc_h2(td, td, alpha, beta);
1413                let z = if hi > td {
1414                    alpha * (hi * hi - td * td).sqrt()
1415                } else {
1416                    0.0
1417                };
1418                let damp = exp(-(beta * hi - z));
1419                let h2hi = if hi < td {
1420                    0.0
1421                } else {
1422                    alpha * alpha * td * damp * i1e_over_x(z)
1423                };
1424                let h2_first = twiceintlinfunc(td, hi, td, h2lo, h2hi, td, hi) / dp;
1425                let c2 = intlinfunc(td, hi, h2lo, h2hi, td, hi) - h2_first;
1426                let h3hi = if hi <= td || beta == 0.0 {
1427                    0.0
1428                } else {
1429                    damp * i0e(z) - exp(-beta * td)
1430                };
1431                let h3_first = intlinfunc(td, hi, 0.0, h3hi, td, hi) / dp;
1432                let c3 = h3hi - h3_first;
1433                let fs = self.fit.as_mut().ok_or(PRUNED)?;
1434                fs.exps(dp);
1435                let (s2a, s2b) = (
1436                    fs.tail(1, aux, I2).ok_or(PRUNED)?,
1437                    fs.tail(1, aux, I1).ok_or(PRUNED)?,
1438                );
1439                let (s3a, s3b) = (
1440                    fs.tail(2, aux, V2).ok_or(PRUNED)?,
1441                    fs.tail(2, aux, V1).ok_or(PRUNED)?,
1442                );
1443                e1 = (dl.i2 - self.init_i2) * h2_first + c2 * self.dev(I2, aux) + s2a;
1444                e2 = (dl.i1 - self.init_i1) * h2_first + c2 * self.dev(I1, aux) + s2b;
1445                f1 = (dl.v2 - self.init_v2) * h3_first + c3 * self.dev(V2, aux) + s3a;
1446                f2 = (dl.v1 - self.init_v1) * h3_first + c3 * self.dev(V1, aux) + s3b;
1447            }
1448            let p = &self.p;
1449            e1 += self.init_i2 * p.int_h2;
1450            e2 += self.init_i1 * p.int_h2;
1451            in1 += e1;
1452            in2 += e2;
1453            f1 += self.init_v2 * p.int_h3dash;
1454            f2 += self.init_v1 * p.int_h3dash;
1455            in1 += admit * f1;
1456            in2 += admit * f2;
1457        }
1458        let p = &self.p;
1459        match del {
1460            None => {
1461                in1 += p.attenuation * (self.init_v2 * p.admit + self.init_i2);
1462                in2 += p.attenuation * (self.init_v1 * p.admit + self.init_i1);
1463            }
1464            Some(dl) => {
1465                in1 += p.attenuation * (dl.v2 * p.admit + dl.i2);
1466                in2 += p.attenuation * (dl.v1 * p.admit + dl.i1);
1467            }
1468        }
1469        self.input1 = in1;
1470        self.input2 = in2;
1471        Ok(())
1472    }
1473
1474    /// Recursive mode, RC: the exact coefficients of
1475    /// `LTRArcCoeffsSetup` over the window of lags `< W` (from the
1476    /// newest point `b` at least `W` old), the recursion beyond it.
1477    fn fit_inputs_rc(&mut self, time: f64) -> Result<(), &'static str> {
1478        const PRUNED: &str = "LTRA: recursive history state pruned";
1479        let n = self.times.len() - 1;
1480        let (cbyr, rclsqr) = (self.p.cbyr, self.p.rclsqr);
1481        let w = self.fit.as_ref().ok_or(PRUNED)?.fit.window;
1482        let b = self
1483            .times
1484            .partition_point(|&t| time - t >= w)
1485            .saturating_sub(1)
1486            .min(n);
1487        let lb = time - self.times[b];
1488        let fs = self.fit.as_mut().ok_or(PRUNED)?;
1489        fs.exps(lb);
1490        // sums[k][port]: kernel k against (v1|i2|v2) for port 1 and
1491        // (v2|i1|v1) for port 2, like `inputs_rc`.
1492        let waves = [[V1, V2], [I2, I1], [V2, V1]];
1493        let mut tails = [[0.0; 2]; 3];
1494        for k in 0..3 {
1495            for q in 0..2 {
1496                tails[k][q] = fs.tail(k, b, waves[k][q]).ok_or(PRUNED)?;
1497            }
1498        }
1499        let mut firsts = [0.0; 3];
1500        let mut sums = tails;
1501        for k in 0..3 {
1502            // H''(L_i) for i = n (first segment), walking older.
1503            let ln = time - self.times[n];
1504            let mut hi_val = rc_integrals(k, cbyr, rclsqr, ln).1;
1505            let mut dd_new = hi_val / ln; // DD of the segment [n, now]
1506            firsts[k] = dd_new;
1507            for i in (b + 1..=n).rev() {
1508                let lag = time - self.times[i - 1];
1509                let v = rc_integrals(k, cbyr, rclsqr, lag).1;
1510                let dd_old = (v - hi_val) / (self.times[i] - self.times[i - 1]);
1511                let c = dd_old - dd_new;
1512                for q in 0..2 {
1513                    sums[k][q] += c * self.dev(waves[k][q], i);
1514                }
1515                hi_val = v;
1516                dd_new = dd_old;
1517            }
1518            // The boundary point b: its share of lags [L_{b+1}, L_b].
1519            let c_b = rc_integrals(k, cbyr, rclsqr, lb).0 - dd_new;
1520            for q in 0..2 {
1521                sums[k][q] += c_b * self.dev(waves[k][q], b);
1522            }
1523        }
1524        self.co.h1_first = firsts[0];
1525        self.co.h2_first = firsts[1];
1526        self.co.h3_first = firsts[2];
1527        let p = &self.p;
1528        let init = |wave: usize| match wave {
1529            V1 => self.init_v1,
1530            V2 => self.init_v2,
1531            I1 => self.init_i1,
1532            _ => self.init_i2,
1533        };
1534        let ints = [p.int_h1dash, p.int_h2, p.int_h3dash];
1535        let mut inp = [0.0; 2];
1536        for q in 0..2 {
1537            for k in 0..3 {
1538                let x0 = init(waves[k][q]);
1539                let d = sums[k][q] + x0 * ints[k] - x0 * firsts[k];
1540                if k == 0 {
1541                    inp[q] -= d;
1542                } else {
1543                    inp[q] += d;
1544                }
1545            }
1546        }
1547        self.input1 = inp[0];
1548        self.input2 = inp[1];
1549        Ok(())
1550    }
1551
1552    /// Advance the recursive states over the newest accepted segment
1553    /// and drop snapshots no later load can reach.
1554    fn fit_accept(&mut self) {
1555        let k = self.times.len() - 1;
1556        let h = self.times[k] - self.times[k - 1];
1557        let dn = [V1, V2, I1, I2].map(|w| self.dev(w, k));
1558        let dp = [V1, V2, I1, I2].map(|w| self.dev(w, k - 1));
1559        let keep = self.oldest_needed();
1560        if let Some(fs) = self.fit.as_mut() {
1561            fs.advance(h, dn, dp);
1562            fs.prune(keep);
1563        }
1564    }
1565
1566    /// The DC / RG stamps of `LTRAload` (`MODEDC`, or the RG case at
1567    /// any time).
1568    fn load_dc(&mut self, ctx: &mut LoadCtx) {
1569        let s = self.slots;
1570        let p = &self.p;
1571        match p.case {
1572            LtraCase::Rg => {
1573                ctx.add(s.ibr1_pos1, 1.0);
1574                ctx.add(s.ibr1_neg1, -1.0);
1575                ctx.add(s.ibr1_pos2, -p.cosh_lroot_gr);
1576                ctx.add(s.ibr1_neg2, p.cosh_lroot_gr);
1577                ctx.add(s.ibr1_ibr2, (1.0 + ctx.gmin) * p.r_rs_lr_gr_or_g);
1578
1579                ctx.add(s.ibr2_ibr2, p.cosh_lroot_gr);
1580                ctx.add(s.ibr2_pos2, -(1.0 + ctx.gmin) * p.r_gs_lr_gr_or_r);
1581                ctx.add(s.ibr2_neg2, (1.0 + ctx.gmin) * p.r_gs_lr_gr_or_r);
1582                ctx.add(s.ibr2_ibr1, 1.0);
1583
1584                ctx.add(s.pos1_ibr1, 1.0);
1585                ctx.add(s.neg1_ibr1, -1.0);
1586                ctx.add(s.pos2_ibr2, 1.0);
1587                ctx.add(s.neg2_ibr2, -1.0);
1588            }
1589            LtraCase::Lc | LtraCase::Rlc | LtraCase::Rc => {
1590                // "load a simple resistor": i1 + i2 = 0 and
1591                // v(P1+) − v(P2+) = R·len·i1 — the C ignores the
1592                // negative nodes here (ngspice too).
1593                ctx.add(s.pos1_ibr1, 1.0);
1594                ctx.add(s.neg1_ibr1, -1.0);
1595                ctx.add(s.pos2_ibr2, 1.0);
1596                ctx.add(s.neg2_ibr2, -1.0);
1597
1598                ctx.add(s.ibr1_ibr1, 1.0);
1599                ctx.add(s.ibr1_ibr2, 1.0);
1600                ctx.add(s.ibr2_pos1, 1.0);
1601                ctx.add(s.ibr2_pos2, -1.0);
1602                ctx.add(s.ibr2_ibr1, -p.resist * p.length);
1603            }
1604        }
1605        self.input1 = 0.0;
1606        self.input2 = 0.0;
1607    }
1608
1609    /// The delayed-timepoint search and interpolation of `LTRAload`
1610    /// (LC/RLC, `tdover`). `None` is the C's E_INTERN "cannot find
1611    /// delayed timepoint" (the step is then cut like a failed
1612    /// Newton solve).
1613    fn delayed(&self, time: f64) -> Option<Delayed> {
1614        let td = self.p.td;
1615        let time_index = self.times.len() - 1;
1616        let target = time - td;
1617        let mut i: isize = time_index as isize;
1618        while i >= 0 {
1619            if self.times[i as usize] < target {
1620                break;
1621            }
1622            i -= 1;
1623        }
1624        if i == time_index as isize {
1625            i -= 1;
1626        }
1627        if i < 0 {
1628            return None;
1629        }
1630        Some(self.interp_delayed(i as usize, target))
1631    }
1632
1633    /// [`Self::delayed`] by bisection (recursive mode): the same
1634    /// bracketing point — the newest one strictly before `time − T`,
1635    /// never the newest of all — in O(log n) instead of the C's
1636    /// backward scan.
1637    fn delayed_bisect(&self, time: f64) -> Option<Delayed> {
1638        let target = time - self.p.td;
1639        let time_index = self.times.len() - 1;
1640        let below = self.times.partition_point(|&t| t < target);
1641        if below == 0 {
1642            return None;
1643        }
1644        let i = (below - 1).min(time_index.checked_sub(1)?);
1645        Some(self.interp_delayed(i, target))
1646    }
1647
1648    /// The interpolation of `LTRAload` around `times[isaved]`,
1649    /// `times[isaved + 1]` (and `times[isaved − 1]` for quadratic).
1650    fn interp_delayed(&self, isaved: usize, target: f64) -> Delayed {
1651        let t2 = self.times[isaved];
1652        let t3 = self.times[isaved + 1];
1653        let interp = self.p.interp;
1654        let quad_ok = isaved != 0 && matches!(interp, LtraInterp::Quadratic | LtraInterp::Mixed);
1655        let mut qf = (0.0, 0.0, 0.0);
1656        if quad_ok {
1657            let t1 = self.times[isaved - 1];
1658            qf = quad_interp(target, t1, t2, t3).unwrap_or((0.0, 0.0, 0.0));
1659        }
1660        let mut lf = (0.0, 0.0);
1661        if isaved == 0 || matches!(interp, LtraInterp::Mixed | LtraInterp::Linear) {
1662            lf = lin_interp(target, t2, t3).unwrap_or((0.0, 0.0));
1663        }
1664        let one = |h: &[f64]| -> f64 {
1665            let mut d = 0.0;
1666            let (mut max, mut min) = (0.0, 0.0);
1667            if quad_ok {
1668                let (a, b, c) = (h[isaved - 1], h[isaved], h[isaved + 1]);
1669                d = a * qf.0 + b * qf.1 + c * qf.2;
1670                max = f64::max(f64::max(a, b), c);
1671                min = f64::min(f64::min(a, b), c);
1672            }
1673            if interp == LtraInterp::Linear || isaved == 0 || (quad_ok && (d > max || d < min)) {
1674                // QUADINTERP keeps the out-of-range quadratic value
1675                // (the C only prints a debug warning).
1676                if !(quad_ok && interp == LtraInterp::Quadratic) {
1677                    d = h[isaved] * lf.0 + h[isaved + 1] * lf.1;
1678                }
1679            }
1680            d
1681        };
1682        Delayed {
1683            v1: one(&self.v1),
1684            i1: one(&self.i1),
1685            v2: one(&self.v2),
1686            i2: one(&self.i2),
1687        }
1688    }
1689
1690    /// The `MODEINITPRED | MODEINITTRAN` part of `LTRAload` for
1691    /// LC/RLC: the history inputs of both branch equations.
1692    fn inputs_lc_rlc(&mut self, del: Option<Delayed>) {
1693        let p = &self.p;
1694        let time_index = self.times.len() - 1;
1695        let (mut in1, mut in2) = (0.0, 0.0);
1696        if p.case == LtraCase::Rlc {
1697            let co = &self.co;
1698            // Convolution of h1' with v1 and v2.
1699            let (mut d1, mut d2) = (0.0, 0.0);
1700            for i in (1..=time_index).rev() {
1701                if co.h1[i] != 0.0 {
1702                    d1 += co.h1[i] * (self.v1[i] - self.init_v1);
1703                    d2 += co.h1[i] * (self.v2[i] - self.init_v2);
1704                }
1705            }
1706            d1 += self.init_v1 * p.int_h1dash;
1707            d2 += self.init_v2 * p.int_h1dash;
1708            d1 -= self.init_v1 * co.h1_first;
1709            d2 -= self.init_v2 * co.h1_first;
1710            in1 -= d1 * p.admit;
1711            in2 -= d2 * p.admit;
1712
1713            // Convolution of h2 with i2 and i1.
1714            let (mut d1, mut d2) = (0.0, 0.0);
1715            if let Some(dl) = del {
1716                d1 = (dl.i2 - self.init_i2) * co.h2_first;
1717                d2 = (dl.i1 - self.init_i1) * co.h2_first;
1718                for i in (1..=co.aux_index).rev() {
1719                    if co.h2[i] != 0.0 {
1720                        d1 += co.h2[i] * (self.i2[i] - self.init_i2);
1721                        d2 += co.h2[i] * (self.i1[i] - self.init_i1);
1722                    }
1723                }
1724            }
1725            d1 += self.init_i2 * p.int_h2;
1726            d2 += self.init_i1 * p.int_h2;
1727            in1 += d1;
1728            in2 += d2;
1729
1730            // Convolution of h3' with v2 and v1.
1731            let (mut d1, mut d2) = (0.0, 0.0);
1732            if let Some(dl) = del {
1733                d1 = (dl.v2 - self.init_v2) * co.h3_first;
1734                d2 = (dl.v1 - self.init_v1) * co.h3_first;
1735                for i in (1..=co.aux_index).rev() {
1736                    if co.h3[i] != 0.0 {
1737                        d1 += co.h3[i] * (self.v2[i] - self.init_v2);
1738                        d2 += co.h3[i] * (self.v1[i] - self.init_v1);
1739                    }
1740                }
1741            }
1742            d1 += self.init_v2 * p.int_h3dash;
1743            d2 += self.init_v1 * p.int_h3dash;
1744            in1 += p.admit * d1;
1745            in2 += p.admit * d2;
1746        }
1747        // The lossless-like parts (RLC falls through into LC).
1748        match del {
1749            None => {
1750                in1 += p.attenuation * (self.init_v2 * p.admit + self.init_i2);
1751                in2 += p.attenuation * (self.init_v1 * p.admit + self.init_i1);
1752            }
1753            Some(dl) => {
1754                in1 += p.attenuation * (dl.v2 * p.admit + dl.i2);
1755                in2 += p.attenuation * (dl.v1 * p.admit + dl.i1);
1756            }
1757        }
1758        self.input1 = in1;
1759        self.input2 = in2;
1760    }
1761
1762    /// The RC inputs of `LTRAload`.
1763    fn inputs_rc(&mut self) {
1764        let p = &self.p;
1765        let co = &self.co;
1766        let time_index = self.times.len() - 1;
1767        let (mut in1, mut in2) = (0.0, 0.0);
1768
1769        let (mut d1, mut d2) = (0.0, 0.0);
1770        for i in (1..=time_index).rev() {
1771            if co.h1[i] != 0.0 {
1772                d1 += co.h1[i] * (self.v1[i] - self.init_v1);
1773                d2 += co.h1[i] * (self.v2[i] - self.init_v2);
1774            }
1775        }
1776        d1 += self.init_v1 * p.int_h1dash;
1777        d2 += self.init_v2 * p.int_h1dash;
1778        d1 -= self.init_v1 * co.h1_first;
1779        d2 -= self.init_v2 * co.h1_first;
1780        in1 -= d1;
1781        in2 -= d2;
1782
1783        let (mut d1, mut d2) = (0.0, 0.0);
1784        for i in (1..=time_index).rev() {
1785            if co.h2[i] != 0.0 {
1786                d1 += co.h2[i] * (self.i2[i] - self.init_i2);
1787                d2 += co.h2[i] * (self.i1[i] - self.init_i1);
1788            }
1789        }
1790        d1 += self.init_i2 * p.int_h2;
1791        d2 += self.init_i1 * p.int_h2;
1792        d1 -= self.init_i2 * co.h2_first;
1793        d2 -= self.init_i1 * co.h2_first;
1794        in1 += d1;
1795        in2 += d2;
1796
1797        let (mut d1, mut d2) = (0.0, 0.0);
1798        for i in (1..=time_index).rev() {
1799            if co.h3[i] != 0.0 {
1800                d1 += co.h3[i] * (self.v2[i] - self.init_v2);
1801                d2 += co.h3[i] * (self.v1[i] - self.init_v1);
1802            }
1803        }
1804        d1 += self.init_v2 * p.int_h3dash;
1805        d2 += self.init_v1 * p.int_h3dash;
1806        d1 -= self.init_v2 * co.h3_first;
1807        d2 -= self.init_v1 * co.h3_first;
1808        in1 += d1;
1809        in2 += d2;
1810
1811        self.input1 = in1;
1812        self.input2 = in2;
1813    }
1814}
1815
1816impl Device for LtraI {
1817    fn par_load(&self) -> bool {
1818        true
1819    }
1820
1821    /// `LTRAinfo` has no `DEVdisto`: the line is linear.
1822    fn disto_setup(&mut self, _ctx: &DistoSetupCtx) -> Result<(), &'static str> {
1823        Ok(())
1824    }
1825
1826    /// The recursive mode's report (issue #8): the model and its
1827    /// error against the closed-form responses, on the setup grid and
1828    /// at the lags the last timepoint's convolution actually spanned.
1829    fn tran_notes(&self) -> Vec<String> {
1830        if !self.fit_on {
1831            return Vec::new();
1832        }
1833        let name = &self.p.name;
1834        let Some(fs) = &self.fit else {
1835            let why = self.fit_skip.unwrap_or("not started");
1836            return vec![format!(
1837                "`{name}`: ltrafit not applied ({why}); exact convolution"
1838            )];
1839        };
1840        let f = &fs.fit;
1841        let (labels, delayed) = match self.p.case {
1842            LtraCase::Rc => (["h1", "h2", "h3"], false),
1843            _ => (["h1'", "h2", "h3'"], true),
1844        };
1845        let mut hist = [0.0; 3];
1846        if let Some(&te) = self.times.last() {
1847            let n = self.times.len() - 1;
1848            let w = f.window;
1849            let lags0 = self.times[..n].iter().map(|t| te - t).filter(|l| *l >= w);
1850            hist[0] = f.err_at(0, lags0);
1851            for (k, h) in hist.iter_mut().enumerate().skip(1) {
1852                *h = if delayed {
1853                    let td = self.p.td;
1854                    let lags = self.times.iter().map(|t| te - td - t).filter(|l| *l > 0.0);
1855                    f.err_at(k, lags)
1856                } else {
1857                    f.err_at(
1858                        k,
1859                        self.times[..n].iter().map(|t| te - t).filter(|l| *l >= w),
1860                    )
1861                };
1862            }
1863        }
1864        let errs: Vec<String> = (0..3)
1865            .map(|k| {
1866                format!(
1867                    "{} {:.1e}/{:.1e}/{:.1e}",
1868                    labels[k], f.err[k].max_rel, f.err[k].l1_rel, hist[k]
1869                )
1870            })
1871            .collect();
1872        let regime = match self.p.case {
1873            LtraCase::Rc => format!(
1874                "RC, RCl²={:.3e}s, exact window {:.3e}s",
1875                self.p.rclsqr, f.window
1876            ),
1877            _ => format!("RLC, T={:.3e}s, R/2L={:.3e}/s", self.p.td, self.p.alpha),
1878        };
1879        vec![format!(
1880            "`{name}`: ltrafit {regime}: {} real poles ({} panels x {} Gauss points); \
1881             kernel error max/L1 on [{:.3e}s, {:.3e}s] / max at the {} history lags: {}",
1882            f.rates.len(),
1883            f.panels,
1884            f.order,
1885            f.window,
1886            f.horizon,
1887            self.times.len(),
1888            errs.join(", ")
1889        )]
1890    }
1891
1892    fn alloc(&mut self, mb: &mut MatrixBuilder) {
1893        let (p1, n1, p2, n2, b1, b2) = (
1894            self.pos1, self.neg1, self.pos2, self.neg2, self.br1, self.br2,
1895        );
1896        self.slots = Slots {
1897            ibr1_pos1: mb.slot(b1, p1),
1898            ibr1_neg1: mb.slot(b1, n1),
1899            ibr1_pos2: mb.slot(b1, p2),
1900            ibr1_neg2: mb.slot(b1, n2),
1901            ibr1_ibr1: mb.slot(b1, b1),
1902            ibr1_ibr2: mb.slot(b1, b2),
1903            ibr2_pos1: mb.slot(b2, p1),
1904            ibr2_neg1: mb.slot(b2, n1),
1905            ibr2_pos2: mb.slot(b2, p2),
1906            ibr2_neg2: mb.slot(b2, n2),
1907            ibr2_ibr1: mb.slot(b2, b1),
1908            ibr2_ibr2: mb.slot(b2, b2),
1909            pos1_ibr1: mb.slot(p1, b1),
1910            neg1_ibr1: mb.slot(n1, b1),
1911            pos2_ibr2: mb.slot(p2, b2),
1912            neg2_ibr2: mb.slot(n2, b2),
1913        };
1914        // "so that SMPpreOrder does not screw up on occasion — for
1915        // example, when one end of the lossy line is hanging".
1916        mb.slot(p1, p1);
1917        mb.slot(n1, n1);
1918        mb.slot(p2, p2);
1919        mb.slot(n2, n2);
1920    }
1921
1922    fn load(&mut self, ctx: &mut LoadCtx) {
1923        if ctx.is_dc() {
1924            self.gmin = ctx.gmin;
1925            self.load_dc(ctx);
1926            ctx.add_rhs(self.br1, self.input1);
1927            ctx.add_rhs(self.br2, self.input2);
1928            return;
1929        }
1930        if self.times.is_empty() {
1931            // The operating point is always accepted (and recorded)
1932            // before the first transient load.
1933            ctx.fault = Some("LTRA: transient load before the operating point was stored");
1934            return;
1935        }
1936        if self.periodic {
1937            if let Some(f) = self.periodic_fault {
1938                ctx.fault = Some(f);
1939                return;
1940            }
1941            if self.fit.is_none() && matches!(self.p.case, LtraCase::Rlc | LtraCase::Rc) {
1942                // The exact walk sums a history that starts at an
1943                // operating point; the periodic past has none.
1944                ctx.fault = Some(
1945                    "LTRA: a lossy (RLC/RC) line in .pss needs the recursive convolution \
1946                     (.options ltrafit)",
1947                );
1948                return;
1949            }
1950        }
1951        let first = matches!(ctx.mode, InitMode::Tran | InitMode::Pred);
1952        let time_index = self.times.len() - 1;
1953        // `.pss`: the periodic past reaches back past every delay.
1954        let tdover = matches!(self.p.case, LtraCase::Lc | LtraCase::Rlc)
1955            && (ctx.time > self.p.td || self.periodic);
1956        let mut del = None;
1957        if first && self.fit.is_some() {
1958            // Recursive mode (issue #8): coefficients and inputs at once.
1959            if tdover {
1960                match self.delayed_bisect(ctx.time) {
1961                    Some(d) => del = Some(d),
1962                    None => {
1963                        ctx.fault = Some("LTRA: cannot find delayed timepoint");
1964                        return;
1965                    }
1966                }
1967            }
1968        } else if first {
1969            match self.p.case {
1970                LtraCase::Rlc => rlc_coeffs(
1971                    &mut self.co,
1972                    self.p.td,
1973                    self.p.alpha,
1974                    self.p.beta,
1975                    ctx.time,
1976                    &self.times,
1977                    time_index,
1978                    self.p.chop_reltol,
1979                ),
1980                LtraCase::Rc => rc_coeffs(
1981                    &mut self.co,
1982                    self.p.cbyr,
1983                    self.p.rclsqr,
1984                    ctx.time,
1985                    &self.times,
1986                    time_index,
1987                    self.p.chop_reltol,
1988                ),
1989                LtraCase::Lc | LtraCase::Rg => {}
1990            }
1991            if tdover {
1992                match self.delayed(ctx.time) {
1993                    Some(d) => del = Some(d),
1994                    None => {
1995                        ctx.fault = Some("LTRA: cannot find delayed timepoint");
1996                        return;
1997                    }
1998                }
1999            }
2000        }
2001
2002        if self.p.case == LtraCase::Rg {
2003            self.load_dc(ctx);
2004            ctx.add_rhs(self.br1, self.input1);
2005            ctx.add_rhs(self.br2, self.input2);
2006            return;
2007        }
2008
2009        // First timepoint after zero: record the operating point.
2010        if ctx.mode == InitMode::Tran && !ctx.uic && !self.periodic {
2011            self.init_v1 = ctx.sol[self.pos1] - ctx.sol[self.neg1];
2012            self.init_v2 = ctx.sol[self.pos2] - ctx.sol[self.neg2];
2013            self.init_i1 = ctx.sol[self.br1];
2014            self.init_i2 = ctx.sol[self.br2];
2015        }
2016
2017        // Recursive mode: the first coefficients the stamps below use
2018        // come out of the same pass as the history inputs.
2019        if first && self.fit.is_some() {
2020            let r = match self.p.case {
2021                LtraCase::Lc | LtraCase::Rlc => self.fit_inputs_lc_rlc(ctx.time, del),
2022                LtraCase::Rc => self.fit_inputs_rc(ctx.time),
2023                LtraCase::Rg => Ok(()),
2024            };
2025            if let Err(e) = r {
2026                ctx.fault = Some(e);
2027                return;
2028            }
2029        }
2030
2031        // Matrix loading, every call.
2032        let s = self.slots;
2033        let p = &self.p;
2034        match p.case {
2035            LtraCase::Rlc | LtraCase::Lc => {
2036                if p.case == LtraCase::Rlc {
2037                    let d = p.admit * self.co.h1_first;
2038                    ctx.add(s.ibr1_pos1, d);
2039                    ctx.add(s.ibr1_neg1, -d);
2040                    ctx.add(s.ibr2_pos2, d);
2041                    ctx.add(s.ibr2_neg2, -d);
2042                }
2043                ctx.add(s.ibr1_pos1, p.admit);
2044                ctx.add(s.ibr1_neg1, -p.admit);
2045                ctx.add(s.ibr1_ibr1, -1.0);
2046                ctx.add(s.pos1_ibr1, 1.0);
2047                ctx.add(s.neg1_ibr1, -1.0);
2048
2049                ctx.add(s.ibr2_pos2, p.admit);
2050                ctx.add(s.ibr2_neg2, -p.admit);
2051                ctx.add(s.ibr2_ibr2, -1.0);
2052                ctx.add(s.pos2_ibr2, 1.0);
2053                ctx.add(s.neg2_ibr2, -1.0);
2054            }
2055            LtraCase::Rc => {
2056                ctx.add(s.ibr1_ibr1, -1.0);
2057                ctx.add(s.pos1_ibr1, 1.0);
2058                ctx.add(s.neg1_ibr1, -1.0);
2059
2060                ctx.add(s.ibr2_ibr2, -1.0);
2061                ctx.add(s.pos2_ibr2, 1.0);
2062                ctx.add(s.neg2_ibr2, -1.0);
2063
2064                let d = self.co.h1_first;
2065                ctx.add(s.ibr1_pos1, d);
2066                ctx.add(s.ibr1_neg1, -d);
2067                ctx.add(s.ibr2_pos2, d);
2068                ctx.add(s.ibr2_neg2, -d);
2069
2070                let d = self.co.h2_first;
2071                ctx.add(s.ibr1_ibr2, -d);
2072                ctx.add(s.ibr2_ibr1, -d);
2073
2074                let d = self.co.h3_first;
2075                ctx.add(s.ibr1_pos2, -d);
2076                ctx.add(s.ibr1_neg2, d);
2077                ctx.add(s.ibr2_pos1, -d);
2078                ctx.add(s.ibr2_neg1, d);
2079            }
2080            LtraCase::Rg => {} // stamped by `load_dc` above
2081        }
2082
2083        if first && self.fit.is_none() {
2084            match self.p.case {
2085                LtraCase::Lc | LtraCase::Rlc => self.inputs_lc_rlc(del),
2086                LtraCase::Rc => self.inputs_rc(),
2087                LtraCase::Rg => {}
2088            }
2089        }
2090
2091        ctx.add_rhs(self.br1, self.input1);
2092        ctx.add_rhs(self.br2, self.input2);
2093    }
2094
2095    /// `LTRAtrunc`: the delay ceiling (`STEPLIMIT`, or a derivative
2096    /// change of the incident waves under `NOSTEPLIMIT`) and the RLC
2097    /// impulse-response safe step. The LTE branch needs
2098    /// `fullcontrol`/`halfcontrol`, never settable, so it is absent.
2099    fn trunc(&self, t: &TerrCtx, time_step: &mut f64) {
2100        let p = &self.p;
2101        if matches!(p.case, LtraCase::Lc | LtraCase::Rlc) {
2102            if p.step_limit {
2103                *time_step = time_step.min(p.td);
2104            } else if self.times.len() >= 2 {
2105                let idx = self.times.len() - 1;
2106                let sol = t.sol;
2107                let a = p.admit;
2108                let att = p.attenuation;
2109                let i1 = ((sol[self.pos2] - sol[self.neg2]) * a + sol[self.br2]) * att;
2110                let i2 = (self.v2[idx] * a + self.i2[idx]) * att;
2111                let i3 = (self.v2[idx - 1] * a + self.i2[idx - 1]) * att;
2112                let i4 = ((sol[self.pos1] - sol[self.neg1]) * a + sol[self.br1]) * att;
2113                let i5 = (self.v1[idx] * a + self.i1[idx]) * att;
2114                let i6 = (self.v1[idx - 1] * a + self.i1[idx - 1]) * att;
2115                let h_now = t.time - self.times[idx];
2116                let h_old = self.times[idx] - self.times[idx - 1];
2117                let d1 = (i1 - i2) / h_now;
2118                let d2 = (i2 - i3) / h_old;
2119                let d3 = (i4 - i5) / h_now;
2120                let d4 = (i5 - i6) / h_old;
2121                if (d1 - d2).abs() >= p.reltol * f64::max(d1.abs(), d2.abs()) + p.abstol
2122                    || (d3 - d4).abs() >= p.reltol * f64::max(d3.abs(), d4.abs()) + p.abstol
2123                {
2124                    // "derivative changing - need to schedule after
2125                    // delay"
2126                    *time_step = time_step.min(p.td);
2127                }
2128            }
2129        }
2130        if p.case == LtraCase::Rlc && !p.trunc_dont_cut {
2131            *time_step = time_step.min(p.max_safe_step);
2132        }
2133    }
2134
2135    /// `LTRAacLoad`: `Y0(s)·V1 − I1 = e^{−λ(s)·l}·(Y0(s)·V2 + I2)` and
2136    /// its mirror, `Y0 = √((sC+G)/(sL+R))`, `λ = √((sC+G)(sL+R))`.
2137    /// RG is loaded exactly as in DC.
2138    fn load_ac(&mut self, ctx: &mut AcCtx) {
2139        let p = &self.p;
2140        let s = self.slots;
2141        let w = ctx.omega;
2142        let (y0_r, y0_i, lambda_r, lambda_i) = match p.case {
2143            LtraCase::Lc => (p.admit, 0.0, 0.0, p.td * w),
2144            LtraCase::Rlc => {
2145                let theta = 0.5 * atan(p.resist / (w * p.induct));
2146                let zmag = (p.resist * p.resist + w * w * p.induct * p.induct).sqrt();
2147                let mag = (w * p.capac / zmag).sqrt();
2148                let y0_r = mag * cos(theta);
2149                let y0_i = mag * sin(theta);
2150                let theta = std::f64::consts::FRAC_PI_2 - theta;
2151                let mag = mag * zmag;
2152                (y0_r, y0_i, mag * cos(theta), mag * sin(theta))
2153            }
2154            LtraCase::Rc => {
2155                let y = (0.5 * w * p.cbyr).sqrt();
2156                let l = (0.5 * w * p.resist * p.capac).sqrt();
2157                (y, y, l, l)
2158            }
2159            LtraCase::Rg => {
2160                let g1 = (1.0 + self.gmin) * p.r_rs_lr_gr_or_g;
2161                let g2 = (1.0 + self.gmin) * p.r_gs_lr_gr_or_r;
2162                ctx.add_g(s.ibr1_pos1, 1.0);
2163                ctx.add_g(s.ibr1_neg1, -1.0);
2164                ctx.add_g(s.ibr1_pos2, -p.cosh_lroot_gr);
2165                ctx.add_g(s.ibr1_neg2, p.cosh_lroot_gr);
2166                ctx.add_g(s.ibr1_ibr2, g1);
2167                ctx.add_g(s.ibr2_ibr2, p.cosh_lroot_gr);
2168                ctx.add_g(s.ibr2_pos2, -g2);
2169                ctx.add_g(s.ibr2_neg2, g2);
2170                ctx.add_g(s.ibr2_ibr1, 1.0);
2171                ctx.add_g(s.pos1_ibr1, 1.0);
2172                ctx.add_g(s.neg1_ibr1, -1.0);
2173                ctx.add_g(s.pos2_ibr2, 1.0);
2174                ctx.add_g(s.neg2_ibr2, -1.0);
2175                return;
2176            }
2177        };
2178        let exparg_r = -lambda_r * p.length;
2179        let exparg_i = -lambda_i * p.length;
2180        let explambda_r = exp(exparg_r) * cos(exparg_i);
2181        let explambda_i = exp(exparg_r) * sin(exparg_i);
2182        let y0exp_r = y0_r * explambda_r - y0_i * explambda_i;
2183        let y0exp_i = y0_r * explambda_i + y0_i * explambda_r;
2184
2185        let both = |ctx: &mut AcCtx, sl: Slot, re: f64, im: f64| {
2186            ctx.add_g(sl, re);
2187            ctx.add_b(sl, im);
2188        };
2189        both(ctx, s.ibr1_pos1, y0_r, y0_i);
2190        both(ctx, s.ibr1_neg1, -y0_r, -y0_i);
2191        ctx.add_g(s.ibr1_ibr1, -1.0);
2192        both(ctx, s.ibr1_pos2, -y0exp_r, -y0exp_i);
2193        both(ctx, s.ibr1_neg2, y0exp_r, y0exp_i);
2194        both(ctx, s.ibr1_ibr2, -explambda_r, -explambda_i);
2195
2196        both(ctx, s.ibr2_pos2, y0_r, y0_i);
2197        both(ctx, s.ibr2_neg2, -y0_r, -y0_i);
2198        ctx.add_g(s.ibr2_ibr2, -1.0);
2199        both(ctx, s.ibr2_pos1, -y0exp_r, -y0exp_i);
2200        both(ctx, s.ibr2_neg1, y0exp_r, y0exp_i);
2201        both(ctx, s.ibr2_ibr1, -explambda_r, -explambda_i);
2202
2203        ctx.add_g(s.pos1_ibr1, 1.0);
2204        ctx.add_g(s.neg1_ibr1, -1.0);
2205        ctx.add_g(s.pos2_ibr2, 1.0);
2206        ctx.add_g(s.neg2_ibr2, -1.0);
2207    }
2208
2209    fn compact_ready(&self) -> Option<bool> {
2210        self.straight_tail()
2211    }
2212
2213    fn compact(&mut self) {
2214        self.drop_middle();
2215    }
2216
2217    fn history_len(&self) -> Option<usize> {
2218        Some(self.times.len())
2219    }
2220
2221    /// `LTRAaccept`: store the accepted point in the history and, when
2222    /// the slope of an incident wave `(v + Z0·i)·e^{−βT}` changes,
2223    /// plant a breakpoint one delay after the *previous* point (where
2224    /// the change happened).
2225    fn accept(&mut self, ctx: &mut AcceptCtx) {
2226        if ctx.first {
2227            // MODEINITTRAN: the operating point starts the history.
2228            self.wave_peak = [0.0; 2];
2229            self.times.clear();
2230            self.v1.clear();
2231            self.i1.clear();
2232            self.v2.clear();
2233            self.i2.clear();
2234            self.periodic = false;
2235            self.periodic_fault = None;
2236            if let Some(past) = ctx.periodic {
2237                self.seed_periodic(past, ctx);
2238                return;
2239            }
2240        }
2241        let sol = ctx.sol;
2242        self.times.push(ctx.time);
2243        self.v1.push(sol[self.pos1] - sol[self.neg1]);
2244        self.v2.push(sol[self.pos2] - sol[self.neg2]);
2245        self.i1.push(sol[self.br1]);
2246        self.i2.push(sol[self.br2]);
2247
2248        let idx = self.times.len() - 1;
2249        if self.fit_on {
2250            if ctx.first {
2251                self.start_fit(ctx.final_time);
2252            } else if idx > 0 && self.fit.is_some() {
2253                self.fit_accept();
2254            }
2255        }
2256        let p = &self.p;
2257        let wave = |v: f64, i: f64| ((v + i * p.imped) * p.attenuation).abs();
2258        self.wave_peak[0] = self.wave_peak[0].max(wave(self.v1[idx], self.i1[idx]));
2259        self.wave_peak[1] = self.wave_peak[1].max(wave(self.v2[idx], self.i2[idx]));
2260        if idx == 0 {
2261            return;
2262        }
2263        if self.slope_changed(idx, ctx.reltol, ctx.abstol) {
2264            let t = self.times[idx - 1] + self.p.td;
2265            ctx.set_slope_break(t);
2266        }
2267    }
2268}
2269
2270impl LtraI {
2271    /// `trytocompact`'s test in `LTRAaccept` (`ltraacct.c:84-127`):
2272    /// whether the last three samples of `v1`, `v2`, `i1` and `i2`
2273    /// each lie on a straight line in time within the model's
2274    /// `COMPACTREL`/`COMPACTABS` (`LTRAstraightLineCheck`). `None` when
2275    /// the line takes no part (fewer than three samples — the C's
2276    /// `CKTtimeIndex >= 2` —, the recursive mode, or a `.pss` run).
2277    fn straight_tail(&self) -> Option<bool> {
2278        let n = self.times.len();
2279        if n < 3 || self.fit_on || self.periodic {
2280            return None;
2281        }
2282        let (t1, t2, t3) = (self.times[n - 3], self.times[n - 2], self.times[n - 1]);
2283        let (rt, at) = (self.p.st_line_reltol, self.p.st_line_abstol);
2284        let straight =
2285            |y: &[f64]| straight_line_check(t1, y[n - 3], t2, y[n - 2], t3, y[n - 1], rt, at);
2286        Some(straight(&self.v1) && straight(&self.v2) && straight(&self.i1) && straight(&self.i2))
2287    }
2288
2289    /// The compaction itself (`ltraacct.c:262-285`): the newest sample
2290    /// overwrites the middle one, which leaves the history.
2291    fn drop_middle(&mut self) {
2292        let n = self.times.len();
2293        debug_assert!(n >= 3);
2294        for h in [
2295            &mut self.times,
2296            &mut self.v1,
2297            &mut self.v2,
2298            &mut self.i1,
2299            &mut self.i2,
2300        ] {
2301            h.swap_remove(n - 2);
2302        }
2303    }
2304
2305    /// `LTRAaccept`'s test at history point `idx ≥ 1`: whether the
2306    /// slope of an incident wave changed enough (and the wave is not
2307    /// a straight line within tolerance) to want a breakpoint one
2308    /// delay after point `idx − 1`.
2309    fn slope_changed(&self, idx: usize, reltol: f64, abstol: f64) -> bool {
2310        let p = &self.p;
2311        let wave1 = |k: usize| (self.v1[k] + self.i1[k] * p.imped) * p.attenuation;
2312        let wave2 = |k: usize| (self.v2[k] + self.i2[k] * p.imped) * p.attenuation;
2313        let v1 = wave1(idx);
2314        let v2 = wave1(idx - 1);
2315        let v3 = if idx < 2 { v2 } else { wave1(idx - 2) };
2316        let v4 = wave2(idx);
2317        let v5 = wave2(idx - 1);
2318        let v6 = if idx < 2 { v5 } else { wave2(idx - 2) };
2319        let h1 = self.times[idx] - self.times[idx - 1];
2320        let d1 = (v1 - v2) / h1;
2321        let d3 = (v4 - v5) / h1;
2322        // At the first step the C divides the zero `v2 − v3` by a
2323        // difference reaching before the list (`CKTtimePoints[-1]`);
2324        // the quotient is zero.
2325        let (d2, d4) = if idx < 2 {
2326            (0.0, 0.0)
2327        } else {
2328            let h2 = self.times[idx - 1] - self.times[idx - 2];
2329            ((v2 - v3) / h2, (v5 - v6) / h2)
2330        };
2331        // The C's own test of "not a straight line" compares the
2332        // spread of the three values with 50·RELTOL of their *mean*:
2333        // around zero that is 50·ABSTOL, and the residue of a settled
2334        // edge passes it at every point. The floor asks the spread to
2335        // be visible at the scale of the line's signals (the larger
2336        // of the two waves: the backward wave of a matched line is
2337        // all residue).
2338        let peak = f64::max(self.wave_peak[0], self.wave_peak[1]);
2339        let check = |a: f64, b: f64, c: f64| {
2340            let spread = f64::max(f64::max(a, b), c) - f64::min(f64::min(a, b), c);
2341            spread >= (50.0 * (reltol / 3.0 * (a + b + c) + abstol)).abs()
2342                && (!self.slope_floor || spread >= reltol * peak)
2343        };
2344        let test1 = (d1 - d2).abs() >= p.reltol * f64::max(d1.abs(), d2.abs()) + p.abstol
2345            && check(v1, v2, v3);
2346        let test2 = (d3 - d4).abs() >= p.reltol * f64::max(d3.abs(), d4.abs()) + p.abstol
2347            && check(v4, v5, v6);
2348        test1 || test2
2349    }
2350
2351    /// `.pss` (issue #20): the history of a shooting interval starting
2352    /// at `ctx.time = t₀` is the periodic past. The port histories get
2353    /// whole periods of the orbit back to the oldest lag a load can
2354    /// reach (one delay; the exact window of an RC fit), then the
2355    /// shooting state at `t₀`. The deviations are taken from the
2356    /// orbit's mean (not the operating point: there is none), so the
2357    /// constant part is the closed-form `∫h` term as always and the
2358    /// recursive states see a zero-mean periodic input, which
2359    /// [`FitState::periodic_start`] sums over the infinite past in
2360    /// closed form. The breakpoints the slope rule would have planted
2361    /// one delay after the past's slope changes are planted where they
2362    /// fall inside the interval.
2363    fn seed_periodic(&mut self, past: &PeriodicPast, ctx: &mut AcceptCtx) {
2364        self.periodic = true;
2365        let t0 = ctx.time;
2366        let period = past.period;
2367        let mut reach = self.p.td;
2368        if self.fit_on && self.p.case == LtraCase::Rc {
2369            reach = reach.max(RC_WINDOW_FRACTION * self.p.rclsqr);
2370        }
2371        // A sliver more than the reach, so a delay of exactly k periods
2372        // still finds a point before its target (quadratic interpolation).
2373        let from = t0 - reach - 1e-6 * period;
2374        let Some(samples) = past.samples(t0, from, ctx.sol) else {
2375            self.periodic_fault = Some("LTRA: the delay spans too many periods for .pss");
2376            return;
2377        };
2378        let (p1, n1, p2, n2, b1, b2) = (
2379            self.pos1, self.neg1, self.pos2, self.neg2, self.br1, self.br2,
2380        );
2381        for (t, x) in samples.into_iter().chain([(t0, ctx.sol)]) {
2382            self.times.push(t);
2383            self.v1.push(x[p1] - x[n1]);
2384            self.v2.push(x[p2] - x[n2]);
2385            self.i1.push(x[b1]);
2386            self.i2.push(x[b2]);
2387        }
2388        // One period is points 0..=per of the first copy.
2389        let per = past.phase.len() + 1;
2390        let mean = |w: &[f64]| {
2391            let mut acc = 0.0;
2392            for k in 1..=per {
2393                acc += 0.5 * (w[k] + w[k - 1]) * (self.times[k] - self.times[k - 1]);
2394            }
2395            acc / (self.times[per] - self.times[0])
2396        };
2397        self.init_v1 = mean(&self.v1);
2398        self.init_v2 = mean(&self.v2);
2399        self.init_i1 = mean(&self.i1);
2400        self.init_i2 = mean(&self.i2);
2401        if matches!(self.p.case, LtraCase::Rlc | LtraCase::Rc) {
2402            // The DC pin. With G = 0 the characteristic form loses the
2403            // line's DC drop: `Y0(0) = 0`, so at s = 0 both branch
2404            // equations reduce to `i1 + i2 = 0`, and the drop
2405            // `v1 − v2 = R·LEN·i1` lives only in the `√s` order — in
2406            // the time domain, the `τ^{−3/2}` tails integrated over a
2407            // history that starts at an operating point (whose DC
2408            // stamps are that resistor). A past that has always been
2409            // periodic carries no such start: its mean drop is a
2410            // neutral mode the orbit just copies (measured: the line's
2411            // apparent DC resistance drifting a fixed amount per
2412            // iteration, the period mismatch never closing at tight
2413            // tolerances). The past is pinned to the exact DC
2414            // relation instead: its mean voltages are shifted
2415            // symmetrically, the mean current kept, so that the mean
2416            // drop is `R·LEN` times the mean current. A fixed point of
2417            // the iteration then has the past equal to the orbit, so
2418            // the orbit itself meets the DC relation — the shift is
2419            // only nonzero while iterating.
2420            let i = 0.5 * (self.init_i1 - self.init_i2);
2421            let drop = self.p.resist * self.p.length * i;
2422            let avg = 0.5 * (self.init_v1 + self.init_v2);
2423            let (s1, s2) = (
2424                avg + 0.5 * drop - self.init_v1,
2425                avg - 0.5 * drop - self.init_v2,
2426            );
2427            let last = self.times.len() - 1;
2428            for k in 0..last {
2429                self.v1[k] += s1;
2430                self.v2[k] += s2;
2431            }
2432            self.init_v1 += s1;
2433            self.init_v2 += s2;
2434        }
2435        if self.fit_on {
2436            self.build_fit(ctx.final_time.max(PERIODIC_HORIZON_PERIODS * period));
2437            let seg = |k: usize| {
2438                (
2439                    self.times[k] - self.times[k - 1],
2440                    [V1, V2, I1, I2].map(|w| self.dev(w, k)),
2441                    [V1, V2, I1, I2].map(|w| self.dev(w, k - 1)),
2442                )
2443            };
2444            let first: Vec<_> = (1..=per).map(seg).collect();
2445            let rest: Vec<_> = (1..self.times.len()).map(seg).collect();
2446            let keep = self.oldest_needed();
2447            let span = self.times[per] - self.times[0];
2448            if let Some(fs) = self.fit.as_mut() {
2449                fs.periodic_start(span, &first);
2450                for (h, dn, dp) in rest {
2451                    fs.advance(h, dn, dp);
2452                }
2453                fs.prune(keep);
2454            }
2455        }
2456        for idx in 1..self.times.len() {
2457            let t = self.times[idx - 1] + self.p.td;
2458            if t > t0 + ctx.min_break
2459                && t < ctx.final_time - ctx.min_break
2460                && self.slope_changed(idx, ctx.reltol, ctx.abstol)
2461            {
2462                ctx.set_slope_break(t);
2463            }
2464        }
2465    }
2466}
2467
2468/// The C's unscaled Bessel fits, for the scaled ones' tests.
2469#[cfg(test)]
2470pub(crate) fn tests_bess(x: f64) -> (f64, f64) {
2471    (bess_i0(x), bess_i1(x))
2472}
2473
2474#[cfg(test)]
2475mod tests {
2476    use super::*;
2477
2478    fn close(a: f64, b: f64, rel: f64) -> bool {
2479        (a - b).abs() <= rel * f64::max(a.abs(), b.abs())
2480    }
2481
2482    /// `LTRArlcH1dashFunc` (test reference only; the load uses its
2483    /// closed-form twice integral).
2484    fn rlc_h1dash(time: f64, alpha: f64, beta: f64) -> f64 {
2485        if alpha == 0.0 {
2486            return 0.0;
2487        }
2488        (bess_i1(alpha * time) - bess_i0(alpha * time)) * alpha * (-beta * time).exp()
2489    }
2490
2491    /// `LTRArlcH3dashFunc`.
2492    fn rlc_h3dash(time: f64, t: f64, alpha: f64, beta: f64) -> f64 {
2493        if alpha == 0.0 || time < t {
2494            return 0.0;
2495        }
2496        let besselarg = if time != t {
2497            alpha * (time * time - t * t).sqrt()
2498        } else {
2499            0.0
2500        };
2501        (alpha * time * bess_i1_x_over_x(besselarg) - bess_i0(besselarg))
2502            * alpha
2503            * (-beta * time).exp()
2504    }
2505
2506    /// `LTRArlcH1dashTwiceIntFunc`.
2507    fn rlc_h1dash_twice_int(time: f64, beta: f64) -> f64 {
2508        if beta == 0.0 {
2509            return time;
2510        }
2511        let arg = beta * time;
2512        if arg == 0.0 {
2513            return 0.0;
2514        }
2515        (bess_i1(arg) + bess_i0(arg)) * time * (-arg).exp() - time
2516    }
2517
2518    /// `LTRArlcH3dashIntFunc`.
2519    fn rlc_h3dash_int(time: f64, t: f64, beta: f64) -> f64 {
2520        if time <= t || beta == 0.0 {
2521            return 0.0;
2522        }
2523        (-beta * time).exp() * bess_i0(beta * (time * time - t * t).sqrt()) - (-beta * t).exp()
2524    }
2525
2526    #[test]
2527    fn bessel_fits_match_reference_values() {
2528        // Abramowitz & Stegun table values; NR fits are good to ~1e-7.
2529        assert!(close(bess_i0(1.0), 1.266_065_877_752_008, 2e-7));
2530        assert!(close(bess_i1(1.0), 0.565_159_103_992_485, 2e-7));
2531        assert!(close(bess_i0(5.0), 27.239_871_823_604_44, 2e-7));
2532        assert!(close(bess_i1(5.0), 24.335_642_142_450_52, 2e-7));
2533        assert!(close(bess_i1(-5.0), -24.335_642_142_450_52, 2e-7));
2534        assert!(close(
2535            bess_i1_x_over_x(5.0),
2536            24.335_642_142_450_52 / 5.0,
2537            2e-7
2538        ));
2539        assert_eq!(bess_i1_x_over_x(0.0), 0.5);
2540        assert!(close(bess_i1_x_over_x(2.0), bess_i1(2.0) / 2.0, 1e-15));
2541    }
2542
2543    #[test]
2544    fn linear_integrals_are_exact() {
2545        // h(τ) = 1 + τ through (0, 1) and (2, 3).
2546        assert!(close(intlinfunc(0.0, 2.0, 1.0, 3.0, 0.0, 2.0), 4.0, 1e-15));
2547        assert!(close(intlinfunc(0.5, 1.5, 1.0, 3.0, 0.0, 2.0), 2.0, 1e-15));
2548        // ∫_0^2 ∫_0^τ (1 + τ') dτ' dτ = ∫_0^2 (τ + τ²/2) dτ = 2 + 4/3.
2549        let v = twiceintlinfunc(0.0, 2.0, 0.0, 1.0, 3.0, 0.0, 2.0);
2550        assert!(close(v, 2.0 + 4.0 / 3.0, 1e-14), "{v}");
2551        // Inner lower limit 1: ∫_1^2 ∫_1^τ (1+τ') = ∫_1^2 (τ−1)(3+τ)/2
2552        // = 7/6.
2553        let v = twiceintlinfunc(1.0, 2.0, 1.0, 1.0, 3.0, 0.0, 2.0);
2554        assert!(close(v, 7.0 / 6.0, 1e-14), "{v}");
2555    }
2556
2557    #[test]
2558    fn interpolation_reproduces_polynomials() {
2559        let (c1, c2, c3) = quad_interp(1.7, 0.0, 1.0, 3.0).unwrap();
2560        let f = |t: f64| 2.0 - t + 0.5 * t * t;
2561        let q = c1 * f(0.0) + c2 * f(1.0) + c3 * f(3.0);
2562        assert!(close(q, f(1.7), 1e-14));
2563        assert_eq!(quad_interp(1.0, 0.0, 1.0, 3.0), Some((0.0, 1.0, 0.0)));
2564        assert_eq!(quad_interp(0.5, 1.0, 1.0, 3.0), None);
2565        let (l1, l2) = lin_interp(0.25, 0.0, 1.0).unwrap();
2566        assert_eq!((l1, l2), (0.75, 0.25));
2567    }
2568
2569    #[test]
2570    fn closed_form_integrals_differentiate_to_the_responses() {
2571        // α = β (G = 0): H1''' = h1', d/dt H3int = h3'.
2572        let (alpha, t) = (1.1e7, 4.38e-9);
2573        for &time in &[1e-9, 5e-9, 2e-8] {
2574            let h = time * 1e-4;
2575            let f = |x: f64| rlc_h1dash_twice_int(x, alpha);
2576            let second = (f(time + h) - 2.0 * f(time) + f(time - h)) / (h * h);
2577            assert!(
2578                close(second, rlc_h1dash(time, alpha, alpha), 1e-4),
2579                "{second} vs {}",
2580                rlc_h1dash(time, alpha, alpha)
2581            );
2582            if time > t {
2583                let g = |x: f64| rlc_h3dash_int(x, t, alpha);
2584                let first = (g(time + h) - g(time - h)) / (2.0 * h);
2585                assert!(close(first, rlc_h3dash(time, t, alpha, alpha), 1e-4));
2586            }
2587        }
2588    }
2589
2590    #[test]
2591    fn rlc_coefficients_telescope_to_the_last_divided_difference() {
2592        // With chopping off, h1First + Σ h1[i] is the divided
2593        // difference of H1'' over the oldest interval.
2594        let (alpha, td) = (1.1e7, 4.38e-9);
2595        let times: Vec<f64> = (0..40)
2596            .map(|k| k as f64 * 0.1e-9 + (k * k) as f64 * 1e-12)
2597            .collect();
2598        let n = times.len() - 1;
2599        let cur = times[n] + 0.07e-9;
2600        let mut co = Coeffs::default();
2601        rlc_coeffs(&mut co, td, alpha, alpha, cur, &times, n, 0.0);
2602        let sum: f64 = co.h1_first + co.h1[1..=n].iter().sum::<f64>();
2603        let f = |x: f64| rlc_h1dash_twice_int(x, alpha);
2604        let last = (f(cur - times[0]) - f(cur - times[1])) / (times[1] - times[0]);
2605        assert!(close(sum, last, 1e-9), "{sum} vs {last}");
2606        // The first coefficient is H1''(Δ)/Δ.
2607        let d = cur - times[n];
2608        assert!(close(co.h1_first, f(d) / d, 1e-15));
2609        // The lag-T search: the point just older than cur − T.
2610        assert!(cur - times[co.aux_index] > td);
2611        assert!(cur - times[co.aux_index + 1] <= td);
2612        assert!(co.h2_first > 0.0);
2613    }
2614
2615    #[test]
2616    fn rc_coefficients_telescope() {
2617        let (cbyr, rclsqr) = (3.65e-12 / 0.2, 0.2 * 3.65e-12 * 24.0 * 24.0);
2618        let times: Vec<f64> = (0..30).map(|k| k as f64 * 0.1e-9).collect();
2619        let n = times.len() - 1;
2620        let cur = times[n] + 0.05e-9;
2621        let mut co = Coeffs::default();
2622        rc_coeffs(&mut co, cbyr, rclsqr, cur, &times, n, 0.0);
2623        let f = |x: f64| (4.0 * cbyr * x / std::f64::consts::PI).sqrt();
2624        let sum: f64 = co.h1_first + co.h1[1..=n].iter().sum::<f64>();
2625        let last = (f(cur - times[0]) - f(cur - times[1])) / (times[1] - times[0]);
2626        assert!(close(sum, last, 1e-9));
2627    }
2628
2629    /// A matched lossless line: the far end is the near end delayed by
2630    /// `T`, and the near end sees `Z0` (a 2:1 divider with the source
2631    /// resistance) until the delay is over and forever after.
2632    #[test]
2633    fn matched_lc_line_delays_by_td() {
2634        use crate::circuit::{Circuit, Ltra, Resistor, Vsource};
2635        let (l, c, len) = (250e-9, 100e-12, 1.0); // Z0 = 50 Ω, T = 5 ns
2636        let mut ckt = Circuit::new("matched line");
2637        ckt.add(Vsource {
2638            name: "v1".into(),
2639            nodes: ["1".into(), "0".into()],
2640            dc: None,
2641            wave: Some(crate::srcfn::Wave::Pulse(vec![
2642                0.0, 1.0, 1e-9, 1e-9, 1e-9, 100e-9, 200e-9,
2643            ])),
2644            ac: None,
2645            distof1: None,
2646            distof2: None,
2647            port: None,
2648        })
2649        .unwrap();
2650        for (name, a, b) in [("rs", "1", "2"), ("rl", "3", "0")] {
2651            ckt.add(Resistor {
2652                name: name.into(),
2653                nodes: [a.into(), b.into()],
2654                value: 50.0,
2655            })
2656            .unwrap();
2657        }
2658        ckt.add(Ltra {
2659            name: "o1".into(),
2660            nodes: ["2".into(), "0".into(), "3".into(), "0".into()],
2661            model: LtraModel {
2662                r: Some(0.0),
2663                l: Some(l),
2664                c: Some(c),
2665                len: Some(len),
2666                ..LtraModel::default()
2667            },
2668        })
2669        .unwrap();
2670        let opts = crate::options::Options::default();
2671        let tr = ckt.tran(&opts, 0.1e-9, 20e-9, 0.0, None, false).unwrap();
2672        let t = tr.solution.column("time").unwrap();
2673        let v2 = tr.solution.column("v(2)").unwrap();
2674        let v3 = tr.solution.column("v(3)").unwrap();
2675        assert!(tr.solution.column("v(o1#i1)").is_some());
2676        let at = |col: &[f64], when: f64| {
2677            let k = t.iter().position(|&x| x >= when).unwrap();
2678            let f = (when - t[k - 1]) / (t[k] - t[k - 1]);
2679            col[k - 1] + f * (col[k] - col[k - 1])
2680        };
2681        // Before the wave arrives the far end is quiet.
2682        assert!(at(v3, 5.5e-9).abs() < 1e-6, "{}", at(v3, 5.5e-9));
2683        // Mid-ramp: v3(t) = v2(t − 5 ns), both half the source.
2684        assert!((at(v2, 1.5e-9) - 0.25).abs() < 2e-3, "{}", at(v2, 1.5e-9));
2685        assert!((at(v3, 6.5e-9) - 0.25).abs() < 2e-3, "{}", at(v3, 6.5e-9));
2686        assert!((at(v3, 12e-9) - 0.5).abs() < 1e-6);
2687        assert!((at(v2, 12e-9) - 0.5).abs() < 1e-6);
2688    }
2689
2690    #[test]
2691    fn setup_classifies_and_rejects_like_ltraset() {
2692        let base = LtraModel {
2693            r: Some(0.2),
2694            l: Some(9.13e-9),
2695            c: Some(3.65e-12),
2696            len: Some(24.0),
2697            ..LtraModel::default()
2698        };
2699        let p = LtraParams::new("o1", &base, 1e-3, 1e-12).unwrap();
2700        assert_eq!(p.case, LtraCase::Rlc);
2701        assert!(close(p.td, (9.13e-9f64 * 3.65e-12).sqrt() * 24.0, 1e-15));
2702        assert!(p.max_safe_step > 0.0 && p.max_safe_step <= 9.0 * p.td);
2703        assert!(p.notes.is_empty());
2704
2705        let lc = LtraModel {
2706            r: Some(0.0),
2707            ..base.clone()
2708        };
2709        assert_eq!(
2710            LtraParams::new("o1", &lc, 1e-3, 1e-12).unwrap().case,
2711            LtraCase::Lc
2712        );
2713        let rc = LtraModel {
2714            l: Some(0.0),
2715            ..base.clone()
2716        };
2717        assert_eq!(
2718            LtraParams::new("o1", &rc, 1e-3, 1e-12).unwrap().case,
2719            LtraCase::Rc
2720        );
2721        let rl = LtraModel {
2722            c: Some(0.0),
2723            ..base.clone()
2724        };
2725        assert!(
2726            LtraParams::new("o1", &rl, 1e-3, 1e-12)
2727                .unwrap_err()
2728                .contains("RL line")
2729        );
2730        let rlcg = LtraModel {
2731            g: Some(1e-3),
2732            ..base.clone()
2733        };
2734        assert!(
2735            LtraParams::new("o1", &rlcg, 1e-3, 1e-12)
2736                .unwrap_err()
2737                .contains("Nonzero G")
2738        );
2739        let rg = LtraModel {
2740            g: Some(1e-3),
2741            l: Some(0.0),
2742            c: Some(0.0),
2743            ..base.clone()
2744        };
2745        let p = LtraParams::new("o1", &rg, 1e-3, 1e-12).unwrap();
2746        assert_eq!(p.case, LtraCase::Rg);
2747        assert!(p.cosh_lroot_gr > 1.0);
2748        let nolen = LtraModel {
2749            len: None,
2750            ..base.clone()
2751        };
2752        assert!(
2753            LtraParams::new("o1", &nolen, 1e-3, 1e-12)
2754                .unwrap_err()
2755                .contains("length")
2756        );
2757        let one = LtraModel {
2758            r: None,
2759            l: None,
2760            ..base.clone()
2761        };
2762        let e = LtraParams::new("o1", &one, 1e-3, 1e-12).unwrap_err();
2763        assert!(e.contains("At least two"), "{e}");
2764        let nan = LtraModel {
2765            r: Some(f64::NAN),
2766            ..base
2767        };
2768        assert!(LtraParams::new("o1", &nan, 1e-3, 1e-12).is_err());
2769    }
2770}