Skip to main content

dae_runtime/
lib.rs

1//! Assembles a circuit's linear MNA system (via `general-mna`, including its `'D'` stamp) with
2//! PWL device segments (via `pwl-devices`) into one Linear Complementarity Problem, solves it
3//! (via `lcp-solver`), and reports the resolved DC operating point. No Newton-Raphson, no
4//! voltage limiting, anywhere in this crate — see this repository's `docs/architecture.md`.
5//!
6//! ## The generic Thevenin/LCP fold
7//!
8//! `general-mna` stamps each diode `k` as a *fixed* conductance `{k}_G` plus a per-instance
9//! current-source symbol `{k}_Ioff`. Fixing `{k}_G` at the diode's canonical reference slope
10//! `g_off` (see `pwl_devices::IdealDiode::canonical`) makes the whole linear system `A0` genuinely
11//! fixed — independent of which segment every diode ends up in — with every segment's actual
12//! nonlinearity pushed entirely into the `{k}_Ioff` terms via each diode's canonical
13//! `max(0, ...)` (`z`) decomposition. Since the system is linear in those `Ioff` terms, each
14//! diode's terminal voltage is an affine function of every diode's `z` variables:
15//!
16//! ```text
17//! x(z)   = x0 + sum_j w_j * raw_Ioff_j                  (raw_Ioff_j = delta_on_j*z2_j - delta_br_j*z1_j)
18//! V_k(z) = v0_k + sum_j gamma_kj * raw_Ioff_j            (gamma_kj = w_j[p_k] - w_j[n_k])
19//! ```
20//!
21//! where `x0 = solve(A0, u0)` is the baseline operating point with every diode's `Ioff = 0`,
22//! and `w_j = solve(A0, B[:, diode j's input column])` is how much a unit "raw Ioff" on diode
23//! `j` moves every unknown. Substituting `V_k(z)` into each diode's guard equations
24//! (`w1_k = V_k - v_breakdown_k + z1_k`, `w2_k = v_th_k - V_k + z2_k`) gives exactly the LCP
25//! `(M, q)` this crate builds and hands to `lcp_solver::solve`.
26
27mod block_graph;
28mod closed_loop;
29mod linsolve;
30mod step_control;
31mod topology;
32
33pub use block_graph::{
34    reject_sig2phys_wired_into_circuit, simulate_transient_with_blocks,
35    simulate_transient_with_blocks_capped, simulate_transient_with_blocks_streamed, BlockInstance,
36    BlockKind, ConstValue, GainValue, GateBinding, Phys2SigTarget, PhysicalDomain, PidClamp,
37    SampleTimeSpec, Signal, SignalValue, TransientWithBlocksStep, ADAPTIVE_STEP_HARD_CAP,
38};
39pub use closed_loop::{sawtooth_carrier, simulate_closed_loop};
40pub use step_control::{AdaptiveConfig, TimeStep};
41
42use std::collections::BTreeMap;
43
44use general_mna::{
45    BuildError, BuildOptions, EvaluationError, Expression, InitialStateError, MnaBuilder, MnaSystem,
46};
47use general_spice_core::ast::Statement;
48use general_spice_core::Dialect;
49use lcp_solver::LcpError;
50use linsolve::{dense_solve, SingularMatrix};
51use pwl_devices::{IdealDiode, IdealSwitch};
52
53pub use general_mna::SwitchState as GateState;
54pub use general_mna::TransientFunction;
55
56#[derive(Debug, Clone, PartialEq)]
57pub struct OperatingPoint {
58    pub unknowns: Vec<String>,
59    pub x: Vec<f64>,
60    /// Resolved `(z1, z2)` for each diode, in the same iteration order as the `diodes` map
61    /// passed to [`solve_dc`] (a `BTreeMap`, so alphabetical by name) — useful for reporting
62    /// which segment each diode ended up in.
63    pub diode_names: Vec<String>,
64    pub diode_z: Vec<(f64, f64)>,
65    /// Each diode's true (unscaled) resolved current `delta_on*z2 - delta_br*z1`, same order
66    /// as `diode_names`/`diode_z`. Needed as history by [`simulate_transient`]'s trapezoidal
67    /// step (see its doc comment); exposed here rather than recomputed by every caller.
68    pub diode_raw_ioff: Vec<f64>,
69}
70
71impl OperatingPoint {
72    pub fn value(&self, unknown: &str) -> Option<f64> {
73        self.unknowns
74            .iter()
75            .position(|name| name == unknown)
76            .map(|index| self.x[index])
77    }
78}
79
80#[derive(Debug, Clone, PartialEq)]
81pub enum DaeError {
82    /// Parsing/hierarchy-flattening the netlist itself failed — see
83    /// [`general_mna::parse_and_flatten`]; a `.subckt`/`X` structural error (undefined
84    /// subcircuit, node-count mismatch, a recursive instantiation, ...) surfaces here, distinct
85    /// from [`DaeError::Build`]'s "parsed fine, but this statement has no valid electrical
86    /// stamp" class of error.
87    Parse(String),
88    /// A streaming `on_step` callback's own I/O failed (writing a CSV/raw row straight to a
89    /// file/stream as it's produced — see [`block_graph::simulate_transient_with_blocks_streamed`]).
90    /// Carries the formatted underlying `std::io::Error` as a string rather than the error type
91    /// itself, since `DaeError` derives `PartialEq` and `io::Error` doesn't implement it.
92    Io(String),
93    Build(BuildError),
94    /// The netlist declares `ic=` initial conditions that could not be assigned — see
95    /// [`general_mna::MnaSystem::initial_state`], whose own error explains the two ways that
96    /// fails: conditions that contradict each other (a loop of `ic`-bearing capacitors whose
97    /// declared voltages do not sum to zero), and an assignment that violates one of the
98    /// circuit's own algebraic equations in which every unknown is already fixed by an `ic=`
99    /// (an `ic` on a capacitor across an ideal voltage source; series inductors declaring
100    /// different currents).
101    InitialCondition(InitialStateError),
102    Evaluate(EvaluationError),
103    Linear(SingularMatrix),
104    Lcp(LcpError),
105    UnknownDiodeInput(String),
106    /// A [`block_graph::BlockInstance`]'s input, or a [`block_graph::GateBinding`], names a
107    /// block that doesn't exist anywhere in the graph (a typo, or a genuinely undeclared name)
108    /// — declaration *position* is no longer a possible cause: [`block_graph::topological_order`]
109    /// derives each step's evaluation order from the `Signal::Block` dependency graph itself, so
110    /// a block may reference another declared anywhere in the same slice, before or after it.
111    UnknownBlockInput(String),
112    /// The `Signal::Block` dependency graph among a [`block_graph::BlockInstance`] slice
113    /// contains a genuine same-step cycle — computed once, upfront, by
114    /// [`block_graph::topological_order`] (a DFS-based topological sort; a cycle shows up as a
115    /// back-edge into a node still on the current recursion path) before any step is solved.
116    /// `cycle` is the exact closing path, block names in dependency order with the first name
117    /// repeated at the end to show the loop closing (e.g. `["A", "B", "C", "A"]`); a
118    /// self-referencing block reports `["A", "A"]`. Fix by inserting a `Signal::BlockPrev`
119    /// somewhere in the cycle — the one-sample delay that turns a same-step algebraic loop into
120    /// a legitimate sampled-data feedback path.
121    AlgebraicLoop {
122        cycle: Vec<String>,
123    },
124    /// Loading or resolving symbols in a [`block_graph::BlockKind::CScript`]'s shared library
125    /// failed — see [`cscript_ffi::CScriptError`].
126    CScript(cscript_ffi::CScriptError),
127    /// A netlist declares a [`block_graph::BlockKind::CScript`] block whose library doesn't
128    /// export `cscript_clone`, but the run was requested with [`TimeStep::Adaptive`], which
129    /// needs to clone every block's state before each trial step — see `cscript_ffi`'s own
130    /// module doc comment, "Adaptive step-size control and instance cloning." Pass a fixed
131    /// `TimeStep::Fixed` instead, or add `cscript_clone` to the library.
132    CScriptRequiresCloneForAdaptiveStep {
133        block_name: String,
134    },
135    /// A netlist declares a [`block_graph::BlockKind::CScript`] block with `ts=variable`
136    /// (`block_graph::SampleTimeSpec::Variable`), but its library doesn't export
137    /// `cscript_next_sample_hit` — the required function for a block that computes its own
138    /// schedule; see `cscript_ffi`'s own module doc comment, "The optional block-controlled
139    /// sample time." Checked once, up front, the same "checked once, up front" discipline
140    /// `CScriptRequiresCloneForAdaptiveStep` already uses.
141    CScriptRequiresNextSampleHitForVariableSampleTime {
142        block_name: String,
143    },
144    /// The `PyBlock` counterpart to [`Self::CScriptRequiresNextSampleHitForVariableSampleTime`]
145    /// — a `.py` file declared `ts=variable` but doesn't define `next_sample_hit`.
146    #[cfg(feature = "python")]
147    PyBlockRequiresNextSampleHitForVariableSampleTime {
148        block_name: String,
149    },
150    /// Loading, calling into, or cloning a [`block_graph::BlockKind::PyBlock`]'s own `.py` file
151    /// failed — see [`pyblock_ffi::PyBlockError`]. Unlike [`Self::CScriptRequiresCloneForAdaptiveStep`],
152    /// there is no separate "doesn't support adaptive stepping" variant for `PyBlock`: cloning
153    /// uses Python's own generic `copy.deepcopy`, which needs no author opt-in, so a `PyBlock`
154    /// is always eligible — a genuine failure to deep-copy its own state instead surfaces here,
155    /// as an ordinary [`pyblock_ffi::PyBlockError::Exception`].
156    #[cfg(feature = "python")]
157    PyBlock(pyblock_ffi::PyBlockError),
158    /// A netlist declares a [`block_graph::BlockKind::PyBlock`]/[`block_graph::BlockKind::
159    /// PyFunction`] block, but this build of `dae-runtime` was compiled without the optional
160    /// `python` feature (which pulls in `pyblock-ffi`, and through it a build-time dependency
161    /// on a discoverable Python/libpython) — unconditional, unlike the two variants above,
162    /// specifically so a build without that feature can still report a clear, actionable error
163    /// instead of failing to compile at all or panicking.
164    PythonSupportNotCompiledIn {
165        block_name: String,
166    },
167    /// Spawning the shared `octave-cli` subprocess, adding a [`block_graph::BlockKind::OctFunc`]
168    /// block's own `.m` file directory to its path, or calling into it failed — see
169    /// [`octave_ffi::OctaveError`]'s own three cases (not found on `PATH`, the process died, or
170    /// an ordinary Octave-side runtime error the session survives). Unlike
171    /// [`Self::PythonSupportNotCompiledIn`], there is no "not compiled in" counterpart for this
172    /// variant — `octave-ffi` is an unconditional dependency of this crate (a pure subprocess
173    /// manager, never linking against Octave itself), so `kind=octfunc` is always available to
174    /// parse and construct; only an actually-missing `octave-cli` binary on `PATH` at runtime
175    /// surfaces here, as [`octave_ffi::OctaveError::NotFound`].
176    Octave(octave_ffi::OctaveError),
177    /// A [`block_graph::BlockKind::OctBlock`]'s own `path=` directory is missing one of the
178    /// `.m` files its declared contract requires (see that variant's own doc comment for the
179    /// full file-per-function table) — checked once, up front at construction, the same
180    /// "checked once, up front" discipline [`Self::CScriptRequiresCloneForAdaptiveStep`]
181    /// already uses, and deliberately *before* ever spawning `octave-cli` for this block, since
182    /// the filesystem already has the answer without needing a round trip through Octave's own
183    /// "undefined function" error.
184    OctBlockMissingRequiredFile {
185        block_name: String,
186        expected_path: std::path::PathBuf,
187    },
188    /// A netlist declares a [`block_graph::BlockKind::OctBlock`] block with `ts=variable`
189    /// (`block_graph::SampleTimeSpec::Variable`), but `<function>_next_sample_hit.m` doesn't
190    /// exist in its own `path=` directory — the `OctBlock` counterpart to
191    /// [`Self::CScriptRequiresNextSampleHitForVariableSampleTime`]/
192    /// [`Self::PyBlockRequiresNextSampleHitForVariableSampleTime`].
193    OctBlockRequiresNextSampleHitForVariableSampleTime {
194        block_name: String,
195    },
196    /// A netlist declares a [`block_graph::BlockKind::OctBlock`] block, but the run was
197    /// requested with [`TimeStep::Adaptive`], which clones the whole `block_states` vector
198    /// before every trial step and simply discards a rejected trial's clone (see
199    /// [`Self::CScriptRequiresCloneForAdaptiveStep`]'s own doc comment). That protocol depends
200    /// on a block's own state living entirely inside the cloned Rust value -- true for
201    /// `CScript`/`PyBlock` (an owned, independently-cloned native/Python state), but **not**
202    /// true for `OctBlock`: its own opaque per-instance state lives inside the one shared
203    /// `octave-cli` session itself (see [`block_graph::BlockState::OctBlock`]'s own doc
204    /// comment), which is never cloned, so a rejected trial's own state-mutating calls
205    /// (`output`/`output_xc`/`update`) would silently persist in the real Octave-side state
206    /// with no way to roll them back. Unlike `CScriptRequiresCloneForAdaptiveStep` (opt-in,
207    /// satisfiable by exporting `cscript_clone`), this restriction is unconditional -- there is
208    /// no `.m`-file convention that could make Octave's own shared global-struct state
209    /// trial-cloneable. Use a fixed `TimeStep::Fixed` for any netlist using `kind=octblock`.
210    OctBlockDoesNotSupportAdaptiveStep {
211        block_name: String,
212    },
213    /// [`TimeStep::Adaptive`] took more than [`ADAPTIVE_STEP_HARD_CAP`] accepted steps without
214    /// reaching `t_final` — a hard safety ceiling, not a normal error a well-behaved run should
215    /// ever hit. Exists because the adaptive loop accumulates one row per accepted step into an
216    /// in-memory trace with no other bound, and a genuinely stalled step controller (e.g. a
217    /// near-zero-`dt` loop that never makes real forward progress — the exact class of bug
218    /// `next_pwm_edge_dt`'s own `THETA_EPS` guards against, see its doc comment) would otherwise
219    /// grow that trace without limit until the process — and, on the real run that first hit
220    /// this, the whole machine — ran out of memory. `steps_taken` is how many were accepted
221    /// before the cap tripped; `t_reached`/`t_final` show how far the run actually got.
222    AdaptiveStepStalled {
223        steps_taken: usize,
224        t_reached: f64,
225        t_final: f64,
226    },
227    /// A [`block_graph::GateBinding`] names a block that exists but isn't a `domain=voltage`
228    /// [`block_graph::BlockKind::Sig2Phys`] — the enforced physical/signal-domain boundary:
229    /// an ideal switch's gate is itself a voltage, so any signal driving it must first pass through
230    /// the same `domain=voltage` `Sig2Phys` converter a `V`-source's own magnitude uses, never a
231    /// raw `Pid`/`Vco`/`Hysteresis`/etc. block directly, and never a `domain=current` `Sig2Phys`
232    /// either. `gate` is the ideal switch this binding belongs to; `block` and `found_kind` name
233    /// the offending target and (for a human-readable message) what it actually is.
234    GateTargetNotSig2Voltage {
235        gate: String,
236        block: String,
237        found_kind: &'static str,
238    },
239    /// An independent `V`/`I` source's own literal value in the netlist is a bare symbol that
240    /// names a declared block, but that block isn't a [`block_graph::BlockKind::Sig2Phys`] of
241    /// the matching domain (`V` needs `domain=voltage`, `I` needs `domain=current`) — the
242    /// enforced Signal-to-PS boundary for driving a source's own magnitude from the block graph.
243    SourceNotSig2PhysicalConverter {
244        source: String,
245        block: String,
246        expected_kind: &'static str,
247        found_kind: &'static str,
248    },
249    /// A [`block_graph::BlockKind::Sig2Phys`] converter's own name is also used as an ordinary
250    /// circuit node on an element line — i.e. the converter was *wired into* the physical
251    /// network instead of being *referenced by name* from the one place that can consume it.
252    ///
253    /// A `kind=sig2phys` block has no terminals and stamps nothing into the MNA system; it is
254    /// purely a named Signal-to-PS value another statement substitutes. So a net that happens to
255    /// share its name is just an ordinary, otherwise-undriven node: its KCL row is solved
256    /// consistently at `0` (a resistor to ground is a perfectly non-singular
257    /// `G·v = 0`) and the run silently reports `V(<name>) = 0` next to the block's own,
258    /// correct, non-zero output column. That silent wrong answer is exactly what this variant
259    /// exists to turn into a build-time error, before any step is solved.
260    ///
261    /// The two legitimate ways to consume a `Sig2Phys` are both by name, never by wire:
262    /// an independent `V`/`I` source's own value field (`V1 a 0 VDRV`, see
263    /// [`DaeError::SourceNotSig2PhysicalConverter`]) and an ideal switch's `gate=`/`ctrl=` field
264    /// (see [`DaeError::GateTargetNotSig2Voltage`]).
265    ///
266    /// `block` is the converter as declared, `element` the first element line that wires it, and
267    /// `node` that element's node token as written. Node names are matched case-insensitively,
268    /// matching how the netlist grammar itself treats them (`A` and `a` are one node).
269    Sig2PhysUsedAsCircuitNode {
270        block: String,
271        element: String,
272        node: String,
273    },
274    /// Two blocks in the same slice resolve to the same name — either two
275    /// [`block_graph::BlockInstance`]s declared with the same `.name`, or one block's own
276    /// extra `output_names` entry (a [`block_graph::BlockKind::CScript`]/`CoordinateTransform`/
277    /// `Pmsm`/`Pwm`/`PhaseShiftPwm`'s secondary output alias) colliding with another block's
278    /// name. Without this check, `block_index_by_name`'s `BTreeMap::insert` would silently let
279    /// the later one win, so a `Signal::Block(name)` reference would silently resolve to the
280    /// wrong block instead of failing loudly.
281    DuplicateBlockName(String),
282    /// A [`block_graph::BlockKind`] that requires a `SignalValue::Scalar` input (or a specific
283    /// operand shape, e.g. `Sum`/`Product`'s "all-scalar or all-vector, never mixed" rule, or a
284    /// matrix `Gain`'s own required vector length) received a `SignalValue::Vector` it can't
285    /// accept — the default, fail-closed rule for any block kind without an elementwise/
286    /// broadcast rule of its own. See `book/dev-guide/src/vector-signals.md` for exactly which
287    /// block kinds accept a `Vector` and under what rule.
288    VectorSignalNotSupported {
289        block: String,
290    },
291    /// Two (or more) `SignalValue::Vector`s feeding the same block disagree in length (e.g.
292    /// `Sum`'s own inputs, `MathFn2`'s two operands), or a `Vector`'s own length doesn't match
293    /// a fixed arity the block itself declares (a matrix `Gain`'s own column count, a
294    /// `StateSpace`'s own declared input count).
295    VectorSignalSizeMismatch {
296        block: String,
297        expected: usize,
298        got: usize,
299    },
300}
301
302/// Solves the DC operating point of a netlist containing linear devices plus any number of
303/// `D` (diode) elements, whose piecewise-linear parameters are supplied in `diodes` (keyed by
304/// element name) rather than parsed from the netlist — SPICE's `.model` syntax has no notion
305/// of this crate's breakdown/leakage/forward segments.
306pub fn solve_dc(
307    source: &str,
308    dialect: Dialect,
309    diodes: &BTreeMap<String, IdealDiode>,
310) -> Result<OperatingPoint, DaeError> {
311    let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
312    let system = MnaBuilder::new(dialect)
313        .build_statements(&statements)
314        .map_err(DaeError::Build)?;
315    fold_and_solve(
316        &system,
317        &statements,
318        diodes,
319        &Scheme::Dc,
320        0.0,
321        &BTreeMap::new(),
322        &BTreeMap::new(),
323    )
324}
325
326/// Which implicit integration formula a given step of [`simulate_transient`] uses. Both
327/// reduce a descriptor DAE `A x + K dx/dt = B u` to the same linear-solve shape [`solve_dc`]
328/// already uses (an effective matrix/RHS folded into the diode LCP unchanged) — see
329/// `docs/architecture.md` and each variant's own derivation below.
330enum Scheme<'a> {
331    /// `A x = B u` directly (no time derivative at all) — an ordinary DC operating point.
332    Dc,
333    /// `dx/dt ~= (x_{n+1} - x_n) / dt`, giving `(A + K/dt) x_{n+1} = B u_{n+1} + (K/dt) x_n`.
334    /// First-order accurate, but tolerant of an inconsistent `x_prev` (doesn't need `x_prev`
335    /// to already satisfy the circuit's algebraic constraints exactly) — this is what makes
336    /// it the right choice for the very first transient step, and immediately after a
337    /// LCP-resolved mode change (see `Trapezoidal`'s doc comment for why trapezoidal is *not*
338    /// safe in either of those cases).
339    BackwardEuler { x_prev: &'a [f64], dt: f64 },
340    /// Second-order accurate. Derived by summing the DAE at both `t_n` and `t_{n+1}` and using
341    /// the trapezoidal relation `x'_n + x'_{n+1} = (2/dt)(x_{n+1} - x_n)` to eliminate the
342    /// derivatives entirely:
343    ///
344    /// ```text
345    /// (A/2)(x_n + x_{n+1}) + (K/dt)(x_{n+1} - x_n) = (B/2)(u_n + u_{n+1})
346    /// => (A/2 + K/dt) x_{n+1} = (B/2)(u_n + u_{n+1}) + (K/dt - A/2) x_n
347    /// ```
348    ///
349    /// Crucially, `B u` includes each diode's *nonlinear* current, not just the netlist's own
350    /// (constant, in this crate's scope) sources — true trapezoidal accuracy requires
351    /// averaging that too, not just the linear part. Since the new step's diode current
352    /// contributes `(B/2) * raw_Ioff_{n+1}` rather than the full `B * raw_Ioff_{n+1}`, the
353    /// LCP fold's per-diode coupling coefficients are scaled by `0.5` for this scheme (see
354    /// `fold_and_solve`'s `coupling_scale`) — while the *previous* step's already-known
355    /// current contributes its own `(B/2) * raw_Ioff_n` term directly to the effective RHS,
356    /// via `prev_diode_raw_ioff`.
357    ///
358    /// This derivation assumes `x_n` already satisfies the circuit's algebraic constraints
359    /// exactly (so that summing the DAE at `t_n` contributes nothing extra beyond
360    /// `B u_n - A x_n = 0`) — true right after a [`Scheme::BackwardEuler`] or [`Scheme::Dc`]
361    /// step, not true in general starting from an arbitrary `x_initial`. This is the DAE
362    /// analog of "trapezoidal needs consistent initial conditions," and is why
363    /// [`simulate_transient`] always starts with backward Euler and falls back to it whenever
364    /// a diode's resolved segment changes between consecutive steps.
365    ///
366    /// That "constant, in this crate's scope" assumption about the netlist's own linear
367    /// sources held until [`TransientFunction`](general_mna::TransientFunction) support was
368    /// added: for a genuinely time-varying `V`/`I` source, `u_n != u_{n+1}` for that source's
369    /// own column too, not just for diode currents — `fold_and_solve` evaluates `numeric0.u`
370    /// (i.e. `B u_{n+1}`) a second time at `t_n = t_{n+1} - dt` and averages the two, exactly
371    /// mirroring the diode-current averaging already described above, rather than silently
372    /// reusing the same "constant source" shortcut for a source that no longer is one.
373    Trapezoidal {
374        x_prev: &'a [f64],
375        dt: f64,
376        prev_diode_raw_ioff: &'a BTreeMap<String, f64>,
377    },
378}
379
380/// Runs a transient simulation of a netlist containing linear devices (including storage —
381/// `C`, `L`) plus any number of `D` diodes, from `t = 0` to `t_final`, starting from
382/// `x_initial` (all zero if `None` — the usual "circuit at rest, then a step/DC source turns
383/// on at `t = 0`" case used by this crate's own tests). `step` picks fixed or adaptive timing
384/// — see [`TimeStep`]/[`AdaptiveConfig`]; `TimeStep::Fixed(dt)` reproduces exactly the fixed-`dt`
385/// behavior this function had before `TimeStep` existed.
386///
387/// Uses [`Scheme::Trapezoidal`] (second-order accurate, matching Xyce/SPICE's own default) for
388/// most steps, but falls back to [`Scheme::BackwardEuler`] for the very first step (an
389/// arbitrary `x_initial` is not guaranteed to satisfy the circuit's algebraic constraints —
390/// trapezoidal needs that) and for any step where a diode's resolved segment (breakdown /
391/// leakage / forward) differs from the *previous* step's — the architecture's own sanctioned
392/// policy for staying robust across an LCP-resolved mode change (see `docs/architecture.md`).
393/// This is a lagging, not predictive, policy: it reacts to the mode change already observed in
394/// the previous step's result, rather than trying to foresee this step's mode before solving
395/// it — simpler, and sufficient for the well-behaved circuits this crate targets so far.
396///
397/// No ideal switch/PWM support yet in the transient loop — see this crate's journal for why.
398/// The `x` a transient run starts from, in `system.unknowns` order.
399///
400/// An explicit `x_initial` from the caller always wins — it is the more specific instruction,
401/// and several of this crate's own tests hand-build one. Failing that, the netlist's own `ic=`
402/// values are honored via [`general_mna::MnaSystem::initial_state`], which *assigns* the
403/// declared states — an `ic`-bearing inductor's own branch current, an `ic`-bearing capacitor's
404/// node-voltage difference — and leaves every other unknown at rest, without touching the
405/// circuit's equations. Failing *that* — the overwhelmingly common case of a netlist with no
406/// `ic=` anywhere — the circuit starts from rest, exactly as before.
407///
408/// A seeded vector is therefore **not** a consistent operating point: the other node voltages
409/// and every source's branch current start at zero even where the circuit's algebraic
410/// constraints say otherwise. That is fine here, and worth saying out loud rather than leaving
411/// for the next reader to rediscover: [`simulate_transient`] already takes its first step with
412/// backward Euler precisely because an arbitrary `x_initial` need not satisfy those constraints,
413/// and that first step is what re-imposes them. The one thing an inconsistent seed must not do
414/// is pass silently, and it does not — `initial_state` reports an assignment that contradicts an
415/// equation nothing is left free to satisfy, as [`DaeError::InitialCondition`].
416///
417/// `values` is built at `t = 0` with every diode at its own off-segment reference slope and zero
418/// Norton current, matching how the first real step's `base_values` is built in `solve_step`, so
419/// that the consistency check `initial_state` runs sees the same circuit the first step will.
420pub(crate) fn resolve_initial_state(
421    system: &MnaSystem,
422    diodes: &BTreeMap<String, IdealDiode>,
423    x_initial: Option<&[f64]>,
424) -> Result<Vec<f64>, DaeError> {
425    if let Some(x) = x_initial {
426        return Ok(x.to_vec());
427    }
428    let mut values = BTreeMap::new();
429    for (name, diode) in diodes {
430        values.insert(format!("{name}_G"), diode.g_off);
431        values.insert(format!("{name}_Ioff"), 0.0);
432    }
433    for (name, transient_fn) in &system.transient_sources {
434        values.insert(name.clone(), transient_fn.value_at(0.0));
435    }
436    match system
437        .initial_state(&values, general_mna::DEFAULT_INITIAL_STATE_TOLERANCE)
438        .map_err(DaeError::InitialCondition)?
439    {
440        Some(x) => Ok(x),
441        None => Ok(vec![0.0; system.order()]),
442    }
443}
444
445pub fn simulate_transient(
446    source: &str,
447    dialect: Dialect,
448    diodes: &BTreeMap<String, IdealDiode>,
449    x_initial: Option<&[f64]>,
450    t_final: f64,
451    step: TimeStep,
452) -> Result<Vec<(f64, OperatingPoint)>, DaeError> {
453    let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
454    let system = MnaBuilder::new(dialect)
455        .build_statements(&statements)
456        .map_err(DaeError::Build)?;
457
458    let mut x_prev = resolve_initial_state(&system, diodes, x_initial)?;
459    let mut x_prev_prev: Option<Vec<f64>> = None;
460    let mut prev_diode_raw_ioff: BTreeMap<String, f64> = BTreeMap::new();
461    let mut prev_segments: Option<Vec<Segment>> = None;
462    let mut ringing_cooldown: u32 = 0;
463
464    let mut trace = Vec::new();
465    let mut t = 0.0;
466
467    match step {
468        TimeStep::Fixed(dt) => {
469            let steps = (t_final / dt).round() as usize;
470            trace.reserve(steps);
471            for step_index in 0..steps {
472                t += dt;
473                let forced = step_index == 0 || ringing_cooldown > 0;
474                let (point, used_backward_euler) = step_with_fallback(
475                    &system,
476                    &statements,
477                    diodes,
478                    x_prev_prev.as_deref(),
479                    &x_prev,
480                    dt,
481                    &prev_diode_raw_ioff,
482                    &prev_segments,
483                    forced,
484                    t,
485                    &BTreeMap::new(),
486                    &BTreeMap::new(),
487                )?;
488                if used_backward_euler && !forced {
489                    ringing_cooldown = RINGING_COOLDOWN_STEPS;
490                } else if ringing_cooldown > 0 {
491                    ringing_cooldown = ringing_cooldown.saturating_sub(1);
492                }
493
494                prev_segments = Some(classify_segments(&point));
495                prev_diode_raw_ioff = point
496                    .diode_names
497                    .iter()
498                    .cloned()
499                    .zip(point.diode_raw_ioff.iter().copied())
500                    .collect();
501                x_prev_prev = Some(std::mem::replace(&mut x_prev, point.x.clone()));
502                trace.push((t, point));
503            }
504        }
505        TimeStep::Adaptive(config) => {
506            let mut dt_next = config.dt_init;
507            let mut step_index = 0usize;
508            while t < t_final {
509                let dt_trial = dt_next.min(t_final - t);
510                let forced = step_index == 0 || ringing_cooldown > 0;
511                let (point, used_backward_euler, dt_used, next_dt) = step_control::adaptive_step(
512                    &system,
513                    &statements,
514                    diodes,
515                    x_prev_prev.as_deref(),
516                    &x_prev,
517                    dt_trial,
518                    &prev_diode_raw_ioff,
519                    &prev_segments,
520                    forced,
521                    &config,
522                    t,
523                )?;
524                if used_backward_euler && !forced {
525                    ringing_cooldown = RINGING_COOLDOWN_STEPS;
526                } else if ringing_cooldown > 0 {
527                    ringing_cooldown = ringing_cooldown.saturating_sub(1);
528                }
529
530                t += dt_used;
531                dt_next = next_dt;
532                prev_segments = Some(classify_segments(&point));
533                prev_diode_raw_ioff = point
534                    .diode_names
535                    .iter()
536                    .cloned()
537                    .zip(point.diode_raw_ioff.iter().copied())
538                    .collect();
539                x_prev_prev = Some(std::mem::replace(&mut x_prev, point.x.clone()));
540                trace.push((t, point));
541                step_index += 1;
542            }
543        }
544    }
545    Ok(trace)
546}
547
548#[derive(Debug, Clone, PartialEq, Eq)]
549enum Segment {
550    Breakdown,
551    Leakage,
552    Forward,
553}
554
555fn classify_segments(point: &OperatingPoint) -> Vec<Segment> {
556    point
557        .diode_z
558        .iter()
559        .map(|&(z1, z2)| {
560            if z1 > 1e-9 {
561                Segment::Breakdown
562            } else if z2 > 1e-9 {
563                Segment::Forward
564            } else {
565                Segment::Leakage
566            }
567        })
568        .collect()
569}
570
571/// Detects trapezoidal "ringing": trapezoidal integration is A-stable (bounded) but not
572/// L-stable, so a very lightly damped mode (e.g. a switch node left nearly floating during
573/// ideal switch dead time, with only tiny leakage conductance) doesn't decay under it — it
574/// oscillates at the Nyquist frequency (sign-flipping every single step) with roughly
575/// constant amplitude instead. Detected as three consecutive values of the same unknown
576/// alternating in sign (`x_prev_prev`, `x_prev`, `trial` share the outer two signs, opposite
577/// the middle one) with the magnitude not shrinking step to step — the direct signature of a
578/// sustained oscillation, as opposed to a legitimate sign change while settling (which
579/// shrinks, not sustains, in magnitude) or ordinary numerical noise near zero (excluded by
580/// the noise floor). Found and root-caused via `general-simulator`'s LLC validation
581/// (`crates/dae-runtime/examples/llc_validation.rs`): the switching node's voltage oscillated
582/// between roughly +/-3000V for the entire ~200ns ideal switch dead-time window every period, while
583/// every other tracked quantity (notably the actual circuit output) stayed smooth and
584/// physically reasonable throughout — falling back to backward Euler (which has no such
585/// weakness) the instant this is detected fixes it, consistent with backward Euler already
586/// being this crate's answer to every other kind of transient stiffness.
587fn is_ringing(x_prev_prev: &[f64], x_prev: &[f64], trial: &[f64]) -> bool {
588    const NOISE_FLOOR: f64 = 1e-9;
589    x_prev_prev
590        .iter()
591        .zip(x_prev)
592        .zip(trial)
593        .any(|((&a, &b), &c)| {
594            if a.abs() < NOISE_FLOOR || b.abs() < NOISE_FLOOR || c.abs() < NOISE_FLOOR {
595                return false;
596            }
597            let alternating = (a > 0.0) == (c > 0.0) && (a > 0.0) != (b > 0.0);
598            alternating && c.abs() >= b.abs() * 0.9
599        })
600}
601
602/// How many additional steps to keep using backward Euler after a ringing catch, before
603/// trusting trapezoidal again. A single corrective backward-Euler step pulls the ringing
604/// mode's *value* back to something reasonable, but doesn't fully re-establish it as "settled"
605/// in the sense trapezoidal's own derivation needs (see [`Scheme::Trapezoidal`]'s doc comment
606/// on consistent initial conditions) — resuming trapezoidal immediately was observed to let a
607/// smaller residual oscillation resume and drift to a stale-but-stable wrong plateau, rather
608/// than fully recovering. A short cooldown of plain, unconditionally-stable backward-Euler
609/// steps lets the correction actually settle first.
610const RINGING_COOLDOWN_STEPS: u32 = 3;
611
612/// Solves one timestep, choosing between [`Scheme::Trapezoidal`] and [`Scheme::BackwardEuler`]
613/// the same lagging way [`simulate_transient`] and [`simulate_transient_with_ideal_switches`] both
614/// need: `force_backward_euler` covers reasons known *before* solving (the very first step, a
615/// gate state that just changed, or an active [`RINGING_COOLDOWN_STEPS`] cooldown); a diode
616/// segment change and trapezoidal ringing (see [`is_ringing`]) are only detectable *after*
617/// trying trapezoidal, so either one redoes the step with backward Euler. `x_prev_prev` (the
618/// state two steps back) is `None` for the first two steps of a run, when ringing can't yet be
619/// detected — the existing `force_backward_euler` on the very first step, plus ringing needing
620/// at least one full oscillation to show its signature, means this is never a gap in practice.
621///
622/// Returns `(point, used_backward_euler)` — callers use the flag to drive a
623/// [`RINGING_COOLDOWN_STEPS`]-step cooldown after any backward-Euler fallback (not just a
624/// ringing-triggered one — a segment or gate change deserves the same settling courtesy).
625#[allow(clippy::too_many_arguments)]
626fn step_with_fallback(
627    system: &MnaSystem,
628    statements: &[Statement],
629    diodes: &BTreeMap<String, IdealDiode>,
630    x_prev_prev: Option<&[f64]>,
631    x_prev: &[f64],
632    dt: f64,
633    prev_diode_raw_ioff: &BTreeMap<String, f64>,
634    prev_segments: &Option<Vec<Segment>>,
635    force_backward_euler: bool,
636    t: f64,
637    extra_values: &BTreeMap<String, f64>,
638    extra_values_prev: &BTreeMap<String, f64>,
639) -> Result<(OperatingPoint, bool), DaeError> {
640    if force_backward_euler {
641        return fold_and_solve(
642            system,
643            statements,
644            diodes,
645            &Scheme::BackwardEuler { x_prev, dt },
646            t,
647            extra_values,
648            extra_values_prev,
649        )
650        .map(|point| (point, true));
651    }
652    let trial = fold_and_solve(
653        system,
654        statements,
655        diodes,
656        &Scheme::Trapezoidal {
657            x_prev,
658            dt,
659            prev_diode_raw_ioff,
660        },
661        t,
662        extra_values,
663        extra_values_prev,
664    )?;
665    let trial_segments = classify_segments(&trial);
666    let segments_changed = Some(&trial_segments) != prev_segments.as_ref();
667    let ringing = x_prev_prev.is_some_and(|xpp| is_ringing(xpp, x_prev, &trial.x));
668    if segments_changed || ringing {
669        fold_and_solve(
670            system,
671            statements,
672            diodes,
673            &Scheme::BackwardEuler { x_prev, dt },
674            t,
675            extra_values,
676            extra_values_prev,
677        )
678        .map(|point| (point, true))
679    } else {
680        Ok((trial, false))
681    }
682}
683
684/// Solves the DC operating point of a netlist containing linear devices, ordinary `D` diodes
685/// (`diodes`), and any number of `IdealSwitch` instances (`ideal_switches`), each with its own known gate
686/// state (see [`GateState`], a re-export of `general_mna::SwitchState` — the same concept: an
687/// exogenous, externally-decided mode, not something the LCP resolves).
688///
689/// A gated-on ideal switch is stamped as a plain `r_on` switch (reusing `general-mna`'s existing
690/// switch mechanism — every gated-on ideal switch in one call shares `shared_r_on`, matching that
691/// mechanism's own single-shared-resistance design; per-instance `Ron` is a possible future
692/// extension, not needed yet). A gated-off ideal switch is folded into the LCP exactly like an
693/// ordinary diode, using [`IdealSwitch::body_diode_for_drain_source_stamping`] (not `body_diode`
694/// directly) — see that method's own doc comment for why: the netlist declares an ideal switch's two
695/// terminals in plain SPICE-conventional `(drain, source)` order, and the mirrored curve is
696/// what makes evaluating it against those nodes as-declared give the physically correct
697/// result. Each ideal switch element must still use device letter `'D'` in the netlist text (not
698/// `'M'`) — see this crate's `docs`/journal for why.
699pub fn solve_dc_with_ideal_switches(
700    source: &str,
701    dialect: Dialect,
702    diodes: &BTreeMap<String, IdealDiode>,
703    ideal_switches: &BTreeMap<String, (IdealSwitch, GateState)>,
704    shared_r_on: f64,
705) -> Result<OperatingPoint, DaeError> {
706    let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
707    let (system, all_diodes) =
708        build_with_ideal_switches(&statements, dialect, diodes, ideal_switches, shared_r_on)?;
709    fold_and_solve(
710        &system,
711        &statements,
712        &all_diodes,
713        &Scheme::Dc,
714        0.0,
715        &BTreeMap::new(),
716        &BTreeMap::new(),
717    )
718}
719
720/// Runs a transient simulation of a netlist containing linear devices, ordinary `D` diodes,
721/// and any number of `IdealSwitch` instances whose gate state can vary over time — a PWM driver,
722/// unlike [`solve_dc_with_ideal_switches`]'s fixed per-call state. `gate_signal(name, t)` is called
723/// once per ideal switch per timestep to get that instance's [`GateState`] at time `t`; the caller
724/// owns the PWM logic entirely (duty cycle, frequency, phase — this crate has no opinion).
725///
726/// Because a gate state change means the *symbolic* `general-mna` system itself must be
727/// rebuilt (a switch and a `'D'`-stamped diode are structurally different stamps, not just
728/// different numeric values — see `docs/architecture.md`), this rebuilds the system every
729/// timestep, unlike [`simulate_transient`]'s single build reused throughout. A documented
730/// scope choice, not an oversight: fine for the small circuits this crate targets so far: see
731/// this crate's journal for the reasoning and what a future optimization would look like.
732///
733/// Uses the same trapezoidal-with-backward-Euler-fallback policy as [`simulate_transient`],
734/// extended to also force backward Euler on any step where *any* ideal switch's gate state just
735/// changed from the previous step — a gate transition is exactly the kind of topology change
736/// the architecture's "backward Euler after a mode change" policy exists for, arguably more so
737/// than a diode's segment change, since it's a real switching event a PWM converter circuit
738/// will trigger constantly.
739#[allow(clippy::too_many_arguments)]
740pub fn simulate_transient_with_ideal_switches(
741    source: &str,
742    dialect: Dialect,
743    diodes: &BTreeMap<String, IdealDiode>,
744    ideal_switches: &BTreeMap<String, IdealSwitch>,
745    gate_signal: impl Fn(&str, f64) -> GateState,
746    shared_r_on: f64,
747    x_initial: Option<&[f64]>,
748    t_final: f64,
749    dt: f64,
750) -> Result<Vec<(f64, OperatingPoint)>, DaeError> {
751    let states_at = |t: f64| -> BTreeMap<String, (IdealSwitch, GateState)> {
752        ideal_switches
753            .iter()
754            .map(|(name, m)| (name.clone(), (*m, gate_signal(name, t))))
755            .collect()
756    };
757
758    let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
759    let (system0, _) =
760        build_with_ideal_switches(&statements, dialect, diodes, &states_at(0.0), shared_r_on)?;
761    let mut x_prev = resolve_initial_state(&system0, diodes, x_initial)?;
762    let mut x_prev_prev: Option<Vec<f64>> = None;
763    let mut prev_diode_raw_ioff: BTreeMap<String, f64> = BTreeMap::new();
764    let mut prev_segments: Option<Vec<Segment>> = None;
765    let mut prev_gate_states: Option<BTreeMap<String, GateState>> = None;
766    let mut ringing_cooldown: u32 = 0;
767
768    let steps = (t_final / dt).round() as usize;
769    let mut trace = Vec::with_capacity(steps);
770    let mut t = 0.0;
771    for step_index in 0..steps {
772        t += dt;
773        let states = states_at(t);
774        let gate_states: BTreeMap<String, GateState> = states
775            .iter()
776            .map(|(name, (_, state))| (name.clone(), *state))
777            .collect();
778        let gate_changed = prev_gate_states.as_ref() != Some(&gate_states);
779        let forced = step_index == 0 || gate_changed || ringing_cooldown > 0;
780
781        let (system, all_diodes) =
782            build_with_ideal_switches(&statements, dialect, diodes, &states, shared_r_on)?;
783        let (point, used_backward_euler) = step_with_fallback(
784            &system,
785            &statements,
786            &all_diodes,
787            x_prev_prev.as_deref(),
788            &x_prev,
789            dt,
790            &prev_diode_raw_ioff,
791            &prev_segments,
792            forced,
793            t,
794            &BTreeMap::new(),
795            &BTreeMap::new(),
796        )?;
797        if used_backward_euler && !forced {
798            ringing_cooldown = RINGING_COOLDOWN_STEPS;
799        } else if ringing_cooldown > 0 {
800            ringing_cooldown = ringing_cooldown.saturating_sub(1);
801        }
802
803        prev_segments = Some(classify_segments(&point));
804        prev_gate_states = Some(gate_states);
805        prev_diode_raw_ioff = point
806            .diode_names
807            .iter()
808            .cloned()
809            .zip(point.diode_raw_ioff.iter().copied())
810            .collect();
811        x_prev_prev = Some(std::mem::replace(&mut x_prev, point.x.clone()));
812        trace.push((t, point));
813    }
814    Ok(trace)
815}
816
817fn build_with_ideal_switches(
818    statements: &[Statement],
819    dialect: Dialect,
820    diodes: &BTreeMap<String, IdealDiode>,
821    ideal_switches: &BTreeMap<String, (IdealSwitch, GateState)>,
822    shared_r_on: f64,
823) -> Result<(MnaSystem, BTreeMap<String, IdealDiode>), DaeError> {
824    let mut options = BuildOptions {
825        on_resistance: Expression::Constant(shared_r_on),
826        ..BuildOptions::default()
827    };
828
829    let mut all_diodes = diodes.clone();
830    for (name, (switch, state)) in ideal_switches {
831        match state {
832            GateState::On => options.set_switch(name, GateState::On),
833            GateState::Off => {
834                all_diodes.insert(name.clone(), switch.body_diode_for_drain_source_stamping());
835            }
836        }
837    }
838
839    let system = MnaBuilder::with_options(dialect, options)
840        .build_statements(statements)
841        .map_err(DaeError::Build)?;
842    Ok((system, all_diodes))
843}
844
845#[allow(clippy::too_many_arguments)]
846fn fold_and_solve(
847    system: &MnaSystem,
848    statements: &[Statement],
849    diodes: &BTreeMap<String, IdealDiode>,
850    scheme: &Scheme,
851    t: f64,
852    extra_values: &BTreeMap<String, f64>,
853    extra_values_prev: &BTreeMap<String, f64>,
854) -> Result<OperatingPoint, DaeError> {
855    let nodes = topology::diode_nodes(statements);
856    let order = system.order();
857
858    // Fix every diode's conductance at its canonical reference slope and its Norton current at
859    // zero: this is the "A0"/"u0" the whole LCP fold above is built on. Also supply every
860    // time-varying V/I source's own current value at `t` -- `system.transient_sources` is
861    // empty for a netlist with no `SIN`/`PULSE`/`EXP`/`PWL`/`SFFM` source, so this is a no-op
862    // for every existing (plain, static-source) netlist. `t=0.0` for `Scheme::Dc` matches
863    // standard SPICE convention (a DC operating point uses a transient source's own value at
864    // time zero, not its DC-only fallback, when no separate `DC` value was given). `extra_values`
865    // is this step's full block-graph output map (empty for every caller with no block graph at
866    // all) -- `system.evaluate` only ever substitutes a symbol actually present in an
867    // expression tree, so passing every block's output here unconditionally is harmless; the
868    // *only* symbols that can legitimately appear this way are a `BlockKind::Sig2Phys`
869    // converter's own name, since `simulate_transient_with_blocks` already
870    // rejects any other block name appearing as a bare V/I source literal before any step runs
871    // (see `DaeError::SourceNotSig2PhysicalConverter`).
872    let mut base_values = BTreeMap::new();
873    for (name, diode) in diodes {
874        base_values.insert(format!("{name}_G"), diode.g_off);
875        base_values.insert(format!("{name}_Ioff"), 0.0);
876    }
877    for (name, transient_fn) in &system.transient_sources {
878        base_values.insert(name.clone(), transient_fn.value_at(t));
879    }
880    for (name, value) in extra_values {
881        base_values.insert(name.clone(), *value);
882    }
883    let numeric0 = system.evaluate(&base_values).map_err(DaeError::Evaluate)?;
884
885    // a_eff/u_eff_base: the effective matrix and the part of the effective RHS that doesn't
886    // depend on this step's own diode currents (those are added per-diode below, since
887    // Trapezoidal's history term needs each diode's own B column). coupling_scale multiplies
888    // how much *this* step's resolved diode current contributes to x/V — see Scheme::Trapezoidal.
889    let (a_eff, u_eff_base, coupling_scale): (general_mna::Matrix<f64>, Vec<f64>, f64) =
890        match scheme {
891            Scheme::Dc => (numeric0.a.clone(), numeric0.u.clone(), 1.0),
892            Scheme::BackwardEuler { x_prev, dt } => {
893                let mut a_eff = numeric0.a.clone();
894                for row in 0..order {
895                    for col in 0..order {
896                        a_eff[(row, col)] += numeric0.k[(row, col)] / dt;
897                    }
898                }
899                let u_eff: Vec<f64> = (0..order)
900                    .map(|row| {
901                        let k_x: f64 = (0..order)
902                            .map(|col| numeric0.k[(row, col)] * x_prev[col])
903                            .sum();
904                        numeric0.u[row] + k_x / dt
905                    })
906                    .collect();
907                (a_eff, u_eff, 1.0)
908            }
909            Scheme::Trapezoidal { x_prev, dt, .. } => {
910                let mut a_eff = numeric0.a.clone();
911                for row in 0..order {
912                    for col in 0..order {
913                        a_eff[(row, col)] = a_eff[(row, col)] / 2.0 + numeric0.k[(row, col)] / dt;
914                    }
915                }
916                // True trapezoidal RHS uses (B/2)*(u_n + u_{n+1}), not B*u_{n+1} alone (see
917                // Scheme::Trapezoidal's own doc comment) -- correct as-is only because every
918                // netlist source was constant (u_n == u_{n+1}) until time-varying sources
919                // existed. `u_prev` re-evaluates the netlist's own linear sources at `t - dt`
920                // for a `TransientFunction` source (an analytic, re-evaluatable function of
921                // time), and substitutes `extra_values_prev` (the *previous* step's already-
922                // computed block outputs -- a block-driven source has no analytic form to
923                // re-evaluate, only the discrete sample already used last step, zero-order-held
924                // for that step, exactly the sampled-data convention this whole block graph
925                // uses) for a `Sig2Phys`-driven one. Skipped (and `numeric0.u`
926                // cloned directly, exactly the previous behavior) only when there are neither,
927                // since u_n == u_{n+1} trivially and a second `evaluate` call would be pure
928                // overhead.
929                let u_prev: Vec<f64> =
930                    if system.transient_sources.is_empty() && extra_values_prev.is_empty() {
931                        numeric0.u.clone()
932                    } else {
933                        let mut base_values_prev = base_values.clone();
934                        for (name, transient_fn) in &system.transient_sources {
935                            base_values_prev.insert(name.clone(), transient_fn.value_at(t - dt));
936                        }
937                        for (name, value) in extra_values_prev {
938                            base_values_prev.insert(name.clone(), *value);
939                        }
940                        system
941                            .evaluate(&base_values_prev)
942                            .map_err(DaeError::Evaluate)?
943                            .u
944                    };
945                let u_eff: Vec<f64> = (0..order)
946                    .map(|row| {
947                        let k_x: f64 = (0..order)
948                            .map(|col| numeric0.k[(row, col)] * x_prev[col])
949                            .sum();
950                        let a_x: f64 = (0..order)
951                            .map(|col| numeric0.a[(row, col)] * x_prev[col])
952                            .sum();
953                        (numeric0.u[row] + u_prev[row]) / 2.0 + k_x / dt - a_x / 2.0
954                    })
955                    .collect();
956                (a_eff, u_eff, 0.5)
957            }
958        };
959
960    struct DiodeInfo {
961        name: String,
962        canonical: pwl_devices::IdealDiodeCanonical,
963        p: Option<usize>,
964        n: Option<usize>,
965        w: Vec<f64>,
966    }
967
968    let mut u_eff = u_eff_base;
969    let mut infos = Vec::with_capacity(diodes.len());
970    for (name, diode) in diodes {
971        let column = system
972            .inputs
973            .iter()
974            .position(|input| input == name)
975            .ok_or_else(|| DaeError::UnknownDiodeInput(name.clone()))?;
976        let b_col: Vec<f64> = (0..order).map(|row| numeric0.b[(row, column)]).collect();
977
978        // Trapezoidal history: the previous step's already-known diode current contributes
979        // its own (B/2)*raw_Ioff_n term to this step's effective RHS directly (only this
980        // step's *new* current needs the LCP-fold coupling_scale treatment below).
981        if let Scheme::Trapezoidal {
982            prev_diode_raw_ioff,
983            ..
984        } = scheme
985        {
986            if let Some(&prev_ioff) = prev_diode_raw_ioff.get(name) {
987                for (row, &b) in b_col.iter().enumerate() {
988                    u_eff[row] += 0.5 * b * prev_ioff;
989                }
990            }
991        }
992
993        let w = dense_solve(&a_eff, &b_col).map_err(DaeError::Linear)?;
994
995        let terminals = &nodes[name];
996        let p = topology::node_index(&system.unknowns, &terminals.positive);
997        let n = topology::node_index(&system.unknowns, &terminals.negative);
998
999        infos.push(DiodeInfo {
1000            name: name.clone(),
1001            canonical: diode.canonical(),
1002            p,
1003            n,
1004            w,
1005        });
1006    }
1007
1008    let x0 = dense_solve(&a_eff, &u_eff).map_err(DaeError::Linear)?;
1009
1010    let get = |x: &[f64], index: Option<usize>| index.map(|i| x[i]).unwrap_or(0.0);
1011
1012    let n_diodes = infos.len();
1013    let v0: Vec<f64> = infos
1014        .iter()
1015        .map(|d| get(&x0, d.p) - get(&x0, d.n))
1016        .collect();
1017    // gamma[k][j] = w_j[p_k] - w_j[n_k]: how much diode j's unit raw current moves diode k's
1018    // own terminal voltage (the diagonal, gamma[k][k], is the self term; everything else is
1019    // genuine cross-coupling through the shared linear network).
1020    let gamma: Vec<Vec<f64>> = infos
1021        .iter()
1022        .map(|k| {
1023            infos
1024                .iter()
1025                .map(|j| get(&j.w, k.p) - get(&j.w, k.n))
1026                .collect()
1027        })
1028        .collect();
1029
1030    let dim = 2 * n_diodes;
1031    let mut m = vec![vec![0.0; dim]; dim];
1032    let mut q = vec![0.0; dim];
1033    for k in 0..n_diodes {
1034        let row_w1 = 2 * k;
1035        q[row_w1] = v0[k] - infos[k].canonical.v_breakdown;
1036        for (j, info_j) in infos.iter().enumerate() {
1037            m[row_w1][2 * j] += -gamma[k][j] * info_j.canonical.delta_br * coupling_scale;
1038            m[row_w1][2 * j + 1] += gamma[k][j] * info_j.canonical.delta_on * coupling_scale;
1039        }
1040        m[row_w1][2 * k] += 1.0;
1041
1042        let row_w2 = 2 * k + 1;
1043        q[row_w2] = infos[k].canonical.v_th - v0[k];
1044        for (j, info_j) in infos.iter().enumerate() {
1045            m[row_w2][2 * j] += gamma[k][j] * info_j.canonical.delta_br * coupling_scale;
1046            m[row_w2][2 * j + 1] += -gamma[k][j] * info_j.canonical.delta_on * coupling_scale;
1047        }
1048        m[row_w2][2 * k + 1] += 1.0;
1049    }
1050
1051    let sol = lcp_solver::solve(&m, &q).map_err(DaeError::Lcp)?;
1052
1053    let mut x = x0;
1054    let mut diode_z = Vec::with_capacity(n_diodes);
1055    let mut diode_raw_ioff = Vec::with_capacity(n_diodes);
1056    for (k, info) in infos.iter().enumerate() {
1057        let z1 = sol.z[2 * k];
1058        let z2 = sol.z[2 * k + 1];
1059        // True (unscaled) physical current, used for reporting and as the next step's
1060        // trapezoidal history — NOT the same as how much it moves x this step (that's scaled
1061        // by coupling_scale, since only half of it entered the effective RHS above).
1062        let raw_ioff = info.canonical.delta_on * z2 - info.canonical.delta_br * z1;
1063        let x_contribution = raw_ioff * coupling_scale;
1064        for (xi, wi) in x.iter_mut().zip(info.w.iter()) {
1065            *xi += wi * x_contribution;
1066        }
1067        diode_z.push((z1, z2));
1068        diode_raw_ioff.push(raw_ioff);
1069    }
1070
1071    Ok(OperatingPoint {
1072        unknowns: system.unknowns.clone(),
1073        x,
1074        diode_names: infos.into_iter().map(|d| d.name).collect(),
1075        diode_z,
1076        diode_raw_ioff,
1077    })
1078}
1079
1080#[cfg(test)]
1081mod scheme_tests {
1082    //! `Scheme` and `fold_and_solve` are private, so the convergence-rate check that proves
1083    //! trapezoidal is actually second-order (not just "still passes at the same tolerance")
1084    //! has to live here rather than in `tests/`.
1085    use super::*;
1086
1087    enum Kind {
1088        BackwardEuler,
1089        /// Trapezoidal for every step after the first (which is always backward Euler, for a
1090        /// consistent `x0` — matching `simulate_transient`'s own policy).
1091        Trapezoidal,
1092    }
1093
1094    /// Runs the same RC circuit as `tests/transient.rs`'s
1095    /// `rc_charging_matches_closed_form_exponential` (`Vc(t) = 5*(1-e^-t)`) with a single
1096    /// scheme throughout, and returns the error against the closed-form solution at `t_final`.
1097    fn rc_final_error(kind: &Kind, dt: f64, t_final: f64) -> f64 {
1098        let source = "V1 a 0 5\nR1 a b 1\nC1 b 0 1";
1099        let statements = general_mna::parse_and_flatten(source, Dialect::Ngspice).unwrap();
1100        let system = MnaBuilder::new(Dialect::Ngspice)
1101            .build_statements(&statements)
1102            .unwrap();
1103        let diodes = BTreeMap::new();
1104        let steps = (t_final / dt).round() as usize;
1105
1106        let mut x = vec![0.0; system.order()];
1107        for step in 0..steps {
1108            let t = (step + 1) as f64 * dt;
1109            let use_be = matches!(kind, Kind::BackwardEuler) || step == 0;
1110            let point = if use_be {
1111                fold_and_solve(
1112                    &system,
1113                    &statements,
1114                    &diodes,
1115                    &Scheme::BackwardEuler { x_prev: &x, dt },
1116                    t,
1117                    &BTreeMap::new(),
1118                    &BTreeMap::new(),
1119                )
1120            } else {
1121                fold_and_solve(
1122                    &system,
1123                    &statements,
1124                    &diodes,
1125                    &Scheme::Trapezoidal {
1126                        x_prev: &x,
1127                        dt,
1128                        prev_diode_raw_ioff: &BTreeMap::new(),
1129                    },
1130                    t,
1131                    &BTreeMap::new(),
1132                    &BTreeMap::new(),
1133                )
1134            }
1135            .unwrap();
1136            x = point.x;
1137        }
1138
1139        let vb_index = system.unknowns.iter().position(|u| u == "V(b)").unwrap();
1140        let expected = 5.0 * (1.0 - (-t_final).exp());
1141        (x[vb_index] - expected).abs()
1142    }
1143
1144    /// The standard way to verify a method's convergence *order* is to halve `dt` and check
1145    /// how much the error shrinks, not to compare absolute error magnitudes at one `dt`
1146    /// against another method's (which depends on unknown, method-specific constants and can
1147    /// easily mislead). Backward Euler is first-order: halving `dt` should roughly halve the
1148    /// error. Both checked over the same halving, at deliberately coarse `dt` so the halving
1149    /// ratio is clearly visible before floating-point/near-exact-cancellation noise matters.
1150    #[test]
1151    fn backward_euler_error_roughly_halves_when_dt_halves() {
1152        let t_final = 2.0;
1153        let error_coarse = rc_final_error(&Kind::BackwardEuler, 0.1, t_final);
1154        let error_fine = rc_final_error(&Kind::BackwardEuler, 0.05, t_final);
1155        let ratio = error_coarse / error_fine;
1156        assert!(
1157            (1.7..=2.3).contains(&ratio),
1158            "backward-Euler error ratio (dt vs dt/2) = {ratio}, expected close to 2.0 (first-order)"
1159        );
1160    }
1161
1162    /// Trapezoidal is second-order: halving `dt` should quarter the error.
1163    #[test]
1164    fn trapezoidal_error_roughly_quarters_when_dt_halves() {
1165        let t_final = 2.0;
1166        let error_coarse = rc_final_error(&Kind::Trapezoidal, 0.1, t_final);
1167        let error_fine = rc_final_error(&Kind::Trapezoidal, 0.05, t_final);
1168        let ratio = error_coarse / error_fine;
1169        assert!(
1170            (3.0..=5.5).contains(&ratio),
1171            "trapezoidal error ratio (dt vs dt/2) = {ratio}, expected close to 4.0 (second-order)"
1172        );
1173    }
1174
1175    /// And, directly: at the same coarse `dt`, trapezoidal's error should be substantially
1176    /// smaller than backward Euler's (not asserting a specific factor, since that depends on
1177    /// problem-specific constants — just that it is, robustly, much better).
1178    #[test]
1179    fn trapezoidal_is_more_accurate_than_backward_euler_at_the_same_dt() {
1180        let t_final = 2.0;
1181        let dt = 0.1;
1182        let error_be = rc_final_error(&Kind::BackwardEuler, dt, t_final);
1183        let error_tr = rc_final_error(&Kind::Trapezoidal, dt, t_final);
1184        assert!(
1185            error_tr < error_be / 10.0,
1186            "trapezoidal error {error_tr} should be well under backward-Euler error {error_be} at dt={dt}"
1187        );
1188    }
1189}