Skip to main content

general_mna/
block_graph.rs

1//! The block/signal-domain type vocabulary: `BlockKind`/`BlockInstance` (one named block and
2//! what it computes), `Signal` (where a block's input comes from), `GateBinding` (how a
3//! an ideal switch's gate state resolves from a block's output), `Phys2SigTarget`/`PidClamp` (the two
4//! `BlockKind` variants complex enough to need their own payload type). Moved here from
5//! `dae-runtime` (Phase 2 of the format-unification plan — see `general-simulator`'s own
6//! `docs/journal/`): `general-mna` is now the single place a netlist's *meaning* is built, both
7//! electrical (`MnaSystem`, unchanged) and signal-domain (this module) — `dae-runtime` only
8//! evaluates a graph of these types over time, it doesn't define what they are or parse them
9//! out of source text anymore.
10//!
11//! Every block does one job and is meant to be wired to the others by the caller — an error
12//! signal is a `Sum` block's output, a filtered-derivative PID compensator is a
13//! `TransferFunction` given its own `N(s)/D(s)` coefficients, and a frequency-modulated PWM
14//! carrier is `Pid -> Gain -> PhaseShiftPwm`, not a single function that bakes a specific
15//! topology together.
16//!
17//! **There is no separate "closed-loop mode," and no non-block-driven gate at all** — every
18//! [`GateBinding`] is `Block(name)`, reading a named block's current output (`>= 0.5` means
19//! on), whether that block's own input chain traces back to a [`BlockKind::Phys2Sig`] of the
20//! circuit's own state or is just a `Const` — both are resolved by exactly the same code, every
21//! step, because from the solver's point of view they're the same kind of question: "what's
22//! this device's terminal condition right now."
23//!
24//! This module defines *what these types are*; evaluating them over time (`BlockState`,
25//! `evaluate_blocks`, `topological_order`, `simulate_transient_with_blocks`) stays in
26//! `dae-runtime`, which imports everything here.
27
28use std::collections::BTreeMap;
29
30use continuous_blocks::{
31    CoordinateTransform, DiscretePid, FlipFlopKind, Hysteresis, LatchPriority, LogicOp, MathFn1,
32    MathFn2, MathFn3, Pid, Pmsm, StateSpace, TransferFunction, Vco,
33};
34
35use crate::{SwitchState, TransientFunction};
36
37/// Where a block's input value comes from: another block's output this same step, or that (or
38/// any) block's own output from the *previous* step. There is deliberately **no** variant that
39/// reads a circuit quantity (`V(node)`/`I(branch)`) directly — that crossing from the physical
40/// domain into the signal domain must go through an explicit, named [`BlockKind::Phys2Sig`] block
41/// instead (referenced afterward like any other block, via `Signal::Block`). See
42/// [`BlockKind::Phys2Sig`]'s own doc comment for why this boundary is enforced rather than
43/// implicit, the same way a real block-diagram tool requires an explicit physical/signal
44/// converter block between a physical port and a signal port instead of wiring them together
45/// directly.
46#[derive(Debug, Clone, PartialEq)]
47pub enum Signal {
48    /// Another block's output *this* step — may name any block in the same slice, declared
49    /// before or after this one: `topological_order` derives each step's actual evaluation
50    /// order from the full `Signal::Block` dependency graph, not declaration position, so
51    /// "before/after" in the source text no longer has to match causal order (see that
52    /// function). A genuine same-step cycle among these edges (`A` depends on `B` depends on
53    /// `A`, however indirectly, including a block naming itself) is a model error reported as
54    /// `DaeError::AlgebraicLoop` before any step is solved — see [`BlockInstance`]'s own doc
55    /// comment.
56    Block(String),
57    /// A named block's own output from the *previous* step (`0.0` before the first step,
58    /// matching every dynamic block's own "starts at rest" convention). Unlike `Signal::Block`,
59    /// this is not a same-step dependency at all — it reads state fixed before this step even
60    /// starts — so it never contributes an edge to the dependency graph `topological_order`
61    /// (in `dae-runtime`) builds, and is consequently the *sanctioned* way to close what would otherwise be a
62    /// same-step cycle (e.g. a current controller regulating a [`BlockKind::Pmsm`]'s own
63    /// `id`/`iq` outputs, or a PLL's angle estimate feeding the very
64    /// [`BlockKind::CoordinateTransform`] `Park` block that produced its own error signal): the
65    /// one-sample delay every real digital controller reading its own last output already has.
66    BlockPrev(String),
67}
68
69/// The value one named block produces (or one `Signal` resolves to) at a given step: a bare
70/// scalar — everything this graph supported before this variant existed — or a fixed-length
71/// vector of scalars. Arity is fixed once a block declares it (known at graph-build time from
72/// its own parameters, e.g. a matrix `Gain`'s own row count, a `Const` vector literal's own
73/// length, `StateSpace`'s own `C` row count) — there is no dynamic/runtime-determined length.
74///
75/// **No type tagging beyond `Scalar`/`Vector` exists, or is needed.** This graph has never had
76/// a `bool` type, even for scalars — a "boolean" signal (a `Hysteresis` output, a PWM
77/// `main`/`complement` output) has always just been an `f64` interpreted via a `>= 0.5`
78/// threshold by whatever reads it. A `Vector`'s own elements are exactly as untyped as a scalar
79/// signal already was; nothing tracked "this element is really a voltage" vs. "this element is
80/// really a gate command" before, and nothing needs to start now.
81///
82/// Which `BlockKind`s accept/produce a `Vector`, and the exact broadcast/reduction/rejection
83/// rule for each, is a per-block-kind decision worked out in
84/// `general-simulator`'s own `book/dev-guide/src/vector-signals.md`.
85#[derive(Debug, Clone, PartialEq)]
86pub enum SignalValue {
87    /// A single number.
88    Scalar(f64),
89    /// A fixed-length bundle of numbers.
90    Vector(Vec<f64>),
91}
92
93impl SignalValue {
94    /// `1` for a `Scalar`, the element count for a `Vector`.
95    pub fn len(&self) -> usize {
96        match self {
97            SignalValue::Scalar(_) => 1,
98            SignalValue::Vector(v) => v.len(),
99        }
100    }
101
102    /// `true` only for an empty `Vector` (a `Scalar` is always length 1).
103    pub fn is_empty(&self) -> bool {
104        self.len() == 0
105    }
106
107    /// `Some(x)` for a `Scalar`, `None` for a `Vector` — the check every scalar-only `BlockKind`
108    /// makes on each of its own inputs before doing anything else.
109    pub fn as_scalar(&self) -> Option<f64> {
110        match self {
111            SignalValue::Scalar(x) => Some(*x),
112            SignalValue::Vector(_) => None,
113        }
114    }
115
116    /// This value's own elements, in order, as a plain slice — a `Scalar` is a length-1 slice.
117    /// The flattening primitive every input-bundling block (`cscript`, `statespace`,
118    /// `CoordinateTransform`, `Pmsm`) builds its own input vector from: several `SignalValue`s,
119    /// scalar or vector, concatenated in declared order.
120    pub fn as_slice(&self) -> &[f64] {
121        match self {
122            SignalValue::Scalar(x) => std::slice::from_ref(x),
123            SignalValue::Vector(v) => v,
124        }
125    }
126}
127
128/// What a [`BlockKind::Phys2Sig`] reads from the circuit's own previous-step operating point —
129/// `V(node)` or `I(branch)`, anything `OperatingPoint::value` (in `dae-runtime`) accepts, keyed by exactly the
130/// same `V(...)`/`I(...)` naming convention `general-mna` itself uses for MNA unknowns.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum Phys2SigTarget {
133    /// `V(node)` — the named node's voltage.
134    Voltage(String),
135    /// `I(branch)` — the named branch's current.
136    Current(String),
137}
138
139/// A [`BlockKind::Pid`]'s anti-windup bound: fixed at model-build time, or read fresh from the
140/// graph every step. `Fixed` is every existing use of `Pid` before this variant existed —
141/// unchanged behavior, one input (the error signal) as always. `Dynamic` is for a controller
142/// whose *achievable* output range genuinely depends on other, still-evolving state (e.g. a
143/// current-loop PID commanding a pole voltage that can't physically exceed roughly half the
144/// DC bus voltage, itself still rising during a soft-start ramp) — a `Fixed` bound sized for
145/// the final steady-state range is badly oversized early on, so the PID's own anti-windup never
146/// engages even though the real plant is already saturated far below that fixed bound,
147/// producing sustained, hard-to-diagnose windup-driven oscillation (worked example: an
148/// `elspice-pwl-pfc-three-phase-vsc` experiment's own three-phase active-front-end current loop,
149/// in the sibling `internal-archive` repo). `Dynamic` reads two *extra* inputs beyond
150/// the error signal, in order `(clamp_lo, clamp_hi)`, evaluated fresh every step exactly like
151/// any other block input — see [`BlockInstance`]'s own doc comment for the resulting input
152/// count.
153#[derive(Debug, Clone, Copy, PartialEq)]
154pub enum PidClamp {
155    /// A fixed `(lo, hi)` anti-windup bound, set once at model-build time.
156    Fixed(f64, f64),
157    /// The anti-windup bound is read fresh from two extra block inputs every step.
158    Dynamic,
159}
160
161/// A [`BlockKind::Const`]'s own fixed value.
162#[derive(Debug, Clone, PartialEq)]
163pub enum ConstValue {
164    /// A fixed number.
165    Scalar(f64),
166    /// A fixed vector.
167    Vector(Vec<f64>),
168}
169
170/// A [`BlockKind::Gain`]'s own scale factor — a plain scalar (the only form before vector
171/// signals existed, unchanged), or a fixed `M x N` matrix (row-major, `matrix[row][col]`) for a
172/// genuine matrix-vector product.
173#[derive(Debug, Clone, PartialEq)]
174pub enum GainValue {
175    /// A plain scale factor.
176    Scalar(f64),
177    /// A fixed `M x N` matrix, row-major (`matrix[row][col]`).
178    Matrix(Vec<Vec<f64>>),
179}
180
181/// How a `CScript`/`PyBlock`/`PyFunction`/`OctFunc` block's own execution is scheduled, independent of
182/// the circuit's own resolved step (see each `BlockKind` variant's own `sample_time` field).
183#[derive(Debug, Clone, Copy, PartialEq)]
184pub enum SampleTimeSpec {
185    /// A fixed sample period `period` (from `ts=`/`freq=`), with an optional phase `offset`
186    /// (from `to=`, required to satisfy `0.0 <= offset < period`) delaying when the *first* hit
187    /// lands. Every hit after the first is spaced by exactly `period`.
188    ///
189    /// **Default, when `to=` is omitted: `offset == 0.0`** — this preserves the exact
190    /// pre-existing behavior every `ts=`/`freq=`-using netlist already had before this field
191    /// could carry an offset at all: `dae-runtime` seeds its own per-instance accumulator so the
192    /// *first* `evaluate_blocks` call a block participates in is always due, unconditionally,
193    /// regardless of `period`'s own value (verified directly against `dae-runtime`'s own
194    /// construction code, not assumed) — i.e. the pre-existing behavior already *was* "no
195    /// offset," not "one period's delay" as it might look at first glance. An explicit `to=X`
196    /// (`0 < X < period`) genuinely delays the first hit to `t=X` instead.
197    Periodic {
198        /// The fixed sample period.
199        period: f64,
200        /// Phase offset delaying the first hit; `0.0 <= offset < period`.
201        offset: f64,
202    },
203    /// The block computes its own next execution time itself, every time it runs (`ts=variable`
204    /// in the netlist) — for a block whose own next event is known analytically at runtime (a
205    /// modulator's own scheduled switching instant) rather than fixed at parse time. Requires
206    /// the backing `.so`/`.py` to export the corresponding optional next-sample-hit
207    /// function/symbol; see `cscript_ffi`'s/`pyblock_ffi`'s own module doc comments. Not
208    /// available for [`BlockKind::PyFunction`]/[`BlockKind::OctFunc`] (rejected at parse time) —
209    /// a stateless function call has no instance to remember a requested next-hit time against.
210    Variable,
211}
212
213/// One block's behavior. `Const`/`Pwc`/`Pwl`/`Sin`/`Pulse`/`Exp`/`Sffm` are sources (zero
214/// inputs); `Sum`/`Gain` are stateless (recomputed fresh from their inputs every step);
215/// `Pid`/`StateSpace`/`TransferFunction`/`Vco` carry their own state forward across steps.
216#[derive(Debug, Clone, PartialEq)]
217pub enum BlockKind {
218    /// <!-- component -->
219    /// # Constant
220    /// **Purpose:** a fixed reference value — a setpoint, bias, or offset that doesn't vary with
221    /// time.
222    /// **Library:** Sources
223    ///
224    /// ## Description
225    /// A fixed value, independent of time: a scalar (`value=5`) or a fixed vector
226    /// (`value=[1,2,3]`, a Python-list literal). No inputs, no state, nothing to evaluate per
227    /// step. The vector form exists specifically to feed the vector-aware math blocks — a
228    /// per-element offset into a vector `Sum`, or a matrix `Gain`'s input.
229    ///
230    /// ## Parameters
231    /// - `value=<f64>` — a plain number (the scalar form).
232    /// - `value=[x1,x2,...]` — a Python-style list literal (the vector form). Entries must be
233    ///   finite: `nan`/`inf` are rejected at parse time, since a NaN would otherwise silently
234    ///   propagate into downstream sorts/comparisons and panic the process.
235    ///
236    /// ## Errors
237    /// - `value=abc` (scalar not a number) — rejected at parse time:
238    ///   `field 'value' is not a number`.
239    /// - `value=[1,x,3]` (vector entry not a number) — rejected at parse time:
240    ///   `field 'value' entry 'x' is not a number`.
241    /// - `value=[1,nan,3]` (non-finite vector entry) — rejected at parse time:
242    ///   `field 'value' entry 'nan' must be a finite number (got NaN)`.
243    /// - A missing `value=` is the generic `missing field 'value'` error every `kind=` block
244    ///   shares — see [`BlockInstance`]'s own doc comment.
245    ///
246    /// ## Netlist form
247    /// ```text
248    /// NAME kind=const value=<f64> | value=[x1,x2,...]
249    /// ```
250    ///
251    /// ## Example
252    /// A scalar setpoint and a constant vector offset, unchanged at every step:
253    /// ```text
254    /// SETPOINT kind=const value=5
255    /// OFFSETS kind=const value=[1,2,3]
256    /// ```
257    Const(ConstValue),
258    /// <!-- component -->
259    /// # Time
260    /// **Purpose:** the current simulated time as a signal — the block-diagram "clock" source.
261    /// **Library:** Sources
262    ///
263    /// ## Description
264    /// Outputs the current step's own simulated time in seconds. Takes no fields and no inputs.
265    /// Its job is building genuine time-varying signals out of the stateless math blocks: there
266    /// is otherwise no way for a block to see `t` directly (`pwc`/`pwl`/`waveform`'s own use of
267    /// time is internal to those blocks alone). The standard `sin(2*pi*f*t)` recipe is
268    /// `time -> gain(k=2*pi*f) -> sin` — see the Example.
269    ///
270    /// ## Parameters
271    /// None — `kind=time` takes no fields at all.
272    ///
273    /// ## Errors
274    /// None — there is nothing component-specific to get wrong beyond the generic
275    /// `unknown device kind` error for a misspelled kind.
276    ///
277    /// ## Netlist form
278    /// ```text
279    /// NAME kind=time
280    /// ```
281    ///
282    /// ## Example
283    /// A 1 kHz sine wave built entirely from ordinary blocks (`6283.185307179586` is
284    /// `2*pi*1000`):
285    /// ```text
286    /// T kind=time
287    /// G kind=gain in=T k=6283.185307179586
288    /// S kind=sin in=G
289    /// ```
290    Time,
291    /// <!-- component -->
292    /// # Piecewise-Constant Source (pwc)
293    /// **Purpose:** a time schedule that holds a constant value between its breakpoints —
294    /// reference schedules and step tests.
295    /// **Library:** Sources
296    ///
297    /// ## Description
298    /// A piecewise-**constant** function of time: the value is the last breakpoint's value at or
299    /// before `t` (the first point's value before it, the last point's value forever after). Two
300    /// points make a step test; more points make an arbitrary staircase schedule. With
301    /// `repeat=true`, `t` wraps into `[points[0].0, points[last].0)` (period = last time − first
302    /// time) once past the last point, making a periodic square/staircase waveform — a repeating
303    /// list needs a final point back at the value the cycle starts from, since the wrapped `t`
304    /// lands in `[first, last)` and never reaches the last point's own value.
305    ///
306    /// Not the same interpolation as [`BlockKind::Pwl`] (real SPICE piecewise-*linear*
307    /// semantics): this block is named `pwc` at the CLI level specifically to avoid the
308    /// ambiguity a shared `pwl` name would create — `pwc` holds between breakpoints, `pwl`
309    /// interpolates.
310    ///
311    /// ## Parameters
312    /// - `points=[[t1,v1],[t2,v2],...]` — `(time, value)` breakpoints as a Python list of
313    ///   2-element lists. Sorted ascending by `t` at parse time, so declaration order doesn't
314    ///   matter.
315    /// - `repeat=true` — optional (default: hold flat past the last point); wraps `t` into the
316    ///   breakpoint span as above. Matched exactly: any other spelling (including `True`) means
317    ///   no repeat.
318    ///
319    /// ## Errors
320    /// - A `points=` entry that is not a 2-element `[x,y]` list — rejected at parse time:
321    ///   `field 'points': each entry must be a 2-element '[x,y]' list (got '[1.0]')`.
322    /// - `points=abc` (not a Python list at all) — rejected at parse time:
323    ///   `field 'points' must be a Python-style list, e.g. '[1,2,3]' or '[[1,2],[3,4]]' (got
324    ///   'abc')`.
325    /// - A missing `points=` is the generic `missing field 'points'` error — see
326    ///   [`BlockInstance`]'s own doc comment.
327    ///
328    /// ## Netlist form
329    /// ```text
330    /// NAME kind=pwc points=[[t1,v1],[t2,v2],...] [repeat=true]
331    /// ```
332    ///
333    /// ## Example
334    /// A step test at `t = 0.001`, and a periodic square wave (period 0.001):
335    /// ```text
336    /// STEP kind=pwc points=[[0,0],[0.001,1]]
337    /// SQUARE kind=pwc points=[[0,0],[0.0005,1],[0.001,0]] repeat=true
338    /// ```
339    Pwc {
340        /// `(time, value)` breakpoints, in order.
341        points: Vec<(f64, f64)>,
342        /// If `true`, wraps `t` into the breakpoint range instead of holding flat past the last point.
343        repeat: bool,
344    },
345    /// <!-- component -->
346    /// # Piecewise-Linear Source (pwl)
347    /// **Purpose:** a time waveform linearly interpolated between breakpoints — real SPICE PWL
348    /// semantics in the signal domain.
349    /// **Library:** Sources
350    ///
351    /// ## Description
352    /// A piecewise-**linear** function of time: linear interpolation between breakpoints, held
353    /// at the first/last point's value before/after the breakpoint range — exactly
354    /// [`TransientFunction::Pwl`]'s own electrical-domain behavior, so the same breakpoint list
355    /// means the same waveform whether it drives a `V`/`I` source directly or a signal-domain
356    /// reference through this block. With `repeat=true`, `t` wraps into `[points[0].0,
357    /// points[last].0)` (period = last time − first time) once past the last point — the
358    /// electrical-domain `PWL` source has no such option, so a genuinely periodic
359    /// piecewise-linear waveform (a triangle/sawtooth reference, a repeating ramp) is only
360    /// available here in the signal domain. Not the same interpolation as [`BlockKind::Pwc`]
361    /// (piecewise-*constant*): `pwl` interpolates, `pwc` holds.
362    ///
363    /// ## Parameters
364    /// - `points=[[t1,v1],[t2,v2],...]` — `(time, value)` breakpoints as a Python list of
365    ///   2-element lists. Sorted ascending by `t` at parse time, so declaration order doesn't
366    ///   matter.
367    /// - `repeat=true` — optional (default: hold flat past the last point); wraps `t` into the
368    ///   breakpoint span as above. Matched exactly: any other spelling (including `True`) means
369    ///   no repeat.
370    ///
371    /// ## Errors
372    /// - A `points=` entry that is not a 2-element `[x,y]` list — rejected at parse time:
373    ///   `field 'points': each entry must be a 2-element '[x,y]' list (got '[1.0]')`.
374    /// - `points=` not a Python list at all — rejected at parse time with the same
375    ///   `field 'points' must be a Python-style list, ...` error as `pwc` (shared parser — see
376    ///   the pwc entry).
377    /// - A missing `points=` is the generic `missing field 'points'` error — see
378    ///   [`BlockInstance`]'s own doc comment.
379    ///
380    /// ## Netlist form
381    /// ```text
382    /// NAME kind=pwl points=[[t1,v1],[t2,v2],...] [repeat=true]
383    /// ```
384    ///
385    /// ## Example
386    /// A ramp to 1, and a periodic triangle (period 0.001):
387    /// ```text
388    /// RAMP kind=pwl points=[[0,0],[0.001,1]]
389    /// TRI kind=pwl points=[[0,0],[0.0005,1],[0.001,0]] repeat=true
390    /// ```
391    Pwl {
392        /// `(time, value)` breakpoints, in order.
393        points: Vec<(f64, f64)>,
394        /// If `true`, wraps `t` into the breakpoint range instead of holding flat past the last point.
395        repeat: bool,
396    },
397    /// <!-- component -->
398    /// # Waveform Sources (sinwave / pulsewave / expwave / sffmwave)
399    /// **Purpose:** the electrical domain's four non-PWL time-varying source forms, reusable as
400    /// zero-input signal references.
401    /// **Library:** Sources
402    ///
403    /// ## Description
404    /// One of [`TransientFunction`]'s four non-`Pwl` variants, reused directly rather than
405    /// reimplemented: `kind=sinwave`/`pulsewave`/`expwave`/`sffmwave` take the same field
406    /// names, order and defaults as SPICE's `SIN()`/`PULSE()`/`EXP()`/`SFFM()` sources, so a
407    /// `V`/`I` source and a signal-domain reference built from the same parameters produce
408    /// bit-for-bit the same waveform (evaluated via [`TransientFunction::value_at`] at the
409    /// current step's own `t`). See [`TransientFunction`]'s own doc comment for the exact
410    /// formula each form implements (offset + damped sinusoid, periodic trapezoid, two-stage
411    /// exponential, single-frequency FM). The fifth form, `PWL`, is its own block kind here
412    /// ([`BlockKind::Pwl`]) — the only member of the family with the `repeat` option
413    /// [`TransientFunction`] doesn't have.
414    ///
415    /// ## Parameters
416    /// - `sinwave`: `va=<f64>` `freq=<f64>` required (amplitude; frequency in Hz). Optional:
417    ///   `v0=<f64>` (0), `td=<f64>` (0), `theta=<f64>` (0, exponential damping), `phase=<f64>`
418    ///   (0, degrees).
419    /// - `pulsewave`: `v1=<f64>` `v2=<f64>` required (low/high levels). Optional: `td` (0),
420    ///   `tr` (0), `tf` (0), `pw` (default: effectively forever), `per` (effectively forever).
421    ///   `tr`/`tf` of exactly 0 are instantaneous edges.
422    /// - `expwave`: `v1=<f64>` `v2=<f64>` required. Optional: `td1` (0), `tau1` (1), `td2`
423    ///   (effectively never — not `td1`), `tau2` (1).
424    /// - `sffmwave`: `va=<f64>` `fc=<f64>` `fs=<f64>` required (carrier amplitude, carrier
425    ///   frequency, signal frequency, all Hz/amplitude as in SPICE). Optional: `v0` (0),
426    ///   `mdi` (0, modulation index).
427    /// - An *optional* field that is present but doesn't parse as a number **silently falls back
428    ///   to its default** — `td=abc` behaves exactly like an omitted `td`, with no error.
429    ///
430    /// ## Errors
431    /// - A required field missing (`sinwave` without `va`) — the generic `missing field 'va'`
432    ///   error (see [`BlockInstance`]'s own doc comment).
433    /// - A required field not a number (`va=abc`) — rejected at parse time:
434    ///   `field 'va' is not a number`.
435    ///
436    /// ## Netlist form
437    /// ```text
438    /// NAME kind=sinwave    va=<f64> freq=<f64> [v0=<f64>] [td=<f64>] [theta=<f64>] [phase=<f64>]
439    /// NAME kind=pulsewave  v1=<f64> v2=<f64> [td=<f64>] [tr=<f64>] [tf=<f64>] [pw=<f64>] [per=<f64>]
440    /// NAME kind=expwave    v1=<f64> v2=<f64> [td1=<f64>] [tau1=<f64>] [td2=<f64>] [tau2=<f64>]
441    /// NAME kind=sffmwave   va=<f64> fc=<f64> fs=<f64> [v0=<f64>] [mdi=<f64>]
442    /// ```
443    ///
444    /// ## Example
445    /// A 1 kHz sinusoid, a delayed 1 kHz square wave, an exponential rise/fall, and an
446    /// unmodulated FM carrier, all as signal-domain references:
447    /// ```text
448    /// SINREF kind=sinwave va=10 freq=1000
449    /// PULSEREF kind=pulsewave v1=0 v2=10 td=0.001 tr=0.0001 tf=0.0001 pw=0.0002 per=0.001
450    /// EXPREF kind=expwave v1=0 v2=1 td1=0 tau1=0.0001 td2=0.001 tau2=0.0001
451    /// FMREF kind=sffmwave v0=0 va=1 fc=1000 mdi=0 fs=100
452    /// ```
453    Waveform(TransientFunction),
454    /// <!-- component -->
455    /// # Sum
456    /// **Purpose:** weighted sum of its inputs, one sign per input — e.g. an error junction.
457    /// **Library:** Sources / Math operations
458    ///
459    /// ## Description
460    /// Computes $s_1 x_1 + s_2 x_2 + \dots$ with one sign per input (`+1.0`/`-1.0` for an
461    /// error junction; any number is allowed, so a weighted average is the same block with
462    /// fractional signs). Input-shape rule (shared with `Product`): all-`Scalar` inputs give a
463    /// `Scalar`; otherwise every input must be a `Vector` of one common length `N`, reduced
464    /// elementwise to a `Vector(N)` — a mix of `Scalar` and `Vector` inputs is rejected rather
465    /// than guessed at (an N-input reduction has no unambiguous placement for a lone scalar
466    /// once more than one vector is already present).
467    ///
468    /// ## Parameters
469    /// - `inputs=<sig1,sig2,...>` — comma-separated input signals, one per term.
470    /// - `signs=<s1,s2,...>` — one sign (any number) per input, comma-separated, exactly as many
471    ///   entries as `inputs` has.
472    ///
473    /// ## Errors
474    /// - `inputs` and `signs` counts differ — rejected at parse time:
475    ///   `'inputs' has 2 entries but 'signs' has 1 (need one sign per input)`.
476    /// - A `signs` entry that is not a number — rejected at parse time:
477    ///   `field 'signs' entry 'x' is not a number`.
478    /// - Mixed `Scalar`/`Vector` inputs — rejected at evaluation time:
479    ///   `VectorSignalNotSupported { block: "<name>" }`.
480    /// - `Vector` inputs of differing lengths — rejected at evaluation time:
481    ///   `VectorSignalSizeMismatch { block: "<name>", expected: N, got: M }`.
482    /// - A missing `inputs=`/`signs=` is the generic `missing field '<key>'` error — see
483    ///   [`BlockInstance`]'s own doc comment.
484    ///
485    /// ## Netlist form
486    /// ```text
487    /// NAME kind=sum inputs=<sig1,sig2,...> signs=<s1,s2,...>
488    /// ```
489    ///
490    /// ## Example
491    /// An error junction (`A - B`) and an elementwise vector sum:
492    /// ```text
493    /// A kind=const value=3
494    /// B kind=const value=1
495    /// ERR kind=sum inputs=A,B signs=1,-1
496    /// OA kind=const value=[1,2]
497    /// OB kind=const value=[10,20]
498    /// VSUM kind=sum inputs=OA,OB signs=1,1
499    /// ```
500    Sum(Vec<f64>),
501    /// <!-- component -->
502    /// # Gain
503    /// **Purpose:** scales its single input — a plain factor, or a full matrix-vector product.
504    /// **Library:** Sources / Math operations
505    ///
506    /// ## Description
507    /// `k` as a plain number (`Scalar`): `Scalar -> Scalar` (`k*x`), or `Vector(N) ->
508    /// Vector(N)` (every element scaled by `k`, broadcast). `k` as a matrix (`[[...],[...]]`,
509    /// an `M x N` matrix, row-major `matrix[row][col]`): requires a `Vector` input of length
510    /// exactly `N`, and outputs `Vector(M)`, the matrix-vector product $K\,x$ — the one math
511    /// block that changes a signal's length. A flat list (`k=[1,2,3]`) is not a valid `Gain`
512    /// shape at all (unlike `Const`, `Gain`'s own value is never itself a vector) and is
513    /// rejected at parse time.
514    ///
515    /// ## Parameters
516    /// - `in=<signal>` — the single input.
517    /// - `k=<f64>` — a plain scale factor.
518    /// - `k=[[r1...],[r2...],...]` — an `M x N` matrix (Python-style nested list, row-major);
519    ///   the input must be a `Vector` of length `N`, the output is `Vector(M)`.
520    ///
521    /// ## Errors
522    /// - `k=[1,2,3]` (flat list) — rejected at parse time: `field 'k' must be a scalar (e.g.
523    ///   '2.0') or a matrix (e.g. '[[1,0],[0,1]]') -- got a flat list '[1,2,3]', which is not a
524    ///   valid Gain shape`.
525    /// - `k=abc` — rejected at parse time: `field 'k' is not a number`.
526    /// - A matrix `k` with a `Scalar` input — rejected at evaluation time:
527    ///   `VectorSignalNotSupported { block: "<name>" }`.
528    /// - A matrix `k` with a `Vector` input whose length isn't `N` — rejected at evaluation
529    ///   time: `VectorSignalSizeMismatch { block: "<name>", expected: N, got: M }`.
530    /// - A missing `in=`/`k=` is the generic `missing field '<key>'` error — see
531    ///   [`BlockInstance`]'s own doc comment.
532    ///
533    /// ## Netlist form
534    /// ```text
535    /// NAME kind=gain in=<signal> k=<f64> | k=[[r1...],[r2...],...]
536    /// ```
537    ///
538    /// ## Example
539    /// A scalar gain and a 2x3 matrix gain fed by a length-3 vector:
540    /// ```text
541    /// IN kind=const value=2
542    /// G kind=gain in=IN k=3
543    /// V kind=const value=[1,2,3]
544    /// M kind=gain in=V k=[[1,0,0],[0,1,0]]
545    /// ```
546    Gain(GainValue),
547    /// <!-- component -->
548    /// # PID Controller
549    /// **Purpose:** closed-loop error compensation with a filtered derivative and anti-windup.
550    /// **Library:** Control / Continuous
551    ///
552    /// ## Description
553    /// A parallel PID ($C(s) = K_p + \dfrac{K_i}{s} + \dfrac{K_d N s}{s + N}$, filtered-derivative
554    /// form — see `continuous_blocks::Pid`'s own doc comment for the transfer-function
555    /// derivation) with
556    /// two-sided conditional-integration anti-windup against `clamp`: while the compensator's
557    /// raw (unclamped) output would exceed `clamp`'s bound, the integral term stops
558    /// accumulating in the direction that would make the saturation worse, but keeps
559    /// integrating normally in the direction that would relieve it — so the controller recovers
560    /// immediately once the error's sign allows it to, instead of first having to "unwind" a
561    /// runaway integral term. `clamp` is this PID's own notion of "my output is saturated,"
562    /// independent of whatever downstream `Gain`/`Vco` block does to the value afterward — the
563    /// same role a real PID block's own configured output limits play.
564    ///
565    /// See [`PidClamp`] for the fixed-vs-dynamic choice, which also changes this block's own
566    /// input count (one, just the error signal, for `Fixed`; three — error, `clamp_lo`,
567    /// `clamp_hi` — for `Dynamic`). Reach for `Dynamic` specifically when the achievable output
568    /// range is itself state-dependent (e.g. a current-loop PID commanding a pole voltage that
569    /// can't physically exceed roughly half a DC bus voltage that is itself still rising during
570    /// a soft-start ramp) — a `Fixed` bound sized for the final steady-state range is badly
571    /// oversized early on, so anti-windup never engages even though the real plant is already
572    /// saturated far below that fixed bound, producing sustained, hard-to-diagnose
573    /// windup-driven oscillation.
574    ///
575    /// ## Parameters
576    /// - `in=<signal>` — the error signal (one input).
577    /// - `kp=<f64>`, `ki=<f64>`, `kd=<f64>` — proportional/integral/derivative gains. No sign or
578    ///   magnitude restriction (a negative gain is a legitimate, if unusual, choice depending on
579    ///   the plant's own sign convention).
580    /// - `n=<f64>` — the derivative filter coefficient (the filter pole sits at `-n`); must be
581    ///   `> 0`. A larger `n` tracks the ideal (unrealizable) pure derivative more closely, at the
582    ///   cost of stiffening the resulting ODE.
583    /// - Anti-windup bound, exactly one of:
584    ///   - `clamp_lo=<f64> clamp_hi=<f64>` — fixed bound ([`PidClamp::Fixed`]).
585    ///   - `clamp_lo_in=<signal> clamp_hi_in=<signal>` — read fresh from the graph every step
586    ///     ([`PidClamp::Dynamic`]), added as two extra inputs after the error signal, in that
587    ///     order.
588    /// - `ic=<f64>` — optional (default: start from rest); pre-loads the integrator so the
589    ///   controller output starts at this value with zero error — a bumpless start at a known
590    ///   operating point. Resolved through `continuous_blocks::TransferFunction::settled_state`
591    ///   on this PID's own transfer function.
592    ///
593    /// ## Errors
594    /// - `n <= 0.0` — rejected at parse time (`invalid PID (NonPositiveFilterCoefficient)`): a
595    ///   non-positive filter coefficient puts the derivative filter's pole at the origin or in
596    ///   the right half-plane, a non-causal or outright unstable filter.
597    /// - Giving only one of `clamp_lo_in`/`clamp_hi_in` (not both, and not neither) — rejected at
598    ///   parse time: `'clamp_lo_in'/'clamp_hi_in' must both be given together (dynamic clamp) or
599    ///   both omitted (fixed clamp= clamp_lo/clamp_hi)`.
600    /// - A missing or non-numeric field (`kp`/`ki`/`kd`/`n`/`clamp_lo`/`clamp_hi`) is the same
601    ///   generic `missing field '<key>'`/`field '<key>' is not a number` error every `kind=`
602    ///   block produces — see [`BlockInstance`]'s own doc comment.
603    /// - `ic=` with `ki=0` — rejected at parse time: `field 'ic' pre-loads the integrator, but
604    ///   this PID has ki=0 -- there is no integrator to hold it`.
605    ///
606    /// ## Netlist form
607    /// ```text
608    /// NAME kind=pid in=<signal> kp=<f64> ki=<f64> kd=<f64> n=<f64> \
609    ///      (clamp_lo=<f64> clamp_hi=<f64> | clamp_lo_in=<signal> clamp_hi_in=<signal>) [ic=<f64>]
610    /// ```
611    ///
612    /// ## Example
613    /// A fixed-clamp PI (no derivative action) regulating an error signal `ERR` to `[-1, 1]`:
614    /// ```text
615    /// PID1 kind=pid in=ERR kp=1 ki=0 kd=0 n=1 clamp_lo=-1 clamp_hi=1
616    /// ```
617    Pid {
618        /// The compiled PID gains/state.
619        pid: Pid,
620        /// The fixed-vs-dynamic anti-windup bound.
621        clamp: PidClamp,
622    },
623    /// <!-- component -->
624    /// # State-Space
625    /// **Purpose:** an arbitrary continuous-time linear block given directly as `(A, B, C, D)`
626    /// matrices.
627    /// **Library:** Control / Continuous
628    ///
629    /// ## Description
630    /// A compensator/filter that doesn't already have a named convenience constructor, e.g. a
631    /// low-pass filter placed ahead of a `Pid` to damp a resonant plant:
632    /// $\dot{x} = Ax + Bu, \quad y = Cx + Du$. Genuinely MIMO: `B`'s own column count
633    /// (`StateSpace::inputs()`) and `C`'s own row count (`StateSpace::outputs()`) are not
634    /// constrained to `1` — a single-input single-output declaration is simply the `1x1` case.
635    /// `outputs() == 1` produces a `SignalValue::Scalar`; `outputs() > 1` produces a
636    /// `SignalValue::Vector` of that length. Inputs are the flattened concatenation of this
637    /// block's own declared `Signal`s (scalar or vector, in order) — see `evaluate_blocks`'/
638    /// `dae-runtime`'s own input-flattening convention, shared with
639    /// `CoordinateTransform`/`Pmsm`/`CScript`. No anti-windup (that's specifically a `Pid`
640    /// output's own concern, not every dynamic block's); stepped forward unconditionally every
641    /// timestep via `StateSpace::rk4_step` (RK4, not backward Euler — this block's own state is
642    /// never part of the circuit's own descriptor-DAE solve).
643    ///
644    /// ## Parameters
645    /// - `a=<matrix>` — the `n x n` dynamics matrix, e.g. `a=[[0,1],[-1,-1]]`.
646    /// - `b=<matrix|vector>` — `n x p` (`p` inputs); a flat vector (`b=[1,0]`) is SISO shorthand
647    ///   for `p=1`, matching the pre-vector-signals convention unchanged.
648    /// - `c=<matrix|vector>` — `q x n` (`q` outputs); same flat-vector SISO shorthand for `q=1`.
649    /// - `d=<matrix|scalar>` — optional, defaults to an all-zero `q x n` matrix; a bare scalar
650    ///   is only accepted when `q=1` and `p=1` (SISO) — a MIMO system must give the full matrix,
651    ///   since a lone scalar has no unambiguous placement in a larger `D`.
652    /// - `in=<signal>` (SISO, `p` must be `1`) or `inputs=<sig1,...>` (exactly `p` entries,
653    ///   each independently scalar or vector; the *flattened* total length must equal `p`,
654    ///   checked at evaluation time, not parse time, since a vector signal's own arity isn't
655    ///   knowable from netlist text alone).
656    /// - `ic=[x1,...,xn]` — optional (default: every state zero); the initial state vector
657    ///   $x(0)$, one entry per state. A bare number (`ic=2`) is accepted for a one-state system.
658    ///
659    /// ## Errors
660    /// - `q != 1 || p != 1` with a bare scalar `d=` — rejected at parse time: `field 'd' is a
661    ///   bare scalar, but this system has <q> output(s) and <p> input(s) -- declare
662    ///   'd=[[...],...]' (<q>x<p>) for a MIMO system, a bare scalar is only valid for a 1x1
663    ///   (SISO) one`.
664    /// - There is no `e=` (descriptor-matrix) field exposed at the netlist level yet, so
665    ///   `StateSpaceError::NonInvertibleDescriptorMatrix` (a singular descriptor matrix) is
666    ///   currently unreachable through this parser — `e` is always `None` (ordinary,
667    ///   non-descriptor state-space) for every netlist-declared instance.
668    /// - `ic=` with a number of entries other than the block's own state count — rejected at
669    ///   parse time: `field 'ic' has <m> value(s), but this block has <n> state(s)`.
670    ///
671    /// ## Netlist form
672    /// ```text
673    /// NAME kind=statespace a=<matrix> b=<matrix|vector> c=<matrix|vector> [d=<matrix|scalar>] \
674    ///      (in=<signal> | inputs=<sig1,sig2,...>) [ic=<vector>]
675    /// ```
676    ///
677    /// ## Example
678    /// A first-order low-pass ($\dot{x} = -x + u$, $y = x$, pole at $s=-1$) — verified end to
679    /// end, `SRC=1` settling toward `SS1=1`:
680    /// ```text
681    /// SRC kind=const value=1
682    /// SS1 kind=statespace a=[[-1]] b=[1] c=[1] in=SRC
683    /// ```
684    StateSpace(StateSpace),
685    /// <!-- component -->
686    /// # Transfer Function
687    /// **Purpose:** a single-input single-output block given as a rational $N(s)/D(s)$.
688    /// **Library:** Control / Continuous
689    ///
690    /// ## Description
691    /// Numerator/denominator coefficients, highest-degree first, rather than a `Pid`'s
692    /// `Kp`/`Ki`/`Kd` convenience parameterization — e.g. a hand-derived PID-with-filtered-
693    /// derivative compensator ($C(s) = K_p + K_i/s + K_d N s/(s+N)$, put over one denominator
694    /// first: a pure derivative term alone is non-causal/unrealizable, so every real PID,
695    /// textbook or otherwise, filters it — see `continuous_blocks::Pid::to_transfer_function`'s
696    /// own doc comment for the derivation). Compiled once via
697    /// `TransferFunction::to_state_space` (controllable canonical form); no anti-windup, for
698    /// the same reason [`BlockKind::StateSpace`] above has none.
699    ///
700    /// ## Parameters
701    /// - `num=<vector>` — numerator coefficients, highest-degree first, e.g. `num=[1,2]` for
702    ///   $s + 2$.
703    /// - `den=<vector>` — denominator coefficients, highest-degree first, e.g. `den=[1,3,2]`
704    ///   for $s^2 + 3s + 2$. Must be non-empty and nonzero-leading; `deg(num) <= deg(den)`
705    ///   (a proper transfer function — every realizable continuous-time physical system is).
706    /// - `in=<signal>` — the single input (one input, always — this block is SISO by
707    ///   definition).
708    /// - `ic=[x1,...,xn]` — optional (default: every state zero); the initial state of the
709    ///   controllable canonical realization (see
710    ///   `continuous_blocks::TransferFunction::to_state_space`), $n = \deg(\text{den})$ entries.
711    ///   With the denominator made monic, $x_1$ is the state whose $k$-th derivative is
712    ///   $x_{k+1}$, and the output is $y = \sum_i b_i x_{i+1} + d\,u$.
713    /// - `y0=<f64>` — optional, mutually exclusive with `ic=`; starts the filter already settled
714    ///   at output $y_0$: $x = (y_0 / N(0), 0, \dots, 0)$ with $N(0)$ the normalized numerator's
715    ///   constant term (see `continuous_blocks::TransferFunction::settled_state`). Fed the
716    ///   matching constant input $u = y_0 / G(0)$ the output stays at $y_0$ exactly; a pole at
717    ///   the origin is fine (the matching input is then $0$).
718    ///
719    /// ## Errors
720    /// - `den=[]` (empty) — rejected at parse time: `invalid transfer function
721    ///   (EmptyDenominator)`.
722    /// - `den`'s first (highest-degree) coefficient is `0.0` — rejected: `invalid transfer
723    ///   function (ZeroLeadingDenominatorCoefficient)` (a zero leading coefficient means the
724    ///   stated degree is a lie — the true denominator degree is lower).
725    /// - `deg(num) > deg(den)` (more numerator coefficients than denominator ones) — rejected:
726    ///   `invalid transfer function (ImproperTransferFunction)` — an improper transfer function
727    ///   has no causal realization.
728    /// - `ic=` with a number of entries other than the block's own state count — rejected at
729    ///   parse time: `field 'ic' has <m> value(s), but this block has <n> state(s)`.
730    /// - `ic=` and `y0=` both given — rejected at parse time: `'ic' (the state vector) and 'y0'
731    ///   (the settled output) both set an initial condition -- give one or the other`.
732    /// - `y0=` on a transfer function whose numerator is zero at DC — rejected at parse time:
733    ///   `field 'y0': this transfer function's numerator is zero at DC, so its settled output is
734    ///   always 0 and no state holds the requested one`.
735    ///
736    /// ## Netlist form
737    /// ```text
738    /// NAME kind=tf num=<vector> den=<vector> in=<signal> [ic=<vector> | y0=<f64>]
739    /// ```
740    ///
741    /// ## Example
742    /// The same first-order low-pass as `StateSpace`'s own example ($1/(s+1)$), verified to
743    /// settle toward the same steady-state value:
744    /// ```text
745    /// SRC kind=const value=1
746    /// TF1 kind=tf num=[1] den=[1,1] in=SRC
747    /// ```
748    TransferFunction(TransferFunction),
749    /// <!-- component -->
750    /// # Discrete State-Space
751    /// **Purpose:** the discrete-domain counterpart to `StateSpace` — a plain linear recursion.
752    /// **Library:** Control / Discrete
753    ///
754    /// ## Description
755    /// $x_{i+1} = Ax_i + Bu_i$, $y_i = Cx_i + Du_i$ — no RK4, no `dt` at all: `A`/`B`/`C`/`D`
756    /// are already discrete-domain matrices, given directly by the netlist author, not derived
757    /// from continuous ones. `sample_time` is **required** here (unlike `cscript`'s own
758    /// optional field) and must be periodic — a discrete system's own dynamics *are* its
759    /// sample period, there is no "continuous" fallback the way omitting it means for
760    /// `cscript`, and a solver-chosen variable schedule doesn't compose with a fixed-period
761    /// recursion at all. See `general-simulator`'s own `book/dev-guide/src/discrete-time-blocks.md`.
762    ///
763    /// ## Parameters
764    /// - `a=`/`b=`/`c=`/`d=`/`in=`/`inputs=` — identical shape and MIMO rules to
765    ///   [`BlockKind::StateSpace`]'s own Parameters (see there); the only difference is these
766    ///   matrices are already discrete-domain.
767    /// - `ts=<f64>` / `freq=<f64>` (with optional `to=<f64>` offset) — required; unlike
768    ///   `cscript`, `ts=variable` is not accepted here (see Errors).
769    /// - `ic=[x1,...,xn]` — optional (default: every state zero); the initial state vector
770    ///   $x_0$, one entry per state (a bare number for a one-state system). With a nonzero
771    ///   sample `offset`, the output held before the first sample hit is $C\,x_0$.
772    ///
773    /// ## Errors
774    /// - Same MIMO scalar-`d` rejection as `StateSpace` (see there).
775    /// - `ts=`/`freq=` missing entirely — rejected at parse time: `missing 'ts=' or 'freq='
776    ///   -- a discrete-time block's own sample period is not optional (its dynamics *are* that
777    ///   period), unlike the optional 'ts='/'freq=' on kind=cscript/pyblock/pyfunc`.
778    /// - `ts=variable` — rejected at parse time: `ts=variable is not available here -- a
779    ///   discrete block's own recursion has its coefficients baked in at one fixed sample
780    ///   period, which 'the block decides its own next execution time' doesn't compose with`.
781    /// - `ic=` with a number of entries other than the block's own state count — rejected at
782    ///   parse time: `field 'ic' has <m> value(s), but this block has <n> state(s)`.
783    ///
784    /// ## Netlist form
785    /// ```text
786    /// NAME kind=discretestatespace a=<matrix> b=<matrix|vector> c=<matrix|vector> \
787    ///      [d=<matrix|scalar>] (ts=<f64> | freq=<f64> [to=<f64>]) \
788    ///      (in=<signal> | inputs=<sig1,sig2,...>) [ic=<vector>]
789    /// ```
790    ///
791    /// ## Example
792    /// A discrete integrator ($x_{i+1} = x_i + 0.1 \cdot u_i$, $y=x$, `ts=0.1`) fed a constant
793    /// `1` — verified end to end, `DS1` reaching `0.5` after 5 sample hits ($5 \times 0.1$):
794    /// ```text
795    /// SRC kind=const value=1
796    /// DS1 kind=discretestatespace a=[[1]] b=[0.1] c=[1] ts=0.1 in=SRC
797    /// ```
798    DiscreteStateSpace {
799        /// The discrete-domain `A`/`B`/`C`/`D` matrices.
800        ss: StateSpace,
801        /// Must be [`SampleTimeSpec::Periodic`] — a discrete system's dynamics are its sample period.
802        sample_time: SampleTimeSpec,
803    },
804    /// <!-- component -->
805    /// # Discrete Transfer Function
806    /// **Purpose:** the discrete-domain counterpart to `Transfer Function` — $Y(z)/U(z) = N(z)/D(z)$.
807    /// **Library:** Control / Discrete
808    ///
809    /// ## Description
810    /// Coefficients already in the $z$-domain. Realized via the exact same
811    /// `TransferFunction::to_state_space` the continuous version uses (coefficient-to-
812    /// companion-form conversion is domain-agnostic algebra — it doesn't know or care whether
813    /// the variable is called $s$ or $z$), evaluated via `StateSpace::discrete_step` instead of
814    /// `rk4_step`. Same mandatory-periodic-`sample_time` rule as [`BlockKind::DiscreteStateSpace`].
815    ///
816    /// ## Parameters
817    /// - `num=`/`den=`/`in=` — identical shape and validity rules to
818    ///   [`BlockKind::TransferFunction`]'s own Parameters (see there); coefficients are already
819    ///   in the $z$-domain rather than $s$.
820    /// - `ts=<f64>` / `freq=<f64>` (with optional `to=<f64>`) — required, same rule as
821    ///   `DiscreteStateSpace`.
822    /// - `ic=[x1,...,xn]` — optional (default: every state zero); the initial state of the same
823    ///   controllable canonical realization as [`BlockKind::TransferFunction`]'s own `ic=`,
824    ///   stepped as a difference equation.
825    /// - `y0=<f64>` — optional, mutually exclusive with `ic=`; starts the filter already settled
826    ///   at output $y_0$ — every canonical state equal to $y_0 / N(1)$, with $N(1)$ the
827    ///   normalized numerator evaluated at $z = 1$ (see
828    ///   `continuous_blocks::TransferFunction::settled_state_discrete`). Fed the matching
829    ///   constant input $u = y_0 / H(1)$ the output stays at $y_0$ exactly.
830    ///
831    /// ## Errors
832    /// Identical to [`BlockKind::TransferFunction`]'s own (`EmptyDenominator`,
833    /// `ZeroLeadingDenominatorCoefficient`, `ImproperTransferFunction`), plus the same
834    /// missing-`ts=`/`ts=variable`-rejected errors as `DiscreteStateSpace`.
835    /// - `ic=` and `y0=` both given — rejected at parse time: `'ic' (the state vector) and 'y0'
836    ///   (the settled output) both set an initial condition -- give one or the other`.
837    /// - `y0=` on a transfer function whose numerator is zero at DC — rejected at parse time:
838    ///   `field 'y0': this transfer function's numerator is zero at DC, so its settled output is
839    ///   always 0 and no state holds the requested one`.
840    ///
841    /// ## Netlist form
842    /// ```text
843    /// NAME kind=discretetf num=<vector> den=<vector> (ts=<f64> | freq=<f64> [to=<f64>]) in=<signal> \
844    ///      [ic=<vector> | y0=<f64>]
845    /// ```
846    ///
847    /// ## Example
848    /// The exact $z$-domain realization of `DiscreteStateSpace`'s own example above ($Y(z)/U(z)
849    /// = 0.1/(z-1)$, a discrete integrator) — verified to reach the same `DTF1=0.5` after 5
850    /// sample hits:
851    /// ```text
852    /// SRC kind=const value=1
853    /// DTF1 kind=discretetf num=[0.1] den=[1,-1] ts=0.1 in=SRC
854    /// ```
855    DiscreteTransferFunction {
856        /// The `z`-domain numerator/denominator coefficients.
857        tf: TransferFunction,
858        /// Must be [`SampleTimeSpec::Periodic`].
859        sample_time: SampleTimeSpec,
860    },
861    /// <!-- component -->
862    /// # Discrete PID Controller
863    /// **Purpose:** the discrete-domain counterpart to `PID Controller`.
864    /// **Library:** Control / Discrete
865    ///
866    /// ## Description
867    /// Reuses the exact same [`PidClamp`] anti-windup mechanism as [`BlockKind::Pid`], but the
868    /// integral/derivative actions advance once per declared sample period via
869    /// `continuous_blocks::DiscretePid::step` instead of RK4-integrating continuously. Not
870    /// built by converting to one combined $z$-domain transfer function and back — realized
871    /// directly from the block's own diagram (three parallel branches, summed). Same
872    /// mandatory-periodic-`sample_time` rule as `DiscreteStateSpace`/`DiscreteTransferFunction`
873    /// above — this block's own integration `period` is set *from* `sample_time`, not a
874    /// separately-entered value.
875    ///
876    /// ## Parameters
877    /// - `in=<signal>`, `kp=`/`ki=`/`kd=`/`n=`, and the fixed-vs-dynamic clamp fields
878    ///   (`clamp_lo=`/`clamp_hi=` or `clamp_lo_in=`/`clamp_hi_in=`) — identical meaning to
879    ///   [`BlockKind::Pid`]'s own Parameters (see there).
880    /// - `ts=<f64>` / `freq=<f64>` (with optional `to=<f64>`) — required.
881    /// - `integration_method=<forward|backward|trapezoidal>` — optional, defaults to
882    ///   `forward` (forward Euler); selects the discrete integration rule the integral term
883    ///   uses each sample period.
884    /// - `ic=<f64>` — optional (default: start from rest); pre-loads the integrator so the
885    ///   controller output starts at this value with zero error (the integrator's accumulated
886    ///   value is set to $\text{ic}/k_i$).
887    ///
888    /// ## Errors
889    /// - Same `n <= 0.0` and clamp-pairing errors as [`BlockKind::Pid`] (see there).
890    /// - Same missing-`ts=`/`ts=variable`-rejected errors as `DiscreteStateSpace`.
891    /// - `integration_method` present but not one of the three known names — rejected at parse
892    ///   time: `unknown integration_method '<value>' (expected 'forward', 'backward', or
893    ///   'trapezoidal')`.
894    /// - `ic=` with `ki=0` — rejected at parse time: `field 'ic' pre-loads the integrator, but
895    ///   this PID has ki=0 -- there is no integrator to hold it`.
896    ///
897    /// ## Netlist form
898    /// ```text
899    /// NAME kind=discretepid in=<signal> kp=<f64> ki=<f64> kd=<f64> n=<f64> \
900    ///      (ts=<f64> | freq=<f64> [to=<f64>]) \
901    ///      (clamp_lo=<f64> clamp_hi=<f64> | clamp_lo_in=<signal> clamp_hi_in=<signal>) \
902    ///      [integration_method=<forward|backward|trapezoidal>] [ic=<f64>]
903    /// ```
904    ///
905    /// ## Example
906    /// A discrete PI (no derivative action) sampled every 0.1 s, integrating a fixed error
907    /// signal once per sample hit — verified end to end, `DPID1` stepping `0.5 -> 0.525 -> 0.55
908    /// -> 0.575 -> 0.6` at each `ts=0.1` boundary (unchanged between hits, matching the
909    /// discrete-recursion contract exactly):
910    /// ```text
911    /// ERR kind=const value=0.5
912    /// DPID1 kind=discretepid in=ERR kp=1 ki=0.5 kd=0 n=1 ts=0.1 clamp_lo=-1 clamp_hi=1
913    /// ```
914    DiscretePid {
915        /// The compiled discrete PID gains/state.
916        pid: DiscretePid,
917        /// The fixed-vs-dynamic anti-windup bound.
918        clamp: PidClamp,
919        /// Must be [`SampleTimeSpec::Periodic`]; also sets `pid`'s own `period`.
920        sample_time: SampleTimeSpec,
921    },
922    /// <!-- component -->
923    /// # VCO (Voltage-Controlled Oscillator)
924    /// **Purpose:** a bare, standalone oscillator producing a `[0, 1)` ramp from a frequency input.
925    /// **Library:** Control / Continuous
926    ///
927    /// ## Description
928    /// A raw frequency-to-ramp conversion, still useful on its own outside gate-driving PWM —
929    /// e.g. feeding a `MathFn1::Sin`/`Gain` chain to build a variable-frequency sinusoidal
930    /// reference. Not how a gate-driving PWM modulator gets its own switching frequency, though
931    /// — see [`BlockKind::Pwm`]/[`BlockKind::PhaseShiftPwm`] below, neither of which reads this
932    /// block at all (each owns its own internal oscillator).
933    ///
934    /// ## Parameters
935    /// - `f_min=<f64>`, `f_max=<f64>` — the frequency clamp range, Hz; the one input (`in=`) is
936    ///   internally clamped to `[f_min, f_max]` before integration.
937    /// - `in=<signal>` — the frequency command, Hz (one input).
938    /// - `ic=<f64>` — optional (default `0`); the initial phase, in cycles,
939    ///   $0 \le \text{ic} < 1$.
940    ///
941    /// ## Errors
942    /// - `f_min > f_max` — rejected at parse time: `invalid vco (FMinExceedsFMax)`.
943    /// - `ic=` outside $0 \le \text{ic} < 1$ — rejected at parse time: `field 'ic' is the initial
944    ///   phase in cycles and must satisfy 0 <= ic < 1 (got <value>)`.
945    ///
946    /// ## Netlist form
947    /// ```text
948    /// NAME kind=vco f_min=<f64> f_max=<f64> in=<signal> [ic=<f64>]
949    /// ```
950    ///
951    /// ## Example
952    /// A fixed 10 Hz oscillator, verified to produce a `[0,1)` ramp (not stuck at a constant):
953    /// ```text
954    /// FREQ kind=const value=10
955    /// VCO1 kind=vco f_min=1 f_max=1000 in=FREQ
956    /// ```
957    Vco(Vco),
958    /// <!-- component -->
959    /// # PWM Modulator 1
960    /// **Purpose:** fixed-frequency, duty-driven, active-high complementary PWM.
961    /// **Library:** Power Electronics
962    ///
963    /// ## Description
964    /// One input, `duty` (`[0,1]`, clamped, read fresh every step from anywhere in the graph —
965    /// a `Pid`, a filtered `TransferFunction`, a plain `Const`...), fixed carrier frequency
966    /// `freq_hz`. Two outputs, following the [`BlockKind::CScript`] `output_names` convention:
967    /// `output_names[0]` (aliasing this block's own `.name`) is the main signal, `output_names[1]`
968    /// its active-high complement. `red`/`fed` (seconds) are independent per-edge dead-time
969    /// delays — see `math_ops::complementary_pwm_with_deadtime` (in `dae-runtime`) for the
970    /// exact rising-edge-only-delay semantics and why `red=fed=0.0` recovers the ideal,
971    /// gap-free, overlap-free pair exactly. Stateless: a pure function of `(t, duty)` every
972    /// step, no internal oscillator.
973    ///
974    /// ## Parameters
975    /// - `freq=<f64>` — fixed carrier frequency, Hz.
976    /// - `in=<signal>` — the duty command, `[0,1]` (clamped internally; no error for a value
977    ///   outside that range).
978    /// - `red=<f64>`, `fed=<f64>` — optional, default `0.0`; rising/falling-edge dead time,
979    ///   seconds.
980    /// - `outputs=<main,complement>` — optional; defaults to `<name>,<name>_comp`. Exactly 2
981    ///   entries if given.
982    ///
983    /// ## Errors
984    /// - `outputs=` with a count other than 2 — rejected at parse time: `'outputs' needs
985    ///   exactly 2 entries (main, complement; got <n>)`.
986    /// - `red=`/`fed=` present but not a number — the generic `field '<key>' is not a number`
987    ///   error.
988    ///
989    /// ## Netlist form
990    /// ```text
991    /// NAME kind=pwm freq=<f64> in=<signal> [red=<f64>] [fed=<f64>] [outputs=<main,complement>]
992    /// ```
993    ///
994    /// ## Example
995    /// A 10 kHz, 30% duty modulator with no dead time — verified end to end: `PWM1` high
996    /// (`>= 0.99`) for the first ~30% of each 100 µs period and its complement exactly
997    /// inverted, `PWM1 + PWM1_comp == 1` at every sampled instant:
998    /// ```text
999    /// DUTY kind=const value=0.3
1000    /// PWM1 kind=pwm freq=10000 in=DUTY
1001    /// ```
1002    Pwm {
1003        /// Fixed carrier frequency, Hz.
1004        freq_hz: f64,
1005        /// Rising-edge dead time, seconds.
1006        red: f64,
1007        /// Falling-edge dead time, seconds.
1008        fed: f64,
1009        /// `[main, complement]` output names.
1010        output_names: Vec<String>,
1011    },
1012    /// <!-- component -->
1013    /// # PWM Modulator 2 (Phase-Shift PWM)
1014    /// **Purpose:** frequency+phase+duty-driven, active-high complementary PWM with its own
1015    /// internal oscillator.
1016    /// **Library:** Power Electronics
1017    ///
1018    /// ## Description
1019    /// This is *not* a variant of [`BlockKind::Vco`] — it owns its own frequency-integration
1020    /// state directly (`osc` reuses [`Vco`]'s own clamp-and-integrate math purely as an
1021    /// implementation detail, the same formula, not a shared block reference), so two instances
1022    /// fed the *same* `freq` input stay bit-for-bit phase-synchronized (deterministic
1023    /// integration, same `dt`, same starting phase `0.0`), the way e.g. a dual-active-bridge's
1024    /// two legs need to be, without a separately-declared shared oscillator block in between.
1025    /// `red`/`fed` are in seconds, exactly like [`BlockKind::Pwm`]'s own, but converted to a
1026    /// phase fraction using *this step's own* resolved frequency (not a fixed constant) — this
1027    /// matters for a variable-frequency converter, since the same absolute dead time eats a
1028    /// larger fraction of the period at higher switching frequency, a real effect on e.g. a
1029    /// resonant converter's own ZVS margin, not just bookkeeping.
1030    ///
1031    /// ## Parameters
1032    /// - `f_min=<f64>`, `f_max=<f64>` — the internal oscillator's frequency clamp range, Hz.
1033    /// - `inputs=<freq,phase,duty>` — exactly 3, in this order: `freq` (Hz, clamped internally
1034    ///   to `[f_min, f_max]`), `phase` (`[0,1)`, a phase-shift command as a fraction of one
1035    ///   carrier period — *not* this block's own internal integration state, a different
1036    ///   thing; applied as a **lead**: conduction begins at $(1 - \text{phase})$ of the
1037    ///   carrier period, so `0.25` starts the pulse three quarters of the way through the
1038    ///   period, not one quarter — see the user guide's gate-bindings chapter for the run that
1039    ///   shows it), `duty` (`[0,1]`, clamped).
1040    /// - `red=<f64>`, `fed=<f64>` — optional, default `0.0`; seconds, converted internally to a
1041    ///   phase fraction using the current resolved frequency.
1042    /// - `outputs=<main,complement>` — optional; defaults to `<name>,<name>_comp`.
1043    /// - `ic=<f64>` — optional (default `0`); the carrier's own initial phase, in cycles,
1044    ///   $0 \le \text{ic} < 1$ — applied before, and independent of, the `phase` input's own
1045    ///   offset.
1046    ///
1047    /// ## Errors
1048    /// - `inputs=` with a count other than 3 — rejected at parse time: `kind='pspwm' needs 3
1049    ///   inputs (freq,phase,duty; got <n>)`.
1050    /// - `f_min > f_max` — rejected at parse time: `invalid pspwm oscillator
1051    ///   (FMinExceedsFMax)`.
1052    /// - `outputs=` with a count other than 2 — same error as [`BlockKind::Pwm`]'s own.
1053    /// - `ic=` outside $0 \le \text{ic} < 1$ — rejected at parse time: `field 'ic' is the initial
1054    ///   phase in cycles and must satisfy 0 <= ic < 1 (got <value>)`.
1055    ///
1056    /// ## Netlist form
1057    /// ```text
1058    /// NAME kind=pspwm f_min=<f64> f_max=<f64> inputs=<freq_signal,phase_signal,duty_signal> \
1059    ///      [red=<f64>] [fed=<f64>] [outputs=<main,complement>] [ic=<f64>]
1060    /// ```
1061    ///
1062    /// ## Example
1063    /// A 10 kHz, zero-phase-shift, 40% duty modulator — verified end to end: both outputs
1064    /// `[0,1]`-valued, `PSPWM1 + PSPWM1_comp == 1` at every sampled instant:
1065    /// ```text
1066    /// FREQ kind=const value=10000
1067    /// PHASE kind=const value=0
1068    /// DUTY kind=const value=0.4
1069    /// PSPWM1 kind=pspwm f_min=1000 f_max=50000 inputs=FREQ,PHASE,DUTY
1070    /// ```
1071    PhaseShiftPwm {
1072        /// The internal frequency-integrating oscillator.
1073        osc: Vco,
1074        /// Rising-edge dead time, seconds.
1075        red: f64,
1076        /// Falling-edge dead time, seconds.
1077        fed: f64,
1078        /// `[main, complement]` output names.
1079        output_names: Vec<String>,
1080    },
1081    /// <!-- component -->
1082    /// # Product
1083    /// **Purpose:** multiplies all its inputs together.
1084    /// **Library:** Sources / Math operations
1085    ///
1086    /// ## Description
1087    /// The product $x_1 \cdot x_2 \cdot \dots$ of its inputs. Input-shape rule shared with
1088    /// `Sum`: all-`Scalar` inputs give a `Scalar`; otherwise every input must be a `Vector` of
1089    /// one common length `N`, multiplied elementwise to a `Vector(N)` — a mix of `Scalar` and
1090    /// `Vector` inputs is rejected rather than guessed at (see the Sum entry).
1091    ///
1092    /// ## Parameters
1093    /// - `inputs=<sig1,sig2,...>` — comma-separated input signals, one per factor.
1094    ///
1095    /// ## Errors
1096    /// - Mixed `Scalar`/`Vector` inputs — rejected at evaluation time:
1097    ///   `VectorSignalNotSupported { block: "<name>" }`.
1098    /// - `Vector` inputs of differing lengths — rejected at evaluation time:
1099    ///   `VectorSignalSizeMismatch { block: "<name>", expected: N, got: M }`.
1100    /// - A missing `inputs=` is the generic `missing field 'inputs'` error — see
1101    ///   [`BlockInstance`]'s own doc comment.
1102    ///
1103    /// ## Netlist form
1104    /// ```text
1105    /// NAME kind=product inputs=<sig1,sig2,...>
1106    /// ```
1107    ///
1108    /// ## Example
1109    /// ```text
1110    /// A kind=const value=2
1111    /// B kind=const value=3
1112    /// C kind=const value=4
1113    /// P kind=product inputs=A,B,C
1114    /// ```
1115    Product,
1116    /// <!-- component -->
1117    /// # Saturation
1118    /// **Purpose:** clamps its single input to a symmetric ±limit.
1119    /// **Library:** Sources / Math operations
1120    ///
1121    /// ## Description
1122    /// Clamps its input to `[-limit, limit]` (elementwise for a `Vector` input) — the
1123    /// block-diagram saturation/limiter. See `continuous_blocks::math_ops::saturation`'s own
1124    /// doc comment for why this is a plain direct evaluation rather than a PWL device: the
1125    /// active segment depends only on this block's own input, so there is no
1126    /// simultaneous-resolution problem the way there is for a diode's terminal voltage.
1127    ///
1128    /// ## Parameters
1129    /// - `in=<signal>` — the single input.
1130    /// - `limit=<f64>` — the symmetric bound. Must be non-negative — but this is **not** checked
1131    ///   at parse time; a negative `limit` panics the process at the first evaluation (see
1132    ///   Errors).
1133    ///
1134    /// ## Errors
1135    /// - `limit=-1` — not a clean error: parse time never validates `limit`, so the evaluation
1136    ///   code's own assert fires and the whole process panics with
1137    ///   `limit must be nonnegative`. Keep `limit >= 0`.
1138    /// - A missing `in=`/`limit=` or a non-numeric `limit=` is the generic
1139    ///   `missing field '<key>'`/`field '<key>' is not a number` error — see
1140    ///   [`BlockInstance`]'s own doc comment.
1141    ///
1142    /// ## Netlist form
1143    /// ```text
1144    /// NAME kind=saturation in=<signal> limit=<f64>
1145    /// ```
1146    ///
1147    /// ## Example
1148    /// The time ramp (0..2 s) clamped to ±1 — passes through while `|x| <= 1`, holds 1 beyond:
1149    /// ```text
1150    /// X kind=time
1151    /// LIM kind=saturation in=X limit=1
1152    /// ```
1153    Saturation(f64),
1154    /// <!-- component -->
1155    /// # Table Lookup
1156    /// **Purpose:** linear interpolation through a fixed `(x, y)` table.
1157    /// **Library:** Sources / Math operations
1158    ///
1159    /// ## Description
1160    /// A `table(x, a, b, c, d, ...)`-style lookup: linear interpolation through the fixed
1161    /// `(x, y)` breakpoints (elementwise for a `Vector` input), clamped — not extrapolated —
1162    /// outside the range, holding the nearest endpoint's `y`. Implemented by
1163    /// `continuous_blocks::waveform_arithmetic::table`.
1164    ///
1165    /// ## Parameters
1166    /// - `in=<signal>` — the single input (`x`).
1167    /// - `points=[[x1,y1],[x2,y2],...]` — the lookup table as a Python list of 2-element lists.
1168    ///   Sorted ascending by `x` at parse time, so declaration order doesn't matter. Must have
1169    ///   at least one point — but that is **not** checked at parse time; an empty list panics
1170    ///   the process at the first evaluation (see Errors).
1171    ///
1172    /// ## Errors
1173    /// - A `points=` entry that is not a 2-element `[x,y]` list — rejected at parse time:
1174    ///   `field 'points': each entry must be a 2-element '[x,y]' list (got '[1.0]')`.
1175    /// - `points=[]` — not a clean error: parse time never rejects an empty list, so the
1176    ///   evaluation code's own assert fires and the whole process panics with
1177    ///   `table needs at least one point`.
1178    /// - A missing `in=`/`points=` is the generic `missing field '<key>'` error — see
1179    ///   [`BlockInstance`]'s own doc comment.
1180    ///
1181    /// ## Netlist form
1182    /// ```text
1183    /// NAME kind=table in=<signal> points=[[x1,y1],[x2,y2],...]
1184    /// ```
1185    ///
1186    /// ## Example
1187    /// A trapezoid profile (ramp up, flat, ramp down, held at 0) driven by the time ramp:
1188    /// ```text
1189    /// X kind=time
1190    /// T kind=table in=X points=[[0,0],[1,10],[2,10],[3,0]]
1191    /// ```
1192    Table(Vec<(f64, f64)>),
1193    /// <!-- component -->
1194    /// # Waveform Arithmetic Functions (unary)
1195    /// **Purpose:** one of the 26 single-argument real functions — trig, exponential/log,
1196    /// rounding, sign, step — as a stateless block.
1197    /// **Library:** Sources / Math operations
1198    ///
1199    /// ## Description
1200    /// One entry for the whole unary family: every member is a pure `Scalar -> Scalar` function
1201    /// (elementwise `Vector -> Vector` for a `Vector` input), selected by its own `kind=` name,
1202    /// so they all share one input/error contract. Each name maps onto the same-named `f64`
1203    /// method where one exists (`continuous_blocks::waveform_arithmetic::MathFn1::call`), with
1204    /// the same domain/range behavior — trig in radians, `sqrt`/`ln` NaN for negative
1205    /// arguments, and so on. What the library as a whole deliberately leaves out (a
1206    /// finite-difference derivative, noise/random generators, complex-data functions, boolean
1207    /// comparison operators) is argued in `continuous_blocks::waveform_arithmetic`'s own module
1208    /// doc comment.
1209    ///
1210    /// | name | formula | notes |
1211    /// |---|---|---|
1212    /// | `abs` | $|x|$ | |
1213    /// | `acos` | $\arccos x$ | |
1214    /// | `acosh` | $\operatorname{arcosh} x$ | |
1215    /// | `asin` | $\arcsin x$ | |
1216    /// | `asinh` | $\operatorname{arsinh} x$ | |
1217    /// | `atan` | $\arctan x$ | |
1218    /// | `atanh` | $\operatorname{artanh} x$ | |
1219    /// | `buf` | $1$ if $x > 0.5$ else $0$ | threshold/buffer, companion to `inv` |
1220    /// | `ceil` | $\lceil x \rceil$ | |
1221    /// | `cos` | $\cos x$ | radians |
1222    /// | `cosh` | $\cosh x$ | |
1223    /// | `exp` | $e^x$ | |
1224    /// | `floor` | $\lfloor x \rfloor$ | |
1225    /// | `int` | truncation toward zero | |
1226    /// | `inv` | $0$ if $x > 0.5$ else $1$ | complement of `buf` |
1227    /// | `ln` | $\ln x$ | natural log |
1228    /// | `log10` | $\log_{10} x$ | |
1229    /// | `round` | round half away from zero | |
1230    /// | `sgn` | $-1$/$0$/$1$ | sign; 0 at the origin (unlike `f64::signum`, which returns 1 there) |
1231    /// | `sin` | $\sin x$ | radians |
1232    /// | `sinh` | $\sinh x$ | |
1233    /// | `sqrt` | $\sqrt{x}$ | |
1234    /// | `tan` | $\tan x$ | radians |
1235    /// | `tanh` | $\tanh x$ | |
1236    /// | `u` | $1$ if $x > 0$ else $0$ | unit step |
1237    /// | `uramp` | $x$ if $x > 0$ else $0$ | ramp that starts at the origin (Relu) |
1238    ///
1239    /// ## Parameters
1240    /// - `in=<signal>` — the single argument.
1241    ///
1242    /// ## Errors
1243    /// - A misspelled/unknown name (`kind=cosx`) — rejected at parse time:
1244    ///   `unknown device kind 'cosx'`.
1245    /// - A missing `in=` is the generic `missing field 'in'` error — see [`BlockInstance`]'s own
1246    ///   doc comment.
1247    ///
1248    /// ## Netlist form
1249    /// ```text
1250    /// NAME kind=<fn> in=<signal>
1251    /// ```
1252    ///
1253    /// ## Example
1254    /// `sin(2*pi*1000*t)` built from ordinary blocks, plus `cos`/`exp` and the elementwise
1255    /// vector form:
1256    /// ```text
1257    /// T kind=time
1258    /// G kind=gain in=T k=6283.185307179586
1259    /// S kind=sin in=G
1260    /// C kind=cos in=G
1261    /// E kind=exp in=T
1262    /// SV kind=const value=[1,4,9]
1263    /// SQ kind=sqrt in=SV
1264    /// ```
1265    MathFn1(MathFn1),
1266    /// <!-- component -->
1267    /// # Waveform Arithmetic Functions (binary)
1268    /// **Purpose:** one of the eight two-argument real functions — `atan2`/`hypot`/`pow` family,
1269    /// `min`/`max`, `anglewrap` — as a stateless block.
1270    /// **Library:** Sources / Math operations
1271    ///
1272    /// ## Description
1273    /// One entry for the whole binary family: every member is a pure two-argument function
1274    /// selected by its own `kind=` name, taking `in1=`/`in2=` in that order. Input-shape rule:
1275    /// two `Scalar`s give a `Scalar`; otherwise every `Vector` operand must share one length
1276    /// `N` (elementwise application, with a lone `Scalar` operand broadcast against it).
1277    ///
1278    /// | name | formula | notes |
1279    /// |---|---|---|
1280    /// | `atan2` | $\operatorname{atan2}(x, y)$ | Rust's `x.atan2(y)`: the four-quadrant angle whose tangent is `x/y` |
1281    /// | `anglewrap` | $\operatorname{atan2}(\beta, \alpha)$ wrapped to $[0, 2\pi)$ | takes `(alpha, beta)`; the angle-tracking half of a synchronous-reference-frame PLL — see below |
1282    /// | `hypot` | $\sqrt{x^2 + y^2}$ | |
1283    /// | `max` | $\max(x, y)$ | |
1284    /// | `min` | $\min(x, y)$ | |
1285    /// | `pow` | $x^y$ | plain `f64::powf` (negative base with non-integer exponent is NaN) |
1286    /// | `pwr` | $|x|^y$ | like `pow` but always real-valued (a negative base raised to a non-integer power would otherwise be complex) |
1287    /// | `pwrs` | $\operatorname{sgn}(x)\,|x|^y$ | `pwr` with `x`'s original sign reapplied — odd-symmetric |
1288    ///
1289    /// `anglewrap` is the special member: `(alpha, beta) -> theta` — the `atan2(beta, alpha)`
1290    /// angle shifted by a full turn when negative, so `theta` stays in `[0, 2*pi)` and is a
1291    /// monotonically-sensible input to `park`/`clarke_park` across a full revolution — the
1292    /// angle-tracking half of a synchronous-reference-frame PLL (see
1293    /// `continuous_blocks::coordinate_transforms::anglewrap`, whose output feeds `park`/
1294    /// `clarke_park`). It lives here rather than with the Clarke/Park transforms because it is
1295    /// single-output: an ordinary two-argument function like every other member.
1296    ///
1297    /// ## Parameters
1298    /// - `in1=<signal>` `in2=<signal>` — the two arguments, in formula order above.
1299    ///
1300    /// ## Errors
1301    /// - A misspelled/unknown name — the same `unknown device kind '<name>'` error as the
1302    ///   unary entry.
1303    /// - `Vector` operands of differing lengths — rejected at evaluation time:
1304    ///   `VectorSignalSizeMismatch { block: "<name>", expected: N, got: M }`.
1305    /// - A missing `in1=`/`in2=` is the generic `missing field '<key>'` error — see
1306    ///   [`BlockInstance`]'s own doc comment.
1307    ///
1308    /// ## Netlist form
1309    /// ```text
1310    /// NAME kind=<fn> in1=<signal> in2=<signal>
1311    /// ```
1312    ///
1313    /// ## Example
1314    /// The textbook 3-4-5 triangle, and the same pair's `anglewrap` result (`atan2(4,3)` ~
1315    /// 0.9273 rad):
1316    /// ```text
1317    /// X kind=const value=3
1318    /// Y kind=const value=4
1319    /// H kind=hypot in1=X in2=Y
1320    /// AW kind=anglewrap in1=X in2=Y
1321    /// ```
1322    MathFn2(MathFn2),
1323    /// <!-- component -->
1324    /// # Waveform Arithmetic Functions (ternary: if, limit)
1325    /// **Purpose:** a threshold select (`if`) and a clamp (`limit`) — the two three-argument
1326    /// functions.
1327    /// **Library:** Sources / Math operations
1328    ///
1329    /// ## Description
1330    /// One entry for the two three-argument functions — genuinely different semantics, but one
1331    /// shared input/error contract (documented at the type's own granularity). Both take
1332    /// `in1=`/`in2=`/`in3=` in the order below, and both use the binary entry's `Scalar`/
1333    /// `Vector` rule unchanged.
1334    ///
1335    /// | name | formula | notes |
1336    /// |---|---|---|
1337    /// | `if` | $y$ if $x > 0.5$ else $z$ | select/comparator: `in2` while `in1 > 0.5`, else `in3` |
1338    /// | `limit` | clamp $x$ to $[\min(y, z), \max(y, z)]$ | the "intermediate value" of `x`, `y`, `z` — the bounds may be given in either order |
1339    ///
1340    /// `limit`'s bounds are not fixed at ±`limit` the way `kind=saturation`'s are — they are two
1341    /// ordinary inputs, so they can themselves come from elsewhere in the graph.
1342    ///
1343    /// ## Parameters
1344    /// - `in1=<signal>` `in2=<signal>` `in3=<signal>` — the three arguments, in formula order
1345    ///   above.
1346    ///
1347    /// ## Errors
1348    /// - A misspelled/unknown name — the same `unknown device kind '<name>'` error as the
1349    ///   unary entry.
1350    /// - A missing `in1=`/`in2=`/`in3=` is the generic `missing field '<key>'` error — see
1351    ///   [`BlockInstance`]'s own doc comment.
1352    ///
1353    /// ## Netlist form
1354    /// ```text
1355    /// NAME kind=if     in1=<signal> in2=<signal> in3=<signal>
1356    /// NAME kind=limit  in1=<signal> in2=<signal> in3=<signal>
1357    /// ```
1358    ///
1359    /// ## Example
1360    /// A select picking between two references, and a clamp of 5 to the span [0, 2]:
1361    /// ```text
1362    /// CND kind=const value=1
1363    /// THEN kind=const value=10
1364    /// ELSE kind=const value=20
1365    /// SEL kind=if in1=CND in2=THEN in3=ELSE
1366    /// V kind=const value=5
1367    /// LO kind=const value=0
1368    /// HI kind=const value=2
1369    /// L kind=limit in1=V in2=LO in3=HI
1370    /// ```
1371    MathFn3(MathFn3),
1372    /// <!-- component -->
1373    /// # Hysteresis (Schmitt Trigger)
1374    /// **Purpose:** a bang-bang/hysteresis-band comparator.
1375    /// **Library:** Logic
1376    ///
1377    /// ## Description
1378    /// Stays HIGH until the input drops below `low`, stays LOW until the input rises above
1379    /// `high` (see `continuous_blocks::Hysteresis`) — used for current-mode control when
1380    /// there's no fixed switching frequency to modulate a duty command onto (unlike `Pid`
1381    /// feeding a [`BlockKind::Pwm`]). Its output is `1.0`/`0.0`, read directly by a
1382    /// [`GateBinding::Block`] rather than compared against a carrier. Deliberately not a
1383    /// `StateSpace`: the on/off memory is a genuine discrete latch, not a linear dynamic.
1384    ///
1385    /// ## Parameters
1386    /// - `high=<f64>`, `low=<f64>` — the two switching thresholds; must satisfy `low <= high`.
1387    /// - `in=<signal>` — the input signal (one input).
1388    /// - `ic=0|1` — optional (default `0`); the output the block starts the run holding, until
1389    ///   its own inputs first change it.
1390    ///
1391    /// ## Errors
1392    /// - `low > high` — rejected at parse time: `invalid hysteresis (LowExceedsHigh)`.
1393    /// - `ic=` that is neither `0` nor `1` — rejected at parse time: `field 'ic' is the initial
1394    ///   logic output and must be 0 or 1 (got '<value>')`.
1395    ///
1396    /// ## Netlist form
1397    /// ```text
1398    /// NAME kind=hysteresis high=<f64> low=<f64> in=<signal> [ic=0|1]
1399    /// ```
1400    ///
1401    /// ## Example
1402    /// A `[-1, 1]` band, verified end to end: a rising `Time`-driven ramp is LOW until crossing
1403    /// `1`, then HIGH:
1404    /// ```text
1405    /// T kind=time
1406    /// RAMP kind=gain k=1 in=T
1407    /// HYST1 kind=hysteresis high=1 low=-1 in=RAMP
1408    /// ```
1409    Hysteresis(Hysteresis),
1410    /// <!-- component -->
1411    /// # Logic Gate
1412    /// **Purpose:** a combinational digital logic gate.
1413    /// **Library:** Logic
1414    ///
1415    /// ## Description
1416    /// `and`/`or`/`xor`/`nand`/`nor`/`xnor` (N-input, `N >= 2`) or `not` (exactly 1 input) —
1417    /// see `continuous_blocks::LogicOp::call` for the exact reduction rule (`Xor`/`Xnor` use the
1418    /// standard N-input generalization: true iff an odd/even number of inputs are true, not
1419    /// "exactly one"). Every input/output is an ordinary `f64` signal, thresholded at `>= 0.5`
1420    /// — the same convention `GateBinding`/[`BlockKind::Hysteresis`] already use; there is no
1421    /// dedicated boolean `SignalValue` variant anywhere in this crate. Purely combinational —
1422    /// no persistent state, recomputed fresh every step, the same as
1423    /// [`BlockKind::Sum`]/[`BlockKind::Gain`] already are.
1424    ///
1425    /// ## Parameters
1426    /// - `kind=<and|or|xor|nand|nor|xnor|not>` — which gate.
1427    /// - `inputs=<sig1,sig2,...>` — for every kind except `not`; at least 2 entries.
1428    /// - `in=<signal>` — for `kind=not` only; exactly 1 input.
1429    ///
1430    /// ## Errors
1431    /// - `and`/`or`/`xor`/`nand`/`nor`/`xnor` with fewer than 2 `inputs=` entries — rejected at
1432    ///   parse time: `kind=<name> needs at least 2 comma-separated inputs= entries (got <n>)`.
1433    ///
1434    /// ## Netlist form
1435    /// ```text
1436    /// NAME kind=<and|or|xor|nand|nor|xnor> inputs=<sig1,sig2,...>
1437    /// NAME kind=not in=<signal>
1438    /// ```
1439    ///
1440    /// ## Example
1441    /// A 2-input `and`, verified end to end (`1 and 0 = 0`, `1 and 1 = 1`):
1442    /// ```text
1443    /// A kind=const value=1
1444    /// B kind=const value=0
1445    /// G1 kind=and inputs=A,B
1446    /// ```
1447    LogicGate(LogicOp),
1448    /// <!-- component -->
1449    /// # SR Latch
1450    /// **Purpose:** a level-triggered set/reset latch.
1451    /// **Library:** Logic
1452    ///
1453    /// ## Description
1454    /// No clock — `set`/`reset` act every step, immediately. The one genuinely new state shape
1455    /// in this family (a single persisted `bool`, updated every step from whichever of
1456    /// `set`/`reset` is currently asserted — see `continuous_blocks::srlatch_next`):
1457    /// `set,reset -> q_next`: `false,false` holds; `true,false` sets `true`; `false,true` sets
1458    /// `false`; `true,true` (both at once) resolves per `priority`. `Set` (the default) is the
1459    /// right default for this block's own motivating use case, a sticky fault latch — a fault
1460    /// occurring in the same step a reset is asserted should still latch, not silently clear.
1461    ///
1462    /// ## Parameters
1463    /// - `set=<signal>`, `reset=<signal>` — both required.
1464    /// - `priority=<set|reset>` — optional, defaults to `set`; which input wins when both are
1465    ///   asserted simultaneously.
1466    /// - `ic=0|1` — optional (default `0`); the output the block starts the run holding, until
1467    ///   its own inputs first change it.
1468    ///
1469    /// ## Errors
1470    /// - `priority=` present but not `set`/`reset` — rejected at parse time: `field 'priority'
1471    ///   must be 'set' or 'reset' (got '<value>')`.
1472    /// - `ic=` that is neither `0` nor `1` — rejected at parse time: `field 'ic' is the initial
1473    ///   logic output and must be 0 or 1 (got '<value>')`.
1474    ///
1475    /// ## Netlist form
1476    /// ```text
1477    /// NAME kind=srlatch set=<signal> reset=<signal> [priority=<set|reset>] [ic=0|1]
1478    /// ```
1479    ///
1480    /// ## Example
1481    /// A fault latch, verified end to end: `FAULT` pulses to `1` briefly then returns to `0`
1482    /// at `t=0.1`, but `LATCH1` stays `1` afterward (no separate reset asserted):
1483    /// ```text
1484    /// FAULT kind=pwc points=[[0,1],[0.1,0]]
1485    /// CLEAR kind=const value=0
1486    /// LATCH1 kind=srlatch set=FAULT reset=CLEAR
1487    /// ```
1488    SrLatch {
1489        /// Which input wins when `set` and `reset` are asserted simultaneously.
1490        priority: LatchPriority,
1491    },
1492    /// <!-- component -->
1493    /// # Flip-Flop
1494    /// **Purpose:** an edge-triggered D/JK/T flip-flop.
1495    /// **Library:** Logic
1496    ///
1497    /// ## Description
1498    /// Unlike [`BlockKind::SrLatch`] above, the next-state rule only fires at a detected rising
1499    /// `clk` edge (`continuous_blocks::rising_edge`); the previous `clk` sample is held
1500    /// alongside the output `q` between edges, the bookkeeping a level-triggered latch doesn't
1501    /// need at all.
1502    ///
1503    /// ## Parameters
1504    /// - `kind=<dff|jkff|tff>` — which flip-flop.
1505    /// - `clk=<signal>` — the clock input, required for every kind.
1506    /// - `d=<signal>` — for `kind=dff` only: the data input.
1507    /// - `t=<signal>` — for `kind=tff` only: the toggle-enable input.
1508    /// - `j=<signal>`, `k=<signal>` — for `kind=jkff` only: both required.
1509    /// - `reset=<signal>` — optional; if given, declares a synchronous reset input.
1510    /// - `ic=0|1` — optional (default `0`); the output the block starts the run holding, until
1511    ///   its own inputs first change it.
1512    ///
1513    /// ## Errors
1514    /// - The kind-specific data input (`d=`/`t=`/`j=`+`k=`) missing for its own kind — the
1515    ///   generic `missing field '<key>'` error.
1516    /// - `ic=` that is neither `0` nor `1` — rejected at parse time: `field 'ic' is the initial
1517    ///   logic output and must be 0 or 1 (got '<value>')`.
1518    ///
1519    /// ## Netlist form
1520    /// ```text
1521    /// NAME kind=dff clk=<signal> d=<signal> [reset=<signal>] [ic=0|1]
1522    /// NAME kind=tff clk=<signal> t=<signal> [reset=<signal>] [ic=0|1]
1523    /// NAME kind=jkff clk=<signal> j=<signal> k=<signal> [reset=<signal>] [ic=0|1]
1524    /// ```
1525    ///
1526    /// ## Example
1527    /// A D flip-flop, verified end to end: `Q1` only updates to `D`'s current value at a clock
1528    /// rising edge, not continuously:
1529    /// ```text
1530    /// CLK kind=pwc points=[[0,0],[5e-3,1]]
1531    /// D kind=const value=1
1532    /// Q1 kind=dff clk=CLK d=D
1533    /// ```
1534    FlipFlop {
1535        /// `dff`/`jkff`/`tff`.
1536        kind: FlipFlopKind,
1537        /// Whether this instance declares a synchronous reset input.
1538        reset: bool,
1539    },
1540    /// <!-- component -->
1541    /// # Counter
1542    /// **Purpose:** a clocked up/down counter.
1543    /// **Library:** Logic
1544    ///
1545    /// ## Description
1546    /// Shares the same rising-edge-detection skeleton [`BlockKind::FlipFlop`] uses, generalized
1547    /// from a single bit to an integer count. `up_down`/`modulus`/`reset` are all optional:
1548    /// omitting `up_down` always increments; omitting `modulus` gives a free-running signed
1549    /// `i64` that wraps only at `i64`'s own bounds; omitting `reset` means no synchronous reset
1550    /// input at all.
1551    ///
1552    /// ## Parameters
1553    /// - `clk=<signal>` — the clock input, required.
1554    /// - `up_down=<signal>` — optional; if given, declares a direction input (counts down when
1555    ///   its value thresholds true, up otherwise).
1556    /// - `modulus=<u32>` — optional; wraps the count into `[0, modulus)` if given.
1557    /// - `reset=<signal>` — optional; if given, declares a synchronous reset input.
1558    /// - `ic=<integer>` — optional (default `0`); the initial count. With `modulus=`, must
1559    ///   satisfy $0 \le \text{ic} < \text{modulus}$.
1560    ///
1561    /// ## Errors
1562    /// - `modulus=` present but not a non-negative integer — rejected at parse time: `field
1563    ///   'modulus' is not a non-negative integer`.
1564    /// - `up_down=`/`reset=` declared (field present) but the signal itself malformed — the
1565    ///   generic `missing field '<key>'`/parse-signal errors.
1566    /// - `ic=` not an integer — rejected at parse time: `field 'ic' is not an integer`.
1567    /// - `ic=` outside the modulus — rejected at parse time: `field 'ic' must satisfy 0 <= ic <
1568    ///   modulus (<m>) (got <value>)`.
1569    ///
1570    /// ## Netlist form
1571    /// ```text
1572    /// NAME kind=counter clk=<signal> [up_down=<signal>] [modulus=<u32>] [reset=<signal>] \
1573    ///      [ic=<integer>]
1574    /// ```
1575    ///
1576    /// ## Example
1577    /// A free-running up counter clocked by a repeating pulse train — verified end to end,
1578    /// `CNT1` increasing by exactly `1` at each detected clock rising edge:
1579    /// ```text
1580    /// CLK kind=pwc points=[[0,0],[1e-3,1],[2e-3,0]] repeat=true
1581    /// CNT1 kind=counter clk=CLK
1582    /// ```
1583    Counter {
1584        /// Whether this instance declares an up/down direction input (unset: always increments).
1585        up_down: bool,
1586        /// Wraps at this value if set; free-running `i64` otherwise.
1587        modulus: Option<u32>,
1588        /// Whether this instance declares a synchronous reset input.
1589        reset: bool,
1590    },
1591    /// <!-- component -->
1592    /// # CScript
1593    /// **Purpose:** call into a user-supplied, precompiled native shared library once per
1594    /// (block-local) step — an escape hatch for stateful behavior no existing block covers.
1595    /// **Library:** Extensibility
1596    ///
1597    /// ## Description
1598    /// A dynamically-loaded, user-supplied block: `lib` is a precompiled shared library
1599    /// (`.so`/`.dylib`/`.dll`) exporting `cscript_start`/`cscript_output`/(optionally)
1600    /// `cscript_free`/`cscript_clone`, filling `output_names.len()` outputs. Unlike every
1601    /// other `BlockKind`, this one can carry state no Rust type here knows anything about —
1602    /// see `cscript_ffi`'s own module doc comment (in the sibling `cscript-ffi` crate) for the
1603    /// full C-side contract. **This is the one place in the workspace where arbitrary native
1604    /// code loads into the process** — calling into it is unsafe by construction (in-process,
1605    /// full host privileges, can corrupt memory or crash the process); this is an accepted,
1606    /// bounded risk of an explicitly opt-in feature (the user names their own `.so` in their
1607    /// own netlist), not something sandboxed away.
1608    ///
1609    /// `sample_time`, if given, makes this block run on its *own* schedule, independent of the
1610    /// circuit's own resolved step size — either a fixed period (optionally phase-offset), or a
1611    /// schedule the block computes for itself every time it runs. `None` (the default) calls
1612    /// `cscript_output` every resolved circuit step instead, passing that step's own `dt` — the
1613    /// right choice for a block meant to behave continuously. See [`SampleTimeSpec`]'s own doc
1614    /// comment for the two `Some(..)` cases.
1615    ///
1616    /// `xc_count`, if nonzero, declares this block as owning that many continuous states the
1617    /// *solver itself* numerically integrates (one independent RK4 per block, the same
1618    /// convention every other dynamic `BlockKind` here uses), as opposed to a block hand-
1619    /// integrating its own state inside `cscript_output` (still the right choice for a fixed-
1620    /// rate discrete recursion, e.g. a bilinear-transform-derived filter — see `cscript_ffi`'s
1621    /// own module doc comment, "The optional continuous-state (`xc`) contract," for exactly
1622    /// which case this is for). `0` (the default) is the plain, single-function contract
1623    /// unchanged from before this field existed: `lib` must export `cscript_start`/
1624    /// `cscript_output`/(optionally) `cscript_free`/`cscript_clone`. Nonzero requires `lib` to
1625    /// export `cscript_start`/`cscript_derivative`/`cscript_output_xc`/(optionally)
1626    /// `cscript_free`/`cscript_clone` *instead of* `cscript_output`.
1627    ///
1628    /// ## Parameters
1629    /// - `lib=<path>` — the precompiled shared library. Like every field, this is whitespace-
1630    ///   tokenized; **a path containing whitespace must be `"double-quoted"`**
1631    ///   (`lib="my libs/gain.so"`) — verified directly against a real space-containing
1632    ///   directory. An unquoted path with no whitespace needs no quotes, unchanged.
1633    /// - `outputs=<name1,name2,...>` — this block's own output names; defaults to a single
1634    ///   output aliasing the block's own `.name` if omitted.
1635    /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these; `inputs=` for more
1636    ///   than one input, in the order `cscript_output`'s own `in`/`in_len` receives them.
1637    /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` / `ts=variable` — optional; see
1638    ///   [`SampleTimeSpec`]. Omit entirely to run every resolved circuit step.
1639    /// - `xc_count=<usize>` — optional, default `0`; number of solver-integrated continuous
1640    ///   states (switches the required C export set — see Description above).
1641    ///
1642    /// ## Errors
1643    /// - `lib`/`in` missing, or both `in` and `inputs` given, or neither — the generic
1644    ///   `missing field '<key>'` error (see [`BlockInstance`]'s own doc comment); there is no
1645    ///   `inputs`-vs-`in` mutual-exclusion check specifically, `inputs=` simply takes priority
1646    ///   when both are present.
1647    /// - `xc_count` present but not a non-negative integer — `field 'xc_count' is not a
1648    ///   non-negative integer`.
1649    /// - `ts=variable` combined with `freq=`/`to=` — rejected at parse time: `ts=variable is
1650    ///   exclusive with 'freq'/'to' (the block computes its own schedule; there's no fixed
1651    ///   period/offset to combine it with)`.
1652    /// - **Adaptive step-size control requires `cscript_clone`** to be exported — the solver
1653    ///   retries a rejected trial step from an independent copy of every block's state. Running
1654    ///   a `CScript` block with no `cscript_clone` export under adaptive stepping (i.e. no
1655    ///   `--dt` given to the CLI) fails at the first step with
1656    ///   `CScriptRequiresCloneForAdaptiveStep { block_name: "<name>" }` (verified directly: this
1657    ///   is the CLI's raw `{e:?}` `Debug` formatting of `dae_runtime`'s own error type, not a
1658    ///   hand-written message). Use a fixed `--dt` instead if the library doesn't export it.
1659    /// - A `.so` missing a required export, or a signature mismatch, surfaces as a load-time or
1660    ///   call-time failure from `cscript_ffi` itself — see that crate's own error type.
1661    ///
1662    /// ## Netlist form
1663    /// ```text
1664    /// NAME kind=cscript lib=<path> (in=<signal> | inputs=<sig1,sig2,...>) \
1665    ///      [outputs=<name1,name2,...>] [ts=<f64>|freq=<f64> [to=<f64>] | ts=variable] \
1666    ///      [xc_count=<usize>]
1667    /// ```
1668    ///
1669    /// ## Example
1670    /// A fixed-gain block computed in C (`out = 2 * in`), run every circuit step — `lib` names
1671    /// a shared library compiled from a two-function `.c` file exporting exactly
1672    /// `cscript_start`/`cscript_output`. Verified end to end (compiled, run through the real
1673    /// CLI, `G1`'s output confirmed to track `2 * SRC` every step, e.g. `SRC=3` produces
1674    /// `G1=6`):
1675    /// ```text
1676    /// SRC kind=const value=3
1677    /// G1 kind=cscript lib=gain.so in=SRC
1678    /// ```
1679    CScript {
1680        /// The precompiled shared library exporting the `cscript_*` C ABI.
1681        lib: std::path::PathBuf,
1682        /// This block's own output names, in order.
1683        output_names: Vec<String>,
1684        /// `None` runs every resolved circuit step; `Some` runs on its own schedule.
1685        sample_time: Option<SampleTimeSpec>,
1686        /// Number of solver-integrated continuous states this block owns; `0` for the plain contract.
1687        xc_count: usize,
1688    },
1689    /// <!-- component -->
1690    /// # PyBlock
1691    /// **Purpose:** call into a user-supplied, stateful Python function once per step — the
1692    /// Python-hosted counterpart to [`BlockKind::CScript`].
1693    /// **Library:** Extensibility
1694    ///
1695    /// ## Description
1696    /// A dynamically-loaded, user-supplied Python block (see `pyblock_ffi`): an escape hatch
1697    /// to a full scripting language (including `numpy`/`scipy`) when the existing block
1698    /// library doesn't cover something. `path` is a `.py` file exporting `start`/`output` (or,
1699    /// if `xc_count > 0`, `start`/`derivative`/`output_xc` *instead of* `output` — the same
1700    /// continuous-state split `CScript`'s own `xc_count` has, for the same reason).
1701    /// `output_names`/`sample_time`/`xc_count` all have exactly the same meaning as `CScript`'s
1702    /// own fields — deliberately scalar-only outputs, the same zero-order-hold `sample_time`
1703    /// convention, the same solver-integrated-vs-hand-managed state split. See
1704    /// `general-simulator`'s own `book/dev-guide/src/python-blocks.md` for the full design and
1705    /// the measurements behind it.
1706    ///
1707    /// ## Parameters
1708    /// - `path=<path>` — the `.py` file exporting `start`/`output` (or the `xc` contract). Same
1709    ///   whitespace-tokenization rule as `CScript`'s `lib=` — `"double-quote"` a path containing
1710    ///   whitespace.
1711    /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1712    ///   block's own `.name`.
1713    /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1714    /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` / `ts=variable` — optional; see
1715    ///   [`SampleTimeSpec`]. `ts=variable` here requires the `.py` file to also export
1716    ///   `next_sample_hit` (unlike [`BlockKind::PyFunction`], where `ts=variable` is rejected
1717    ///   outright).
1718    /// - `xc_count=<usize>` — optional, default `0`.
1719    ///
1720    /// ## Errors
1721    /// - **This block requires the CLI/library built with the `python` Cargo feature enabled**
1722    ///   (`cargo build --features python`) — it is *not* on by default, since it needs a
1723    ///   discoverable Python/`libpython` at build/link time and `kind=cscript` already covers
1724    ///   the same "dynamically-loaded custom block" need without that dependency. Without it,
1725    ///   any `kind=pyblock`/`kind=pyfunc` netlist fails at the first step with
1726    ///   `PythonSupportNotCompiledIn { block_name: "<name>" }` (verified directly — the CLI's
1727    ///   raw `{e:?}` formatting of `dae_runtime`'s own error, not a hand-written message).
1728    /// - `path`/`in` missing, or malformed `outputs=`/`xc_count=` — same generic/`xc_count`
1729    ///   errors as [`BlockKind::CScript`].
1730    /// - A `.py` file missing a required function, raising an exception, or returning the wrong
1731    ///   arity surfaces as a Python-traceback-bearing failure from `pyblock_ffi` itself at call
1732    ///   time, not at parse time.
1733    ///
1734    /// ## Netlist form
1735    /// ```text
1736    /// NAME kind=pyblock path=<path> (in=<signal> | inputs=<sig1,sig2,...>) \
1737    ///      [outputs=<name1,name2,...>] [ts=<f64>|freq=<f64> [to=<f64>] | ts=variable] \
1738    ///      [xc_count=<usize>]
1739    /// ```
1740    ///
1741    /// ## Example
1742    /// A fixed-gain block computed in Python (`out = 2 * in`) — verified end to end against a
1743    /// `--features python` build of the CLI, `SRC=3` producing `G1=6`:
1744    /// ```text
1745    /// SRC kind=const value=3
1746    /// G1 kind=pyblock path=gain.py in=SRC
1747    /// ```
1748    /// where `gain.py` is:
1749    /// ```python
1750    /// def start():
1751    ///     return None
1752    ///
1753    /// def output(state, t, dt, inputs):
1754    ///     return inputs[0] * 2.0
1755    /// ```
1756    /// The `xc_count>0` contract (`derivative`/`output_xc`) is verified separately end to end
1757    /// against its own analytic solution ($\dot{x}_c = 1 - x_c$, starting at rest, so
1758    /// $x_c(t) = 1 - e^{-t}$) — see `doc-verify/pyblock/xc_example.cir`.
1759    PyBlock {
1760        /// The `.py` file exporting `start`/`output` (or `start`/`derivative`/`output_xc`).
1761        path: std::path::PathBuf,
1762        /// This block's own output names, in order.
1763        output_names: Vec<String>,
1764        /// `None` runs every resolved circuit step; `Some` runs on its own schedule.
1765        sample_time: Option<SampleTimeSpec>,
1766        /// Number of solver-integrated continuous states this block owns; `0` for the plain contract.
1767        xc_count: usize,
1768    },
1769    /// <!-- component -->
1770    /// # PyFunction
1771    /// **Purpose:** call a plain, stateless, named Python function once per step.
1772    /// **Library:** Extensibility
1773    ///
1774    /// ## Description
1775    /// A genuinely separate contract from [`BlockKind::PyBlock`] above (not a mode of it): no
1776    /// `start`, no persistent `state`, no `t`/`dt` boilerplate, just `function` (a name inside
1777    /// `path`'s own `.py` file) called with each declared `inputs=` entry as its own
1778    /// positional argument (`f(*inputs)`, never bundled into one list), returning a single
1779    /// value or a tuple/list matching `output_names`. The closest equivalent to a plain
1780    /// named-input/named-output function block in other block-diagram tools. `output_names`/
1781    /// `sample_time` mean the same as `PyBlock`'s own (still scalar-only outputs, still the
1782    /// same zero-order-hold convention) — there is no `xc_count` here at all, since a purely
1783    /// stateless function has nothing for a continuous state to mean. See
1784    /// `pyblock_ffi::PyFunctionInstance`'s own module doc comment for the full contract.
1785    ///
1786    /// ## Parameters
1787    /// - `path=<path>` — the `.py` file containing `function`. `"double-quote"` a path
1788    ///   containing whitespace, same as `CScript`'s `lib=`.
1789    /// - `function=<name>` — required, no default; the function called as `f(*inputs)`.
1790    /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1791    ///   block's own `.name`.
1792    /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1793    /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` — optional, [`SampleTimeSpec::Periodic`] only;
1794    ///   `ts=variable` is rejected (see Errors).
1795    ///
1796    /// ## Errors
1797    /// - **Requires a `--features python` build** — see [`BlockKind::PyBlock`]'s own Errors
1798    ///   section; identical `PythonSupportNotCompiledIn` failure.
1799    /// - `ts=variable` — rejected at parse time, verified directly: `ts=variable is not
1800    ///   available for kind=pyfunc (a stateless function call has no instance to remember a
1801    ///   requested next-hit time against) -- use kind=pyblock instead`. A stateless function
1802    ///   call has no instance to remember "when am I next due" against.
1803    /// - `function` missing — the generic `missing field 'function'` error.
1804    /// - A `.py` file missing `function`, raising an exception, or returning the wrong arity
1805    ///   surfaces as a Python-traceback-bearing failure from `pyblock_ffi` at call time.
1806    ///
1807    /// ## Netlist form
1808    /// ```text
1809    /// NAME kind=pyfunc path=<path> function=<name> (in=<signal> | inputs=<sig1,sig2,...>) \
1810    ///      [outputs=<name1,name2,...>] [ts=<f64> | freq=<f64> [to=<f64>]]
1811    /// ```
1812    ///
1813    /// ## Example
1814    /// Verified end to end against a `--features python` build, `SRC=3` producing `G1=4`:
1815    /// ```text
1816    /// SRC kind=const value=3
1817    /// G1 kind=pyfunc path=add.py function=add_one in=SRC
1818    /// ```
1819    /// where `add.py` is:
1820    /// ```python
1821    /// def add_one(x):
1822    ///     return x + 1.0
1823    /// ```
1824    /// `inputs=A,B` calling `f(A, B)` as two genuinely distinct positional arguments (never
1825    /// bundled into one list) is verified separately — see `doc-verify/pyfunc/example_two_inputs.cir`.
1826    PyFunction {
1827        /// The `.py` file containing `function`.
1828        path: std::path::PathBuf,
1829        /// The function name called with each declared input as a positional argument.
1830        function: String,
1831        /// This block's own output names, in order.
1832        output_names: Vec<String>,
1833        /// `None` runs every resolved circuit step; `Some` must be [`SampleTimeSpec::Periodic`].
1834        sample_time: Option<SampleTimeSpec>,
1835    },
1836    /// <!-- component -->
1837    /// # OctFunc
1838    /// **Purpose:** call a plain, stateless, named Octave-compatible function once per step.
1839    /// **Library:** Extensibility
1840    ///
1841    /// ## Description
1842    /// The `.m`-file counterpart to [`BlockKind::PyFunction`] above -- same genuinely separate,
1843    /// stateless contract (no `start`, no persistent state, no `t`/`dt` boilerplate), for
1844    /// people with legacy Octave-compatible `.m` scripts instead of Python. `function` (a
1845    /// name inside `path`'s own `.m` file, which must itself be named `<function>.m` -- Octave's
1846    /// own requirement that a function's file name match its function name) is called with each
1847    /// declared `inputs=` entry as its own positional argument (`f(arg0, arg1, ...)`, never
1848    /// bundled into one array), returning a single value or as many comma-separated return
1849    /// values as `output_names` declares (`[y1, y2] = f(...)`). `output_names`/`sample_time`
1850    /// mean the same as `PyFunction`'s own -- still scalar-only outputs, still the same
1851    /// zero-order-hold convention -- and there is no `xc_count` here either, for the same reason
1852    /// `PyFunction` has none: a purely stateless function has nothing for a continuous state to
1853    /// mean.
1854    ///
1855    /// Unlike `PyFunction`, this block never embeds an interpreter in-process: it calls into a
1856    /// separately installed `octave-cli` binary as a subprocess (one shared, persistent process
1857    /// for the whole simulation run, spawned lazily on first use), specifically so this
1858    /// permissively-licensed project never links against GPLv3-licensed Octave code -- see
1859    /// `octave_ffi`'s own module doc comment and `general-simulator`'s own
1860    /// `book/dev-guide/src/octave-blocks.md` for the full licensing rationale and the measured
1861    /// costs behind this design.
1862    ///
1863    /// ## Parameters
1864    /// - `path=<path>` — the `.m` file containing `function`; its own file name (minus `.m`)
1865    ///   must equal `function`. `"double-quote"` a path containing whitespace, same as
1866    ///   `CScript`'s `lib=`.
1867    /// - `function=<name>` — required, no default; the function called as `f(arg0, arg1, ...)`,
1868    ///   and the required base name of `path`'s own file.
1869    /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1870    ///   block's own `.name`.
1871    /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1872    /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` — optional, [`SampleTimeSpec::Periodic`] only;
1873    ///   `ts=variable` is rejected (see Errors), for exactly the reason `PyFunction`'s own is.
1874    ///
1875    /// ## Errors
1876    /// - `ts=variable` — rejected at parse time, the same wording `PyFunction` uses (a stateless
1877    ///   function call has no instance to remember a requested next-hit time against): `ts=variable
1878    ///   is not available for kind=octfunc (a stateless function call has no instance to remember
1879    ///   a requested next-hit time against)`.
1880    /// - `function` missing — the generic `missing field 'function'` error.
1881    /// - `octave-cli` not found on `PATH` when this block is first evaluated, an Octave-side
1882    ///   exception raised by the called function, or a malformed/desynchronized reply from the
1883    ///   shared session — surfaces as a call-time failure from `octave_ffi` itself (see
1884    ///   `octave_ffi::OctaveError`'s own three cases: not-found, process-exited, and Octave-side
1885    ///   runtime error), not at parse time.
1886    ///
1887    /// ## Netlist form
1888    /// ```text
1889    /// NAME kind=octfunc path=<file.m> function=<name> (in=<signal> | inputs=<sig1,sig2,...>) \
1890    ///      [outputs=<name1,name2,...>] [ts=<f64> | freq=<f64> [to=<f64>]]
1891    /// ```
1892    ///
1893    /// ## Example
1894    /// Verified end to end against the real CLI (no special feature flag needed -- unlike
1895    /// `kind=pyblock`/`kind=pyfunc`, this block builds and runs unconditionally), `SRC=3`
1896    /// producing `G1=4`:
1897    /// ```text
1898    /// SRC kind=const value=3
1899    /// G1 kind=octfunc path=add_one.m function=add_one in=SRC
1900    /// ```
1901    /// where `add_one.m` is:
1902    /// ```text
1903    /// function y = add_one(x)
1904    ///   y = x + 1;
1905    /// end
1906    /// ```
1907    /// `inputs=A,B` calling `f(A, B)` as two genuinely distinct positional arguments is verified
1908    /// separately -- see `doc-verify/octfunc/example_two_inputs.cir`.
1909    OctFunc {
1910        /// The `.m` file containing `function` -- its own base file name must equal `function`.
1911        path: std::path::PathBuf,
1912        /// The function name called with each declared input as a positional argument.
1913        function: String,
1914        /// This block's own output names, in order.
1915        output_names: Vec<String>,
1916        /// `None` runs every resolved circuit step; `Some` must be [`SampleTimeSpec::Periodic`].
1917        sample_time: Option<SampleTimeSpec>,
1918    },
1919    /// <!-- component -->
1920    /// # OctBlock
1921    /// **Purpose:** call into a user-supplied, *stateful* Octave-compatible function once per
1922    /// step -- the Octave-hosted counterpart to [`BlockKind::PyBlock`], and the stateful sibling
1923    /// of [`BlockKind::OctFunc`] (not a mode of it -- see that variant's own doc comment for the
1924    /// stateless contract this one deliberately does not share).
1925    /// **Library:** Extensibility
1926    ///
1927    /// ## Description
1928    /// An escape hatch to Octave-compatible `.m`-file functions with real persistent state
1929    /// across steps -- for people with legacy Octave-compatible `.m` scripts who need
1930    /// `pyblock`'s own `start`/`output`/`update`/`xc_count` contract, not `octfunc`'s stateless
1931    /// one. `output_names`/`sample_time`/`xc_count` all mean exactly what [`BlockKind::PyBlock`]'s
1932    /// own do (scalar-only outputs, the same zero-order-hold `sample_time` convention, the same
1933    /// solver-integrated-vs-hand-managed `xc` split).
1934    ///
1935    /// **`path=` names a directory, not a single file** -- the one place this contract cannot
1936    /// simply reuse `OctFunc`'s own single-`.m`-file convention: Octave only auto-loads the
1937    /// *first* `function ... end` block in a `.m` file by filename, so a second function in the
1938    /// same file is an invisible private subfunction (confirmed empirically against real
1939    /// `octave-cli`). Every contract function therefore needs **its own file**, named
1940    /// `<function>_<role>.m`, all living together in `path`'s own directory:
1941    ///
1942    /// | File | Required | Signature |
1943    /// |---|---|---|
1944    /// | `<function>_start.m` | always | `state = <function>_start()` |
1945    /// | `<function>.m` | unless `xc_count>0` | `[new_state, y1, y2, ...] = <function>(state, t, dt, u1, u2, ...)` |
1946    /// | `<function>_derivative.m` | only if `xc_count>0` | `xc_dot = <function>_derivative(state, u1, ..., xc)` -- pure, must not mutate `state`; called up to 4x/step (RK4 stages), including from discarded trial steps under adaptive stepping |
1947    /// | `<function>_output_xc.m` | only if `xc_count>0` | `[new_state, y1, ...] = <function>_output_xc(state, t, dt, u1, ..., xc)` -- `xc` here is this step's own already-integrated continuous state |
1948    /// | `<function>_update.m` | optional | `new_state = <function>_update(state, t, dt, u1, ...)` -- called once per resolved step, after output; if absent, `output`/`output_xc`'s own returned `new_state` is the only state advance |
1949    /// | `<function>_next_sample_hit.m` | only if `ts=variable` | `seconds = <function>_next_sample_hit(state, t, dt, u1, ...)` |
1950    ///
1951    /// A user coming from Octave/legacy-language habits of "one script, many local functions"
1952    /// hits this immediately -- this is not a buried caveat, it is the load-bearing difference
1953    /// from every other block kind's own `path=`.
1954    ///
1955    /// Each instance's own opaque `state` (whatever `<function>_start` returns) lives entirely
1956    /// **inside the shared Octave session itself**, in one global struct keyed by this block's
1957    /// own instance name (`global __gs_state; __gs_state.('<name>') = ...`) -- it is never
1958    /// serialized back into Rust at all, unlike `PyBlock`'s own `state` (an opaque Python
1959    /// object `pyblock_ffi` holds a handle to) or `CScript`'s (an opaque `void*`). Two instances
1960    /// of the *same* Octave function never contaminate each other's state -- validated directly
1961    /// against real `octave-cli` (interleaved calls, zero cross-contamination; see
1962    /// `octave_ffi::OctaveSession`'s own `tests/stateful_session.rs`). The one piece of state
1963    /// that *does* cross the pipe as explicit numeric data (the same `%.17g`-per-line protocol
1964    /// `octfunc` already uses, extended to a literal Octave vector) is the solver-owned `xc`
1965    /// continuous-state vector for the `xc_count > 0` case -- that's the *solver's* state, not
1966    /// the block's own opaque one, so it has to be explicit, exactly mirroring `cscript`'s/
1967    /// `pyblock`'s own `xc` vs. opaque-`state` split. See `general-simulator`'s own
1968    /// `book/dev-guide/src/octave-blocks.md` for the full protocol, licensing rationale, and
1969    /// measured costs.
1970    ///
1971    /// Like `OctFunc`, this block shares **one** persistent `octave-cli` subprocess with every
1972    /// other Octave-hosted block kind in the same run (spawned lazily, on first use) -- never a
1973    /// second process.
1974    ///
1975    /// ## Parameters
1976    /// - `path=<dir>` — the directory containing `<function>_*.m` (see the file table above).
1977    ///   `"double-quote"` a path containing whitespace, same as `CScript`'s `lib=`.
1978    /// - `function=<name>` — required, no default; the base name every `<function>_<role>.m`
1979    ///   file shares.
1980    /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1981    ///   block's own `.name`.
1982    /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1983    /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` / `ts=variable` — optional; see
1984    ///   [`SampleTimeSpec`]. `ts=variable` here requires `<function>_next_sample_hit.m` to also
1985    ///   exist in `path`'s own directory.
1986    /// - `xc_count=<usize>` — optional, default `0`.
1987    ///
1988    /// ## Errors
1989    /// - `path`/`function`/`in` missing, or malformed `outputs=`/`xc_count=` — same generic/
1990    ///   `xc_count` errors as [`BlockKind::CScript`].
1991    /// - A required `<function>_*.m` file missing from `path`'s own directory (per the file
1992    ///   table above, given this block's own `xc_count`/`ts=`) — checked once, up front, at
1993    ///   construction time, *before* `octave-cli` is ever asked about it: `dae_runtime::DaeError
1994    ///   ::OctBlockMissingRequiredFile { block_name, expected_path }`.
1995    /// - `ts=variable` without `<function>_next_sample_hit.m` present — checked the same way:
1996    ///   `dae_runtime::DaeError::OctBlockRequiresNextSampleHitForVariableSampleTime`.
1997    /// - `octave-cli` not found on `PATH`, an Octave-side exception raised by a called function,
1998    ///   or a malformed/desynchronized reply — surfaces as a call-time failure from `octave_ffi`
1999    ///   itself (`dae_runtime::DaeError::Octave`), not at parse time.
2000    /// - **`kind=octblock` does not support `TimeStep::Adaptive`** — this instance's own opaque
2001    ///   state lives inside the one shared `octave-cli` session, which is never cloned, so a
2002    ///   rejected adaptive trial step's own state-mutating calls could not be rolled back; a
2003    ///   netlist using `kind=octblock` under an adaptive run fails at construction with
2004    ///   `dae_runtime::DaeError::OctBlockDoesNotSupportAdaptiveStep { block_name }`. Use a fixed
2005    ///   `--dt`.
2006    ///
2007    /// ## Netlist form
2008    /// ```text
2009    /// NAME kind=octblock path=<dir> function=<name> (in=<signal> | inputs=<sig1,sig2,...>) \
2010    ///      [outputs=<name1,name2,...>] [ts=<f64>|freq=<f64> [to=<f64>] | ts=variable] \
2011    ///      [xc_count=<usize>]
2012    /// ```
2013    ///
2014    /// ## Example
2015    /// A stateful accumulator (`out = state + in`, state advances by `in` every step) verified
2016    /// end to end against the real CLI, `SRC=3` producing `G1=3,6,9,...` across successive
2017    /// steps:
2018    /// ```text
2019    /// SRC kind=const value=3
2020    /// G1 kind=octblock path=accum function=accumulate in=SRC
2021    /// ```
2022    /// where `accum/accumulate_start.m` is:
2023    /// ```text
2024    /// function state = accumulate_start()
2025    ///   state = 0;
2026    /// end
2027    /// ```
2028    /// and `accum/accumulate.m` is:
2029    /// ```text
2030    /// function [new_state, y] = accumulate(state, t, dt, u)
2031    ///   new_state = state + u;
2032    ///   y = new_state;
2033    /// end
2034    /// ```
2035    /// The `xc_count>0` contract (`_derivative`/`_output_xc`) is verified separately end to end
2036    /// against its own analytic solution ($\dot{x}_c = 1 - x_c$, starting at rest, so
2037    /// $x_c(t) = 1 - e^{-t}$) — see `doc-verify/octblock/xc_example.cir`, mirroring
2038    /// `doc-verify/pyblock/xc_example.cir`'s own precedent.
2039    OctBlock {
2040        /// The directory containing `<function>_start.m`, `<function>.m` (or
2041        /// `<function>_derivative.m`/`<function>_output_xc.m`), and optionally
2042        /// `<function>_update.m`/`<function>_next_sample_hit.m`.
2043        path: std::path::PathBuf,
2044        /// The shared base name every `<function>_<role>.m` file in `path` uses.
2045        function: String,
2046        /// This block's own output names, in order.
2047        output_names: Vec<String>,
2048        /// `None` runs every resolved circuit step; `Some` runs on its own schedule.
2049        sample_time: Option<SampleTimeSpec>,
2050        /// Number of solver-integrated continuous states this block owns; `0` for the plain contract.
2051        xc_count: usize,
2052    },
2053    /// <!-- component -->
2054    /// # Coordinate Transform (Clarke/Park)
2055    /// **Purpose:** one of the six Clarke/Park three-phase coordinate transforms.
2056    /// **Library:** Coordinate Transforms
2057    ///
2058    /// ## Description
2059    /// The standard `abc`/`alpha-beta-0`/`d-q-0` change of basis (see
2060    /// `continuous_blocks::CoordinateTransform`) used to regulate a three-phase quantity
2061    /// (grid-tied PFC, motor drive) with a `Pid` on a DC-like `d`/`q` value instead of chasing
2062    /// a sine wave directly. Stateless and multi-output, following exactly the same
2063    /// `output_names` convention [`BlockKind::CScript`] established: `inputs` supplies
2064    /// `kind.input_count()` values in the order `CoordinateTransform::call` expects,
2065    /// `output_names.len()` must equal 3 (this family's output count — the conventional
2066    /// per-transform names, e.g. `["alpha", "beta", "zero"]` for `Clarke`), the block's own
2067    /// `.name` binds to the first (primary) output, and the remaining two are inserted under
2068    /// their own `output_names` entries so a downstream block can reference them directly via
2069    /// `Signal::Block(name)`.
2070    ///
2071    /// ## Parameters
2072    /// - `kind=<clarke|clarkeinv|park|parkinv|clarkepark|clarkeparkinv>` — which transform.
2073    /// - `inputs=<sig1,...>` — `3` entries for `clarke`/`clarkeinv`, `4` for the other four
2074    ///   (`park`/`parkinv`/`clarkepark`/`clarkeparkinv` also take an angle input).
2075    /// - `outputs=<name1,name2,name3>` — optional; defaults to `<name>,<name>_<suffix2>,
2076    ///   <name>_<suffix3>` using this transform's own conventional output names.
2077    ///
2078    /// ## Errors
2079    /// - Wrong `inputs=` count for this transform — rejected at parse time: `kind='<kind>'
2080    ///   needs <n> inputs (got <m>)`.
2081    /// - `outputs=` with a count other than 3 — rejected at parse time: `'outputs' needs
2082    ///   exactly 3 entries (got <n>)`.
2083    ///
2084    /// ## Netlist form
2085    /// ```text
2086    /// NAME kind=clarke inputs=<a,b,c> [outputs=<name1,name2,name3>]
2087    /// NAME kind=park inputs=<a,b,c,theta> [outputs=<name1,name2,name3>]
2088    /// ```
2089    ///
2090    /// ## Example
2091    /// A balanced three-phase set through `clarke` — verified end to end: for
2092    /// $a=1,b=-0.5,c=-0.5$ (a peak on phase A), $\alpha = 1$, $\beta = 0$ exactly:
2093    /// ```text
2094    /// A kind=const value=1
2095    /// B kind=const value=-0.5
2096    /// C kind=const value=-0.5
2097    /// CT1 kind=clarke inputs=A,B,C
2098    /// ```
2099    CoordinateTransform {
2100        /// Which of the six Clarke/Park transforms this is.
2101        kind: CoordinateTransform,
2102        /// Output names; length must equal 3 for this family.
2103        output_names: Vec<String>,
2104    },
2105    /// <!-- component -->
2106    /// # PMSM (Permanent-Magnet Synchronous Motor)
2107    /// **Purpose:** a nonlinear permanent-magnet synchronous motor model.
2108    /// **Library:** Machines
2109    ///
2110    /// ## Description
2111    /// Genuinely nonlinear (bilinear speed/current coupling — see `continuous_blocks::Pmsm`),
2112    /// so like [`BlockKind::Vco`] it carries its own state and is integrated via its own
2113    /// `step()` (RK4) rather than compiled to a `StateSpace`. Three inputs, in order: `vd`,
2114    /// `vq` (rotor-frame stator voltage commands, V — typically a `ClarkeParkInv`'s output, or
2115    /// a `CoordinateTransform` intermediate wired through a `Pid`), and `t_load` (N·m, the
2116    /// mechanical load torque). Four outputs, same `output_names` convention as
2117    /// [`BlockKind::CoordinateTransform`]/[`BlockKind::CScript`]: `id`, `iq` (A), `omega_m`
2118    /// (mechanical speed, rad/s), and `theta_e` (electrical angle, already wrapped to
2119    /// $[0, 2\pi)$ via `Pmsm::theta_e_wrapped` — ready to feed a `Park`/`ClarkePark` block
2120    /// directly). Starts at rest (`id = iq = omega_m = theta_e = 0`) — no initial-condition
2121    /// override, matching every other dynamic block in this graph. Surface-mount motors have
2122    /// `l_d == l_q` (no reluctance torque term); interior-PM motors have `l_d != l_q`.
2123    ///
2124    /// ## Parameters
2125    /// - `r_s=<f64>` — stator resistance, Ω; must be `>= 0`.
2126    /// - `l_d=<f64>`, `l_q=<f64>` — d/q-axis inductance, H; both must be `> 0`.
2127    /// - `lambda_pm=<f64>` — permanent-magnet flux linkage, Wb.
2128    /// - `pole_pairs=<f64>` — must be `> 0`.
2129    /// - `inertia=<f64>` — rotor inertia, kg·m²; must be `> 0`.
2130    /// - `friction=<f64>` — viscous friction coefficient; must be `>= 0`.
2131    /// - `inputs=<vd,vq,t_load>` — exactly 3, in this order.
2132    /// - `outputs=<id,iq,omega_m,theta_e>` — optional; defaults to `<name>,<name>_iq,
2133    ///   <name>_omega_m,<name>_theta_e`.
2134    /// - `ic=[id,iq,omega_m,theta_e]` — optional (default: all zero); the four machine states at
2135    ///   $t = 0$: $d$/$q$ currents (A), mechanical speed (rad/s), electrical angle (rad).
2136    ///
2137    /// ## Errors
2138    /// - `r_s < 0` — `invalid pmsm (NegativeResistance)`.
2139    /// - `l_d <= 0` or `l_q <= 0` — `invalid pmsm (NonPositiveInductance)`.
2140    /// - `pole_pairs <= 0` — `invalid pmsm (NonPositivePolePairs)`.
2141    /// - `inertia <= 0` — `invalid pmsm (NonPositiveInertia)`.
2142    /// - `friction < 0` — `invalid pmsm (NegativeFriction)`.
2143    /// - `ic=` with other than four entries — rejected at parse time: `field 'ic' has <m>
2144    ///   value(s), but this block has 4 state(s)`.
2145    ///
2146    /// ## Netlist form
2147    /// ```text
2148    /// NAME kind=pmsm r_s=<f64> l_d=<f64> l_q=<f64> lambda_pm=<f64> pole_pairs=<f64> \
2149    ///      inertia=<f64> friction=<f64> inputs=<vd,vq,t_load> [outputs=<id,iq,omega_m,theta_e>] \
2150    ///      [ic=<vector>]
2151    /// ```
2152    ///
2153    /// ## Example
2154    /// A small surface-mount motor at rest with zero applied voltage/load — verified to run
2155    /// without error and stay at rest (`id = iq = omega_m = 0`, no torque applied):
2156    /// ```text
2157    /// VD kind=const value=0
2158    /// VQ kind=const value=0
2159    /// TLOAD kind=const value=0
2160    /// M1 kind=pmsm r_s=0.5 l_d=1e-3 l_q=1e-3 lambda_pm=0.05 pole_pairs=4 inertia=1e-5 \
2161    ///      friction=1e-6 inputs=VD,VQ,TLOAD
2162    /// ```
2163    Pmsm {
2164        /// The motor's own parameters/state.
2165        pmsm: Pmsm,
2166        /// Output names; length must equal 4 (`id`, `iq`, `omega_m`, `theta_e`).
2167        output_names: Vec<String>,
2168    },
2169    /// <!-- component -->
2170    /// # Phys2Sig (Physical-to-Signal Converter)
2171    /// **Purpose:** the only way a circuit quantity enters the signal domain.
2172    /// **Library:** Electrical Interface
2173    ///
2174    /// ## Description
2175    /// Zero block-graph inputs (it reads the circuit's own previous-step operating point
2176    /// directly). Its value is then an ordinary block output, read by any downstream block via
2177    /// `Signal::Block(this_block's_name)` exactly like any other source block
2178    /// (`Const`/`Pwl`/`Time`). Modeled directly on the physical/signal converter block a real
2179    /// block-diagram simulation tool requires: a physical port and a signal port are
2180    /// type-distinct there and cannot be wired together without one of these in between — the
2181    /// same rule, enforced the same way, at the netlist level instead of a GUI's wiring canvas.
2182    /// Named symmetrically with [`BlockKind::Sig2Phys`] (its write-direction counterpart):
2183    /// `phys2sig` reads a circuit quantity into the signal domain, `sig2phys` drives a
2184    /// signal-domain value onto a circuit quantity.
2185    ///
2186    /// ## Parameters
2187    /// - `node=<name>` — reads `V(node)`. Mutually exclusive with `branch=`.
2188    /// - `branch=<name>` — reads `I(branch)`. Mutually exclusive with `node=`.
2189    ///
2190    /// ## Errors
2191    /// - Both `node=` and `branch=` given — rejected at parse time: `'node' and 'branch' are
2192    ///   mutually exclusive (a phys2sig reads either a node voltage or a branch current, never
2193    ///   both)`.
2194    /// - Neither given — rejected at parse time: `kind='phys2sig' needs 'node=<name>' (reads
2195    ///   V(node)) or 'branch=<name>' (reads I(branch))`.
2196    /// - `branch=<name>` naming an element that has no MNA branch-current unknown at all —
2197    ///   rejected at build time (once the full circuit is known), not silently read back as
2198    ///   `0.0`: only `V`/`L`/`E` (VCVS)/`H` (CCVS) elements carry a branch-current unknown (see
2199    ///   `MnaBuilder::is_branch_device`); naming anything else (a resistor, a capacitor, a
2200    ///   diode, an ideal switch, ...) is `line N: device '<name>' kind='phys2sig'
2201    ///   branch='<branch>' has no current unknown available (only V/L/E/H sources carry a
2202    ///   branch-current unknown) -- insert a 0V voltage source in series in the branch you want
2203    ///   to measure and probe its current instead` — the standard SPICE "ammeter" idiom: a 0V
2204    ///   source in series perturbs nothing electrically, but (being a `V` element) gets its own
2205    ///   branch-current unknown for free, which `branch=` can then read.
2206    /// - `branch=<name>` naming an element that doesn't exist anywhere in the netlist at all
2207    ///   (not just the wrong type) — a distinct build-time error: `line N: device '<name>'
2208    ///   kind='phys2sig' branch='<branch>' names no such element`.
2209    ///
2210    /// ## Netlist form
2211    /// ```text
2212    /// NAME kind=phys2sig node=<node_name>
2213    /// NAME kind=phys2sig branch=<branch_name>
2214    /// ```
2215    ///
2216    /// ## Example
2217    /// Reading a resistor-divider node's own voltage — verified end to end, `PROBE1` tracking
2218    /// `V(out)` exactly:
2219    /// ```text
2220    /// V1 in 0 5
2221    /// R1 in out 1k
2222    /// R2 out 0 1k
2223    /// PROBE1 kind=phys2sig node=out
2224    /// ```
2225    ///
2226    /// The ammeter idiom — measuring the current through `R1` (which has no branch-current
2227    /// unknown of its own) by inserting a 0V source `VAMM` in series and reading *that* instead;
2228    /// verified end to end, `IMEAS` tracking `5 / (1000 + 1000) = 0.0025` A exactly (the 0V
2229    /// source doesn't perturb the divider at all):
2230    /// ```text
2231    /// V1 in 0 5
2232    /// VAMM in mid 0
2233    /// R1 mid out 1000
2234    /// R2 out 0 1000
2235    /// IMEAS kind=phys2sig branch=VAMM
2236    /// ```
2237    Phys2Sig(Phys2SigTarget),
2238    /// <!-- component -->
2239    /// # Sig2Phys (Signal-to-Physical Converter)
2240    /// **Purpose:** the only legal way a signal-domain block's output drives a `V`/`I` source's
2241    /// magnitude or an ideal switch's gate.
2242    /// **Library:** Electrical Interface
2243    ///
2244    /// ## Description
2245    /// Closes the write-direction gap [`BlockKind::Phys2Sig`] doesn't (a phys2sig only ever
2246    /// reads). A
2247    /// `V`/`I` element's own literal value field in the netlist names this block directly (e.g.
2248    /// `V1 a 0 VDRV`, where `VDRV` is a declared `domain=voltage` block) — `general-mna`'s own
2249    /// `Expression::parse_scalar` already accepts a bare symbol there with no change needed on
2250    /// that side; `dae-runtime` requires, at validation time, that any such symbol naming a
2251    /// declared block resolve to exactly this kind with the matching `domain` for the device
2252    /// letter driving it (`V` requires `domain=voltage`, `I` requires `domain=current`) —
2253    /// `DaeError::SourceNotSig2PhysicalConverter` otherwise — and every step, substitutes this
2254    /// block's own just-computed output value into the circuit solve in that symbol's place.
2255    ///
2256    /// Also the *only* legal target for a [`GateBinding::Block`]'s own named block, and there
2257    /// *only* the `domain=voltage` form — `dae-runtime` rejects a `GateBinding` naming anything
2258    /// else, including a `domain=current` `Sig2Phys`, with `DaeError::GateTargetNotSig2Voltage`.
2259    /// An ideal switch's gate is itself a voltage (`V_GS` against the gate's own
2260    /// `v_gs_th`), not a distinct
2261    /// discrete-actuation signal domain, so there is no separate gate-only converter — one type,
2262    /// `Sig2Phys`, parameterized by [`PhysicalDomain`], is the whole Signal-to-PS boundary for
2263    /// "a signal-domain block's output drives a physical voltage or current," whether that
2264    /// voltage happens to source a node, gate a switch, or drive a current source. Purely an
2265    /// identity pass-through numerically (`value = input`) in every role; the `domain` field is
2266    /// what the enforcement keys on. One input.
2267    ///
2268    /// ## Parameters
2269    /// - `domain=<voltage|current>` — which physical quantity this converter drives. Required.
2270    /// - `in=<signal>` — the value to drive onto the physical side (one input).
2271    ///
2272    /// ## Errors
2273    /// - `domain=` missing entirely — rejected at parse time: `line N: device '<name>' missing
2274    ///   field 'domain'`.
2275    /// - `domain=` present but not `voltage`/`current` — rejected at parse time: `line N: device
2276    ///   '<name>' field 'domain' must be 'voltage' or 'current' (got '<value>')`.
2277    /// - Beyond that, none specific to this `kind=` — every real enforcement (a `V`/`I`/gate
2278    ///   target actually naming a `Sig2Phys` of the right domain) happens at `dae-runtime`'s
2279    ///   validation stage, not netlist parse time. `general-mna` itself only ever sees the
2280    ///   device-source half of a document (with `--devices <file>`, it doesn't see the netlist
2281    ///   at all), so it cannot detect a converter's name reused as an ordinary circuit *node* —
2282    ///   that mistake produces no parse error here. `dae-runtime` rejects it as
2283    ///   `DaeError::Sig2PhysUsedAsCircuitNode`: this block has no terminals and stamps nothing
2284    ///   into the MNA system, so a net sharing its name is merely undriven, and KCL solves it to
2285    ///   a silently wrong `0` rather than failing — a converter must always be *referenced by
2286    ///   name* (a source's value field, or a switch's `gate=`/`ctrl=`), never wired.
2287    ///
2288    /// ## Netlist form
2289    /// ```text
2290    /// NAME kind=sig2phys domain=voltage in=<signal>
2291    /// NAME kind=sig2phys domain=current in=<signal>
2292    /// ```
2293    ///
2294    /// ## Example
2295    /// A block-driven voltage source — verified end to end, `V1`'s magnitude tracking a
2296    /// `Const` through the converter exactly:
2297    /// ```text
2298    /// CMD kind=const value=5
2299    /// VDRV kind=sig2phys domain=voltage in=CMD
2300    /// V1 a 0 VDRV
2301    /// R1 a 0 1k
2302    /// ```
2303    ///
2304    /// A block-driven current source — verified end to end, `I1`'s magnitude tracking a
2305    /// `Const` through the converter exactly:
2306    /// ```text
2307    /// CMD kind=const value=0.1
2308    /// IDRV kind=sig2phys domain=current in=CMD
2309    /// I1 a 0 IDRV
2310    /// R1 a 0 1k
2311    /// ```
2312    Sig2Phys {
2313        /// Which physical quantity this converter drives — `V`-source targets and
2314        /// `GateBinding::Block` targets require `Voltage`; `I`-source targets require
2315        /// `Current`.
2316        domain: PhysicalDomain,
2317    },
2318}
2319
2320/// Which physical quantity a [`BlockKind::Sig2Phys`] converter drives. Purely a type-level tag
2321/// for the enforcement sites in `dae-runtime` (`DaeError::GateTargetNotSig2Voltage`,
2322/// `DaeError::SourceNotSig2PhysicalConverter`) — evaluation itself (`value = input`) is
2323/// identical for both.
2324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2325pub enum PhysicalDomain {
2326    /// Drives a `V` source's magnitude, or a [`GateBinding::Block`] target.
2327    Voltage,
2328    /// Drives an `I` source's magnitude.
2329    Current,
2330}
2331
2332/// One named block instance and where its inputs (if any) come from.
2333/// `Const`/`Pwc`/`Pwl`/`Waveform`/`Phys2Sig` blocks must have zero inputs; `Sum`/`Product` need one
2334/// input per sign/factor; `Gain`/
2335/// `StateSpace`/`TransferFunction`/`Vco`/`Saturation`/`Table`/`MathFn1`/`Sig2Phys`
2336/// each need exactly one; `Pid` needs exactly one (the error signal)
2337/// when its `clamp` is `PidClamp::Fixed`, or exactly three (`error, clamp_lo, clamp_hi`, in that
2338/// order) when `PidClamp::Dynamic`; `MathFn2` needs two; `MathFn3` needs three;
2339/// `CoordinateTransform` needs `kind.input_count()` (3 for `Clarke`/`ClarkeInv`, 4 for the
2340/// others — see [`continuous_blocks::CoordinateTransform::input_count`]); `Pmsm` needs exactly
2341/// three (`vd`, `vq`, `t_load`, in that order). Evaluated once per step in the causal order
2342/// `topological_order` (in `dae-runtime`) derives from the slice's own `Signal::Block` dependency graph — *not*
2343/// the order the slice happens to be given in; a `Signal::Block` input may name any block in
2344/// the same slice regardless of declared position (source blocks, naturally, need none, and a
2345/// genuine cycle among these edges is rejected as `DaeError::AlgebraicLoop` before any step
2346/// runs — see `topological_order`'s own doc comment for how).
2347///
2348/// **Generic field-parsing errors**, shared by every `kind=` block and not repeated per
2349/// variant below: a field required by that `kind` but absent from the line is `line N: device
2350/// '<name>' missing field '<key>'`; present but not parseable as the expected type (almost
2351/// always `f64`) is `line N: device '<name>' field '<key>' is not a number`; present but read
2352/// by nothing for that `kind` (a misspelling, or a field that belongs to another kind) is
2353/// `line N: device '<name>' unknown field '<key>' (kind=<kind> accepts only: ...)`, listing the
2354/// keys that `kind` consulted on that line — the same shape a device card's unknown field
2355/// reports. Nothing on a block line is silently ignored: the only keys a kind accepts are the
2356/// ones documented in its own `## Parameters` (plus `ic=`/`y0=` below), and the escape hatches
2357/// (`cscript`/`pyblock`/`pyfunc`/`octfunc`/`octblock`) take no free-form parameters from the
2358/// netlist line either.
2359///
2360/// **Initial conditions.** Every block that carries state across steps accepts an optional
2361/// `ic=` (each such variant's own `## Parameters` says what it means there); an `ic=` on any
2362/// other kind is rejected rather than dropped — `line N: device '<name>' field 'ic': this kind
2363/// has no state to initialize -- 'ic' is accepted on ...` — as is a non-finite entry
2364/// (`initial condition must be finite`). `cscript`/`pyblock`/`octblock` initialize their own
2365/// state and take no `ic=`.
2366#[derive(Debug, Clone, PartialEq)]
2367pub struct BlockInstance {
2368    /// This block's own unique name.
2369    pub name: String,
2370    /// What this block computes.
2371    pub kind: BlockKind,
2372    /// Where each input comes from, in the order `kind` expects.
2373    pub inputs: Vec<Signal>,
2374    /// The state this block starts the run in, or `None` to start from rest (every state zero,
2375    /// every logic output low) exactly as before this field existed. Already resolved into the
2376    /// block's own state layout and already validated by the netlist parser, so `dae-runtime`
2377    /// only has to copy it in:
2378    ///
2379    /// - `StateSpace`/`DiscreteStateSpace` — the state vector $x(0)$, one entry per state.
2380    /// - `TransferFunction`/`DiscreteTransferFunction` — the state vector of the controllable
2381    ///   canonical realization (`ic=`), or the settled state a netlist's `y0=` resolves to (see
2382    ///   `continuous_blocks::TransferFunction::settled_state`).
2383    /// - `Pid` — the canonical state holding the controller output at the netlist's `ic=` with
2384    ///   zero error; `DiscretePid` — one entry, the integrator's accumulated value (`ic / ki`).
2385    /// - `Vco`/`PhaseShiftPwm` — one entry, the phase in cycles, $0 \le \phi_0 < 1$.
2386    /// - `Pmsm` — four entries, $(i_d, i_q, \omega_m, \theta_e)$.
2387    /// - `Hysteresis`/`SrLatch`/`FlipFlop` — one entry, `0.0` or `1.0`, the initial output.
2388    /// - `Counter` — one entry, the (integer-valued) initial count.
2389    ///
2390    /// `None` on every other kind: a stateless block has nothing to initialize, and
2391    /// `cscript`/`pyblock`/`octblock` own their initialization themselves.
2392    pub ic: Option<Vec<f64>>,
2393}
2394
2395/// How one ideal switch's gate state is resolved, every step: always from a named block's
2396/// current output, on while it's `>= 0.5`. No non-block-driven variant exists — even a
2397/// permanently-off gate is an explicit `Const(0.0)` wired through a `domain=voltage`
2398/// [`BlockKind::Sig2Phys`],
2399/// the same as every other gate — and no bare carrier-comparator variant exists either: that
2400/// comparison now lives entirely inside gate-driving `BlockKind`s themselves
2401/// ([`BlockKind::Pwm`]/[`BlockKind::PhaseShiftPwm`], or a hand-built chain of ordinary blocks),
2402/// so `GateBinding` has exactly one job — reading a number and thresholding it — regardless of
2403/// what produced that number: a modulator's own main/complement output, a
2404/// [`BlockKind::Hysteresis`] block (no carrier at all, event-driven bang-bang switching), or any
2405/// other block a caller composes.
2406#[derive(Debug, Clone, PartialEq)]
2407pub enum GateBinding {
2408    /// <!-- component -->
2409    /// # Gate Binding
2410    /// **Purpose:** how an ideal switch's gate state is resolved from a named block, every step.
2411    /// **Library:** Electrical Interface
2412    ///
2413    /// ## Description
2414    /// This is not a `kind=` block itself — it's the `gate=`/`ctrl=` field pair on a
2415    /// `kind=ideal_switch` device line. `GateBinding` has exactly one variant and exactly one
2416    /// job: reading a named block's current output and thresholding it at `>= v_gs_th`. No
2417    /// non-block-driven variant exists — even a permanently-off gate is an explicit `Const(0.0)`
2418    /// wired through a `domain=voltage` [`BlockKind::Sig2Phys`], the same as every other gate.
2419    /// The named block (`ctrl=`) must itself be a `domain=voltage` [`BlockKind::Sig2Phys`] — an
2420    /// ideal switch's gate is itself a voltage ($V_{GS}$, compared against this binding's
2421    /// own `v_gs_th`), not a distinct
2422    /// discrete-actuation signal domain (and never `domain=current`, even though `Sig2Phys`
2423    /// itself allows that domain for `I`-source targets).
2424    ///
2425    /// This comment used to say the gate was compared against `v_th`, which was **false**:
2426    /// `v_th` on a `kind=ideal_switch` line is the *body diode's* forward threshold and the
2427    /// gate path never read it. The comparison was a hard-coded `0.5`. That is the double
2428    /// meaning `v_gs_th` and the `body_` prefix exist to remove.
2429    ///
2430    /// ## Parameters
2431    /// - `gate=block` — the only accepted value; every gate is block-driven.
2432    /// - `ctrl=<name>` — the name of a declared `domain=voltage` [`BlockKind::Sig2Phys`] block.
2433    ///
2434    /// ## Errors
2435    /// - `gate=` missing entirely on a `kind=ideal_switch` line — rejected at parse time:
2436    ///   `missing field 'gate' (gate=block ctrl=<name> -- every gate is block-driven, see this
2437    ///   file's own module doc comment)`.
2438    /// - `gate=` present but not `block` — rejected at parse time: `unknown gate spec '<value>'
2439    ///   (only gate=block ctrl=<name> exists -- every gate is block-driven)`.
2440    /// - `ctrl=` naming a block that isn't a `domain=voltage` [`BlockKind::Sig2Phys`] (including
2441    ///   a `domain=current` one) — rejected at `dae-runtime`'s validation stage (not netlist
2442    ///   parse time): `DaeError::GateTargetNotSig2Voltage`.
2443    ///
2444    /// ## Netlist form
2445    /// ```text
2446    /// NAME kind=ideal_switch r_on=<f64> body_g_breakdown=<f64> body_v_breakdown=<f64> \
2447    ///      body_g_off=<f64> \
2448    ///      body_v_f=<f64> body_g_on=<f64> gate=block ctrl=<name> [v_gs_th=<f64>]
2449    /// ```
2450    ///
2451    /// ## Example
2452    /// An ideal switch permanently held on via a `Const(1)` wired through `Sig2Phys` — the
2453    /// plain `D1 in out idealswitchmodel` line gives the electrical connectivity (drain, source;
2454    /// the model name is unused for a `kind=ideal_switch`-overridden device), the same-named
2455    /// `kind=ideal_switch` line supplies the physics and gate. Verified end to end: `V(out)`
2456    /// settles to `5 * 1000 / (1000 + 0.1) ≈ 4.9995` (a fully-on 0.1 Ω ideal switch in series
2457    /// with a 1 kΩ load):
2458    /// ```text
2459    /// ONVAL kind=const value=1
2460    /// ONGATE kind=sig2phys domain=voltage in=ONVAL
2461    /// V1 in 0 5
2462    /// D1 in out idealswitchmodel
2463    /// D1 kind=ideal_switch r_on=0.1 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 \
2464    ///      body_v_f=0.5 body_g_on=5 \
2465    ///      gate=block ctrl=ONGATE
2466    /// R1 out 0 1k
2467    /// ```
2468    ///
2469    /// On while the named block's current output is at or above `v_gs_th`.
2470    Block {
2471        /// The named block whose output drives this gate.
2472        ctrl: String,
2473        /// The gate threshold, datasheet $V_{GS(th)}$. Defaults to `0.5`.
2474        ///
2475        /// This field closes a trap rather than adding a knob. Before it, the comparison was a
2476        /// hard-coded `0.5` and the language had nowhere to put a real gate threshold -- so
2477        /// anyone modelling a device with a 5 V gate reached for the nearest-looking name,
2478        /// `v_th`, which was the *body diode's* forward threshold. The deck stayed valid, the run
2479        /// completed, and the converter's freewheeling path silently acquired a 5 V diode drop.
2480        ///
2481        /// With `v_gs_th` honoured here the obvious thing to write is also the correct thing, and
2482        /// no body-diode field is a candidate. The `0.5` default leaves every deck written before
2483        /// this field existed behaving identically.
2484        v_gs_th: f64,
2485    },
2486}
2487
2488impl GateBinding {
2489    /// The block this binding reads from.
2490    pub fn source_blocks(&self) -> [Option<&str>; 2] {
2491        match self {
2492            GateBinding::Block { ctrl, .. } => [Some(ctrl), None],
2493        }
2494    }
2495
2496    /// # Panics
2497    /// If the named block's own current value is a `SignalValue::Vector` — unreachable in
2498    /// practice, since the *only* legal `GateBinding` target is a `domain=voltage`
2499    /// `BlockKind::Sig2Phys` converter (enforced before any step runs), and `Sig2Phys` itself
2500    /// rejects a `Vector` input at evaluation time — there is no way for a validly-targeted gate
2501    /// to ever see one here. Also panics if `name` isn't in `outputs` at all, exactly as before
2502    /// this variant existed (equally unreachable, for the same "checked before any step runs"
2503    /// reason).
2504    pub fn resolve(&self, outputs: &BTreeMap<String, SignalValue>) -> SwitchState {
2505        let GateBinding::Block {
2506            ctrl: name,
2507            v_gs_th,
2508        } = self;
2509        let value = outputs[name.as_str()].as_scalar().unwrap_or_else(|| {
2510            panic!(
2511                "gate '{name}' resolved to a vector signal -- unreachable, since Sig2Phys \
2512                 itself must already reject a vector input"
2513            )
2514        });
2515        if value >= *v_gs_th {
2516            SwitchState::On
2517        } else {
2518            SwitchState::Off
2519        }
2520    }
2521}
2522/// A short, human-readable name for a `BlockKind`, for error messages that need to say what a
2523/// mistargeted block actually is (e.g. `DaeError::GateTargetNotSig2Voltage`/
2524/// `SourceNotSig2PhysicalConverter`) without dumping its full parameter set.
2525pub fn block_kind_name(kind: &BlockKind) -> &'static str {
2526    match kind {
2527        BlockKind::Const(_) => "const",
2528        BlockKind::Time => "time",
2529        BlockKind::Pwc { .. } => "pwc",
2530        BlockKind::Pwl { .. } => "pwl",
2531        BlockKind::Waveform(TransientFunction::Sin { .. }) => "sinwave",
2532        BlockKind::Waveform(TransientFunction::Pulse { .. }) => "pulsewave",
2533        BlockKind::Waveform(TransientFunction::Exp { .. }) => "expwave",
2534        BlockKind::Waveform(TransientFunction::Sffm { .. }) => "sffmwave",
2535        // Never actually constructed (general-simulator-cli only builds `Waveform` from
2536        // Sin/Pulse/Exp/Sffm — a Pwl-shaped waveform always goes through `BlockKind::Pwl`
2537        // above instead, since only that variant supports `repeat`), but `TransientFunction`
2538        // is a 5-variant enum so this match must still be exhaustive.
2539        BlockKind::Waveform(TransientFunction::Pwl(_)) => "waveform(pwl)",
2540        BlockKind::Sum(_) => "sum",
2541        BlockKind::Gain(_) => "gain",
2542        BlockKind::Pid { .. } => "pid",
2543        BlockKind::StateSpace(_) => "statespace",
2544        BlockKind::TransferFunction(_) => "tf",
2545        BlockKind::DiscreteStateSpace { .. } => "discretestatespace",
2546        BlockKind::DiscreteTransferFunction { .. } => "discretetf",
2547        BlockKind::DiscretePid { .. } => "discretepid",
2548        BlockKind::Vco(_) => "vco",
2549        BlockKind::Pwm { .. } => "pwm",
2550        BlockKind::PhaseShiftPwm { .. } => "pspwm",
2551        BlockKind::Product => "product",
2552        BlockKind::Saturation(_) => "saturation",
2553        BlockKind::Table(_) => "table",
2554        BlockKind::MathFn1(f) => f.name(),
2555        BlockKind::MathFn2(f) => f.name(),
2556        BlockKind::MathFn3(f) => f.name(),
2557        BlockKind::Hysteresis(_) => "hysteresis",
2558        BlockKind::LogicGate(op) => op.name(),
2559        BlockKind::SrLatch { .. } => "srlatch",
2560        BlockKind::FlipFlop { kind, .. } => kind.name(),
2561        BlockKind::Counter { .. } => "counter",
2562        BlockKind::CScript { .. } => "cscript",
2563        BlockKind::PyBlock { .. } => "pyblock",
2564        BlockKind::PyFunction { .. } => "pyfunc",
2565        BlockKind::OctFunc { .. } => "octfunc",
2566        BlockKind::OctBlock { .. } => "octblock",
2567        BlockKind::CoordinateTransform { kind, .. } => kind.name(),
2568        BlockKind::Pmsm { .. } => "pmsm",
2569        BlockKind::Phys2Sig(_) => "phys2sig",
2570        BlockKind::Sig2Phys {
2571            domain: PhysicalDomain::Voltage,
2572        } => "sig2phys(domain=voltage)",
2573        BlockKind::Sig2Phys {
2574            domain: PhysicalDomain::Current,
2575        } => "sig2phys(domain=current)",
2576    }
2577}