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