Expand description
Assembles a circuit’s linear MNA system (via general-mna, including its 'D' stamp) with
PWL device segments (via pwl-devices) into one Linear Complementarity Problem, solves it
(via lcp-solver), and reports the resolved DC operating point. No Newton-Raphson, no
voltage limiting, anywhere in this crate — see this repository’s docs/architecture.md.
§The generic Thevenin/LCP fold
general-mna stamps each diode k as a fixed conductance {k}_G plus a per-instance
current-source symbol {k}_Ioff. Fixing {k}_G at the diode’s canonical reference slope
g_off (see pwl_devices::IdealDiode::canonical) makes the whole linear system A0 genuinely
fixed — independent of which segment every diode ends up in — with every segment’s actual
nonlinearity pushed entirely into the {k}_Ioff terms via each diode’s canonical
max(0, ...) (z) decomposition. Since the system is linear in those Ioff terms, each
diode’s terminal voltage is an affine function of every diode’s z variables:
x(z) = x0 + sum_j w_j * raw_Ioff_j (raw_Ioff_j = delta_on_j*z2_j - delta_br_j*z1_j)
V_k(z) = v0_k + sum_j gamma_kj * raw_Ioff_j (gamma_kj = w_j[p_k] - w_j[n_k])where x0 = solve(A0, u0) is the baseline operating point with every diode’s Ioff = 0,
and w_j = solve(A0, B[:, diode j's input column]) is how much a unit “raw Ioff” on diode
j moves every unknown. Substituting V_k(z) into each diode’s guard equations
(w1_k = V_k - v_breakdown_k + z1_k, w2_k = v_f_k - V_k + z2_k) gives exactly the LCP
(M, q) this crate builds and hands to lcp_solver::solve.
Modules§
- checkpoint
- Checkpoint/resume: a complete, serializable snapshot of a transient run’s loop-carried state, so a run can stop at some $t$ and continue later — from the same process, from a file, on another machine — with a trace bit-identical to the uninterrupted run.
Structs§
- Adaptive
Config - Parameters for [
lte_attempt]’s local-truncation-error step-size control. - Block
Instance - One named block instance and where its inputs (if any) come from.
Const/Pwc/Pwl/Waveform/Phys2Sigblocks must have zero inputs;Sum/Productneed one input per sign/factor;Gain/StateSpace/TransferFunction/Vco/Saturation/Table/MathFn1/Sig2Physeach need exactly one;Pidneeds exactly one (the error signal) when itsclampisPidClamp::Fixed, or exactly three (error, clamp_lo, clamp_hi, in that order) whenPidClamp::Dynamic;MathFn2needs two;MathFn3needs three;CoordinateTransformneedskind.input_count()(3 forClarke/ClarkeInv, 4 for the others — seecontinuous_blocks::CoordinateTransform::input_count);Pmsmneeds exactly three (vd,vq,t_load, in that order). Evaluated once per step in the causal ordertopological_order(indae-runtime) derives from the slice’s ownSignal::Blockdependency graph — not the order the slice happens to be given in; aSignal::Blockinput may name any block in the same slice regardless of declared position (source blocks, naturally, need none, and a genuine cycle among these edges is rejected asDaeError::AlgebraicLoopbefore any step runs — seetopological_order’s own doc comment for how). - Checkpoint
Control - How a run interacts with checkpoints — see
simulate_transient_with_blocks_checkpointed. - Operating
Point
Enums§
- Block
Kind - One block’s behavior.
Const/Pwc/Pwl/Sin/Pulse/Exp/Sffmare sources (zero inputs);Sum/Gainare stateless (recomputed fresh from their inputs every step);Pid/StateSpace/TransferFunction/Vcocarry their own state forward across steps. - Const
Value - A
BlockKind::Const’s own fixed value. - DaeError
- Gain
Value - A
BlockKind::Gain’s own scale factor — a plain scalar (the only form before vector signals existed, unchanged), or a fixedM x Nmatrix (row-major,matrix[row][col]) for a genuine matrix-vector product. - Gate
Binding - How one ideal switch’s gate state is resolved, every step: always from a named block’s
current output, on while it’s
>= 0.5. No non-block-driven variant exists — even a permanently-off gate is an explicitConst(0.0)wired through adomain=voltageBlockKind::Sig2Phys, the same as every other gate — and no bare carrier-comparator variant exists either: that comparison now lives entirely inside gate-drivingBlockKinds themselves (BlockKind::Pwm/BlockKind::PhaseShiftPwm, or a hand-built chain of ordinary blocks), soGateBindinghas exactly one job — reading a number and thresholding it — regardless of what produced that number: a modulator’s own main/complement output, aBlockKind::Hysteresisblock (no carrier at all, event-driven bang-bang switching), or any other block a caller composes. - Gate
State - State assigned to an idealized converter switch.
- Phys2
SigTarget - What a
BlockKind::Phys2Sigreads from the circuit’s own previous-step operating point —V(node)orI(branch), anythingOperatingPoint::value(indae-runtime) accepts, keyed by exactly the sameV(...)/I(...)naming conventiongeneral-mnaitself uses for MNA unknowns. - Physical
Domain - Which physical quantity a
BlockKind::Sig2Physconverter drives. Purely a type-level tag for the enforcement sites indae-runtime(DaeError::GateTargetNotSig2Voltage,DaeError::SourceNotSig2PhysicalConverter) — evaluation itself (value = input) is identical for both. - PidClamp
- A
BlockKind::Pid’s anti-windup bound: fixed at model-build time, or read fresh from the graph every step.Fixedis every existing use ofPidbefore this variant existed — unchanged behavior, one input (the error signal) as always.Dynamicis for a controller whose achievable output range genuinely depends on other, still-evolving state (e.g. a current-loop PID commanding a pole voltage that can’t physically exceed roughly half the DC bus voltage, itself still rising during a soft-start ramp) — aFixedbound sized for the final steady-state range is badly oversized early on, so the PID’s own anti-windup never engages even though the real plant is already saturated far below that fixed bound, producing sustained, hard-to-diagnose windup-driven oscillation (worked example: anelspice-pwl-pfc-three-phase-vscexperiment’s own three-phase active-front-end current loop, in the siblinginternal-archiverepo).Dynamicreads two extra inputs beyond the error signal, in order(clamp_lo, clamp_hi), evaluated fresh every step exactly like any other block input — seeBlockInstance’s own doc comment for the resulting input count. - Sample
Time Spec - How a
CScript/PyBlock/PyFunction/OctFuncblock’s own execution is scheduled, independent of the circuit’s own resolved step (see eachBlockKindvariant’s ownsample_timefield). - Signal
- Where a block’s input value comes from: another block’s output this same step, or that (or
any) block’s own output from the previous step. There is deliberately no variant that
reads a circuit quantity (
V(node)/I(branch)) directly — that crossing from the physical domain into the signal domain must go through an explicit, namedBlockKind::Phys2Sigblock instead (referenced afterward like any other block, viaSignal::Block). SeeBlockKind::Phys2Sig’s own doc comment for why this boundary is enforced rather than implicit, the same way a real block-diagram tool requires an explicit physical/signal converter block between a physical port and a signal port instead of wiring them together directly. - Signal
Value - The value one named block produces (or one
Signalresolves to) at a given step: a bare scalar — everything this graph supported before this variant existed — or a fixed-length vector of scalars. Arity is fixed once a block declares it (known at graph-build time from its own parameters, e.g. a matrixGain’s own row count, aConstvector literal’s own length,StateSpace’s ownCrow count) — there is no dynamic/runtime-determined length. - Time
Step - How a transient run picks its step size.
- Transient
Function - One parsed transient-function call, in the same field order and names ngspice/Xyce use.
Constants§
- ADAPTIVE_
STEP_ HARD_ CAP - Hard ceiling on accepted
TimeStep::Adaptivesteps for onesimulate_transient_with_blockscall — seeDaeError::AdaptiveStepStalled’s own doc comment for why this exists. Sized generously above any legitimate run this project has actually needed (the largest real fixed-step run on record is 1,000,000 rows for a 20ms/dt=2e-8transient; adaptive stepping should need far fewer accepted steps than that to cover the same window) while staying well under what would exhaust a typical machine’s RAM before this check can fire (each row holds every node voltage/branch current/block output asf64s — a few hundred bytes for a medium-sized circuit — so even 10,000,000 rows stays in the hundreds-of-MB-to-low-GB range, not the tens-of-GB range that actually crashed a machine running the unpatched bug this guards against).
Functions§
- reject_
sig2phys_ wired_ into_ circuit - Rejects a
kind=sig2physconverter that was wired into the physical network — i.e. a block whose own name is also used as a node on some element line — before any system is built or any step is solved. SeeDaeError::Sig2PhysUsedAsCircuitNodefor the full rationale; the short version is that aSig2Physblock has no terminals and stamps nothing, so such a net is an ordinary undriven node that silently solves to0instead of failing. - sawtooth_
carrier - A free-running sawtooth PWM carrier in
[0, 1)at frequencyfreq_hz. Compare a duty command (also[0, 1]) against this to decide gate state: on while the carrier is below the duty command, off otherwise (a standard trailing-edge PWM comparator). - simulate_
closed_ loop - Runs a closed-loop transient: at each timestep,
measurereads a scalar from the previous step’sOperatingPoint(e.g. an output node voltage),controller(its own state carried forward internally) is stepped withreference(t) - measuredas its input via RK4, andpwm(controller_output, t)decides every ideal switch’s gate state for this step from that controller output. Everything else matchescrate::simulate_transient_with_ideal_switches(system rebuilt per step, trapezoidal with backward-Euler fallback on any diode-segment or gate-state change). - simulate_
transient - simulate_
transient_ with_ blocks - Runs a transient with every ideal switch’s gate resolved from a
GateBindingeach step — see this module’s doc comment for why there’s no separate “closed-loop” entry point: a device gated by a plainBlockKind::Hysteresisand one gated by aSum-Pid-BlockKind::PhaseShiftPwmchain that happens to read aBlockKind::Phys2Sigare resolved by exactly the same loop below — everyGateBindingisBlock(name), reading whatevername’s current output happens to be.steppicks fixed or adaptive timing — seeTimeStep/[AdaptiveConfig]. Adaptive mode here can’t reuse [step_control::adaptive_step] directly (that assumes adt-independentsystem): this circuit’s gate states, and so itssystem, are themselves a function ofdtthrough the block graph, so a rejected trial has to redo block evaluation and gate resolution at the smallerdt, not just re-solve the same system — see the retry loop below. - simulate_
transient_ with_ blocks_ capped - Identical to
simulate_transient_with_blocks, with one addition:max_adaptive_stepsoverridesADAPTIVE_STEP_HARD_CAP(seeDaeError::AdaptiveStepStalled’s own doc comment for what this guards against) instead of always using the built-in default. A separate function, rather than adding a parameter tosimulate_transient_with_blocksitself, so this project’s own ~20 existing call sites (mostly tests, positional-argument calls) don’t all need updating for a cap most of them will never want to change —general-simulator-cli’s own--max-stepsflag is the intended caller. - simulate_
transient_ with_ blocks_ checkpointed simulate_transient_with_blocks_streamedplus checkpointing: optionally starts from aCheckpoint, optionally hands one out every so often, and optionally returns the run’s final state as one — the exact loop-carried state after the last accepted step, from which a later call continues bit-identically to a run that never stopped. Seecheckpoint’s own module doc comment for what a snapshot holds and the identity check a resume performs.- simulate_
transient_ with_ blocks_ streamed - The actual transient engine — every other
simulate_transient_with_blocks*function is a thin wrapper over this one. Callson_step(t, point, outputs)once per accepted step, in order, and holds nothing beyond one step’s own data itself: a caller that only needs summary statistics, or that writes each row straight to a file/stream as it arrives, never pays for a full in-memory trace the waysimulate_transient_with_blocks/_cappeddo by design (they exist for exactly the callers — mostly this project’s own tests — that want the wholeVecback).on_stepreturningErraborts the run immediately with that error. - simulate_
transient_ with_ ideal_ switches - Runs a transient simulation of a netlist containing linear devices, ordinary
Ddiodes, and any number ofIdealSwitchinstances whose gate state can vary over time — a PWM driver, unlikesolve_dc_with_ideal_switches’s fixed per-call state.gate_signal(name, t)is called once per ideal switch per timestep to get that instance’sGateStateat timet; the caller owns the PWM logic entirely (duty cycle, frequency, phase — this crate has no opinion). - solve_
dc - Solves the DC operating point of a netlist containing linear devices plus any number of
D(diode) elements, whose piecewise-linear parameters are supplied indiodes(keyed by element name) rather than parsed from the netlist — SPICE’s.modelsyntax has no notion of this crate’s breakdown/leakage/forward segments. - solve_
dc_ with_ ideal_ switches - Solves the DC operating point of a netlist containing linear devices, ordinary
Ddiodes (diodes), and any number ofIdealSwitchinstances (ideal_switches), each with its own known gate state (seeGateState, a re-export ofgeneral_mna::SwitchState— the same concept: an exogenous, externally-decided mode, not something the LCP resolves).
Type Aliases§
- Checkpoint
Sink - What
CheckpointControl::on_checkpointpoints at. - Transient
With Blocks Step - One step’s result:
(t, OperatingPoint, block_outputs), whereblock_outputsis every block’s value that step (by name) — useful for plotting a controller’s internal signals (e.g. aVco’s commanded frequency) without needing to separately re-derive them.