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