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