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 ///
589 /// ## Errors
590 /// - `n <= 0.0` — rejected at parse time (`invalid PID (NonPositiveFilterCoefficient)`): a
591 /// non-positive filter coefficient puts the derivative filter's pole at the origin or in
592 /// the right half-plane, a non-causal or outright unstable filter.
593 /// - Giving only one of `clamp_lo_in`/`clamp_hi_in` (not both, and not neither) — rejected at
594 /// parse time: `'clamp_lo_in'/'clamp_hi_in' must both be given together (dynamic clamp) or
595 /// both omitted (fixed clamp= clamp_lo/clamp_hi)`.
596 /// - A missing or non-numeric field (`kp`/`ki`/`kd`/`n`/`clamp_lo`/`clamp_hi`) is the same
597 /// generic `missing field '<key>'`/`field '<key>' is not a number` error every `kind=`
598 /// block produces — see [`BlockInstance`]'s own doc comment.
599 ///
600 /// ## Netlist form
601 /// ```text
602 /// NAME kind=pid in=<signal> kp=<f64> ki=<f64> kd=<f64> n=<f64> \
603 /// (clamp_lo=<f64> clamp_hi=<f64> | clamp_lo_in=<signal> clamp_hi_in=<signal>)
604 /// ```
605 ///
606 /// ## Example
607 /// A fixed-clamp PI (no derivative action) regulating an error signal `ERR` to `[-1, 1]`:
608 /// ```text
609 /// PID1 kind=pid in=ERR kp=1 ki=0 kd=0 n=1 clamp_lo=-1 clamp_hi=1
610 /// ```
611 Pid {
612 /// The compiled PID gains/state.
613 pid: Pid,
614 /// The fixed-vs-dynamic anti-windup bound.
615 clamp: PidClamp,
616 },
617 /// <!-- component -->
618 /// # State-Space
619 /// **Purpose:** an arbitrary continuous-time linear block given directly as `(A, B, C, D)`
620 /// matrices.
621 /// **Library:** Control / Continuous
622 ///
623 /// ## Description
624 /// A compensator/filter that doesn't already have a named convenience constructor, e.g. a
625 /// low-pass filter placed ahead of a `Pid` to damp a resonant plant:
626 /// $\dot{x} = Ax + Bu, \quad y = Cx + Du$. Genuinely MIMO: `B`'s own column count
627 /// (`StateSpace::inputs()`) and `C`'s own row count (`StateSpace::outputs()`) are not
628 /// constrained to `1` — a single-input single-output declaration is simply the `1x1` case.
629 /// `outputs() == 1` produces a `SignalValue::Scalar`; `outputs() > 1` produces a
630 /// `SignalValue::Vector` of that length. Inputs are the flattened concatenation of this
631 /// block's own declared `Signal`s (scalar or vector, in order) — see `evaluate_blocks`'/
632 /// `dae-runtime`'s own input-flattening convention, shared with
633 /// `CoordinateTransform`/`Pmsm`/`CScript`. No anti-windup (that's specifically a `Pid`
634 /// output's own concern, not every dynamic block's); stepped forward unconditionally every
635 /// timestep via `StateSpace::rk4_step` (RK4, not backward Euler — this block's own state is
636 /// never part of the circuit's own descriptor-DAE solve).
637 ///
638 /// ## Parameters
639 /// - `a=<matrix>` — the `n x n` dynamics matrix, e.g. `a=[[0,1],[-1,-1]]`.
640 /// - `b=<matrix|vector>` — `n x p` (`p` inputs); a flat vector (`b=[1,0]`) is SISO shorthand
641 /// for `p=1`, matching the pre-vector-signals convention unchanged.
642 /// - `c=<matrix|vector>` — `q x n` (`q` outputs); same flat-vector SISO shorthand for `q=1`.
643 /// - `d=<matrix|scalar>` — optional, defaults to an all-zero `q x n` matrix; a bare scalar
644 /// is only accepted when `q=1` and `p=1` (SISO) — a MIMO system must give the full matrix,
645 /// since a lone scalar has no unambiguous placement in a larger `D`.
646 /// - `in=<signal>` (SISO, `p` must be `1`) or `inputs=<sig1,...>` (exactly `p` entries,
647 /// each independently scalar or vector; the *flattened* total length must equal `p`,
648 /// checked at evaluation time, not parse time, since a vector signal's own arity isn't
649 /// knowable from netlist text alone).
650 ///
651 /// ## Errors
652 /// - `q != 1 || p != 1` with a bare scalar `d=` — rejected at parse time: `field 'd' is a
653 /// bare scalar, but this system has <q> output(s) and <p> input(s) -- declare
654 /// 'd=[[...],...]' (<q>x<p>) for a MIMO system, a bare scalar is only valid for a 1x1
655 /// (SISO) one`.
656 /// - There is no `e=` (descriptor-matrix) field exposed at the netlist level yet, so
657 /// `StateSpaceError::NonInvertibleDescriptorMatrix` (a singular descriptor matrix) is
658 /// currently unreachable through this parser — `e` is always `None` (ordinary,
659 /// non-descriptor state-space) for every netlist-declared instance.
660 ///
661 /// ## Netlist form
662 /// ```text
663 /// NAME kind=statespace a=<matrix> b=<matrix|vector> c=<matrix|vector> [d=<matrix|scalar>] \
664 /// (in=<signal> | inputs=<sig1,sig2,...>)
665 /// ```
666 ///
667 /// ## Example
668 /// A first-order low-pass ($\dot{x} = -x + u$, $y = x$, pole at $s=-1$) — verified end to
669 /// end, `SRC=1` settling toward `SS1=1`:
670 /// ```text
671 /// SRC kind=const value=1
672 /// SS1 kind=statespace a=[[-1]] b=[1] c=[1] in=SRC
673 /// ```
674 StateSpace(StateSpace),
675 /// <!-- component -->
676 /// # Transfer Function
677 /// **Purpose:** a single-input single-output block given as a rational $N(s)/D(s)$.
678 /// **Library:** Control / Continuous
679 ///
680 /// ## Description
681 /// Numerator/denominator coefficients, highest-degree first, rather than a `Pid`'s
682 /// `Kp`/`Ki`/`Kd` convenience parameterization — e.g. a hand-derived PID-with-filtered-
683 /// derivative compensator ($C(s) = K_p + K_i/s + K_d N s/(s+N)$, put over one denominator
684 /// first: a pure derivative term alone is non-causal/unrealizable, so every real PID,
685 /// textbook or otherwise, filters it — see `continuous_blocks::Pid::to_transfer_function`'s
686 /// own doc comment for the derivation). Compiled once via
687 /// `TransferFunction::to_state_space` (controllable canonical form); no anti-windup, for
688 /// the same reason [`BlockKind::StateSpace`] above has none.
689 ///
690 /// ## Parameters
691 /// - `num=<vector>` — numerator coefficients, highest-degree first, e.g. `num=[1,2]` for
692 /// $s + 2$.
693 /// - `den=<vector>` — denominator coefficients, highest-degree first, e.g. `den=[1,3,2]`
694 /// for $s^2 + 3s + 2$. Must be non-empty and nonzero-leading; `deg(num) <= deg(den)`
695 /// (a proper transfer function — every realizable continuous-time physical system is).
696 /// - `in=<signal>` — the single input (one input, always — this block is SISO by
697 /// definition).
698 ///
699 /// ## Errors
700 /// - `den=[]` (empty) — rejected at parse time: `invalid transfer function
701 /// (EmptyDenominator)`.
702 /// - `den`'s first (highest-degree) coefficient is `0.0` — rejected: `invalid transfer
703 /// function (ZeroLeadingDenominatorCoefficient)` (a zero leading coefficient means the
704 /// stated degree is a lie — the true denominator degree is lower).
705 /// - `deg(num) > deg(den)` (more numerator coefficients than denominator ones) — rejected:
706 /// `invalid transfer function (ImproperTransferFunction)` — an improper transfer function
707 /// has no causal realization.
708 ///
709 /// ## Netlist form
710 /// ```text
711 /// NAME kind=tf num=<vector> den=<vector> in=<signal>
712 /// ```
713 ///
714 /// ## Example
715 /// The same first-order low-pass as `StateSpace`'s own example ($1/(s+1)$), verified to
716 /// settle toward the same steady-state value:
717 /// ```text
718 /// SRC kind=const value=1
719 /// TF1 kind=tf num=[1] den=[1,1] in=SRC
720 /// ```
721 TransferFunction(TransferFunction),
722 /// <!-- component -->
723 /// # Discrete State-Space
724 /// **Purpose:** the discrete-domain counterpart to `StateSpace` — a plain linear recursion.
725 /// **Library:** Control / Discrete
726 ///
727 /// ## Description
728 /// $x_{i+1} = Ax_i + Bu_i$, $y_i = Cx_i + Du_i$ — no RK4, no `dt` at all: `A`/`B`/`C`/`D`
729 /// are already discrete-domain matrices, given directly by the netlist author, not derived
730 /// from continuous ones. `sample_time` is **required** here (unlike `cscript`'s own
731 /// optional field) and must be periodic — a discrete system's own dynamics *are* its
732 /// sample period, there is no "continuous" fallback the way omitting it means for
733 /// `cscript`, and a solver-chosen variable schedule doesn't compose with a fixed-period
734 /// recursion at all. See `general-simulator`'s own `book/dev-guide/src/discrete-time-blocks.md`.
735 ///
736 /// ## Parameters
737 /// - `a=`/`b=`/`c=`/`d=`/`in=`/`inputs=` — identical shape and MIMO rules to
738 /// [`BlockKind::StateSpace`]'s own Parameters (see there); the only difference is these
739 /// matrices are already discrete-domain.
740 /// - `ts=<f64>` / `freq=<f64>` (with optional `to=<f64>` offset) — required; unlike
741 /// `cscript`, `ts=variable` is not accepted here (see Errors).
742 ///
743 /// ## Errors
744 /// - Same MIMO scalar-`d` rejection as `StateSpace` (see there).
745 /// - `ts=`/`freq=` missing entirely — rejected at parse time: `missing 'ts=' or 'freq='
746 /// -- a discrete-time block's own sample period is not optional (its dynamics *are* that
747 /// period), unlike the optional 'ts='/'freq=' on kind=cscript/pyblock/pyfunc`.
748 /// - `ts=variable` — rejected at parse time: `ts=variable is not available here -- a
749 /// discrete block's own recursion has its coefficients baked in at one fixed sample
750 /// period, which 'the block decides its own next execution time' doesn't compose with`.
751 ///
752 /// ## Netlist form
753 /// ```text
754 /// NAME kind=discretestatespace a=<matrix> b=<matrix|vector> c=<matrix|vector> \
755 /// [d=<matrix|scalar>] (ts=<f64> | freq=<f64> [to=<f64>]) \
756 /// (in=<signal> | inputs=<sig1,sig2,...>)
757 /// ```
758 ///
759 /// ## Example
760 /// A discrete integrator ($x_{i+1} = x_i + 0.1 \cdot u_i$, $y=x$, `ts=0.1`) fed a constant
761 /// `1` — verified end to end, `DS1` reaching `0.5` after 5 sample hits ($5 \times 0.1$):
762 /// ```text
763 /// SRC kind=const value=1
764 /// DS1 kind=discretestatespace a=[[1]] b=[0.1] c=[1] ts=0.1 in=SRC
765 /// ```
766 DiscreteStateSpace {
767 /// The discrete-domain `A`/`B`/`C`/`D` matrices.
768 ss: StateSpace,
769 /// Must be [`SampleTimeSpec::Periodic`] — a discrete system's dynamics are its sample period.
770 sample_time: SampleTimeSpec,
771 },
772 /// <!-- component -->
773 /// # Discrete Transfer Function
774 /// **Purpose:** the discrete-domain counterpart to `Transfer Function` — $Y(z)/U(z) = N(z)/D(z)$.
775 /// **Library:** Control / Discrete
776 ///
777 /// ## Description
778 /// Coefficients already in the $z$-domain. Realized via the exact same
779 /// `TransferFunction::to_state_space` the continuous version uses (coefficient-to-
780 /// companion-form conversion is domain-agnostic algebra — it doesn't know or care whether
781 /// the variable is called $s$ or $z$), evaluated via `StateSpace::discrete_step` instead of
782 /// `rk4_step`. Same mandatory-periodic-`sample_time` rule as [`BlockKind::DiscreteStateSpace`].
783 ///
784 /// ## Parameters
785 /// - `num=`/`den=`/`in=` — identical shape and validity rules to
786 /// [`BlockKind::TransferFunction`]'s own Parameters (see there); coefficients are already
787 /// in the $z$-domain rather than $s$.
788 /// - `ts=<f64>` / `freq=<f64>` (with optional `to=<f64>`) — required, same rule as
789 /// `DiscreteStateSpace`.
790 ///
791 /// ## Errors
792 /// Identical to [`BlockKind::TransferFunction`]'s own (`EmptyDenominator`,
793 /// `ZeroLeadingDenominatorCoefficient`, `ImproperTransferFunction`), plus the same
794 /// missing-`ts=`/`ts=variable`-rejected errors as `DiscreteStateSpace`.
795 ///
796 /// ## Netlist form
797 /// ```text
798 /// NAME kind=discretetf num=<vector> den=<vector> (ts=<f64> | freq=<f64> [to=<f64>]) in=<signal>
799 /// ```
800 ///
801 /// ## Example
802 /// The exact $z$-domain realization of `DiscreteStateSpace`'s own example above ($Y(z)/U(z)
803 /// = 0.1/(z-1)$, a discrete integrator) — verified to reach the same `DTF1=0.5` after 5
804 /// sample hits:
805 /// ```text
806 /// SRC kind=const value=1
807 /// DTF1 kind=discretetf num=[0.1] den=[1,-1] ts=0.1 in=SRC
808 /// ```
809 DiscreteTransferFunction {
810 /// The `z`-domain numerator/denominator coefficients.
811 tf: TransferFunction,
812 /// Must be [`SampleTimeSpec::Periodic`].
813 sample_time: SampleTimeSpec,
814 },
815 /// <!-- component -->
816 /// # Discrete PID Controller
817 /// **Purpose:** the discrete-domain counterpart to `PID Controller`.
818 /// **Library:** Control / Discrete
819 ///
820 /// ## Description
821 /// Reuses the exact same [`PidClamp`] anti-windup mechanism as [`BlockKind::Pid`], but the
822 /// integral/derivative actions advance once per declared sample period via
823 /// `continuous_blocks::DiscretePid::step` instead of RK4-integrating continuously. Not
824 /// built by converting to one combined $z$-domain transfer function and back — realized
825 /// directly from the block's own diagram (three parallel branches, summed). Same
826 /// mandatory-periodic-`sample_time` rule as `DiscreteStateSpace`/`DiscreteTransferFunction`
827 /// above — this block's own integration `period` is set *from* `sample_time`, not a
828 /// separately-entered value.
829 ///
830 /// ## Parameters
831 /// - `in=<signal>`, `kp=`/`ki=`/`kd=`/`n=`, and the fixed-vs-dynamic clamp fields
832 /// (`clamp_lo=`/`clamp_hi=` or `clamp_lo_in=`/`clamp_hi_in=`) — identical meaning to
833 /// [`BlockKind::Pid`]'s own Parameters (see there).
834 /// - `ts=<f64>` / `freq=<f64>` (with optional `to=<f64>`) — required.
835 /// - `integration_method=<forward|backward|trapezoidal>` — optional, defaults to
836 /// `forward` (forward Euler); selects the discrete integration rule the integral term
837 /// uses each sample period.
838 ///
839 /// ## Errors
840 /// - Same `n <= 0.0` and clamp-pairing errors as [`BlockKind::Pid`] (see there).
841 /// - Same missing-`ts=`/`ts=variable`-rejected errors as `DiscreteStateSpace`.
842 /// - `integration_method` present but not one of the three known names — rejected at parse
843 /// time: `unknown integration_method '<value>' (expected 'forward', 'backward', or
844 /// 'trapezoidal')`.
845 ///
846 /// ## Netlist form
847 /// ```text
848 /// NAME kind=discretepid in=<signal> kp=<f64> ki=<f64> kd=<f64> n=<f64> \
849 /// (ts=<f64> | freq=<f64> [to=<f64>]) \
850 /// (clamp_lo=<f64> clamp_hi=<f64> | clamp_lo_in=<signal> clamp_hi_in=<signal>) \
851 /// [integration_method=<forward|backward|trapezoidal>]
852 /// ```
853 ///
854 /// ## Example
855 /// A discrete PI (no derivative action) sampled every 0.1 s, integrating a fixed error
856 /// signal once per sample hit — verified end to end, `DPID1` stepping `0.5 -> 0.525 -> 0.55
857 /// -> 0.575 -> 0.6` at each `ts=0.1` boundary (unchanged between hits, matching the
858 /// discrete-recursion contract exactly):
859 /// ```text
860 /// ERR kind=const value=0.5
861 /// DPID1 kind=discretepid in=ERR kp=1 ki=0.5 kd=0 n=1 ts=0.1 clamp_lo=-1 clamp_hi=1
862 /// ```
863 DiscretePid {
864 /// The compiled discrete PID gains/state.
865 pid: DiscretePid,
866 /// The fixed-vs-dynamic anti-windup bound.
867 clamp: PidClamp,
868 /// Must be [`SampleTimeSpec::Periodic`]; also sets `pid`'s own `period`.
869 sample_time: SampleTimeSpec,
870 },
871 /// <!-- component -->
872 /// # VCO (Voltage-Controlled Oscillator)
873 /// **Purpose:** a bare, standalone oscillator producing a `[0, 1)` ramp from a frequency input.
874 /// **Library:** Control / Continuous
875 ///
876 /// ## Description
877 /// A raw frequency-to-ramp conversion, still useful on its own outside gate-driving PWM —
878 /// e.g. feeding a `MathFn1::Sin`/`Gain` chain to build a variable-frequency sinusoidal
879 /// reference. Not how a gate-driving PWM modulator gets its own switching frequency, though
880 /// — see [`BlockKind::Pwm`]/[`BlockKind::PhaseShiftPwm`] below, neither of which reads this
881 /// block at all (each owns its own internal oscillator).
882 ///
883 /// ## Parameters
884 /// - `f_min=<f64>`, `f_max=<f64>` — the frequency clamp range, Hz; the one input (`in=`) is
885 /// internally clamped to `[f_min, f_max]` before integration.
886 /// - `in=<signal>` — the frequency command, Hz (one input).
887 ///
888 /// ## Errors
889 /// - `f_min > f_max` — rejected at parse time: `invalid vco (FMinExceedsFMax)`.
890 ///
891 /// ## Netlist form
892 /// ```text
893 /// NAME kind=vco f_min=<f64> f_max=<f64> in=<signal>
894 /// ```
895 ///
896 /// ## Example
897 /// A fixed 10 Hz oscillator, verified to produce a `[0,1)` ramp (not stuck at a constant):
898 /// ```text
899 /// FREQ kind=const value=10
900 /// VCO1 kind=vco f_min=1 f_max=1000 in=FREQ
901 /// ```
902 Vco(Vco),
903 /// <!-- component -->
904 /// # PWM Modulator 1
905 /// **Purpose:** fixed-frequency, duty-driven, active-high complementary PWM.
906 /// **Library:** Power Electronics
907 ///
908 /// ## Description
909 /// One input, `duty` (`[0,1]`, clamped, read fresh every step from anywhere in the graph —
910 /// a `Pid`, a filtered `TransferFunction`, a plain `Const`...), fixed carrier frequency
911 /// `freq_hz`. Two outputs, following the [`BlockKind::CScript`] `output_names` convention:
912 /// `output_names[0]` (aliasing this block's own `.name`) is the main signal, `output_names[1]`
913 /// its active-high complement. `red`/`fed` (seconds) are independent per-edge dead-time
914 /// delays — see `math_ops::complementary_pwm_with_deadtime` (in `dae-runtime`) for the
915 /// exact rising-edge-only-delay semantics and why `red=fed=0.0` recovers the ideal,
916 /// gap-free, overlap-free pair exactly. Stateless: a pure function of `(t, duty)` every
917 /// step, no internal oscillator.
918 ///
919 /// ## Parameters
920 /// - `freq=<f64>` — fixed carrier frequency, Hz.
921 /// - `in=<signal>` — the duty command, `[0,1]` (clamped internally; no error for a value
922 /// outside that range).
923 /// - `red=<f64>`, `fed=<f64>` — optional, default `0.0`; rising/falling-edge dead time,
924 /// seconds.
925 /// - `outputs=<main,complement>` — optional; defaults to `<name>,<name>_comp`. Exactly 2
926 /// entries if given.
927 ///
928 /// ## Errors
929 /// - `outputs=` with a count other than 2 — rejected at parse time: `'outputs' needs
930 /// exactly 2 entries (main, complement; got <n>)`.
931 /// - `red=`/`fed=` present but not a number — the generic `field '<key>' is not a number`
932 /// error.
933 ///
934 /// ## Netlist form
935 /// ```text
936 /// NAME kind=pwm freq=<f64> in=<signal> [red=<f64>] [fed=<f64>] [outputs=<main,complement>]
937 /// ```
938 ///
939 /// ## Example
940 /// A 10 kHz, 30% duty modulator with no dead time — verified end to end: `PWM1` high
941 /// (`>= 0.99`) for the first ~30% of each 100 µs period and its complement exactly
942 /// inverted, `PWM1 + PWM1_comp == 1` at every sampled instant:
943 /// ```text
944 /// DUTY kind=const value=0.3
945 /// PWM1 kind=pwm freq=10000 in=DUTY
946 /// ```
947 Pwm {
948 /// Fixed carrier frequency, Hz.
949 freq_hz: f64,
950 /// Rising-edge dead time, seconds.
951 red: f64,
952 /// Falling-edge dead time, seconds.
953 fed: f64,
954 /// `[main, complement]` output names.
955 output_names: Vec<String>,
956 },
957 /// <!-- component -->
958 /// # PWM Modulator 2 (Phase-Shift PWM)
959 /// **Purpose:** frequency+phase+duty-driven, active-high complementary PWM with its own
960 /// internal oscillator.
961 /// **Library:** Power Electronics
962 ///
963 /// ## Description
964 /// This is *not* a variant of [`BlockKind::Vco`] — it owns its own frequency-integration
965 /// state directly (`osc` reuses [`Vco`]'s own clamp-and-integrate math purely as an
966 /// implementation detail, the same formula, not a shared block reference), so two instances
967 /// fed the *same* `freq` input stay bit-for-bit phase-synchronized (deterministic
968 /// integration, same `dt`, same starting phase `0.0`), the way e.g. a dual-active-bridge's
969 /// two legs need to be, without a separately-declared shared oscillator block in between.
970 /// `red`/`fed` are in seconds, exactly like [`BlockKind::Pwm`]'s own, but converted to a
971 /// phase fraction using *this step's own* resolved frequency (not a fixed constant) — this
972 /// matters for a variable-frequency converter, since the same absolute dead time eats a
973 /// larger fraction of the period at higher switching frequency, a real effect on e.g. a
974 /// resonant converter's own ZVS margin, not just bookkeeping.
975 ///
976 /// ## Parameters
977 /// - `f_min=<f64>`, `f_max=<f64>` — the internal oscillator's frequency clamp range, Hz.
978 /// - `inputs=<freq,phase,duty>` — exactly 3, in this order: `freq` (Hz, clamped internally
979 /// to `[f_min, f_max]`), `phase` (`[0,1)`, a phase-shift command as a fraction of one
980 /// carrier period — *not* this block's own internal integration state, a different
981 /// thing), `duty` (`[0,1]`, clamped).
982 /// - `red=<f64>`, `fed=<f64>` — optional, default `0.0`; seconds, converted internally to a
983 /// phase fraction using the current resolved frequency.
984 /// - `outputs=<main,complement>` — optional; defaults to `<name>,<name>_comp`.
985 ///
986 /// ## Errors
987 /// - `inputs=` with a count other than 3 — rejected at parse time: `kind='pspwm' needs 3
988 /// inputs (freq,phase,duty; got <n>)`.
989 /// - `f_min > f_max` — rejected at parse time: `invalid pspwm oscillator
990 /// (FMinExceedsFMax)`.
991 /// - `outputs=` with a count other than 2 — same error as [`BlockKind::Pwm`]'s own.
992 ///
993 /// ## Netlist form
994 /// ```text
995 /// NAME kind=pspwm f_min=<f64> f_max=<f64> inputs=<freq_signal,phase_signal,duty_signal> \
996 /// [red=<f64>] [fed=<f64>] [outputs=<main,complement>]
997 /// ```
998 ///
999 /// ## Example
1000 /// A 10 kHz, zero-phase-shift, 40% duty modulator — verified end to end: both outputs
1001 /// `[0,1]`-valued, `PSPWM1 + PSPWM1_comp == 1` at every sampled instant:
1002 /// ```text
1003 /// FREQ kind=const value=10000
1004 /// PHASE kind=const value=0
1005 /// DUTY kind=const value=0.4
1006 /// PSPWM1 kind=pspwm f_min=1000 f_max=50000 inputs=FREQ,PHASE,DUTY
1007 /// ```
1008 PhaseShiftPwm {
1009 /// The internal frequency-integrating oscillator.
1010 osc: Vco,
1011 /// Rising-edge dead time, seconds.
1012 red: f64,
1013 /// Falling-edge dead time, seconds.
1014 fed: f64,
1015 /// `[main, complement]` output names.
1016 output_names: Vec<String>,
1017 },
1018 /// <!-- component -->
1019 /// # Product
1020 /// **Purpose:** multiplies all its inputs together.
1021 /// **Library:** Sources / Math operations
1022 ///
1023 /// ## Description
1024 /// The product $x_1 \cdot x_2 \cdot \dots$ of its inputs. Input-shape rule shared with
1025 /// `Sum`: all-`Scalar` inputs give a `Scalar`; otherwise every input must be a `Vector` of
1026 /// one common length `N`, multiplied elementwise to a `Vector(N)` — a mix of `Scalar` and
1027 /// `Vector` inputs is rejected rather than guessed at (see the Sum entry).
1028 ///
1029 /// ## Parameters
1030 /// - `inputs=<sig1,sig2,...>` — comma-separated input signals, one per factor.
1031 ///
1032 /// ## Errors
1033 /// - Mixed `Scalar`/`Vector` inputs — rejected at evaluation time:
1034 /// `VectorSignalNotSupported { block: "<name>" }`.
1035 /// - `Vector` inputs of differing lengths — rejected at evaluation time:
1036 /// `VectorSignalSizeMismatch { block: "<name>", expected: N, got: M }`.
1037 /// - A missing `inputs=` is the generic `missing field 'inputs'` error — see
1038 /// [`BlockInstance`]'s own doc comment.
1039 ///
1040 /// ## Netlist form
1041 /// ```text
1042 /// NAME kind=product inputs=<sig1,sig2,...>
1043 /// ```
1044 ///
1045 /// ## Example
1046 /// ```text
1047 /// A kind=const value=2
1048 /// B kind=const value=3
1049 /// C kind=const value=4
1050 /// P kind=product inputs=A,B,C
1051 /// ```
1052 Product,
1053 /// <!-- component -->
1054 /// # Saturation
1055 /// **Purpose:** clamps its single input to a symmetric ±limit.
1056 /// **Library:** Sources / Math operations
1057 ///
1058 /// ## Description
1059 /// Clamps its input to `[-limit, limit]` (elementwise for a `Vector` input) — the
1060 /// block-diagram saturation/limiter. See `continuous_blocks::math_ops::saturation`'s own
1061 /// doc comment for why this is a plain direct evaluation rather than a PWL device: the
1062 /// active segment depends only on this block's own input, so there is no
1063 /// simultaneous-resolution problem the way there is for a diode's terminal voltage.
1064 ///
1065 /// ## Parameters
1066 /// - `in=<signal>` — the single input.
1067 /// - `limit=<f64>` — the symmetric bound. Must be non-negative — but this is **not** checked
1068 /// at parse time; a negative `limit` panics the process at the first evaluation (see
1069 /// Errors).
1070 ///
1071 /// ## Errors
1072 /// - `limit=-1` — not a clean error: parse time never validates `limit`, so the evaluation
1073 /// code's own assert fires and the whole process panics with
1074 /// `limit must be nonnegative`. Keep `limit >= 0`.
1075 /// - A missing `in=`/`limit=` or a non-numeric `limit=` is the generic
1076 /// `missing field '<key>'`/`field '<key>' is not a number` error — see
1077 /// [`BlockInstance`]'s own doc comment.
1078 ///
1079 /// ## Netlist form
1080 /// ```text
1081 /// NAME kind=saturation in=<signal> limit=<f64>
1082 /// ```
1083 ///
1084 /// ## Example
1085 /// The time ramp (0..2 s) clamped to ±1 — passes through while `|x| <= 1`, holds 1 beyond:
1086 /// ```text
1087 /// X kind=time
1088 /// LIM kind=saturation in=X limit=1
1089 /// ```
1090 Saturation(f64),
1091 /// <!-- component -->
1092 /// # Table Lookup
1093 /// **Purpose:** linear interpolation through a fixed `(x, y)` table.
1094 /// **Library:** Sources / Math operations
1095 ///
1096 /// ## Description
1097 /// A `table(x, a, b, c, d, ...)`-style lookup: linear interpolation through the fixed
1098 /// `(x, y)` breakpoints (elementwise for a `Vector` input), clamped — not extrapolated —
1099 /// outside the range, holding the nearest endpoint's `y`. Implemented by
1100 /// `continuous_blocks::waveform_arithmetic::table`.
1101 ///
1102 /// ## Parameters
1103 /// - `in=<signal>` — the single input (`x`).
1104 /// - `points=[[x1,y1],[x2,y2],...]` — the lookup table as a Python list of 2-element lists.
1105 /// Sorted ascending by `x` at parse time, so declaration order doesn't matter. Must have
1106 /// at least one point — but that is **not** checked at parse time; an empty list panics
1107 /// the process at the first evaluation (see Errors).
1108 ///
1109 /// ## Errors
1110 /// - A `points=` entry that is not a 2-element `[x,y]` list — rejected at parse time:
1111 /// `field 'points': each entry must be a 2-element '[x,y]' list (got '[1.0]')`.
1112 /// - `points=[]` — not a clean error: parse time never rejects an empty list, so the
1113 /// evaluation code's own assert fires and the whole process panics with
1114 /// `table needs at least one point`.
1115 /// - A missing `in=`/`points=` is the generic `missing field '<key>'` error — see
1116 /// [`BlockInstance`]'s own doc comment.
1117 ///
1118 /// ## Netlist form
1119 /// ```text
1120 /// NAME kind=table in=<signal> points=[[x1,y1],[x2,y2],...]
1121 /// ```
1122 ///
1123 /// ## Example
1124 /// A trapezoid profile (ramp up, flat, ramp down, held at 0) driven by the time ramp:
1125 /// ```text
1126 /// X kind=time
1127 /// T kind=table in=X points=[[0,0],[1,10],[2,10],[3,0]]
1128 /// ```
1129 Table(Vec<(f64, f64)>),
1130 /// <!-- component -->
1131 /// # Waveform Arithmetic Functions (unary)
1132 /// **Purpose:** one of the 26 single-argument real functions — trig, exponential/log,
1133 /// rounding, sign, step — as a stateless block.
1134 /// **Library:** Sources / Math operations
1135 ///
1136 /// ## Description
1137 /// One entry for the whole unary family: every member is a pure `Scalar -> Scalar` function
1138 /// (elementwise `Vector -> Vector` for a `Vector` input), selected by its own `kind=` name,
1139 /// so they all share one input/error contract. Each name maps onto the same-named `f64`
1140 /// method where one exists (`continuous_blocks::waveform_arithmetic::MathFn1::call`), with
1141 /// the same domain/range behavior — trig in radians, `sqrt`/`ln` NaN for negative
1142 /// arguments, and so on. What the library as a whole deliberately leaves out (a
1143 /// finite-difference derivative, noise/random generators, complex-data functions, boolean
1144 /// comparison operators) is argued in `continuous_blocks::waveform_arithmetic`'s own module
1145 /// doc comment.
1146 ///
1147 /// | name | formula | notes |
1148 /// |---|---|---|
1149 /// | `abs` | $|x|$ | |
1150 /// | `acos` | $\arccos x$ | |
1151 /// | `acosh` | $\operatorname{arcosh} x$ | |
1152 /// | `asin` | $\arcsin x$ | |
1153 /// | `asinh` | $\operatorname{arsinh} x$ | |
1154 /// | `atan` | $\arctan x$ | |
1155 /// | `atanh` | $\operatorname{artanh} x$ | |
1156 /// | `buf` | $1$ if $x > 0.5$ else $0$ | threshold/buffer, companion to `inv` |
1157 /// | `ceil` | $\lceil x \rceil$ | |
1158 /// | `cos` | $\cos x$ | radians |
1159 /// | `cosh` | $\cosh x$ | |
1160 /// | `exp` | $e^x$ | |
1161 /// | `floor` | $\lfloor x \rfloor$ | |
1162 /// | `int` | truncation toward zero | |
1163 /// | `inv` | $0$ if $x > 0.5$ else $1$ | complement of `buf` |
1164 /// | `ln` | $\ln x$ | natural log |
1165 /// | `log10` | $\log_{10} x$ | |
1166 /// | `round` | round half away from zero | |
1167 /// | `sgn` | $-1$/$0$/$1$ | sign; 0 at the origin (unlike `f64::signum`, which returns 1 there) |
1168 /// | `sin` | $\sin x$ | radians |
1169 /// | `sinh` | $\sinh x$ | |
1170 /// | `sqrt` | $\sqrt{x}$ | |
1171 /// | `tan` | $\tan x$ | radians |
1172 /// | `tanh` | $\tanh x$ | |
1173 /// | `u` | $1$ if $x > 0$ else $0$ | unit step |
1174 /// | `uramp` | $x$ if $x > 0$ else $0$ | ramp that starts at the origin (Relu) |
1175 ///
1176 /// ## Parameters
1177 /// - `in=<signal>` — the single argument.
1178 ///
1179 /// ## Errors
1180 /// - A misspelled/unknown name (`kind=cosx`) — rejected at parse time:
1181 /// `unknown device kind 'cosx'`.
1182 /// - A missing `in=` is the generic `missing field 'in'` error — see [`BlockInstance`]'s own
1183 /// doc comment.
1184 ///
1185 /// ## Netlist form
1186 /// ```text
1187 /// NAME kind=<fn> in=<signal>
1188 /// ```
1189 ///
1190 /// ## Example
1191 /// `sin(2*pi*1000*t)` built from ordinary blocks, plus `cos`/`exp` and the elementwise
1192 /// vector form:
1193 /// ```text
1194 /// T kind=time
1195 /// G kind=gain in=T k=6283.185307179586
1196 /// S kind=sin in=G
1197 /// C kind=cos in=G
1198 /// E kind=exp in=T
1199 /// SV kind=const value=[1,4,9]
1200 /// SQ kind=sqrt in=SV
1201 /// ```
1202 MathFn1(MathFn1),
1203 /// <!-- component -->
1204 /// # Waveform Arithmetic Functions (binary)
1205 /// **Purpose:** one of the eight two-argument real functions — `atan2`/`hypot`/`pow` family,
1206 /// `min`/`max`, `anglewrap` — as a stateless block.
1207 /// **Library:** Sources / Math operations
1208 ///
1209 /// ## Description
1210 /// One entry for the whole binary family: every member is a pure two-argument function
1211 /// selected by its own `kind=` name, taking `in1=`/`in2=` in that order. Input-shape rule:
1212 /// two `Scalar`s give a `Scalar`; otherwise every `Vector` operand must share one length
1213 /// `N` (elementwise application, with a lone `Scalar` operand broadcast against it).
1214 ///
1215 /// | name | formula | notes |
1216 /// |---|---|---|
1217 /// | `atan2` | $\operatorname{atan2}(x, y)$ | Rust's `x.atan2(y)`: the four-quadrant angle whose tangent is `x/y` |
1218 /// | `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 |
1219 /// | `hypot` | $\sqrt{x^2 + y^2}$ | |
1220 /// | `max` | $\max(x, y)$ | |
1221 /// | `min` | $\min(x, y)$ | |
1222 /// | `pow` | $x^y$ | plain `f64::powf` (negative base with non-integer exponent is NaN) |
1223 /// | `pwr` | $|x|^y$ | like `pow` but always real-valued (a negative base raised to a non-integer power would otherwise be complex) |
1224 /// | `pwrs` | $\operatorname{sgn}(x)\,|x|^y$ | `pwr` with `x`'s original sign reapplied — odd-symmetric |
1225 ///
1226 /// `anglewrap` is the special member: `(alpha, beta) -> theta` — the `atan2(beta, alpha)`
1227 /// angle shifted by a full turn when negative, so `theta` stays in `[0, 2*pi)` and is a
1228 /// monotonically-sensible input to `park`/`clarke_park` across a full revolution — the
1229 /// angle-tracking half of a synchronous-reference-frame PLL (see
1230 /// `continuous_blocks::coordinate_transforms::anglewrap`, whose output feeds `park`/
1231 /// `clarke_park`). It lives here rather than with the Clarke/Park transforms because it is
1232 /// single-output: an ordinary two-argument function like every other member.
1233 ///
1234 /// ## Parameters
1235 /// - `in1=<signal>` `in2=<signal>` — the two arguments, in formula order above.
1236 ///
1237 /// ## Errors
1238 /// - A misspelled/unknown name — the same `unknown device kind '<name>'` error as the
1239 /// unary entry.
1240 /// - `Vector` operands of differing lengths — rejected at evaluation time:
1241 /// `VectorSignalSizeMismatch { block: "<name>", expected: N, got: M }`.
1242 /// - A missing `in1=`/`in2=` is the generic `missing field '<key>'` error — see
1243 /// [`BlockInstance`]'s own doc comment.
1244 ///
1245 /// ## Netlist form
1246 /// ```text
1247 /// NAME kind=<fn> in1=<signal> in2=<signal>
1248 /// ```
1249 ///
1250 /// ## Example
1251 /// The textbook 3-4-5 triangle, and the same pair's `anglewrap` result (`atan2(4,3)` ~
1252 /// 0.9273 rad):
1253 /// ```text
1254 /// X kind=const value=3
1255 /// Y kind=const value=4
1256 /// H kind=hypot in1=X in2=Y
1257 /// AW kind=anglewrap in1=X in2=Y
1258 /// ```
1259 MathFn2(MathFn2),
1260 /// <!-- component -->
1261 /// # Waveform Arithmetic Functions (ternary: if, limit)
1262 /// **Purpose:** a threshold select (`if`) and a clamp (`limit`) — the two three-argument
1263 /// functions.
1264 /// **Library:** Sources / Math operations
1265 ///
1266 /// ## Description
1267 /// One entry for the two three-argument functions — genuinely different semantics, but one
1268 /// shared input/error contract (documented at the type's own granularity). Both take
1269 /// `in1=`/`in2=`/`in3=` in the order below, and both use the binary entry's `Scalar`/
1270 /// `Vector` rule unchanged.
1271 ///
1272 /// | name | formula | notes |
1273 /// |---|---|---|
1274 /// | `if` | $y$ if $x > 0.5$ else $z$ | select/comparator: `in2` while `in1 > 0.5`, else `in3` |
1275 /// | `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 |
1276 ///
1277 /// `limit`'s bounds are not fixed at ±`limit` the way `kind=saturation`'s are — they are two
1278 /// ordinary inputs, so they can themselves come from elsewhere in the graph.
1279 ///
1280 /// ## Parameters
1281 /// - `in1=<signal>` `in2=<signal>` `in3=<signal>` — the three arguments, in formula order
1282 /// above.
1283 ///
1284 /// ## Errors
1285 /// - A misspelled/unknown name — the same `unknown device kind '<name>'` error as the
1286 /// unary entry.
1287 /// - A missing `in1=`/`in2=`/`in3=` is the generic `missing field '<key>'` error — see
1288 /// [`BlockInstance`]'s own doc comment.
1289 ///
1290 /// ## Netlist form
1291 /// ```text
1292 /// NAME kind=if in1=<signal> in2=<signal> in3=<signal>
1293 /// NAME kind=limit in1=<signal> in2=<signal> in3=<signal>
1294 /// ```
1295 ///
1296 /// ## Example
1297 /// A select picking between two references, and a clamp of 5 to the span [0, 2]:
1298 /// ```text
1299 /// CND kind=const value=1
1300 /// THEN kind=const value=10
1301 /// ELSE kind=const value=20
1302 /// SEL kind=if in1=CND in2=THEN in3=ELSE
1303 /// V kind=const value=5
1304 /// LO kind=const value=0
1305 /// HI kind=const value=2
1306 /// L kind=limit in1=V in2=LO in3=HI
1307 /// ```
1308 MathFn3(MathFn3),
1309 /// <!-- component -->
1310 /// # Hysteresis (Schmitt Trigger)
1311 /// **Purpose:** a bang-bang/hysteresis-band comparator.
1312 /// **Library:** Logic
1313 ///
1314 /// ## Description
1315 /// Stays HIGH until the input drops below `low`, stays LOW until the input rises above
1316 /// `high` (see `continuous_blocks::Hysteresis`) — used for current-mode control when
1317 /// there's no fixed switching frequency to modulate a duty command onto (unlike `Pid`
1318 /// feeding a [`BlockKind::Pwm`]). Its output is `1.0`/`0.0`, read directly by a
1319 /// [`GateBinding::Block`] rather than compared against a carrier. Deliberately not a
1320 /// `StateSpace`: the on/off memory is a genuine discrete latch, not a linear dynamic.
1321 ///
1322 /// ## Parameters
1323 /// - `high=<f64>`, `low=<f64>` — the two switching thresholds; must satisfy `low <= high`.
1324 /// - `in=<signal>` — the input signal (one input).
1325 ///
1326 /// ## Errors
1327 /// - `low > high` — rejected at parse time: `invalid hysteresis (LowExceedsHigh)`.
1328 ///
1329 /// ## Netlist form
1330 /// ```text
1331 /// NAME kind=hysteresis high=<f64> low=<f64> in=<signal>
1332 /// ```
1333 ///
1334 /// ## Example
1335 /// A `[-1, 1]` band, verified end to end: a rising `Time`-driven ramp is LOW until crossing
1336 /// `1`, then HIGH:
1337 /// ```text
1338 /// T kind=time
1339 /// RAMP kind=gain k=1 in=T
1340 /// HYST1 kind=hysteresis high=1 low=-1 in=RAMP
1341 /// ```
1342 Hysteresis(Hysteresis),
1343 /// <!-- component -->
1344 /// # Logic Gate
1345 /// **Purpose:** a combinational digital logic gate.
1346 /// **Library:** Logic
1347 ///
1348 /// ## Description
1349 /// `and`/`or`/`xor`/`nand`/`nor`/`xnor` (N-input, `N >= 2`) or `not` (exactly 1 input) —
1350 /// see `continuous_blocks::LogicOp::call` for the exact reduction rule (`Xor`/`Xnor` use the
1351 /// standard N-input generalization: true iff an odd/even number of inputs are true, not
1352 /// "exactly one"). Every input/output is an ordinary `f64` signal, thresholded at `>= 0.5`
1353 /// — the same convention `GateBinding`/[`BlockKind::Hysteresis`] already use; there is no
1354 /// dedicated boolean `SignalValue` variant anywhere in this crate. Purely combinational —
1355 /// no persistent state, recomputed fresh every step, the same as
1356 /// [`BlockKind::Sum`]/[`BlockKind::Gain`] already are.
1357 ///
1358 /// ## Parameters
1359 /// - `kind=<and|or|xor|nand|nor|xnor|not>` — which gate.
1360 /// - `inputs=<sig1,sig2,...>` — for every kind except `not`; at least 2 entries.
1361 /// - `in=<signal>` — for `kind=not` only; exactly 1 input.
1362 ///
1363 /// ## Errors
1364 /// - `and`/`or`/`xor`/`nand`/`nor`/`xnor` with fewer than 2 `inputs=` entries — rejected at
1365 /// parse time: `kind=<name> needs at least 2 comma-separated inputs= entries (got <n>)`.
1366 ///
1367 /// ## Netlist form
1368 /// ```text
1369 /// NAME kind=<and|or|xor|nand|nor|xnor> inputs=<sig1,sig2,...>
1370 /// NAME kind=not in=<signal>
1371 /// ```
1372 ///
1373 /// ## Example
1374 /// A 2-input `and`, verified end to end (`1 and 0 = 0`, `1 and 1 = 1`):
1375 /// ```text
1376 /// A kind=const value=1
1377 /// B kind=const value=0
1378 /// G1 kind=and inputs=A,B
1379 /// ```
1380 LogicGate(LogicOp),
1381 /// <!-- component -->
1382 /// # SR Latch
1383 /// **Purpose:** a level-triggered set/reset latch.
1384 /// **Library:** Logic
1385 ///
1386 /// ## Description
1387 /// No clock — `set`/`reset` act every step, immediately. The one genuinely new state shape
1388 /// in this family (a single persisted `bool`, updated every step from whichever of
1389 /// `set`/`reset` is currently asserted — see `continuous_blocks::srlatch_next`):
1390 /// `set,reset -> q_next`: `false,false` holds; `true,false` sets `true`; `false,true` sets
1391 /// `false`; `true,true` (both at once) resolves per `priority`. `Set` (the default) is the
1392 /// right default for this block's own motivating use case, a sticky fault latch — a fault
1393 /// occurring in the same step a reset is asserted should still latch, not silently clear.
1394 ///
1395 /// ## Parameters
1396 /// - `set=<signal>`, `reset=<signal>` — both required.
1397 /// - `priority=<set|reset>` — optional, defaults to `set`; which input wins when both are
1398 /// asserted simultaneously.
1399 ///
1400 /// ## Errors
1401 /// - `priority=` present but not `set`/`reset` — rejected at parse time: `field 'priority'
1402 /// must be 'set' or 'reset' (got '<value>')`.
1403 ///
1404 /// ## Netlist form
1405 /// ```text
1406 /// NAME kind=srlatch set=<signal> reset=<signal> [priority=<set|reset>]
1407 /// ```
1408 ///
1409 /// ## Example
1410 /// A fault latch, verified end to end: `FAULT` pulses to `1` briefly then returns to `0`
1411 /// at `t=0.1`, but `LATCH1` stays `1` afterward (no separate reset asserted):
1412 /// ```text
1413 /// FAULT kind=pwc points=[[0,1],[0.1,0]]
1414 /// CLEAR kind=const value=0
1415 /// LATCH1 kind=srlatch set=FAULT reset=CLEAR
1416 /// ```
1417 SrLatch {
1418 /// Which input wins when `set` and `reset` are asserted simultaneously.
1419 priority: LatchPriority,
1420 },
1421 /// <!-- component -->
1422 /// # Flip-Flop
1423 /// **Purpose:** an edge-triggered D/JK/T flip-flop.
1424 /// **Library:** Logic
1425 ///
1426 /// ## Description
1427 /// Unlike [`BlockKind::SrLatch`] above, the next-state rule only fires at a detected rising
1428 /// `clk` edge (`continuous_blocks::rising_edge`); the previous `clk` sample is held
1429 /// alongside the output `q` between edges, the bookkeeping a level-triggered latch doesn't
1430 /// need at all.
1431 ///
1432 /// ## Parameters
1433 /// - `kind=<dff|jkff|tff>` — which flip-flop.
1434 /// - `clk=<signal>` — the clock input, required for every kind.
1435 /// - `d=<signal>` — for `kind=dff` only: the data input.
1436 /// - `t=<signal>` — for `kind=tff` only: the toggle-enable input.
1437 /// - `j=<signal>`, `k=<signal>` — for `kind=jkff` only: both required.
1438 /// - `reset=<signal>` — optional; if given, declares a synchronous reset input.
1439 ///
1440 /// ## Errors
1441 /// - The kind-specific data input (`d=`/`t=`/`j=`+`k=`) missing for its own kind — the
1442 /// generic `missing field '<key>'` error.
1443 ///
1444 /// ## Netlist form
1445 /// ```text
1446 /// NAME kind=dff clk=<signal> d=<signal> [reset=<signal>]
1447 /// NAME kind=tff clk=<signal> t=<signal> [reset=<signal>]
1448 /// NAME kind=jkff clk=<signal> j=<signal> k=<signal> [reset=<signal>]
1449 /// ```
1450 ///
1451 /// ## Example
1452 /// A D flip-flop, verified end to end: `Q1` only updates to `D`'s current value at a clock
1453 /// rising edge, not continuously:
1454 /// ```text
1455 /// CLK kind=pwc points=[[0,0],[5e-3,1]]
1456 /// D kind=const value=1
1457 /// Q1 kind=dff clk=CLK d=D
1458 /// ```
1459 FlipFlop {
1460 /// `dff`/`jkff`/`tff`.
1461 kind: FlipFlopKind,
1462 /// Whether this instance declares a synchronous reset input.
1463 reset: bool,
1464 },
1465 /// <!-- component -->
1466 /// # Counter
1467 /// **Purpose:** a clocked up/down counter.
1468 /// **Library:** Logic
1469 ///
1470 /// ## Description
1471 /// Shares the same rising-edge-detection skeleton [`BlockKind::FlipFlop`] uses, generalized
1472 /// from a single bit to an integer count. `up_down`/`modulus`/`reset` are all optional:
1473 /// omitting `up_down` always increments; omitting `modulus` gives a free-running signed
1474 /// `i64` that wraps only at `i64`'s own bounds; omitting `reset` means no synchronous reset
1475 /// input at all.
1476 ///
1477 /// ## Parameters
1478 /// - `clk=<signal>` — the clock input, required.
1479 /// - `up_down=<signal>` — optional; if given, declares a direction input (counts down when
1480 /// its value thresholds true, up otherwise).
1481 /// - `modulus=<u32>` — optional; wraps the count into `[0, modulus)` if given.
1482 /// - `reset=<signal>` — optional; if given, declares a synchronous reset input.
1483 ///
1484 /// ## Errors
1485 /// - `modulus=` present but not a non-negative integer — rejected at parse time: `field
1486 /// 'modulus' is not a non-negative integer`.
1487 /// - `up_down=`/`reset=` declared (field present) but the signal itself malformed — the
1488 /// generic `missing field '<key>'`/parse-signal errors.
1489 ///
1490 /// ## Netlist form
1491 /// ```text
1492 /// NAME kind=counter clk=<signal> [up_down=<signal>] [modulus=<u32>] [reset=<signal>]
1493 /// ```
1494 ///
1495 /// ## Example
1496 /// A free-running up counter clocked by a repeating pulse train — verified end to end,
1497 /// `CNT1` increasing by exactly `1` at each detected clock rising edge:
1498 /// ```text
1499 /// CLK kind=pwc points=[[0,0],[1e-3,1],[2e-3,0]] repeat=true
1500 /// CNT1 kind=counter clk=CLK
1501 /// ```
1502 Counter {
1503 /// Whether this instance declares an up/down direction input (unset: always increments).
1504 up_down: bool,
1505 /// Wraps at this value if set; free-running `i64` otherwise.
1506 modulus: Option<u32>,
1507 /// Whether this instance declares a synchronous reset input.
1508 reset: bool,
1509 },
1510 /// <!-- component -->
1511 /// # CScript
1512 /// **Purpose:** call into a user-supplied, precompiled native shared library once per
1513 /// (block-local) step — an escape hatch for stateful behavior no existing block covers.
1514 /// **Library:** Extensibility
1515 ///
1516 /// ## Description
1517 /// A dynamically-loaded, user-supplied block: `lib` is a precompiled shared library
1518 /// (`.so`/`.dylib`/`.dll`) exporting `cscript_start`/`cscript_output`/(optionally)
1519 /// `cscript_free`/`cscript_clone`, filling `output_names.len()` outputs. Unlike every
1520 /// other `BlockKind`, this one can carry state no Rust type here knows anything about —
1521 /// see `cscript_ffi`'s own module doc comment (in the sibling `cscript-ffi` crate) for the
1522 /// full C-side contract. **This is the one place in the workspace where arbitrary native
1523 /// code loads into the process** — calling into it is unsafe by construction (in-process,
1524 /// full host privileges, can corrupt memory or crash the process); this is an accepted,
1525 /// bounded risk of an explicitly opt-in feature (the user names their own `.so` in their
1526 /// own netlist), not something sandboxed away.
1527 ///
1528 /// `sample_time`, if given, makes this block run on its *own* schedule, independent of the
1529 /// circuit's own resolved step size — either a fixed period (optionally phase-offset), or a
1530 /// schedule the block computes for itself every time it runs. `None` (the default) calls
1531 /// `cscript_output` every resolved circuit step instead, passing that step's own `dt` — the
1532 /// right choice for a block meant to behave continuously. See [`SampleTimeSpec`]'s own doc
1533 /// comment for the two `Some(..)` cases.
1534 ///
1535 /// `xc_count`, if nonzero, declares this block as owning that many continuous states the
1536 /// *solver itself* numerically integrates (one independent RK4 per block, the same
1537 /// convention every other dynamic `BlockKind` here uses), as opposed to a block hand-
1538 /// integrating its own state inside `cscript_output` (still the right choice for a fixed-
1539 /// rate discrete recursion, e.g. a bilinear-transform-derived filter — see `cscript_ffi`'s
1540 /// own module doc comment, "The optional continuous-state (`xc`) contract," for exactly
1541 /// which case this is for). `0` (the default) is the plain, single-function contract
1542 /// unchanged from before this field existed: `lib` must export `cscript_start`/
1543 /// `cscript_output`/(optionally) `cscript_free`/`cscript_clone`. Nonzero requires `lib` to
1544 /// export `cscript_start`/`cscript_derivative`/`cscript_output_xc`/(optionally)
1545 /// `cscript_free`/`cscript_clone` *instead of* `cscript_output`.
1546 ///
1547 /// ## Parameters
1548 /// - `lib=<path>` — the precompiled shared library. Like every field, this is whitespace-
1549 /// tokenized; **a path containing whitespace must be `"double-quoted"`**
1550 /// (`lib="my libs/gain.so"`) — verified directly against a real space-containing
1551 /// directory. An unquoted path with no whitespace needs no quotes, unchanged.
1552 /// - `outputs=<name1,name2,...>` — this block's own output names; defaults to a single
1553 /// output aliasing the block's own `.name` if omitted.
1554 /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these; `inputs=` for more
1555 /// than one input, in the order `cscript_output`'s own `in`/`in_len` receives them.
1556 /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` / `ts=variable` — optional; see
1557 /// [`SampleTimeSpec`]. Omit entirely to run every resolved circuit step.
1558 /// - `xc_count=<usize>` — optional, default `0`; number of solver-integrated continuous
1559 /// states (switches the required C export set — see Description above).
1560 ///
1561 /// ## Errors
1562 /// - `lib`/`in` missing, or both `in` and `inputs` given, or neither — the generic
1563 /// `missing field '<key>'` error (see [`BlockInstance`]'s own doc comment); there is no
1564 /// `inputs`-vs-`in` mutual-exclusion check specifically, `inputs=` simply takes priority
1565 /// when both are present.
1566 /// - `xc_count` present but not a non-negative integer — `field 'xc_count' is not a
1567 /// non-negative integer`.
1568 /// - `ts=variable` combined with `freq=`/`to=` — rejected at parse time: `ts=variable is
1569 /// exclusive with 'freq'/'to' (the block computes its own schedule; there's no fixed
1570 /// period/offset to combine it with)`.
1571 /// - **Adaptive step-size control requires `cscript_clone`** to be exported — the solver
1572 /// retries a rejected trial step from an independent copy of every block's state. Running
1573 /// a `CScript` block with no `cscript_clone` export under adaptive stepping (i.e. no
1574 /// `--dt` given to the CLI) fails at the first step with
1575 /// `CScriptRequiresCloneForAdaptiveStep { block_name: "<name>" }` (verified directly: this
1576 /// is the CLI's raw `{e:?}` `Debug` formatting of `dae_runtime`'s own error type, not a
1577 /// hand-written message). Use a fixed `--dt` instead if the library doesn't export it.
1578 /// - A `.so` missing a required export, or a signature mismatch, surfaces as a load-time or
1579 /// call-time failure from `cscript_ffi` itself — see that crate's own error type.
1580 ///
1581 /// ## Netlist form
1582 /// ```text
1583 /// NAME kind=cscript lib=<path> (in=<signal> | inputs=<sig1,sig2,...>) \
1584 /// [outputs=<name1,name2,...>] [ts=<f64>|freq=<f64> [to=<f64>] | ts=variable] \
1585 /// [xc_count=<usize>]
1586 /// ```
1587 ///
1588 /// ## Example
1589 /// A fixed-gain block computed in C (`out = 2 * in`), run every circuit step — `lib` names
1590 /// a shared library compiled from a two-function `.c` file exporting exactly
1591 /// `cscript_start`/`cscript_output`. Verified end to end (compiled, run through the real
1592 /// CLI, `G1`'s output confirmed to track `2 * SRC` every step, e.g. `SRC=3` produces
1593 /// `G1=6`):
1594 /// ```text
1595 /// SRC kind=const value=3
1596 /// G1 kind=cscript lib=gain.so in=SRC
1597 /// ```
1598 CScript {
1599 /// The precompiled shared library exporting the `cscript_*` C ABI.
1600 lib: std::path::PathBuf,
1601 /// This block's own output names, in order.
1602 output_names: Vec<String>,
1603 /// `None` runs every resolved circuit step; `Some` runs on its own schedule.
1604 sample_time: Option<SampleTimeSpec>,
1605 /// Number of solver-integrated continuous states this block owns; `0` for the plain contract.
1606 xc_count: usize,
1607 },
1608 /// <!-- component -->
1609 /// # PyBlock
1610 /// **Purpose:** call into a user-supplied, stateful Python function once per step — the
1611 /// Python-hosted counterpart to [`BlockKind::CScript`].
1612 /// **Library:** Extensibility
1613 ///
1614 /// ## Description
1615 /// A dynamically-loaded, user-supplied Python block (see `pyblock_ffi`): an escape hatch
1616 /// to a full scripting language (including `numpy`/`scipy`) when the existing block
1617 /// library doesn't cover something. `path` is a `.py` file exporting `start`/`output` (or,
1618 /// if `xc_count > 0`, `start`/`derivative`/`output_xc` *instead of* `output` — the same
1619 /// continuous-state split `CScript`'s own `xc_count` has, for the same reason).
1620 /// `output_names`/`sample_time`/`xc_count` all have exactly the same meaning as `CScript`'s
1621 /// own fields — deliberately scalar-only outputs, the same zero-order-hold `sample_time`
1622 /// convention, the same solver-integrated-vs-hand-managed state split. See
1623 /// `general-simulator`'s own `book/dev-guide/src/python-blocks.md` for the full design and
1624 /// the measurements behind it.
1625 ///
1626 /// ## Parameters
1627 /// - `path=<path>` — the `.py` file exporting `start`/`output` (or the `xc` contract). Same
1628 /// whitespace-tokenization rule as `CScript`'s `lib=` — `"double-quote"` a path containing
1629 /// whitespace.
1630 /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1631 /// block's own `.name`.
1632 /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1633 /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` / `ts=variable` — optional; see
1634 /// [`SampleTimeSpec`]. `ts=variable` here requires the `.py` file to also export
1635 /// `next_sample_hit` (unlike [`BlockKind::PyFunction`], where `ts=variable` is rejected
1636 /// outright).
1637 /// - `xc_count=<usize>` — optional, default `0`.
1638 ///
1639 /// ## Errors
1640 /// - **This block requires the CLI/library built with the `python` Cargo feature enabled**
1641 /// (`cargo build --features python`) — it is *not* on by default, since it needs a
1642 /// discoverable Python/`libpython` at build/link time and `kind=cscript` already covers
1643 /// the same "dynamically-loaded custom block" need without that dependency. Without it,
1644 /// any `kind=pyblock`/`kind=pyfunc` netlist fails at the first step with
1645 /// `PythonSupportNotCompiledIn { block_name: "<name>" }` (verified directly — the CLI's
1646 /// raw `{e:?}` formatting of `dae_runtime`'s own error, not a hand-written message).
1647 /// - `path`/`in` missing, or malformed `outputs=`/`xc_count=` — same generic/`xc_count`
1648 /// errors as [`BlockKind::CScript`].
1649 /// - A `.py` file missing a required function, raising an exception, or returning the wrong
1650 /// arity surfaces as a Python-traceback-bearing failure from `pyblock_ffi` itself at call
1651 /// time, not at parse time.
1652 ///
1653 /// ## Netlist form
1654 /// ```text
1655 /// NAME kind=pyblock path=<path> (in=<signal> | inputs=<sig1,sig2,...>) \
1656 /// [outputs=<name1,name2,...>] [ts=<f64>|freq=<f64> [to=<f64>] | ts=variable] \
1657 /// [xc_count=<usize>]
1658 /// ```
1659 ///
1660 /// ## Example
1661 /// A fixed-gain block computed in Python (`out = 2 * in`) — verified end to end against a
1662 /// `--features python` build of the CLI, `SRC=3` producing `G1=6`:
1663 /// ```text
1664 /// SRC kind=const value=3
1665 /// G1 kind=pyblock path=gain.py in=SRC
1666 /// ```
1667 /// where `gain.py` is:
1668 /// ```python
1669 /// def start():
1670 /// return None
1671 ///
1672 /// def output(state, t, dt, inputs):
1673 /// return inputs[0] * 2.0
1674 /// ```
1675 /// The `xc_count>0` contract (`derivative`/`output_xc`) is verified separately end to end
1676 /// against its own analytic solution ($\dot{x}_c = 1 - x_c$, starting at rest, so
1677 /// $x_c(t) = 1 - e^{-t}$) — see `doc-verify/pyblock/xc_example.cir`.
1678 PyBlock {
1679 /// The `.py` file exporting `start`/`output` (or `start`/`derivative`/`output_xc`).
1680 path: std::path::PathBuf,
1681 /// This block's own output names, in order.
1682 output_names: Vec<String>,
1683 /// `None` runs every resolved circuit step; `Some` runs on its own schedule.
1684 sample_time: Option<SampleTimeSpec>,
1685 /// Number of solver-integrated continuous states this block owns; `0` for the plain contract.
1686 xc_count: usize,
1687 },
1688 /// <!-- component -->
1689 /// # PyFunction
1690 /// **Purpose:** call a plain, stateless, named Python function once per step.
1691 /// **Library:** Extensibility
1692 ///
1693 /// ## Description
1694 /// A genuinely separate contract from [`BlockKind::PyBlock`] above (not a mode of it): no
1695 /// `start`, no persistent `state`, no `t`/`dt` boilerplate, just `function` (a name inside
1696 /// `path`'s own `.py` file) called with each declared `inputs=` entry as its own
1697 /// positional argument (`f(*inputs)`, never bundled into one list), returning a single
1698 /// value or a tuple/list matching `output_names`. The closest equivalent to a plain
1699 /// named-input/named-output function block in other block-diagram tools. `output_names`/
1700 /// `sample_time` mean the same as `PyBlock`'s own (still scalar-only outputs, still the
1701 /// same zero-order-hold convention) — there is no `xc_count` here at all, since a purely
1702 /// stateless function has nothing for a continuous state to mean. See
1703 /// `pyblock_ffi::PyFunctionInstance`'s own module doc comment for the full contract.
1704 ///
1705 /// ## Parameters
1706 /// - `path=<path>` — the `.py` file containing `function`. `"double-quote"` a path
1707 /// containing whitespace, same as `CScript`'s `lib=`.
1708 /// - `function=<name>` — required, no default; the function called as `f(*inputs)`.
1709 /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1710 /// block's own `.name`.
1711 /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1712 /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` — optional, [`SampleTimeSpec::Periodic`] only;
1713 /// `ts=variable` is rejected (see Errors).
1714 ///
1715 /// ## Errors
1716 /// - **Requires a `--features python` build** — see [`BlockKind::PyBlock`]'s own Errors
1717 /// section; identical `PythonSupportNotCompiledIn` failure.
1718 /// - `ts=variable` — rejected at parse time, verified directly: `ts=variable is not
1719 /// available for kind=pyfunc (a stateless function call has no instance to remember a
1720 /// requested next-hit time against) -- use kind=pyblock instead`. A stateless function
1721 /// call has no instance to remember "when am I next due" against.
1722 /// - `function` missing — the generic `missing field 'function'` error.
1723 /// - A `.py` file missing `function`, raising an exception, or returning the wrong arity
1724 /// surfaces as a Python-traceback-bearing failure from `pyblock_ffi` at call time.
1725 ///
1726 /// ## Netlist form
1727 /// ```text
1728 /// NAME kind=pyfunc path=<path> function=<name> (in=<signal> | inputs=<sig1,sig2,...>) \
1729 /// [outputs=<name1,name2,...>] [ts=<f64> | freq=<f64> [to=<f64>]]
1730 /// ```
1731 ///
1732 /// ## Example
1733 /// Verified end to end against a `--features python` build, `SRC=3` producing `G1=4`:
1734 /// ```text
1735 /// SRC kind=const value=3
1736 /// G1 kind=pyfunc path=add.py function=add_one in=SRC
1737 /// ```
1738 /// where `add.py` is:
1739 /// ```python
1740 /// def add_one(x):
1741 /// return x + 1.0
1742 /// ```
1743 /// `inputs=A,B` calling `f(A, B)` as two genuinely distinct positional arguments (never
1744 /// bundled into one list) is verified separately — see `doc-verify/pyfunc/example_two_inputs.cir`.
1745 PyFunction {
1746 /// The `.py` file containing `function`.
1747 path: std::path::PathBuf,
1748 /// The function name called with each declared input as a positional argument.
1749 function: String,
1750 /// This block's own output names, in order.
1751 output_names: Vec<String>,
1752 /// `None` runs every resolved circuit step; `Some` must be [`SampleTimeSpec::Periodic`].
1753 sample_time: Option<SampleTimeSpec>,
1754 },
1755 /// <!-- component -->
1756 /// # OctFunc
1757 /// **Purpose:** call a plain, stateless, named Octave-compatible function once per step.
1758 /// **Library:** Extensibility
1759 ///
1760 /// ## Description
1761 /// The `.m`-file counterpart to [`BlockKind::PyFunction`] above -- same genuinely separate,
1762 /// stateless contract (no `start`, no persistent state, no `t`/`dt` boilerplate), for
1763 /// people with legacy Octave-compatible `.m` scripts instead of Python. `function` (a
1764 /// name inside `path`'s own `.m` file, which must itself be named `<function>.m` -- Octave's
1765 /// own requirement that a function's file name match its function name) is called with each
1766 /// declared `inputs=` entry as its own positional argument (`f(arg0, arg1, ...)`, never
1767 /// bundled into one array), returning a single value or as many comma-separated return
1768 /// values as `output_names` declares (`[y1, y2] = f(...)`). `output_names`/`sample_time`
1769 /// mean the same as `PyFunction`'s own -- still scalar-only outputs, still the same
1770 /// zero-order-hold convention -- and there is no `xc_count` here either, for the same reason
1771 /// `PyFunction` has none: a purely stateless function has nothing for a continuous state to
1772 /// mean.
1773 ///
1774 /// Unlike `PyFunction`, this block never embeds an interpreter in-process: it calls into a
1775 /// separately installed `octave-cli` binary as a subprocess (one shared, persistent process
1776 /// for the whole simulation run, spawned lazily on first use), specifically so this
1777 /// permissively-licensed project never links against GPLv3-licensed Octave code -- see
1778 /// `octave_ffi`'s own module doc comment and `general-simulator`'s own
1779 /// `book/dev-guide/src/octave-blocks.md` for the full licensing rationale and the measured
1780 /// costs behind this design.
1781 ///
1782 /// ## Parameters
1783 /// - `path=<path>` — the `.m` file containing `function`; its own file name (minus `.m`)
1784 /// must equal `function`. `"double-quote"` a path containing whitespace, same as
1785 /// `CScript`'s `lib=`.
1786 /// - `function=<name>` — required, no default; the function called as `f(arg0, arg1, ...)`,
1787 /// and the required base name of `path`'s own file.
1788 /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1789 /// block's own `.name`.
1790 /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1791 /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` — optional, [`SampleTimeSpec::Periodic`] only;
1792 /// `ts=variable` is rejected (see Errors), for exactly the reason `PyFunction`'s own is.
1793 ///
1794 /// ## Errors
1795 /// - `ts=variable` — rejected at parse time, the same wording `PyFunction` uses (a stateless
1796 /// function call has no instance to remember a requested next-hit time against): `ts=variable
1797 /// is not available for kind=octfunc (a stateless function call has no instance to remember
1798 /// a requested next-hit time against)`.
1799 /// - `function` missing — the generic `missing field 'function'` error.
1800 /// - `octave-cli` not found on `PATH` when this block is first evaluated, an Octave-side
1801 /// exception raised by the called function, or a malformed/desynchronized reply from the
1802 /// shared session — surfaces as a call-time failure from `octave_ffi` itself (see
1803 /// `octave_ffi::OctaveError`'s own three cases: not-found, process-exited, and Octave-side
1804 /// runtime error), not at parse time.
1805 ///
1806 /// ## Netlist form
1807 /// ```text
1808 /// NAME kind=octfunc path=<file.m> function=<name> (in=<signal> | inputs=<sig1,sig2,...>) \
1809 /// [outputs=<name1,name2,...>] [ts=<f64> | freq=<f64> [to=<f64>]]
1810 /// ```
1811 ///
1812 /// ## Example
1813 /// Verified end to end against the real CLI (no special feature flag needed -- unlike
1814 /// `kind=pyblock`/`kind=pyfunc`, this block builds and runs unconditionally), `SRC=3`
1815 /// producing `G1=4`:
1816 /// ```text
1817 /// SRC kind=const value=3
1818 /// G1 kind=octfunc path=add_one.m function=add_one in=SRC
1819 /// ```
1820 /// where `add_one.m` is:
1821 /// ```text
1822 /// function y = add_one(x)
1823 /// y = x + 1;
1824 /// end
1825 /// ```
1826 /// `inputs=A,B` calling `f(A, B)` as two genuinely distinct positional arguments is verified
1827 /// separately -- see `doc-verify/octfunc/example_two_inputs.cir`.
1828 OctFunc {
1829 /// The `.m` file containing `function` -- its own base file name must equal `function`.
1830 path: std::path::PathBuf,
1831 /// The function name called with each declared input as a positional argument.
1832 function: String,
1833 /// This block's own output names, in order.
1834 output_names: Vec<String>,
1835 /// `None` runs every resolved circuit step; `Some` must be [`SampleTimeSpec::Periodic`].
1836 sample_time: Option<SampleTimeSpec>,
1837 },
1838 /// <!-- component -->
1839 /// # OctBlock
1840 /// **Purpose:** call into a user-supplied, *stateful* Octave-compatible function once per
1841 /// step -- the Octave-hosted counterpart to [`BlockKind::PyBlock`], and the stateful sibling
1842 /// of [`BlockKind::OctFunc`] (not a mode of it -- see that variant's own doc comment for the
1843 /// stateless contract this one deliberately does not share).
1844 /// **Library:** Extensibility
1845 ///
1846 /// ## Description
1847 /// An escape hatch to Octave-compatible `.m`-file functions with real persistent state
1848 /// across steps -- for people with legacy Octave-compatible `.m` scripts who need
1849 /// `pyblock`'s own `start`/`output`/`update`/`xc_count` contract, not `octfunc`'s stateless
1850 /// one. `output_names`/`sample_time`/`xc_count` all mean exactly what [`BlockKind::PyBlock`]'s
1851 /// own do (scalar-only outputs, the same zero-order-hold `sample_time` convention, the same
1852 /// solver-integrated-vs-hand-managed `xc` split).
1853 ///
1854 /// **`path=` names a directory, not a single file** -- the one place this contract cannot
1855 /// simply reuse `OctFunc`'s own single-`.m`-file convention: Octave only auto-loads the
1856 /// *first* `function ... end` block in a `.m` file by filename, so a second function in the
1857 /// same file is an invisible private subfunction (confirmed empirically against real
1858 /// `octave-cli`). Every contract function therefore needs **its own file**, named
1859 /// `<function>_<role>.m`, all living together in `path`'s own directory:
1860 ///
1861 /// | File | Required | Signature |
1862 /// |---|---|---|
1863 /// | `<function>_start.m` | always | `state = <function>_start()` |
1864 /// | `<function>.m` | unless `xc_count>0` | `[new_state, y1, y2, ...] = <function>(state, t, dt, u1, u2, ...)` |
1865 /// | `<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 |
1866 /// | `<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 |
1867 /// | `<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 |
1868 /// | `<function>_next_sample_hit.m` | only if `ts=variable` | `seconds = <function>_next_sample_hit(state, t, dt, u1, ...)` |
1869 ///
1870 /// A user coming from Octave/legacy-language habits of "one script, many local functions"
1871 /// hits this immediately -- this is not a buried caveat, it is the load-bearing difference
1872 /// from every other block kind's own `path=`.
1873 ///
1874 /// Each instance's own opaque `state` (whatever `<function>_start` returns) lives entirely
1875 /// **inside the shared Octave session itself**, in one global struct keyed by this block's
1876 /// own instance name (`global __gs_state; __gs_state.('<name>') = ...`) -- it is never
1877 /// serialized back into Rust at all, unlike `PyBlock`'s own `state` (an opaque Python
1878 /// object `pyblock_ffi` holds a handle to) or `CScript`'s (an opaque `void*`). Two instances
1879 /// of the *same* Octave function never contaminate each other's state -- validated directly
1880 /// against real `octave-cli` (interleaved calls, zero cross-contamination; see
1881 /// `octave_ffi::OctaveSession`'s own `tests/stateful_session.rs`). The one piece of state
1882 /// that *does* cross the pipe as explicit numeric data (the same `%.17g`-per-line protocol
1883 /// `octfunc` already uses, extended to a literal Octave vector) is the solver-owned `xc`
1884 /// continuous-state vector for the `xc_count > 0` case -- that's the *solver's* state, not
1885 /// the block's own opaque one, so it has to be explicit, exactly mirroring `cscript`'s/
1886 /// `pyblock`'s own `xc` vs. opaque-`state` split. See `general-simulator`'s own
1887 /// `book/dev-guide/src/octave-blocks.md` for the full protocol, licensing rationale, and
1888 /// measured costs.
1889 ///
1890 /// Like `OctFunc`, this block shares **one** persistent `octave-cli` subprocess with every
1891 /// other Octave-hosted block kind in the same run (spawned lazily, on first use) -- never a
1892 /// second process.
1893 ///
1894 /// ## Parameters
1895 /// - `path=<dir>` — the directory containing `<function>_*.m` (see the file table above).
1896 /// `"double-quote"` a path containing whitespace, same as `CScript`'s `lib=`.
1897 /// - `function=<name>` — required, no default; the base name every `<function>_<role>.m`
1898 /// file shares.
1899 /// - `outputs=<name1,name2,...>` — output names; defaults to a single output aliasing the
1900 /// block's own `.name`.
1901 /// - `in=<signal>` or `inputs=<sig1,sig2,...>` — exactly one of these.
1902 /// - `ts=<f64>` / `freq=<f64>` / `to=<f64>` / `ts=variable` — optional; see
1903 /// [`SampleTimeSpec`]. `ts=variable` here requires `<function>_next_sample_hit.m` to also
1904 /// exist in `path`'s own directory.
1905 /// - `xc_count=<usize>` — optional, default `0`.
1906 ///
1907 /// ## Errors
1908 /// - `path`/`function`/`in` missing, or malformed `outputs=`/`xc_count=` — same generic/
1909 /// `xc_count` errors as [`BlockKind::CScript`].
1910 /// - A required `<function>_*.m` file missing from `path`'s own directory (per the file
1911 /// table above, given this block's own `xc_count`/`ts=`) — checked once, up front, at
1912 /// construction time, *before* `octave-cli` is ever asked about it: `dae_runtime::DaeError
1913 /// ::OctBlockMissingRequiredFile { block_name, expected_path }`.
1914 /// - `ts=variable` without `<function>_next_sample_hit.m` present — checked the same way:
1915 /// `dae_runtime::DaeError::OctBlockRequiresNextSampleHitForVariableSampleTime`.
1916 /// - `octave-cli` not found on `PATH`, an Octave-side exception raised by a called function,
1917 /// or a malformed/desynchronized reply — surfaces as a call-time failure from `octave_ffi`
1918 /// itself (`dae_runtime::DaeError::Octave`), not at parse time.
1919 /// - **`kind=octblock` does not support `TimeStep::Adaptive`** — this instance's own opaque
1920 /// state lives inside the one shared `octave-cli` session, which is never cloned, so a
1921 /// rejected adaptive trial step's own state-mutating calls could not be rolled back; a
1922 /// netlist using `kind=octblock` under an adaptive run fails at construction with
1923 /// `dae_runtime::DaeError::OctBlockDoesNotSupportAdaptiveStep { block_name }`. Use a fixed
1924 /// `--dt`.
1925 ///
1926 /// ## Netlist form
1927 /// ```text
1928 /// NAME kind=octblock path=<dir> function=<name> (in=<signal> | inputs=<sig1,sig2,...>) \
1929 /// [outputs=<name1,name2,...>] [ts=<f64>|freq=<f64> [to=<f64>] | ts=variable] \
1930 /// [xc_count=<usize>]
1931 /// ```
1932 ///
1933 /// ## Example
1934 /// A stateful accumulator (`out = state + in`, state advances by `in` every step) verified
1935 /// end to end against the real CLI, `SRC=3` producing `G1=3,6,9,...` across successive
1936 /// steps:
1937 /// ```text
1938 /// SRC kind=const value=3
1939 /// G1 kind=octblock path=accum function=accumulate in=SRC
1940 /// ```
1941 /// where `accum/accumulate_start.m` is:
1942 /// ```text
1943 /// function state = accumulate_start()
1944 /// state = 0;
1945 /// end
1946 /// ```
1947 /// and `accum/accumulate.m` is:
1948 /// ```text
1949 /// function [new_state, y] = accumulate(state, t, dt, u)
1950 /// new_state = state + u;
1951 /// y = new_state;
1952 /// end
1953 /// ```
1954 /// The `xc_count>0` contract (`_derivative`/`_output_xc`) is verified separately end to end
1955 /// against its own analytic solution ($\dot{x}_c = 1 - x_c$, starting at rest, so
1956 /// $x_c(t) = 1 - e^{-t}$) — see `doc-verify/octblock/xc_example.cir`, mirroring
1957 /// `doc-verify/pyblock/xc_example.cir`'s own precedent.
1958 OctBlock {
1959 /// The directory containing `<function>_start.m`, `<function>.m` (or
1960 /// `<function>_derivative.m`/`<function>_output_xc.m`), and optionally
1961 /// `<function>_update.m`/`<function>_next_sample_hit.m`.
1962 path: std::path::PathBuf,
1963 /// The shared base name every `<function>_<role>.m` file in `path` uses.
1964 function: String,
1965 /// This block's own output names, in order.
1966 output_names: Vec<String>,
1967 /// `None` runs every resolved circuit step; `Some` runs on its own schedule.
1968 sample_time: Option<SampleTimeSpec>,
1969 /// Number of solver-integrated continuous states this block owns; `0` for the plain contract.
1970 xc_count: usize,
1971 },
1972 /// <!-- component -->
1973 /// # Coordinate Transform (Clarke/Park)
1974 /// **Purpose:** one of the six Clarke/Park three-phase coordinate transforms.
1975 /// **Library:** Coordinate Transforms
1976 ///
1977 /// ## Description
1978 /// The standard `abc`/`alpha-beta-0`/`d-q-0` change of basis (see
1979 /// `continuous_blocks::CoordinateTransform`) used to regulate a three-phase quantity
1980 /// (grid-tied PFC, motor drive) with a `Pid` on a DC-like `d`/`q` value instead of chasing
1981 /// a sine wave directly. Stateless and multi-output, following exactly the same
1982 /// `output_names` convention [`BlockKind::CScript`] established: `inputs` supplies
1983 /// `kind.input_count()` values in the order `CoordinateTransform::call` expects,
1984 /// `output_names.len()` must equal 3 (this family's output count — the conventional
1985 /// per-transform names, e.g. `["alpha", "beta", "zero"]` for `Clarke`), the block's own
1986 /// `.name` binds to the first (primary) output, and the remaining two are inserted under
1987 /// their own `output_names` entries so a downstream block can reference them directly via
1988 /// `Signal::Block(name)`.
1989 ///
1990 /// ## Parameters
1991 /// - `kind=<clarke|clarkeinv|park|parkinv|clarkepark|clarkeparkinv>` — which transform.
1992 /// - `inputs=<sig1,...>` — `3` entries for `clarke`/`clarkeinv`, `4` for the other four
1993 /// (`park`/`parkinv`/`clarkepark`/`clarkeparkinv` also take an angle input).
1994 /// - `outputs=<name1,name2,name3>` — optional; defaults to `<name>,<name>_<suffix2>,
1995 /// <name>_<suffix3>` using this transform's own conventional output names.
1996 ///
1997 /// ## Errors
1998 /// - Wrong `inputs=` count for this transform — rejected at parse time: `kind='<kind>'
1999 /// needs <n> inputs (got <m>)`.
2000 /// - `outputs=` with a count other than 3 — rejected at parse time: `'outputs' needs
2001 /// exactly 3 entries (got <n>)`.
2002 ///
2003 /// ## Netlist form
2004 /// ```text
2005 /// NAME kind=clarke inputs=<a,b,c> [outputs=<name1,name2,name3>]
2006 /// NAME kind=park inputs=<a,b,c,theta> [outputs=<name1,name2,name3>]
2007 /// ```
2008 ///
2009 /// ## Example
2010 /// A balanced three-phase set through `clarke` — verified end to end: for
2011 /// $a=1,b=-0.5,c=-0.5$ (a peak on phase A), $\alpha = 1$, $\beta = 0$ exactly:
2012 /// ```text
2013 /// A kind=const value=1
2014 /// B kind=const value=-0.5
2015 /// C kind=const value=-0.5
2016 /// CT1 kind=clarke inputs=A,B,C
2017 /// ```
2018 CoordinateTransform {
2019 /// Which of the six Clarke/Park transforms this is.
2020 kind: CoordinateTransform,
2021 /// Output names; length must equal 3 for this family.
2022 output_names: Vec<String>,
2023 },
2024 /// <!-- component -->
2025 /// # PMSM (Permanent-Magnet Synchronous Motor)
2026 /// **Purpose:** a nonlinear permanent-magnet synchronous motor model.
2027 /// **Library:** Machines
2028 ///
2029 /// ## Description
2030 /// Genuinely nonlinear (bilinear speed/current coupling — see `continuous_blocks::Pmsm`),
2031 /// so like [`BlockKind::Vco`] it carries its own state and is integrated via its own
2032 /// `step()` (RK4) rather than compiled to a `StateSpace`. Three inputs, in order: `vd`,
2033 /// `vq` (rotor-frame stator voltage commands, V — typically a `ClarkeParkInv`'s output, or
2034 /// a `CoordinateTransform` intermediate wired through a `Pid`), and `t_load` (N·m, the
2035 /// mechanical load torque). Four outputs, same `output_names` convention as
2036 /// [`BlockKind::CoordinateTransform`]/[`BlockKind::CScript`]: `id`, `iq` (A), `omega_m`
2037 /// (mechanical speed, rad/s), and `theta_e` (electrical angle, already wrapped to
2038 /// $[0, 2\pi)$ via `Pmsm::theta_e_wrapped` — ready to feed a `Park`/`ClarkePark` block
2039 /// directly). Starts at rest (`id = iq = omega_m = theta_e = 0`) — no initial-condition
2040 /// override, matching every other dynamic block in this graph. Surface-mount motors have
2041 /// `l_d == l_q` (no reluctance torque term); interior-PM motors have `l_d != l_q`.
2042 ///
2043 /// ## Parameters
2044 /// - `r_s=<f64>` — stator resistance, Ω; must be `>= 0`.
2045 /// - `l_d=<f64>`, `l_q=<f64>` — d/q-axis inductance, H; both must be `> 0`.
2046 /// - `lambda_pm=<f64>` — permanent-magnet flux linkage, Wb.
2047 /// - `pole_pairs=<f64>` — must be `> 0`.
2048 /// - `inertia=<f64>` — rotor inertia, kg·m²; must be `> 0`.
2049 /// - `friction=<f64>` — viscous friction coefficient; must be `>= 0`.
2050 /// - `inputs=<vd,vq,t_load>` — exactly 3, in this order.
2051 /// - `outputs=<id,iq,omega_m,theta_e>` — optional; defaults to `<name>,<name>_iq,
2052 /// <name>_omega_m,<name>_theta_e`.
2053 ///
2054 /// ## Errors
2055 /// - `r_s < 0` — `invalid pmsm (NegativeResistance)`.
2056 /// - `l_d <= 0` or `l_q <= 0` — `invalid pmsm (NonPositiveInductance)`.
2057 /// - `pole_pairs <= 0` — `invalid pmsm (NonPositivePolePairs)`.
2058 /// - `inertia <= 0` — `invalid pmsm (NonPositiveInertia)`.
2059 /// - `friction < 0` — `invalid pmsm (NegativeFriction)`.
2060 ///
2061 /// ## Netlist form
2062 /// ```text
2063 /// NAME kind=pmsm r_s=<f64> l_d=<f64> l_q=<f64> lambda_pm=<f64> pole_pairs=<f64> \
2064 /// inertia=<f64> friction=<f64> inputs=<vd,vq,t_load> [outputs=<id,iq,omega_m,theta_e>]
2065 /// ```
2066 ///
2067 /// ## Example
2068 /// A small surface-mount motor at rest with zero applied voltage/load — verified to run
2069 /// without error and stay at rest (`id = iq = omega_m = 0`, no torque applied):
2070 /// ```text
2071 /// VD kind=const value=0
2072 /// VQ kind=const value=0
2073 /// TLOAD kind=const value=0
2074 /// 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 \
2075 /// friction=1e-6 inputs=VD,VQ,TLOAD
2076 /// ```
2077 Pmsm {
2078 /// The motor's own parameters/state.
2079 pmsm: Pmsm,
2080 /// Output names; length must equal 4 (`id`, `iq`, `omega_m`, `theta_e`).
2081 output_names: Vec<String>,
2082 },
2083 /// <!-- component -->
2084 /// # Phys2Sig (Physical-to-Signal Converter)
2085 /// **Purpose:** the only way a circuit quantity enters the signal domain.
2086 /// **Library:** Electrical Interface
2087 ///
2088 /// ## Description
2089 /// Zero block-graph inputs (it reads the circuit's own previous-step operating point
2090 /// directly). Its value is then an ordinary block output, read by any downstream block via
2091 /// `Signal::Block(this_block's_name)` exactly like any other source block
2092 /// (`Const`/`Pwl`/`Time`). Modeled directly on the physical/signal converter block a real
2093 /// block-diagram simulation tool requires: a physical port and a signal port are
2094 /// type-distinct there and cannot be wired together without one of these in between — the
2095 /// same rule, enforced the same way, at the netlist level instead of a GUI's wiring canvas.
2096 /// Named symmetrically with [`BlockKind::Sig2Phys`] (its write-direction counterpart):
2097 /// `phys2sig` reads a circuit quantity into the signal domain, `sig2phys` drives a
2098 /// signal-domain value onto a circuit quantity.
2099 ///
2100 /// ## Parameters
2101 /// - `node=<name>` — reads `V(node)`. Mutually exclusive with `branch=`.
2102 /// - `branch=<name>` — reads `I(branch)`. Mutually exclusive with `node=`.
2103 ///
2104 /// ## Errors
2105 /// - Both `node=` and `branch=` given — rejected at parse time: `'node' and 'branch' are
2106 /// mutually exclusive (a phys2sig reads either a node voltage or a branch current, never
2107 /// both)`.
2108 /// - Neither given — rejected at parse time: `kind='phys2sig' needs 'node=<name>' (reads
2109 /// V(node)) or 'branch=<name>' (reads I(branch))`.
2110 /// - `branch=<name>` naming an element that has no MNA branch-current unknown at all —
2111 /// rejected at build time (once the full circuit is known), not silently read back as
2112 /// `0.0`: only `V`/`L`/`E` (VCVS)/`H` (CCVS) elements carry a branch-current unknown (see
2113 /// `MnaBuilder::is_branch_device`); naming anything else (a resistor, a capacitor, a
2114 /// diode, an ideal switch, ...) is `line N: device '<name>' kind='phys2sig'
2115 /// branch='<branch>' has no current unknown available (only V/L/E/H sources carry a
2116 /// branch-current unknown) -- insert a 0V voltage source in series in the branch you want
2117 /// to measure and probe its current instead` — the standard SPICE "ammeter" idiom: a 0V
2118 /// source in series perturbs nothing electrically, but (being a `V` element) gets its own
2119 /// branch-current unknown for free, which `branch=` can then read.
2120 /// - `branch=<name>` naming an element that doesn't exist anywhere in the netlist at all
2121 /// (not just the wrong type) — a distinct build-time error: `line N: device '<name>'
2122 /// kind='phys2sig' branch='<branch>' names no such element`.
2123 ///
2124 /// ## Netlist form
2125 /// ```text
2126 /// NAME kind=phys2sig node=<node_name>
2127 /// NAME kind=phys2sig branch=<branch_name>
2128 /// ```
2129 ///
2130 /// ## Example
2131 /// Reading a resistor-divider node's own voltage — verified end to end, `PROBE1` tracking
2132 /// `V(out)` exactly:
2133 /// ```text
2134 /// V1 in 0 5
2135 /// R1 in out 1k
2136 /// R2 out 0 1k
2137 /// PROBE1 kind=phys2sig node=out
2138 /// ```
2139 ///
2140 /// The ammeter idiom — measuring the current through `R1` (which has no branch-current
2141 /// unknown of its own) by inserting a 0V source `VAMM` in series and reading *that* instead;
2142 /// verified end to end, `IMEAS` tracking `5 / (1000 + 1000) = 0.0025` A exactly (the 0V
2143 /// source doesn't perturb the divider at all):
2144 /// ```text
2145 /// V1 in 0 5
2146 /// VAMM in mid 0
2147 /// R1 mid out 1000
2148 /// R2 out 0 1000
2149 /// IMEAS kind=phys2sig branch=VAMM
2150 /// ```
2151 Phys2Sig(Phys2SigTarget),
2152 /// <!-- component -->
2153 /// # Sig2Phys (Signal-to-Physical Converter)
2154 /// **Purpose:** the only legal way a signal-domain block's output drives a `V`/`I` source's
2155 /// magnitude or an ideal switch's gate.
2156 /// **Library:** Electrical Interface
2157 ///
2158 /// ## Description
2159 /// Closes the write-direction gap [`BlockKind::Phys2Sig`] doesn't (a phys2sig only ever
2160 /// reads). A
2161 /// `V`/`I` element's own literal value field in the netlist names this block directly (e.g.
2162 /// `V1 a 0 VDRV`, where `VDRV` is a declared `domain=voltage` block) — `general-mna`'s own
2163 /// `Expression::parse_scalar` already accepts a bare symbol there with no change needed on
2164 /// that side; `dae-runtime` requires, at validation time, that any such symbol naming a
2165 /// declared block resolve to exactly this kind with the matching `domain` for the device
2166 /// letter driving it (`V` requires `domain=voltage`, `I` requires `domain=current`) —
2167 /// `DaeError::SourceNotSig2PhysicalConverter` otherwise — and every step, substitutes this
2168 /// block's own just-computed output value into the circuit solve in that symbol's place.
2169 ///
2170 /// Also the *only* legal target for a [`GateBinding::Block`]'s own named block, and there
2171 /// *only* the `domain=voltage` form — `dae-runtime` rejects a `GateBinding` naming anything
2172 /// else, including a `domain=current` `Sig2Phys`, with `DaeError::GateTargetNotSig2Voltage`.
2173 /// An ideal switch's gate is itself a voltage (`V_GS` against `v_th`), not a distinct
2174 /// discrete-actuation signal domain, so there is no separate gate-only converter — one type,
2175 /// `Sig2Phys`, parameterized by [`PhysicalDomain`], is the whole Signal-to-PS boundary for
2176 /// "a signal-domain block's output drives a physical voltage or current," whether that
2177 /// voltage happens to source a node, gate a switch, or drive a current source. Purely an
2178 /// identity pass-through numerically (`value = input`) in every role; the `domain` field is
2179 /// what the enforcement keys on. One input.
2180 ///
2181 /// ## Parameters
2182 /// - `domain=<voltage|current>` — which physical quantity this converter drives. Required.
2183 /// - `in=<signal>` — the value to drive onto the physical side (one input).
2184 ///
2185 /// ## Errors
2186 /// - `domain=` missing entirely — rejected at parse time: `line N: device '<name>' missing
2187 /// field 'domain'`.
2188 /// - `domain=` present but not `voltage`/`current` — rejected at parse time: `line N: device
2189 /// '<name>' field 'domain' must be 'voltage' or 'current' (got '<value>')`.
2190 /// - Beyond that, none specific to this `kind=` — every real enforcement (a `V`/`I`/gate
2191 /// target actually naming a `Sig2Phys` of the right domain) happens at `dae-runtime`'s
2192 /// validation stage, not netlist parse time. `general-mna` itself only ever sees the
2193 /// device-source half of a document (with `--devices <file>`, it doesn't see the netlist
2194 /// at all), so it cannot detect a converter's name reused as an ordinary circuit *node* —
2195 /// that mistake produces no parse error here. `dae-runtime` rejects it as
2196 /// `DaeError::Sig2PhysUsedAsCircuitNode`: this block has no terminals and stamps nothing
2197 /// into the MNA system, so a net sharing its name is merely undriven, and KCL solves it to
2198 /// a silently wrong `0` rather than failing — a converter must always be *referenced by
2199 /// name* (a source's value field, or a switch's `gate=`/`ctrl=`), never wired.
2200 ///
2201 /// ## Netlist form
2202 /// ```text
2203 /// NAME kind=sig2phys domain=voltage in=<signal>
2204 /// NAME kind=sig2phys domain=current in=<signal>
2205 /// ```
2206 ///
2207 /// ## Example
2208 /// A block-driven voltage source — verified end to end, `V1`'s magnitude tracking a
2209 /// `Const` through the converter exactly:
2210 /// ```text
2211 /// CMD kind=const value=5
2212 /// VDRV kind=sig2phys domain=voltage in=CMD
2213 /// V1 a 0 VDRV
2214 /// R1 a 0 1k
2215 /// ```
2216 ///
2217 /// A block-driven current source — verified end to end, `I1`'s magnitude tracking a
2218 /// `Const` through the converter exactly:
2219 /// ```text
2220 /// CMD kind=const value=0.1
2221 /// IDRV kind=sig2phys domain=current in=CMD
2222 /// I1 a 0 IDRV
2223 /// R1 a 0 1k
2224 /// ```
2225 Sig2Phys {
2226 /// Which physical quantity this converter drives — `V`-source targets and
2227 /// `GateBinding::Block` targets require `Voltage`; `I`-source targets require
2228 /// `Current`.
2229 domain: PhysicalDomain,
2230 },
2231}
2232
2233/// Which physical quantity a [`BlockKind::Sig2Phys`] converter drives. Purely a type-level tag
2234/// for the enforcement sites in `dae-runtime` (`DaeError::GateTargetNotSig2Voltage`,
2235/// `DaeError::SourceNotSig2PhysicalConverter`) — evaluation itself (`value = input`) is
2236/// identical for both.
2237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2238pub enum PhysicalDomain {
2239 /// Drives a `V` source's magnitude, or a [`GateBinding::Block`] target.
2240 Voltage,
2241 /// Drives an `I` source's magnitude.
2242 Current,
2243}
2244
2245/// One named block instance and where its inputs (if any) come from.
2246/// `Const`/`Pwc`/`Pwl`/`Waveform`/`Phys2Sig` blocks must have zero inputs; `Sum`/`Product` need one
2247/// input per sign/factor; `Gain`/
2248/// `StateSpace`/`TransferFunction`/`Vco`/`Saturation`/`Table`/`MathFn1`/`Sig2Phys`
2249/// each need exactly one; `Pid` needs exactly one (the error signal)
2250/// when its `clamp` is `PidClamp::Fixed`, or exactly three (`error, clamp_lo, clamp_hi`, in that
2251/// order) when `PidClamp::Dynamic`; `MathFn2` needs two; `MathFn3` needs three;
2252/// `CoordinateTransform` needs `kind.input_count()` (3 for `Clarke`/`ClarkeInv`, 4 for the
2253/// others — see [`continuous_blocks::CoordinateTransform::input_count`]); `Pmsm` needs exactly
2254/// three (`vd`, `vq`, `t_load`, in that order). Evaluated once per step in the causal order
2255/// `topological_order` (in `dae-runtime`) derives from the slice's own `Signal::Block` dependency graph — *not*
2256/// the order the slice happens to be given in; a `Signal::Block` input may name any block in
2257/// the same slice regardless of declared position (source blocks, naturally, need none, and a
2258/// genuine cycle among these edges is rejected as `DaeError::AlgebraicLoop` before any step
2259/// runs — see `topological_order`'s own doc comment for how).
2260///
2261/// **Generic field-parsing errors**, shared by every `kind=` block and not repeated per
2262/// variant below: a field required by that `kind` but absent from the line is `line N: device
2263/// '<name>' missing field '<key>'`; present but not parseable as the expected type (almost
2264/// always `f64`) is `line N: device '<name>' field '<key>' is not a number`.
2265#[derive(Debug, Clone, PartialEq)]
2266pub struct BlockInstance {
2267 /// This block's own unique name.
2268 pub name: String,
2269 /// What this block computes.
2270 pub kind: BlockKind,
2271 /// Where each input comes from, in the order `kind` expects.
2272 pub inputs: Vec<Signal>,
2273}
2274
2275/// How one ideal switch's gate state is resolved, every step: always from a named block's
2276/// current output, on while it's `>= 0.5`. No non-block-driven variant exists — even a
2277/// permanently-off gate is an explicit `Const(0.0)` wired through a `domain=voltage`
2278/// [`BlockKind::Sig2Phys`],
2279/// the same as every other gate — and no bare carrier-comparator variant exists either: that
2280/// comparison now lives entirely inside gate-driving `BlockKind`s themselves
2281/// ([`BlockKind::Pwm`]/[`BlockKind::PhaseShiftPwm`], or a hand-built chain of ordinary blocks),
2282/// so `GateBinding` has exactly one job — reading a number and thresholding it — regardless of
2283/// what produced that number: a modulator's own main/complement output, a
2284/// [`BlockKind::Hysteresis`] block (no carrier at all, event-driven bang-bang switching), or any
2285/// other block a caller composes.
2286#[derive(Debug, Clone, PartialEq)]
2287pub enum GateBinding {
2288 /// <!-- component -->
2289 /// # Gate Binding
2290 /// **Purpose:** how an ideal switch's gate state is resolved from a named block, every step.
2291 /// **Library:** Electrical Interface
2292 ///
2293 /// ## Description
2294 /// This is not a `kind=` block itself — it's the `gate=`/`ctrl=` field pair on a
2295 /// `kind=ideal_switch` device line. `GateBinding` has exactly one variant and exactly one
2296 /// job: reading a named block's current output and thresholding it at `>= 0.5`. No
2297 /// non-block-driven variant exists — even a permanently-off gate is an explicit `Const(0.0)`
2298 /// wired through a `domain=voltage` [`BlockKind::Sig2Phys`], the same as every other gate.
2299 /// The named block (`ctrl=`) must itself be a `domain=voltage` [`BlockKind::Sig2Phys`] — an
2300 /// ideal switch's gate is itself a voltage ($V_{GS}$ against $v_{th}$), not a distinct
2301 /// discrete-actuation signal domain (and never `domain=current`, even though `Sig2Phys`
2302 /// itself allows that domain for `I`-source targets).
2303 ///
2304 /// ## Parameters
2305 /// - `gate=block` — the only accepted value; every gate is block-driven.
2306 /// - `ctrl=<name>` — the name of a declared `domain=voltage` [`BlockKind::Sig2Phys`] block.
2307 ///
2308 /// ## Errors
2309 /// - `gate=` missing entirely on a `kind=ideal_switch` line — rejected at parse time:
2310 /// `missing field 'gate' (gate=block ctrl=<name> -- every gate is block-driven, see this
2311 /// file's own module doc comment)`.
2312 /// - `gate=` present but not `block` — rejected at parse time: `unknown gate spec '<value>'
2313 /// (only gate=block ctrl=<name> exists -- every gate is block-driven)`.
2314 /// - `ctrl=` naming a block that isn't a `domain=voltage` [`BlockKind::Sig2Phys`] (including
2315 /// a `domain=current` one) — rejected at `dae-runtime`'s validation stage (not netlist
2316 /// parse time): `DaeError::GateTargetNotSig2Voltage`.
2317 ///
2318 /// ## Netlist form
2319 /// ```text
2320 /// NAME kind=ideal_switch r_on=<f64> g_breakdown=<f64> v_breakdown=<f64> g_off=<f64> \
2321 /// v_th=<f64> g_on=<f64> gate=block ctrl=<sig2phys_voltage_block_name>
2322 /// ```
2323 ///
2324 /// ## Example
2325 /// An ideal switch permanently held on via a `Const(1)` wired through `Sig2Phys` — the
2326 /// plain `D1 in out idealswitchmodel` line gives the electrical connectivity (drain, source;
2327 /// the model name is unused for a `kind=ideal_switch`-overridden device), the same-named
2328 /// `kind=ideal_switch` line supplies the physics and gate. Verified end to end: `V(out)`
2329 /// settles to `5 * 1000 / (1000 + 0.1) ≈ 4.9995` (a fully-on 0.1 Ω ideal switch in series
2330 /// with a 1 kΩ load):
2331 /// ```text
2332 /// ONVAL kind=const value=1
2333 /// ONGATE kind=sig2phys domain=voltage in=ONVAL
2334 /// V1 in 0 5
2335 /// D1 in out idealswitchmodel
2336 /// D1 kind=ideal_switch r_on=0.1 g_breakdown=0 v_breakdown=-100 g_off=0 v_th=0.5 g_on=5 \
2337 /// gate=block ctrl=ONGATE
2338 /// R1 out 0 1k
2339 /// ```
2340 ///
2341 /// On while the named block's current output is `>= 0.5`.
2342 Block(String),
2343}
2344
2345impl GateBinding {
2346 /// The block this binding reads from.
2347 pub fn source_blocks(&self) -> [Option<&str>; 2] {
2348 match self {
2349 GateBinding::Block(name) => [Some(name), None],
2350 }
2351 }
2352
2353 /// # Panics
2354 /// If the named block's own current value is a `SignalValue::Vector` — unreachable in
2355 /// practice, since the *only* legal `GateBinding` target is a `domain=voltage`
2356 /// `BlockKind::Sig2Phys` converter (enforced before any step runs), and `Sig2Phys` itself
2357 /// rejects a `Vector` input at evaluation time — there is no way for a validly-targeted gate
2358 /// to ever see one here. Also panics if `name` isn't in `outputs` at all, exactly as before
2359 /// this variant existed (equally unreachable, for the same "checked before any step runs"
2360 /// reason).
2361 pub fn resolve(&self, outputs: &BTreeMap<String, SignalValue>) -> SwitchState {
2362 let GateBinding::Block(name) = self;
2363 let value = outputs[name.as_str()].as_scalar().unwrap_or_else(|| {
2364 panic!(
2365 "gate '{name}' resolved to a vector signal -- unreachable, since Sig2Phys \
2366 itself must already reject a vector input"
2367 )
2368 });
2369 if value >= 0.5 {
2370 SwitchState::On
2371 } else {
2372 SwitchState::Off
2373 }
2374 }
2375}
2376/// A short, human-readable name for a `BlockKind`, for error messages that need to say what a
2377/// mistargeted block actually is (e.g. `DaeError::GateTargetNotSig2Voltage`/
2378/// `SourceNotSig2PhysicalConverter`) without dumping its full parameter set.
2379pub fn block_kind_name(kind: &BlockKind) -> &'static str {
2380 match kind {
2381 BlockKind::Const(_) => "const",
2382 BlockKind::Time => "time",
2383 BlockKind::Pwc { .. } => "pwc",
2384 BlockKind::Pwl { .. } => "pwl",
2385 BlockKind::Waveform(TransientFunction::Sin { .. }) => "sinwave",
2386 BlockKind::Waveform(TransientFunction::Pulse { .. }) => "pulsewave",
2387 BlockKind::Waveform(TransientFunction::Exp { .. }) => "expwave",
2388 BlockKind::Waveform(TransientFunction::Sffm { .. }) => "sffmwave",
2389 // Never actually constructed (general-simulator-cli only builds `Waveform` from
2390 // Sin/Pulse/Exp/Sffm — a Pwl-shaped waveform always goes through `BlockKind::Pwl`
2391 // above instead, since only that variant supports `repeat`), but `TransientFunction`
2392 // is a 5-variant enum so this match must still be exhaustive.
2393 BlockKind::Waveform(TransientFunction::Pwl(_)) => "waveform(pwl)",
2394 BlockKind::Sum(_) => "sum",
2395 BlockKind::Gain(_) => "gain",
2396 BlockKind::Pid { .. } => "pid",
2397 BlockKind::StateSpace(_) => "statespace",
2398 BlockKind::TransferFunction(_) => "tf",
2399 BlockKind::DiscreteStateSpace { .. } => "discretestatespace",
2400 BlockKind::DiscreteTransferFunction { .. } => "discretetf",
2401 BlockKind::DiscretePid { .. } => "discretepid",
2402 BlockKind::Vco(_) => "vco",
2403 BlockKind::Pwm { .. } => "pwm",
2404 BlockKind::PhaseShiftPwm { .. } => "pspwm",
2405 BlockKind::Product => "product",
2406 BlockKind::Saturation(_) => "saturation",
2407 BlockKind::Table(_) => "table",
2408 BlockKind::MathFn1(f) => f.name(),
2409 BlockKind::MathFn2(f) => f.name(),
2410 BlockKind::MathFn3(f) => f.name(),
2411 BlockKind::Hysteresis(_) => "hysteresis",
2412 BlockKind::LogicGate(op) => op.name(),
2413 BlockKind::SrLatch { .. } => "srlatch",
2414 BlockKind::FlipFlop { kind, .. } => kind.name(),
2415 BlockKind::Counter { .. } => "counter",
2416 BlockKind::CScript { .. } => "cscript",
2417 BlockKind::PyBlock { .. } => "pyblock",
2418 BlockKind::PyFunction { .. } => "pyfunc",
2419 BlockKind::OctFunc { .. } => "octfunc",
2420 BlockKind::OctBlock { .. } => "octblock",
2421 BlockKind::CoordinateTransform { kind, .. } => kind.name(),
2422 BlockKind::Pmsm { .. } => "pmsm",
2423 BlockKind::Phys2Sig(_) => "phys2sig",
2424 BlockKind::Sig2Phys {
2425 domain: PhysicalDomain::Voltage,
2426 } => "sig2phys(domain=voltage)",
2427 BlockKind::Sig2Phys {
2428 domain: PhysicalDomain::Current,
2429 } => "sig2phys(domain=current)",
2430 }
2431}