dae_runtime/block_graph.rs
1//! Evaluates a graph of `general_mna::block_graph` types (`BlockKind`/`BlockInstance`/`Signal`/
2//! `GateBinding` — `Const`, `Time`, `Pwc`, `Pwl`, `Sin`, `Pulse`, `Exp`, `Sffm`, `Sum`, `Gain`,
3//! `Pid`, `StateSpace`, `TransferFunction`, `Vco`, `Pwm`, `PhaseShiftPwm`, `Product`,
4//! `Saturation`, `Table`, `MathFn1`/`2`/`3`, `Hysteresis`, `CoordinateTransform`, `Pmsm`,
5//! `CScript`, `Phys2Sig`, `Sig2Phys`), resolving every ideal switch's gate
6//! state each transient step. `general-mna` owns *what these types are* and *parsing them out
7//! of source text* (`general_mna::build_system`); this module owns *evaluating* the graph over
8//! time (`BlockState`, `evaluate_blocks`, `topological_order`,
9//! `simulate_transient_with_blocks`) — an error signal is a `Sum` block's output, a filtered-
10//! derivative PID compensator is a `TransferFunction` given its own `N(s)/D(s)` coefficients,
11//! and a frequency-modulated PWM carrier is `Pid -> Gain -> PhaseShiftPwm`, not a single
12//! function that bakes a specific topology together.
13//!
14//! **There is no separate "closed-loop mode," and no non-block-driven gate at all** — every
15//! [`GateBinding`] is `Block(name)`, reading a named block's current output (`>= 0.5` means
16//! on), whether that block's own input chain traces back to a
17//! [`BlockKind::Phys2Sig`] of the circuit's own state (the historically "closed-loop" case) or is
18//! just a `Const` (the historically "open-loop, fixed" case, now expressed as an ordinary block
19//! instead of a special no-block `GateBinding` variant) — both are resolved by exactly the same
20//! code, every step, because from the solver's point of view they're the same kind of question:
21//! "what's this device's terminal condition right now," answered from whatever the netlist and
22//! device file actually say. A real circuit simulator doesn't have a closed-loop *mode* either —
23//! closed-loop is a property of how a circuit happens to be wired, not an analysis type the tool
24//! needs to be told about upfront; `.op` and `.tran` are genuinely distinct analyses (different
25//! equations solved), but nothing about *this* function is analysis-specific.
26//!
27//! Sampled-data co-simulation: every block reads the *previous* circuit step's measurement,
28//! the whole graph is evaluated once per circuit step (in the causal order [`topological_order`]
29//! derives from the graph's own `Signal::Block` dependencies — declaration order is not the
30//! evaluation order; see that function and [`BlockInstance`]), and the result decides gate
31//! states before the circuit step itself is solved. [`crate::simulate_closed_loop`] (a single
32//! fixed `Sum`-then-`Pid`-then-duty-
33//! comparator topology, named for the one case it was first built for) remains as a lighter
34//! Rust-level convenience for simple direct callers; this module is the general one, used by
35//! `general-simulator-cli` unconditionally for every ideal switch-containing transient run.
36
37use std::collections::BTreeMap;
38
39use continuous_blocks::logic::{as_bool, from_bool, rising_edge, srlatch_next};
40use continuous_blocks::{math_ops, DiscretePidState, Hysteresis, Pmsm, StateSpace, Vco};
41use cscript_ffi::CScriptRegistry;
42use general_spice_core::Dialect;
43use pwl_devices::{IdealDiode, IdealSwitch};
44
45use crate::{
46 classify_segments, sawtooth_carrier, step_control, step_with_fallback, DaeError, GateState,
47 OperatingPoint, Segment, TimeStep, RINGING_COOLDOWN_STEPS,
48};
49
50use general_mna::block_graph::block_kind_name;
51pub use general_mna::block_graph::{
52 BlockInstance, BlockKind, ConstValue, GainValue, GateBinding, Phys2SigTarget, PhysicalDomain,
53 PidClamp, SampleTimeSpec, Signal, SignalValue,
54};
55
56/// Hard ceiling on accepted [`TimeStep::Adaptive`] steps for one [`simulate_transient_with_blocks`]
57/// call — see [`DaeError::AdaptiveStepStalled`]'s own doc comment for why this exists. Sized
58/// generously above any legitimate run this project has actually needed (the largest real
59/// fixed-step run on record is 1,000,000 rows for a 20ms/`dt=2e-8` transient; adaptive stepping
60/// should need far fewer accepted steps than that to cover the same window) while staying well
61/// under what would exhaust a typical machine's RAM before this check can fire (each row holds
62/// every node voltage/branch current/block output as `f64`s — a few hundred bytes for a
63/// medium-sized circuit — so even 10,000,000 rows stays in the hundreds-of-MB-to-low-GB range,
64/// not the tens-of-GB range that actually crashed a machine running the unpatched bug this
65/// guards against).
66pub const ADAPTIVE_STEP_HARD_CAP: usize = 10_000_000;
67
68/// Every input must be `Scalar` — the default rule for a `BlockKind` that has no elementwise/
69/// broadcast/flattening rule of its own (`Pid`, `Vco`, `Hysteresis`, `TransferFunction`, `Pwm`,
70/// `PhaseShiftPwm`, `Sig2Phys`). Returns the plain `f64` values in
71/// order, or a clear error naming the block the moment any input is a `Vector`.
72fn require_all_scalar(block_name: &str, input_vals: &[SignalValue]) -> Result<Vec<f64>, DaeError> {
73 input_vals
74 .iter()
75 .map(|v| {
76 v.as_scalar()
77 .ok_or_else(|| DaeError::VectorSignalNotSupported {
78 block: block_name.to_string(),
79 })
80 })
81 .collect()
82}
83
84/// Flattens `input_vals` (each independently `Scalar` or `Vector`) into one `Vec<f64>`, in
85/// order — the input-bundling convention `StateSpace`, `CoordinateTransform`, `Pmsm`, and
86/// `cscript` all share: a downstream block wanting several upstream values can list them one
87/// per `Signal`, mixing scalar and vector references freely, and this is where they get
88/// concatenated into the flat vector each of those blocks' own math actually consumes.
89fn flatten(input_vals: &[SignalValue]) -> Vec<f64> {
90 input_vals
91 .iter()
92 .flat_map(|v| v.as_slice().iter().copied())
93 .collect()
94}
95
96/// The common vector length among `operands` (every `Vector` operand must share one length; a
97/// lone `Scalar` operand broadcasts against it) — `None` if every operand is `Scalar` (no
98/// broadcasting needed, the block should just compute its ordinary scalar result). Used by
99/// `MathFn2`/`MathFn3`, which — unlike `Sum`/`Product` — always have an unambiguous pairing for
100/// a lone scalar operand, so broadcasting it is the right default rather than an error.
101fn common_vector_len(
102 block_name: &str,
103 operands: &[&SignalValue],
104) -> Result<Option<usize>, DaeError> {
105 let mut common: Option<usize> = None;
106 for v in operands {
107 if let SignalValue::Vector(xs) = v {
108 match common {
109 None => common = Some(xs.len()),
110 Some(n) if n == xs.len() => {}
111 Some(n) => {
112 return Err(DaeError::VectorSignalSizeMismatch {
113 block: block_name.to_string(),
114 expected: n,
115 got: xs.len(),
116 })
117 }
118 }
119 }
120 }
121 Ok(common)
122}
123
124/// `v`'s own value at element `i` — its single scalar if `v` is `Scalar` (the broadcast case),
125/// or `v`'s own `i`-th element if `v` is `Vector`. Panics if `v` is a `Vector` shorter than
126/// `i + 1`; callers only ever index up to the common length `common_vector_len` already
127/// validated every `Vector` operand agrees with, so this is never actually out of bounds.
128fn broadcast_at(v: &SignalValue, i: usize) -> f64 {
129 match v {
130 SignalValue::Scalar(x) => *x,
131 SignalValue::Vector(xs) => xs[i],
132 }
133}
134
135/// Every input must be a `Vector`, all the same length — `Sum`/`Product`'s own rule, distinct
136/// from `common_vector_len`'s broadcast: an N-input reduction has no unambiguous placement for
137/// a lone scalar once more than one vector is already present, so a mix of `Scalar` and
138/// `Vector` inputs is rejected outright rather than guessed at (see
139/// `book/dev-guide/src/vector-signals.md`, category 3).
140fn require_uniform_vectors(
141 block_name: &str,
142 input_vals: &[SignalValue],
143) -> Result<usize, DaeError> {
144 let mut common: Option<usize> = None;
145 for v in input_vals {
146 let SignalValue::Vector(xs) = v else {
147 return Err(DaeError::VectorSignalNotSupported {
148 block: block_name.to_string(),
149 });
150 };
151 match common {
152 None => common = Some(xs.len()),
153 Some(n) if n == xs.len() => {}
154 Some(n) => {
155 return Err(DaeError::VectorSignalSizeMismatch {
156 block: block_name.to_string(),
157 expected: n,
158 got: xs.len(),
159 })
160 }
161 }
162 }
163 Ok(common.unwrap_or(0))
164}
165
166/// Filters a block-graph output map down to its `Scalar` entries only, discarding any `Vector`
167/// ones — used specifically where a `V`/`I` source's own literal value needs a scalar-only
168/// symbol table (`fold_and_solve`'s `extra_values`/`extra_values_prev`): the *only* symbols
169/// that can legitimately appear there are a `Sig2Phys` converter's own name,
170/// and both are guaranteed `Scalar` (they reject a `Vector` input at evaluation time — see
171/// their own `evaluate_blocks` arm), so dropping any `Vector` entry here is safe, not a silent
172/// bug: nothing that could legitimately need one is ever filtered out.
173fn scalar_only(outputs: &BTreeMap<String, SignalValue>) -> BTreeMap<String, f64> {
174 outputs
175 .iter()
176 .filter_map(|(k, v)| v.as_scalar().map(|x| (k.clone(), x)))
177 .collect()
178}
179
180#[derive(Clone)]
181enum BlockState {
182 Stateless,
183 /// Shared by `Pid`, `StateSpace`, and `TransferFunction` — all three are, underneath,
184 /// "step this compiled `StateSpace` forward" with only `Pid` additionally applying
185 /// anti-windup (see the match arm in the step loop below).
186 Dynamic {
187 state_space: continuous_blocks::StateSpace,
188 x: Vec<f64>,
189 },
190 /// Shared by [`BlockKind::DiscreteStateSpace`] and [`BlockKind::DiscreteTransferFunction`] —
191 /// the discrete-domain counterpart to [`Self::Dynamic`] above: `x` advances via
192 /// [`continuous_blocks::StateSpace::discrete_step`] instead of `rk4_step`, only on steps this
193 /// block's own mandatory `sample_time` says it's due (see [`BlockKind::CScript`]'s own
194 /// zero-order-hold gating in `evaluate_blocks`, reused unchanged here). `last_output` is what
195 /// gets returned on every step this block *isn't* due — a genuinely discrete system's own
196 /// output is only defined at its own sample instants, not recomputable from a held `x` and a
197 /// fresher `u` in between, unlike the continuous case.
198 DiscreteDynamic {
199 state_space: continuous_blocks::StateSpace,
200 x: Vec<f64>,
201 time_since_sample: f64,
202 last_output: Vec<f64>,
203 },
204 /// [`BlockKind::DiscretePid`]'s own state — [`continuous_blocks::DiscretePidState`] plus the
205 /// same zero-order-hold `time_since_sample`/`last_output` bookkeeping as
206 /// [`Self::DiscreteDynamic`] above (this block's mandatory `sample_time` is where
207 /// [`continuous_blocks::DiscretePid::period`] itself came from at construction — see
208 /// `general-mna`'s own `system_builder.rs`).
209 DiscretePid {
210 state: continuous_blocks::DiscretePidState,
211 time_since_sample: f64,
212 last_output: f64,
213 },
214 Vco {
215 vco: Vco,
216 phase: f64,
217 },
218 /// PWM Modulator 2's own frequency-integration state — structurally identical to `Vco`
219 /// above (both reuse the same [`Vco`] clamp-and-integrate math), but a distinct variant so
220 /// nothing in this module's own dispatch code has to pretend PWM Modulator 2 *is* a `Vco`
221 /// block, which it isn't.
222 PhaseShiftPwm {
223 osc: Vco,
224 phase: f64,
225 },
226 Pmsm {
227 pmsm: Pmsm,
228 x: [f64; 4],
229 },
230 Hysteresis {
231 hysteresis: Hysteresis,
232 on: bool,
233 },
234 /// [`BlockKind::SrLatch`]'s own state -- a single persisted bit, updated every step
235 /// (level-triggered, no clock/edge detection at all, unlike [`Self::FlipFlop`]/
236 /// [`Self::Counter`] below).
237 SrLatch {
238 q: bool,
239 },
240 /// [`BlockKind::FlipFlop`]'s own state -- `q` is the flip-flop's own output, held unchanged
241 /// except at a detected rising `clk` edge; `prev_clk` is this instance's own memory of the
242 /// previous step's `clk` sample, the only way to detect that edge at all (see
243 /// `logic-signals.md`'s own Category 3 for why this lives in `BlockState` rather than
244 /// requiring a separate `prev:`-wired clock signal).
245 FlipFlop {
246 q: bool,
247 prev_clk: f64,
248 },
249 /// [`BlockKind::Counter`]'s own state -- same rising-edge-detection skeleton as
250 /// [`Self::FlipFlop`], generalized from a single bit to a signed running count.
251 Counter {
252 count: i64,
253 prev_clk: f64,
254 },
255 /// A live, per-instance [`cscript_ffi::CScriptInstance`], plus the zero-order-hold
256 /// bookkeeping [`BlockKind::CScript`]'s `sample_time` needs: `time_since_sample` accumulates
257 /// circuit `dt`s until it reaches the configured sample period (or is always "due" every
258 /// step when `sample_time` is `None`), and `last_output` is what gets returned/held on
259 /// every step the block *doesn't* actually run its output function. Cloning this variant
260 /// (only ever needed by [`TimeStep::Adaptive`]'s retry loop, which clones the whole
261 /// `block_states` vector before every trial) calls into `cscript_clone` for `instance` and
262 /// **panics** if the library doesn't export it — see
263 /// [`simulate_transient_with_blocks`]'s own upfront check, which exists specifically so
264 /// that panic is unreachable in practice. `xc` is the block's own continuous-state vector
265 /// (empty when `xc_count == 0`) — a plain, RK4-cloneable `Vec<f64>`, not part of the opaque
266 /// `void *state` `instance` owns; see `cscript_ffi`'s own module doc comment, "The optional
267 /// continuous-state (`xc`) contract."
268 CScript {
269 instance: cscript_ffi::CScriptInstance,
270 time_since_sample: f64,
271 // Only meaningful for `SampleTimeSpec::Variable` -- the interval (seconds, relative)
272 // `cscript_next_sample_hit` returned after this block's last due call, compared against
273 // `time_since_sample` the same way `SampleTimeSpec::Periodic`'s own fixed `period` is.
274 // Starts at `0.0` so a Variable block is unconditionally due on its first call, same
275 // convention every other zero-order-hold block's own first call already has.
276 next_hit_dt: f64,
277 last_output: Vec<f64>,
278 xc: Vec<f64>,
279 },
280 /// The Python-hosted counterpart to `CScript` above — same zero-order-hold `sample_time`
281 /// bookkeeping, same `xc` continuous-state vector, `instance` a live
282 /// [`pyblock_ffi::PyBlockInstance`] instead of a C one. Cloning this variant uses Python's
283 /// own generic `copy.deepcopy` (see `pyblock_ffi`'s own module doc comment) — unlike
284 /// `CScript`, there is no "doesn't support clone" panic path, since `deepcopy` needs no
285 /// author opt-in. Only exists when the optional `python` feature is enabled — see
286 /// `dae-runtime`'s own `Cargo.toml`.
287 #[cfg(feature = "python")]
288 PyBlock {
289 instance: pyblock_ffi::PyBlockInstance,
290 time_since_sample: f64,
291 // Same role as `CScript`'s own `next_hit_dt` above.
292 next_hit_dt: f64,
293 last_output: Vec<f64>,
294 xc: Vec<f64>,
295 },
296 /// The counterpart to `PyBlock` above for [`BlockKind::PyFunction`] — a genuinely separate
297 /// variant (not reusing `PyBlock`'s own fields), since a stateless
298 /// [`pyblock_ffi::PyFunctionInstance`] has no `xc` and cloning it is always trivially cheap
299 /// (`clone_ref`, never `copy.deepcopy`, never fallible) — see that type's own doc comment.
300 /// Still needs the same zero-order-hold `sample_time` bookkeeping every other zero-order-
301 /// hold block has. Only exists when the optional `python` feature is enabled.
302 #[cfg(feature = "python")]
303 PyFunction {
304 instance: pyblock_ffi::PyFunctionInstance,
305 time_since_sample: f64,
306 last_output: Vec<f64>,
307 },
308 /// The `.m`-file counterpart to `PyFunction` above, for [`BlockKind::OctFunc`] — same
309 /// stateless contract, but `session` is an `Rc<RefCell<_>>` around one shared
310 /// [`octave_ffi::OctaveSession`], not an owned interpreter handle: unlike `pyblock_ffi`'s
311 /// embedded Python (process-global via PyO3, so every `PyFunctionInstance` reaches the same
312 /// interpreter automatically), `octave_ffi::OctaveSession` is a real, separate `octave-cli`
313 /// child process this crate itself owns and must explicitly share across every `OctFunc`
314 /// block instance in the same run (see [`simulate_transient_with_blocks`]'s own construction
315 /// loop, which spawns exactly one `OctaveSession`, lazily, the first time an `OctFunc` block
316 /// is actually encountered, and hands every instance an `Rc::clone` of it). Cloning this
317 /// variant (needed only for [`TimeStep::Adaptive`]'s retry loop) is always cheap and
318 /// infallible — an `Rc::clone`, sharing the same underlying process and its own
319 /// per-process-lifetime call-id counter, never spawning a second `octave-cli`; this is
320 /// correct because [`octave_ffi::OctaveSession::call`] carries no state a rejected trial
321 /// step could corrupt (see the module doc comment, "The call protocol" — nothing is ever
322 /// assigned into the shared Octave workspace).
323 OctFunction {
324 session: std::rc::Rc<std::cell::RefCell<octave_ffi::OctaveSession>>,
325 time_since_sample: f64,
326 last_output: Vec<f64>,
327 },
328 /// The stateful counterpart to `OctFunction` above, for [`BlockKind::OctBlock`] -- same
329 /// shared, `Rc`-cloned session every other Octave-hosted block kind in this run uses (see
330 /// `OctFunction`'s own doc comment for why sharing is safe/correct even under
331 /// [`TimeStep::Adaptive`]'s clone-per-trial-step loop), but unlike `OctFunction`, this
332 /// block's own opaque per-instance state genuinely lives *inside* that shared session (one
333 /// global struct, keyed by `instance` -- see `octave_ffi::OctaveSession::call_start`'s own
334 /// doc comment), never inside this Rust struct at all. `instance` is this block's own
335 /// `.name` -- the key into that shared struct -- and `xc` is the block's own solver-owned
336 /// continuous-state vector, exactly the same role `CScript`'s/`PyBlock`'s own `xc` field
337 /// has (empty when `xc_count == 0`). `time_since_sample`/`next_hit_dt`/`last_output` are the
338 /// same zero-order-hold bookkeeping every other sample-time-gated block variant already
339 /// carries.
340 OctBlock {
341 session: std::rc::Rc<std::cell::RefCell<octave_ffi::OctaveSession>>,
342 instance: String,
343 time_since_sample: f64,
344 next_hit_dt: f64,
345 last_output: Vec<f64>,
346 xc: Vec<f64>,
347 /// Whether `<function>_update.m` exists in this block's own `path` directory -- checked
348 /// once, up front, at construction (see [`simulate_transient_with_blocks`]'s own
349 /// construction loop), so `evaluate_blocks` never has to speculatively call an
350 /// `_update.m` that might not exist (which would otherwise surface as a spurious
351 /// Octave-side "undefined function" error for the common case where a block simply has
352 /// no discrete bookkeeping to commit).
353 has_update: bool,
354 },
355}
356
357/// One step's result: `(t, OperatingPoint, block_outputs)`, where `block_outputs` is every
358/// block's value that step (by name) — useful for plotting a controller's internal signals
359/// (e.g. a `Vco`'s commanded frequency) without needing to separately re-derive them.
360pub type TransientWithBlocksStep = (f64, OperatingPoint, BTreeMap<String, SignalValue>);
361
362/// Name -> block index, including a [`BlockKind::CScript`]/[`BlockKind::CoordinateTransform`]/
363/// [`BlockKind::Pmsm`]'s extra `output_names` (aliasing the index of the block that declared
364/// them) — the one piece of bookkeeping both [`topological_order`] and the upfront gate-name
365/// validation in [`simulate_transient_with_blocks`] need identically. Rejects any name — a
366/// block's own `.name`, or one of its extra `output_names` aliases — that collides with one
367/// already seen, rather than letting the later one silently win (see
368/// [`DaeError::DuplicateBlockName`]'s own doc comment for why that matters).
369fn block_index_by_name(blocks: &[BlockInstance]) -> Result<BTreeMap<&str, usize>, DaeError> {
370 let mut index_of = BTreeMap::new();
371 for (i, b) in blocks.iter().enumerate() {
372 if index_of.insert(b.name.as_str(), i).is_some() {
373 return Err(DaeError::DuplicateBlockName(b.name.clone()));
374 }
375 let extra: &[String] = match &b.kind {
376 BlockKind::CScript { output_names, .. }
377 | BlockKind::PyBlock { output_names, .. }
378 | BlockKind::PyFunction { output_names, .. }
379 | BlockKind::OctFunc { output_names, .. }
380 | BlockKind::OctBlock { output_names, .. }
381 | BlockKind::CoordinateTransform { output_names, .. }
382 | BlockKind::Pmsm { output_names, .. }
383 | BlockKind::Pwm { output_names, .. }
384 | BlockKind::PhaseShiftPwm { output_names, .. } => output_names,
385 _ => &[],
386 };
387 for name in extra.iter().skip(1) {
388 if index_of.insert(name.as_str(), i).is_some() {
389 return Err(DaeError::DuplicateBlockName(name.clone()));
390 }
391 }
392 }
393 Ok(index_of)
394}
395
396/// Derives the causal evaluation order for `blocks` from their own `Signal::Block` dependencies
397/// — a topological sort of the same-step dependency graph — instead of relying on declaration
398/// order: a block may name another declared anywhere in the same slice, before or after it.
399/// `BlockKind::Phys2Sig`/`Signal::BlockPrev` inputs never contribute a dependency edge here —
400/// `Phys2Sig` has zero inputs (a source block, like `Const`/`Time`) and `BlockPrev` reads state
401/// from strictly before this step (any block's own previous output), so neither can ever
402/// participate in a same-step cycle by construction — exactly the reason `BlockPrev` exists. A
403/// name that doesn't resolve to any block is not
404/// this function's concern; it's reported at evaluation time instead (`DaeError::
405/// UnknownBlockInput`, from `evaluate_blocks`' own `resolve` closure), so a typo and a
406/// deliberately external reference are diagnosed the same way regardless of graph shape.
407///
408/// Implementation: classic DFS-based topological sort with three-color marking (white/gray/
409/// black), chosen over Kahn's algorithm specifically because a discovered cycle can be reported
410/// as the *exact path* that closes it (`["A", "B", "C", "A"]`, read as "A depends on B depends
411/// on C depends on A") rather than just the set of nodes Kahn's leaves stranded with nonzero
412/// in-degree when it gets stuck.
413fn topological_order(blocks: &[BlockInstance]) -> Result<Vec<usize>, DaeError> {
414 #[derive(Clone, Copy, PartialEq)]
415 enum Color {
416 White,
417 Gray,
418 Black,
419 }
420
421 fn visit(
422 i: usize,
423 blocks: &[BlockInstance],
424 index_of: &BTreeMap<&str, usize>,
425 color: &mut [Color],
426 stack: &mut Vec<usize>,
427 order: &mut Vec<usize>,
428 ) -> Result<(), DaeError> {
429 match color[i] {
430 Color::Black => return Ok(()),
431 Color::Gray => {
432 // A back-edge into a node already on the current DFS path: the cycle is that
433 // node onward through the rest of the path, with it repeated at the end to show
434 // the loop closing.
435 let start = stack.iter().position(|&s| s == i).expect(
436 "a Gray node is always still on the stack by this function's own invariant",
437 );
438 let mut cycle: Vec<String> = stack[start..]
439 .iter()
440 .map(|&idx| blocks[idx].name.clone())
441 .collect();
442 cycle.push(blocks[i].name.clone());
443 return Err(DaeError::AlgebraicLoop { cycle });
444 }
445 Color::White => {}
446 }
447 color[i] = Color::Gray;
448 stack.push(i);
449 for signal in &blocks[i].inputs {
450 if let Signal::Block(name) = signal {
451 if let Some(&dep) = index_of.get(name.as_str()) {
452 visit(dep, blocks, index_of, color, stack, order)?;
453 }
454 }
455 }
456 stack.pop();
457 color[i] = Color::Black;
458 order.push(i);
459 Ok(())
460 }
461
462 let index_of = block_index_by_name(blocks)?;
463 let mut color = vec![Color::White; blocks.len()];
464 let mut order = Vec::with_capacity(blocks.len());
465 let mut stack = Vec::new();
466 for i in 0..blocks.len() {
467 if color[i] == Color::White {
468 visit(i, blocks, &index_of, &mut color, &mut stack, &mut order)?;
469 }
470 }
471 Ok(order)
472}
473
474/// Maps simulated time `t` into the effective evaluation time for a [`BlockKind::Pwc`]/
475/// [`BlockKind::Pwl`] block: unchanged when `repeat` is `false`, or `points` has fewer than two
476/// breakpoints (no well-defined period), or `t` hasn't yet reached the last breakpoint;
477/// otherwise wraps `t` into `[points[0].0, points.last().0)`, period = last breakpoint time −
478/// first breakpoint time, so the same finite breakpoint list repeats forever instead of holding
479/// its last value flat — the periodic PWL/PWC source this session added specifically because
480/// neither `general-mna`'s own electrical-domain `PWL(...)` source nor any prior signal-domain
481/// block had a repeat option.
482fn periodic_time(t: f64, points: &[(f64, f64)], repeat: bool) -> f64 {
483 if !repeat || points.len() < 2 {
484 return t;
485 }
486 let t0 = points[0].0;
487 let t_last = points[points.len() - 1].0;
488 let period = t_last - t0;
489 if period <= 0.0 || t < t_last {
490 return t;
491 }
492 t0 + (t - t0) % period
493}
494
495/// Evaluates every block once, in the causal `order` [`topological_order`] derived from the
496/// graph's own `Signal::Block` dependencies (not declaration order), advancing `block_states`
497/// in place at step size `dt`, reading any [`BlockKind::Phys2Sig`] from `point_prev` and any
498/// [`Signal::BlockPrev`] from `prev_outputs` (the previous call's returned map; an empty map on
499/// the very first step, so every `BlockPrev` reference is `0.0` there) — the one piece of
500/// per-step work both [`TimeStep::Fixed`] and [`TimeStep::Adaptive`] need identically, factored
501/// out so the adaptive loop below can re-run it (against a *cloned* `block_states`) once per
502/// retry at a shrinking trial `dt`, without duplicating the block-dispatch match arms.
503/// Shared by [`BlockKind::Pwm`] and [`BlockKind::PhaseShiftPwm`]'s own `evaluate_blocks` arms:
504/// both modulators produce an **active-high complementary pair**, binding the primary output
505/// under the block's own name (the caller's job, this just returns it) and the secondary
506/// `complement` output under `output_names[1]` (inserted here, if given). One implementation so
507/// a third gate-driving modulator only has to call this, not re-derive the convention.
508fn emit_complementary_pair(
509 outputs: &mut BTreeMap<String, SignalValue>,
510 output_names: &[String],
511 main: bool,
512 complement: bool,
513) -> f64 {
514 if let Some(name) = output_names.get(1) {
515 outputs.insert(
516 name.clone(),
517 SignalValue::Scalar(if complement { 1.0 } else { 0.0 }),
518 );
519 }
520 if main {
521 1.0
522 } else {
523 0.0
524 }
525}
526
527/// The zero-order-hold "due" threshold shared by [`BlockKind::CScript`]/[`BlockKind::PyBlock`]/
528/// [`BlockKind::OctBlock`]'s own per-step gating: `None` sample_time runs continuously (no
529/// threshold at all), `Periodic` uses its fixed `period`, `Variable` uses whatever `next_hit_dt`
530/// this instance's own `next_sample_hit` last reported. Factored out so
531/// [`earliest_next_event_dt`] can reuse the exact same rule its callers' own "due" checks use,
532/// rather than re-deriving it.
533fn sample_threshold(sample_time: Option<&SampleTimeSpec>, next_hit_dt: f64) -> Option<f64> {
534 match sample_time {
535 None => None,
536 Some(SampleTimeSpec::Periodic { period, .. }) => Some(*period),
537 Some(SampleTimeSpec::Variable) => Some(next_hit_dt),
538 }
539}
540
541/// Smallest non-negative relative `dt` (from "now") at which a zero-order-hold block next
542/// becomes due, given its currently-persisted `time_since_sample` accumulator and (already
543/// resolved) `threshold`. `None` propagates through (never due on its own -- e.g. `sample_time
544/// == None`, run-every-step blocks aren't scheduled events for this purpose since they have no
545/// discrete "next hit" at all).
546fn time_until_due(threshold: Option<f64>, time_since_sample: f64) -> Option<f64> {
547 threshold.map(|th| (th - time_since_sample).max(0.0))
548}
549
550/// The smallest relative `dt` (from theta_now, in the same `[0,1)`-wrapped phase space
551/// `sawtooth_carrier`/`Vco::step` use) at which one of `duty`/`Pwm`'s complementary-pair
552/// dead-time thresholds is next crossed, converted to seconds via `freq` (Hz). Shared by
553/// [`BlockKind::Pwm`] and [`BlockKind::PhaseShiftPwm`]'s own [`earliest_next_event_dt`] arms --
554/// both use the identical `{red_frac, duty, duty + fed_frac}` threshold set
555/// [`continuous_blocks::math_ops::complementary_pwm_with_deadtime`] itself compares against.
556/// `None` if `freq` isn't usable (non-positive or non-finite -- would make `delta_t` meaningless
557/// or divide by zero).
558///
559/// A threshold this function itself just reported (and the adaptive loop then landed a step
560/// exactly on, which is the whole point of calling this at all) reads back as `theta_now ==
561/// that threshold` on the very next call -- naively that's `delta_theta == 0`, i.e. "you're
562/// already there," which the adaptive loop's own `ev.max(1e-15)` clamp turns into a real ~1fs
563/// step instead of an error. Theta barely moves in a step that small, so the SAME threshold
564/// reads back as ~0 again next iteration too: an unbounded near-zero-dt loop that silently
565/// consumes memory (one row per iteration, unbounded) until the process is killed -- this
566/// crashed the machine it ran on once already. `THETA_EPS` (a full period's worth of
567/// `f64::EPSILON`-scale noise, times a wide safety margin -- see the constant's own comment)
568/// shifts the search so a threshold within `THETA_EPS` *behind* `theta_now` reads as "already
569/// crossed, wait a full period," never as "0 away" -- while any threshold more than `THETA_EPS`
570/// ahead is unaffected to double-precision noise. Regression test:
571/// `adaptive_event_landing::stepping_repeatedly_lands_exactly_on_the_same_edge_without_stalling`.
572fn next_pwm_edge_dt(
573 theta_now: f64,
574 duty: f64,
575 red_frac: f64,
576 fed_frac: f64,
577 freq: f64,
578) -> Option<f64> {
579 // theta = (t * freq_hz).fract() (see `sawtooth_carrier`) or a phase accumulator advanced by
580 // `freq * dt` each step (see `Vco::step`) -- both accumulate error on the order of
581 // `f64::EPSILON * theta_now.recip_scale()`, comfortably under 1e-9 for any `t`/`phase`
582 // magnitude this engine's own `AdaptiveConfig::from_t_final` would ever produce (t_final up
583 // to ~1e6s would still keep `t * freq_hz` under 1e18, whose `f64::EPSILON`-scale noise is
584 // ~1e2 in absolute terms -- i.e. this bound would need revisiting only for a `t_final`/`freq`
585 // combination many orders of magnitude past anything this project runs).
586 const THETA_EPS: f64 = 1e-9;
587 if !freq.is_finite() || freq <= 0.0 {
588 return None;
589 }
590 let thresholds = [red_frac, duty, duty + fed_frac];
591 let delta_theta = thresholds
592 .iter()
593 .map(|&r| (r - theta_now - THETA_EPS).rem_euclid(1.0) + THETA_EPS)
594 .fold(f64::INFINITY, f64::min);
595 if !delta_theta.is_finite() {
596 return None;
597 }
598 Some(delta_theta / freq)
599}
600
601/// Resolves `signal` against `prev_outputs` (the previous *accepted* step's own output map, not
602/// a trial-in-progress one) as a scalar, or `None` if unresolvable (unknown name, vector-valued,
603/// or -- on the very first step, before any step has been accepted -- simply not there yet).
604/// `Signal::Block` and `Signal::BlockPrev` are treated identically here: both name the same
605/// "last known value" this function wants, unlike `evaluate_blocks`' own `resolve` closure,
606/// which distinguishes "this step's already-computed upstream output" from "strictly the
607/// previous step's" -- a distinction [`earliest_next_event_dt`] has no use for, since it never
608/// computes a same-step `outputs` map of its own at all.
609fn resolve_prev_scalar(
610 prev_outputs: &BTreeMap<String, SignalValue>,
611 signal: &Signal,
612) -> Option<f64> {
613 let name = match signal {
614 Signal::Block(n) | Signal::BlockPrev(n) => n,
615 };
616 prev_outputs.get(name).and_then(|v| v.as_scalar())
617}
618
619/// Computes the earliest relative `dt` (from `t`, using each block's currently-*persisted*
620/// state -- never a trial evaluation) at which some in-scope block's output would next cross a
621/// discrete threshold (a `Pwm`/`PhaseShiftPwm` gate edge, or a zero-order-hold block's next
622/// sample hit), assuming every block's own runtime inputs stay at their last-*evaluated* values
623/// (i.e. `prev_outputs`, the previous accepted step's own outputs). Returns `None` if no in-scope
624/// block reports a finite estimate.
625///
626/// Read fresh, from `block_states`/`prev_outputs` as they stand at the very start of every
627/// accepted-step iteration of [`TimeStep::Adaptive`]'s own loop -- never extrapolated across
628/// multiple steps -- so a stale prediction (an input that changes again before the predicted
629/// edge, e.g. `PhaseShiftPwm`'s closed-loop-driven `freq_command`/`duty`) is bounded to at most
630/// one step's own error, which is strictly better than today's zero prediction, never worse: this
631/// is a *clamp* on the adaptive step, not a substitute for the LTE-driven retry loop that still
632/// runs after it and can shrink `dt` further.
633///
634/// [`BlockKind::Vco`] is deliberately excluded (always contributes `None`) -- its own output is
635/// the raw phase itself (a continuous ramp `[0,1)`, not a discrete/boolean gate signal), so the
636/// only "discontinuity" it has is the phase-wrap seam, which is a slope/value jump in a ramp
637/// signal feeding into some *other* block, not itself a gate transition a downstream comparator
638/// could silently swallow the way a missed `Pwm`/`PhaseShiftPwm` edge is. Out of scope for this
639/// feature.
640///
641/// `kind=octblock` stays out of scope for `TimeStep::Adaptive` entirely (see
642/// [`simulate_transient_with_blocks`]'s own upfront rejection) -- this function still computes an
643/// estimate for it (reusing the same `sample_threshold`/`time_until_due` helpers CScript/PyBlock
644/// use) for whenever that separate restriction is eventually lifted, but it is unreachable in
645/// practice today.
646fn earliest_next_event_dt(
647 blocks: &[BlockInstance],
648 block_states: &[BlockState],
649 prev_outputs: &BTreeMap<String, SignalValue>,
650 t: f64,
651) -> Option<f64> {
652 blocks
653 .iter()
654 .zip(block_states.iter())
655 .filter_map(|(block, state)| match (&block.kind, state) {
656 (
657 BlockKind::Pwm {
658 freq_hz, red, fed, ..
659 },
660 _,
661 ) => {
662 let theta_now = sawtooth_carrier(t, *freq_hz);
663 let duty = resolve_prev_scalar(prev_outputs, block.inputs.first()?)?;
664 next_pwm_edge_dt(theta_now, duty, red * freq_hz, fed * freq_hz, *freq_hz)
665 }
666 (
667 BlockKind::PhaseShiftPwm { red, fed, .. },
668 BlockState::PhaseShiftPwm { osc, phase },
669 ) => {
670 let freq_command = resolve_prev_scalar(prev_outputs, block.inputs.first()?)?;
671 let phase_offset = resolve_prev_scalar(prev_outputs, block.inputs.get(1)?)?;
672 let duty = resolve_prev_scalar(prev_outputs, block.inputs.get(2)?)?;
673 let actual_freq = freq_command.clamp(osc.f_min, osc.f_max);
674 let theta_now = (*phase + phase_offset).rem_euclid(1.0);
675 next_pwm_edge_dt(
676 theta_now,
677 duty,
678 red * actual_freq,
679 fed * actual_freq,
680 actual_freq,
681 )
682 }
683 // BlockKind::Vco: deliberately excluded, see this function's own doc comment.
684 (
685 BlockKind::CScript { sample_time, .. },
686 BlockState::CScript {
687 time_since_sample,
688 next_hit_dt,
689 ..
690 },
691 ) => time_until_due(
692 sample_threshold(sample_time.as_ref(), *next_hit_dt),
693 *time_since_sample,
694 ),
695 #[cfg(feature = "python")]
696 (
697 BlockKind::PyBlock { sample_time, .. },
698 BlockState::PyBlock {
699 time_since_sample,
700 next_hit_dt,
701 ..
702 },
703 ) => time_until_due(
704 sample_threshold(sample_time.as_ref(), *next_hit_dt),
705 *time_since_sample,
706 ),
707 #[cfg(feature = "python")]
708 (
709 BlockKind::PyFunction { sample_time, .. },
710 BlockState::PyFunction {
711 time_since_sample, ..
712 },
713 ) => match sample_time {
714 None | Some(SampleTimeSpec::Variable) => None,
715 Some(SampleTimeSpec::Periodic { period, .. }) => {
716 Some((period - time_since_sample).max(0.0))
717 }
718 },
719 (
720 BlockKind::OctFunc { sample_time, .. },
721 BlockState::OctFunction {
722 time_since_sample, ..
723 },
724 ) => match sample_time {
725 None | Some(SampleTimeSpec::Variable) => None,
726 Some(SampleTimeSpec::Periodic { period, .. }) => {
727 Some((period - time_since_sample).max(0.0))
728 }
729 },
730 (
731 BlockKind::OctBlock { sample_time, .. },
732 BlockState::OctBlock {
733 time_since_sample,
734 next_hit_dt,
735 ..
736 },
737 ) => time_until_due(
738 sample_threshold(sample_time.as_ref(), *next_hit_dt),
739 *time_since_sample,
740 ),
741 (
742 BlockKind::DiscreteStateSpace { sample_time, .. }
743 | BlockKind::DiscreteTransferFunction { sample_time, .. },
744 BlockState::DiscreteDynamic {
745 time_since_sample, ..
746 },
747 ) => match sample_time {
748 SampleTimeSpec::Periodic { period, .. } => {
749 Some((period - time_since_sample).max(0.0))
750 }
751 SampleTimeSpec::Variable => None, // rejected at parse time for this kind
752 },
753 (
754 BlockKind::DiscretePid { sample_time, .. },
755 BlockState::DiscretePid {
756 time_since_sample, ..
757 },
758 ) => match sample_time {
759 SampleTimeSpec::Periodic { period, .. } => {
760 Some((period - time_since_sample).max(0.0))
761 }
762 SampleTimeSpec::Variable => None, // rejected at parse time for this kind
763 },
764 _ => None,
765 })
766 .fold(None, |acc, dt| match acc {
767 None => Some(dt),
768 Some(best) => Some(best.min(dt)),
769 })
770}
771
772fn evaluate_blocks(
773 blocks: &[BlockInstance],
774 order: &[usize],
775 block_states: &mut [BlockState],
776 point_prev: &OperatingPoint,
777 prev_outputs: &BTreeMap<String, SignalValue>,
778 t: f64,
779 dt: f64,
780) -> Result<BTreeMap<String, SignalValue>, DaeError> {
781 let mut outputs: BTreeMap<String, SignalValue> = BTreeMap::new();
782 let resolve = |outputs: &BTreeMap<String, SignalValue>,
783 signal: &Signal|
784 -> Result<SignalValue, DaeError> {
785 match signal {
786 Signal::Block(name) => outputs
787 .get(name)
788 .cloned()
789 .ok_or_else(|| DaeError::UnknownBlockInput(name.clone())),
790 Signal::BlockPrev(name) => Ok(prev_outputs
791 .get(name)
792 .cloned()
793 .unwrap_or(SignalValue::Scalar(0.0))),
794 }
795 };
796
797 for &i in order {
798 let block = &blocks[i];
799 let state = &mut block_states[i];
800 let input_vals: Vec<SignalValue> = block
801 .inputs
802 .iter()
803 .map(|s| resolve(&outputs, s))
804 .collect::<Result<_, _>>()?;
805
806 let value: SignalValue = match (&block.kind, state) {
807 (BlockKind::Const(v), _) => match v {
808 ConstValue::Scalar(x) => SignalValue::Scalar(*x),
809 ConstValue::Vector(xs) => SignalValue::Vector(xs.clone()),
810 },
811 (BlockKind::Time, _) => SignalValue::Scalar(t),
812 (BlockKind::Phys2Sig(target), _) => SignalValue::Scalar(match target {
813 Phys2SigTarget::Voltage(node) => {
814 point_prev.value(&format!("V({node})")).unwrap_or(0.0)
815 }
816 Phys2SigTarget::Current(branch) => {
817 point_prev.value(&format!("I({branch})")).unwrap_or(0.0)
818 }
819 }),
820 (BlockKind::Sig2Phys { .. }, _) => {
821 SignalValue::Scalar(require_all_scalar(&block.name, &input_vals)?[0])
822 }
823 (BlockKind::Pwc { points, repeat }, _) => {
824 let t_eval = periodic_time(t, points, *repeat);
825 let mut v = points.first().map(|(_, v)| *v).unwrap_or(0.0);
826 for &(t_i, v_i) in points {
827 if t_i <= t_eval {
828 v = v_i;
829 } else {
830 break;
831 }
832 }
833 SignalValue::Scalar(v)
834 }
835 (BlockKind::Pwl { points, repeat }, _) => {
836 let t_eval = periodic_time(t, points, *repeat);
837 SignalValue::Scalar(match points.as_slice() {
838 [] => 0.0,
839 [(_, v)] => *v,
840 _ if t_eval <= points[0].0 => points[0].1,
841 _ if t_eval >= points[points.len() - 1].0 => points[points.len() - 1].1,
842 _ => {
843 let mut v = points[points.len() - 1].1;
844 for window in points.windows(2) {
845 let (t0, v0) = window[0];
846 let (t1, v1) = window[1];
847 if t_eval >= t0 && t_eval <= t1 {
848 v = if (t1 - t0).abs() < f64::EPSILON {
849 v1
850 } else {
851 v0 + (v1 - v0) * ((t_eval - t0) / (t1 - t0))
852 };
853 break;
854 }
855 }
856 v
857 }
858 })
859 }
860 (BlockKind::Waveform(f), _) => SignalValue::Scalar(f.value_at(t)),
861 (BlockKind::Sum(signs), _) => {
862 if input_vals
863 .iter()
864 .all(|v| matches!(v, SignalValue::Scalar(_)))
865 {
866 let scalars = require_all_scalar(&block.name, &input_vals)?;
867 SignalValue::Scalar(math_ops::sum(&scalars, signs))
868 } else {
869 let n = require_uniform_vectors(&block.name, &input_vals)?;
870 let out: Vec<f64> = (0..n)
871 .map(|i| {
872 let elems: Vec<f64> =
873 input_vals.iter().map(|v| broadcast_at(v, i)).collect();
874 math_ops::sum(&elems, signs)
875 })
876 .collect();
877 SignalValue::Vector(out)
878 }
879 }
880 (BlockKind::Gain(k), _) => match k {
881 GainValue::Scalar(k) => match &input_vals[0] {
882 SignalValue::Scalar(x) => SignalValue::Scalar(math_ops::gain(*k, *x)),
883 SignalValue::Vector(xs) => {
884 SignalValue::Vector(xs.iter().map(|&x| math_ops::gain(*k, x)).collect())
885 }
886 },
887 GainValue::Matrix(mat) => {
888 let n = mat.first().map_or(0, |row| row.len());
889 let SignalValue::Vector(x) = &input_vals[0] else {
890 return Err(DaeError::VectorSignalNotSupported {
891 block: block.name.clone(),
892 });
893 };
894 if x.len() != n {
895 return Err(DaeError::VectorSignalSizeMismatch {
896 block: block.name.clone(),
897 expected: n,
898 got: x.len(),
899 });
900 }
901 let y: Vec<f64> = mat
902 .iter()
903 .map(|row| row.iter().zip(x).map(|(a, b)| a * b).sum())
904 .collect();
905 SignalValue::Vector(y)
906 }
907 },
908 (BlockKind::Product, _) => {
909 if input_vals
910 .iter()
911 .all(|v| matches!(v, SignalValue::Scalar(_)))
912 {
913 let scalars = require_all_scalar(&block.name, &input_vals)?;
914 SignalValue::Scalar(math_ops::product(&scalars))
915 } else {
916 let n = require_uniform_vectors(&block.name, &input_vals)?;
917 let out: Vec<f64> = (0..n)
918 .map(|i| {
919 let elems: Vec<f64> =
920 input_vals.iter().map(|v| broadcast_at(v, i)).collect();
921 math_ops::product(&elems)
922 })
923 .collect();
924 SignalValue::Vector(out)
925 }
926 }
927 (
928 BlockKind::Pwm {
929 freq_hz,
930 red,
931 fed,
932 output_names,
933 },
934 _,
935 ) => {
936 let theta = sawtooth_carrier(t, *freq_hz);
937 let duty = require_all_scalar(&block.name, &input_vals)?[0];
938 let (main, complement) = math_ops::complementary_pwm_with_deadtime(
939 theta,
940 duty,
941 red * freq_hz,
942 fed * freq_hz,
943 );
944 SignalValue::Scalar(emit_complementary_pair(
945 &mut outputs,
946 output_names,
947 main,
948 complement,
949 ))
950 }
951 (BlockKind::Saturation(limit), _) => match &input_vals[0] {
952 SignalValue::Scalar(x) => SignalValue::Scalar(math_ops::saturation(*x, *limit)),
953 SignalValue::Vector(xs) => SignalValue::Vector(
954 xs.iter()
955 .map(|&x| math_ops::saturation(x, *limit))
956 .collect(),
957 ),
958 },
959 (BlockKind::Table(points), _) => match &input_vals[0] {
960 SignalValue::Scalar(x) => {
961 SignalValue::Scalar(continuous_blocks::waveform_arithmetic::table(*x, points))
962 }
963 SignalValue::Vector(xs) => SignalValue::Vector(
964 xs.iter()
965 .map(|&x| continuous_blocks::waveform_arithmetic::table(x, points))
966 .collect(),
967 ),
968 },
969 (BlockKind::MathFn1(f), _) => match &input_vals[0] {
970 SignalValue::Scalar(x) => SignalValue::Scalar(f.call(*x)),
971 SignalValue::Vector(xs) => {
972 SignalValue::Vector(xs.iter().map(|&x| f.call(x)).collect())
973 }
974 },
975 (BlockKind::MathFn2(f), _) => {
976 match common_vector_len(&block.name, &[&input_vals[0], &input_vals[1]])? {
977 None => SignalValue::Scalar(f.call(
978 input_vals[0].as_scalar().expect("checked Scalar above"),
979 input_vals[1].as_scalar().expect("checked Scalar above"),
980 )),
981 Some(n) => SignalValue::Vector(
982 (0..n)
983 .map(|i| {
984 f.call(
985 broadcast_at(&input_vals[0], i),
986 broadcast_at(&input_vals[1], i),
987 )
988 })
989 .collect(),
990 ),
991 }
992 }
993 (BlockKind::MathFn3(f), _) => {
994 match common_vector_len(
995 &block.name,
996 &[&input_vals[0], &input_vals[1], &input_vals[2]],
997 )? {
998 None => SignalValue::Scalar(f.call(
999 input_vals[0].as_scalar().expect("checked Scalar above"),
1000 input_vals[1].as_scalar().expect("checked Scalar above"),
1001 input_vals[2].as_scalar().expect("checked Scalar above"),
1002 )),
1003 Some(n) => SignalValue::Vector(
1004 (0..n)
1005 .map(|i| {
1006 f.call(
1007 broadcast_at(&input_vals[0], i),
1008 broadcast_at(&input_vals[1], i),
1009 broadcast_at(&input_vals[2], i),
1010 )
1011 })
1012 .collect(),
1013 ),
1014 }
1015 }
1016 (BlockKind::CoordinateTransform { kind, output_names }, _) => {
1017 let flat = flatten(&input_vals);
1018 let outs = kind.call(&flat);
1019 // Same convention as BlockKind::CScript below: the block's own name is bound to
1020 // the primary (first) output, any remaining output_names are inserted directly
1021 // under their own names. Output side stays scalar-only by design -- see
1022 // book/dev-guide/src/vector-signals.md, category 9.
1023 for (name, v) in output_names.iter().zip(outs.iter()).skip(1) {
1024 outputs.insert(name.clone(), SignalValue::Scalar(*v));
1025 }
1026 SignalValue::Scalar(outs[0])
1027 }
1028 (BlockKind::Pid { clamp, .. }, BlockState::Dynamic { state_space, x }) => {
1029 let scalars = require_all_scalar(&block.name, &input_vals)?;
1030 let (lo, hi) = match clamp {
1031 PidClamp::Fixed(lo, hi) => (*lo, *hi),
1032 PidClamp::Dynamic => (scalars[1], scalars[2]),
1033 };
1034 let error = [scalars[0]];
1035 let tentative_x = state_space.rk4_step(x, &error, dt);
1036 let tentative_output = state_space.output(&tentative_x, &error)[0];
1037 let saturating_further = (tentative_output >= hi && error[0] > 0.0)
1038 || (tentative_output <= lo && error[0] < 0.0);
1039 SignalValue::Scalar(if saturating_further {
1040 state_space.output(x, &error)[0].clamp(lo, hi)
1041 } else {
1042 *x = tentative_x;
1043 tentative_output
1044 })
1045 }
1046 (BlockKind::TransferFunction(_), BlockState::Dynamic { state_space, x }) => {
1047 // Genuinely SISO by definition -- a rational N(s)/D(s) has no matrix
1048 // generalization the way StateSpace's own (A,B,C,D) does. Reject a Vector input
1049 // the same way Pid/Vco/Hysteresis do, rather than silently flattening.
1050 let u = require_all_scalar(&block.name, &input_vals)?;
1051 *x = state_space.rk4_step(x, &u, dt);
1052 SignalValue::Scalar(state_space.output(x, &u)[0])
1053 }
1054 (BlockKind::StateSpace(_), BlockState::Dynamic { state_space, x }) => {
1055 // Genuinely MIMO: state_space.inputs()/outputs() are not constrained to 1 --
1056 // see BlockKind::StateSpace's own doc comment. Inputs flatten the same way
1057 // CoordinateTransform/Pmsm/cscript's do; the *total* flattened length must
1058 // match this system's own declared input count exactly (a mismatch can only be
1059 // known here, not at parse time, since a vector-valued upstream signal's own
1060 // length isn't visible from netlist text alone).
1061 let u = flatten(&input_vals);
1062 let expected = state_space.inputs();
1063 if u.len() != expected {
1064 return Err(DaeError::VectorSignalSizeMismatch {
1065 block: block.name.clone(),
1066 expected,
1067 got: u.len(),
1068 });
1069 }
1070 *x = state_space.rk4_step(x, &u, dt);
1071 let y = state_space.output(x, &u);
1072 if y.len() == 1 {
1073 SignalValue::Scalar(y[0])
1074 } else {
1075 SignalValue::Vector(y)
1076 }
1077 }
1078 (
1079 BlockKind::DiscreteStateSpace { sample_time, .. },
1080 BlockState::DiscreteDynamic {
1081 state_space,
1082 x,
1083 time_since_sample,
1084 last_output,
1085 },
1086 ) => {
1087 // Genuinely MIMO, same flattening rule as BlockKind::StateSpace's own continuous
1088 // arm above -- but a discrete system's own output is only defined at its own
1089 // sample instants (see BlockKind::CScript's zero-order-hold gating, reused
1090 // unchanged here): `last_output` is held on every step this block isn't due.
1091 let period = match sample_time {
1092 SampleTimeSpec::Periodic { period, .. } => *period,
1093 SampleTimeSpec::Variable => unreachable!(
1094 "general-mna's parse_required_periodic_sample_time already rejected \
1095 ts=variable for kind=discretestatespace"
1096 ),
1097 };
1098 *time_since_sample += dt;
1099 if *time_since_sample + 1e-15 >= period {
1100 *time_since_sample = 0.0;
1101 let u = flatten(&input_vals);
1102 let expected = state_space.inputs();
1103 if u.len() != expected {
1104 return Err(DaeError::VectorSignalSizeMismatch {
1105 block: block.name.clone(),
1106 expected,
1107 got: u.len(),
1108 });
1109 }
1110 *x = state_space.discrete_step(x, &u);
1111 *last_output = state_space.output(x, &u);
1112 }
1113 if last_output.len() == 1 {
1114 SignalValue::Scalar(last_output[0])
1115 } else {
1116 SignalValue::Vector(last_output.clone())
1117 }
1118 }
1119 (
1120 BlockKind::DiscreteTransferFunction { sample_time, .. },
1121 BlockState::DiscreteDynamic {
1122 state_space,
1123 x,
1124 time_since_sample,
1125 last_output,
1126 },
1127 ) => {
1128 // Genuinely SISO, same rejection of a Vector input as the continuous
1129 // BlockKind::TransferFunction arm above.
1130 let period = match sample_time {
1131 SampleTimeSpec::Periodic { period, .. } => *period,
1132 SampleTimeSpec::Variable => unreachable!(
1133 "general-mna's parse_required_periodic_sample_time already rejected \
1134 ts=variable for kind=discretetf"
1135 ),
1136 };
1137 *time_since_sample += dt;
1138 if *time_since_sample + 1e-15 >= period {
1139 *time_since_sample = 0.0;
1140 let u = require_all_scalar(&block.name, &input_vals)?;
1141 *x = state_space.discrete_step(x, &u);
1142 *last_output = state_space.output(x, &u);
1143 }
1144 SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
1145 }
1146 (
1147 BlockKind::DiscretePid {
1148 pid,
1149 clamp,
1150 sample_time,
1151 },
1152 BlockState::DiscretePid {
1153 state,
1154 time_since_sample,
1155 last_output,
1156 },
1157 ) => {
1158 let period = match sample_time {
1159 SampleTimeSpec::Periodic { period, .. } => *period,
1160 SampleTimeSpec::Variable => unreachable!(
1161 "general-mna's parse_required_periodic_sample_time already rejected \
1162 ts=variable for kind=discretepid"
1163 ),
1164 };
1165 let scalars = require_all_scalar(&block.name, &input_vals)?;
1166 let (lo, hi) = match clamp {
1167 PidClamp::Fixed(lo, hi) => (*lo, *hi),
1168 PidClamp::Dynamic => (scalars[1], scalars[2]),
1169 };
1170 let error = scalars[0];
1171 *time_since_sample += dt;
1172 if *time_since_sample + 1e-15 >= period {
1173 *time_since_sample = 0.0;
1174 // Same tentative-step/reject anti-windup as BlockKind::Pid's own continuous
1175 // arm above, adapted to a discrete recursion: step a *copy* of the state,
1176 // and only commit it if doing so wouldn't push the output further past
1177 // whichever bound it's already saturating against -- the discrete
1178 // counterpart to "don't integrate the error further while already clamped."
1179 let mut tentative_state = *state;
1180 let tentative_output = pid.step(&mut tentative_state, error);
1181 let saturating_further = (tentative_output >= hi && error > 0.0)
1182 || (tentative_output <= lo && error < 0.0);
1183 *last_output = if saturating_further {
1184 tentative_output.clamp(lo, hi)
1185 } else {
1186 *state = tentative_state;
1187 tentative_output
1188 };
1189 }
1190 SignalValue::Scalar(*last_output)
1191 }
1192 (BlockKind::Vco(_), BlockState::Vco { vco, phase }) => {
1193 let u = require_all_scalar(&block.name, &input_vals)?;
1194 *phase = vco.step(*phase, u[0], dt);
1195 SignalValue::Scalar(*phase)
1196 }
1197 (
1198 BlockKind::PhaseShiftPwm {
1199 red,
1200 fed,
1201 output_names,
1202 ..
1203 },
1204 BlockState::PhaseShiftPwm { osc, phase },
1205 ) => {
1206 let u = require_all_scalar(&block.name, &input_vals)?;
1207 let freq_command = u[0];
1208 let phase_offset = u[1];
1209 let duty = u[2];
1210 *phase = osc.step(*phase, freq_command, dt);
1211 let actual_freq = freq_command.clamp(osc.f_min, osc.f_max);
1212 let theta = (*phase + phase_offset).rem_euclid(1.0);
1213 let (main, complement) = math_ops::complementary_pwm_with_deadtime(
1214 theta,
1215 duty,
1216 red * actual_freq,
1217 fed * actual_freq,
1218 );
1219 SignalValue::Scalar(emit_complementary_pair(
1220 &mut outputs,
1221 output_names,
1222 main,
1223 complement,
1224 ))
1225 }
1226 (BlockKind::Pmsm { output_names, .. }, BlockState::Pmsm { pmsm, x }) => {
1227 let flat = flatten(&input_vals);
1228 *x = pmsm.step(*x, flat[0], flat[1], flat[2], dt);
1229 let [id, iq, omega_m, theta_e] = *x;
1230 let full = [id, iq, omega_m, Pmsm::theta_e_wrapped(theta_e)];
1231 for (name, v) in output_names.iter().zip(full.iter()).skip(1) {
1232 outputs.insert(name.clone(), SignalValue::Scalar(*v));
1233 }
1234 SignalValue::Scalar(full[0])
1235 }
1236 (BlockKind::Hysteresis(_), BlockState::Hysteresis { hysteresis, on }) => {
1237 let u = require_all_scalar(&block.name, &input_vals)?;
1238 *on = hysteresis.step(*on, u[0]);
1239 SignalValue::Scalar(if *on { 1.0 } else { 0.0 })
1240 }
1241 (BlockKind::LogicGate(op), _) => {
1242 // Purely combinational -- no BlockState variant at all (matches `_` above,
1243 // same as Sum/Gain), recomputed fresh from this step's own inputs every time.
1244 let u = require_all_scalar(&block.name, &input_vals)?;
1245 let bits: Vec<bool> = u.iter().map(|&x| as_bool(x)).collect();
1246 SignalValue::Scalar(from_bool(op.call(&bits)))
1247 }
1248 (BlockKind::SrLatch { priority }, BlockState::SrLatch { q }) => {
1249 let u = require_all_scalar(&block.name, &input_vals)?;
1250 let (set, reset) = (as_bool(u[0]), as_bool(u[1]));
1251 *q = srlatch_next(*q, set, reset, *priority);
1252 SignalValue::Scalar(from_bool(*q))
1253 }
1254 (BlockKind::FlipFlop { kind, .. }, BlockState::FlipFlop { q, prev_clk }) => {
1255 let u = require_all_scalar(&block.name, &input_vals)?;
1256 let clk = u[0];
1257 // Input order, fixed by system_builder.rs's own parsing: [clk, data_inputs...,
1258 // reset?] -- `kind.input_count()` data inputs right after clk, an optional
1259 // trailing reset beyond that (present iff `u.len()` has one more entry than
1260 // `1 + kind.input_count()` accounts for).
1261 let data = &u[1..1 + kind.input_count()];
1262 let reset_asserted = u.get(1 + kind.input_count()).is_some_and(|&r| as_bool(r));
1263 if rising_edge(clk, *prev_clk) {
1264 let bits: Vec<bool> = data.iter().map(|&x| as_bool(x)).collect();
1265 *q = if reset_asserted {
1266 false
1267 } else {
1268 kind.next_state(*q, &bits)
1269 };
1270 }
1271 *prev_clk = clk;
1272 SignalValue::Scalar(from_bool(*q))
1273 }
1274 (
1275 BlockKind::Counter {
1276 up_down, modulus, ..
1277 },
1278 BlockState::Counter { count, prev_clk },
1279 ) => {
1280 let u = require_all_scalar(&block.name, &input_vals)?;
1281 let clk = u[0];
1282 // Same fixed input order system_builder.rs's own "counter" arm builds:
1283 // [clk, up_down?, reset?] -- both optional, in that order when both present.
1284 let mut idx = 1;
1285 let up_down_asserted = if *up_down {
1286 let v = as_bool(u[idx]);
1287 idx += 1;
1288 v
1289 } else {
1290 true // no up_down= wired: always increments
1291 };
1292 let reset_asserted = u.get(idx).is_some_and(|&r| as_bool(r));
1293 if rising_edge(clk, *prev_clk) {
1294 if reset_asserted {
1295 *count = 0;
1296 } else if up_down_asserted {
1297 *count += 1;
1298 } else {
1299 *count -= 1;
1300 }
1301 if let Some(m) = modulus {
1302 *count = count.rem_euclid(*m as i64);
1303 }
1304 }
1305 *prev_clk = clk;
1306 SignalValue::Scalar(*count as f64)
1307 }
1308 (
1309 BlockKind::CScript {
1310 output_names,
1311 sample_time,
1312 xc_count,
1313 ..
1314 },
1315 BlockState::CScript {
1316 instance,
1317 time_since_sample,
1318 next_hit_dt,
1319 last_output,
1320 xc,
1321 },
1322 ) => {
1323 // sample_time = None: run every step, exactly like every other dynamic block.
1324 // sample_time = Some(Periodic{period,offset}): accumulate circuit dt until the
1325 // current threshold is reached, then run once with the *accumulated* elapsed
1326 // time as this call's dt (not the much finer circuit dt), and hold the result
1327 // (zero-order hold) on every step in between -- see BlockKind::CScript's own
1328 // doc comment for why. sample_time = Some(Variable): identical accumulator
1329 // mechanics, but the threshold itself (`next_hit_dt`) is whatever the block's
1330 // own cscript_next_sample_hit last returned, instead of a fixed `period`. This
1331 // same "due" gating governs xc's own RK4 step too: a block that wants xc to
1332 // integrate continuously every circuit step should simply leave sample_time
1333 // unset, the same way any other continuously-evaluated block already works here
1334 // -- xc never advances on a step this block isn't "due" on, exactly like
1335 // last_output is held rather than recomputed on those steps.
1336 let threshold = sample_threshold(sample_time.as_ref(), *next_hit_dt);
1337 let (due, elapsed) = match threshold {
1338 None => (true, dt),
1339 Some(threshold) => {
1340 *time_since_sample += dt;
1341 if *time_since_sample + 1e-15 >= threshold {
1342 let elapsed = *time_since_sample;
1343 *time_since_sample = 0.0;
1344 (true, elapsed)
1345 } else {
1346 (false, 0.0)
1347 }
1348 }
1349 };
1350 if due {
1351 // Flattened the same way StateSpace/CoordinateTransform/Pmsm's inputs are --
1352 // each declared `inputs=` entry independently scalar or vector, concatenated
1353 // in order into the flat array cscript_output/cscript_output_xc/
1354 // cscript_derivative already expect. No C ABI change needed for this.
1355 let flat = flatten(&input_vals);
1356 *last_output = if *xc_count > 0 {
1357 // Step xc first, then compute output from the *new* xc -- the same
1358 // "step state, then compute output from the updated state" ordering
1359 // BlockKind::StateSpace/TransferFunction's own arm above uses.
1360 *xc = instance.rk4_step_xc(xc, &flat, elapsed);
1361 instance.call_xc(&flat, elapsed, xc, output_names.len())
1362 } else {
1363 instance.call(&flat, elapsed, output_names.len())
1364 };
1365 // Optional, always a no-op if cscript_update wasn't exported -- the
1366 // dedicated place `state`'s own discrete bookkeeping commits forward to the
1367 // next step, called with this same step's already-integrated xc (empty when
1368 // xc_count == 0). See cscript_ffi's own module doc comment, "The optional
1369 // discrete-state update function."
1370 instance.update(&flat, elapsed, xc);
1371 if matches!(sample_time, Some(SampleTimeSpec::Variable)) {
1372 *next_hit_dt = instance.next_sample_hit(&flat, xc);
1373 }
1374 }
1375 // The primary value (this block's own name) is last_output[0], inserted below
1376 // like every other block; any additional declared output_names are inserted
1377 // here under their own names, so a downstream block can reference them
1378 // directly via Signal::Block(name) without needing to know they came from a
1379 // CScript block. Output side stays scalar-only by design (same as
1380 // CoordinateTransform/Pmsm above) -- see book/dev-guide/src/vector-signals.md,
1381 // category 10.
1382 for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
1383 outputs.insert(name.clone(), SignalValue::Scalar(*v));
1384 }
1385 SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
1386 }
1387 #[cfg(feature = "python")]
1388 (
1389 BlockKind::PyBlock {
1390 output_names,
1391 sample_time,
1392 xc_count,
1393 ..
1394 },
1395 BlockState::PyBlock {
1396 instance,
1397 time_since_sample,
1398 next_hit_dt,
1399 last_output,
1400 xc,
1401 },
1402 ) => {
1403 // Identical sample_time/xc gating to BlockKind::CScript's own arm above -- see
1404 // its own comment for the full rationale, unchanged here.
1405 let threshold = sample_threshold(sample_time.as_ref(), *next_hit_dt);
1406 let (due, elapsed) = match threshold {
1407 None => (true, dt),
1408 Some(threshold) => {
1409 *time_since_sample += dt;
1410 if *time_since_sample + 1e-15 >= threshold {
1411 let elapsed = *time_since_sample;
1412 *time_since_sample = 0.0;
1413 (true, elapsed)
1414 } else {
1415 (false, 0.0)
1416 }
1417 }
1418 };
1419 if due {
1420 // Unlike CScript's own flat C array, each declared input keeps its own
1421 // scalar/vector shape here -- Python can express "a list of values, each
1422 // either a float or an ndarray" naturally, so there's no need to flatten
1423 // (see pyblock_ffi's own module doc comment).
1424 let py_inputs: Vec<pyblock_ffi::PyInput> = input_vals
1425 .iter()
1426 .map(|v| match v {
1427 SignalValue::Scalar(x) => pyblock_ffi::PyInput::Scalar(*x),
1428 SignalValue::Vector(xs) => pyblock_ffi::PyInput::Vector(xs),
1429 })
1430 .collect();
1431 *last_output = if *xc_count > 0 {
1432 *xc = instance
1433 .rk4_step_xc(xc, t, &py_inputs, elapsed)
1434 .map_err(DaeError::PyBlock)?;
1435 instance
1436 .call_xc(t, elapsed, &py_inputs, xc, output_names.len())
1437 .map_err(DaeError::PyBlock)?
1438 } else {
1439 instance
1440 .call(t, elapsed, &py_inputs, output_names.len())
1441 .map_err(DaeError::PyBlock)?
1442 };
1443 // Optional, always a no-op if update() wasn't defined -- see cscript's own
1444 // arm above and pyblock_ffi's module doc comment, "The optional
1445 // discrete-state update function."
1446 if *xc_count > 0 {
1447 instance
1448 .update_xc(t, elapsed, &py_inputs, xc)
1449 .map_err(DaeError::PyBlock)?;
1450 } else {
1451 instance
1452 .update(t, elapsed, &py_inputs)
1453 .map_err(DaeError::PyBlock)?;
1454 }
1455 if matches!(sample_time, Some(SampleTimeSpec::Variable)) {
1456 *next_hit_dt = if *xc_count > 0 {
1457 instance
1458 .next_sample_hit_xc(t, elapsed, &py_inputs, xc)
1459 .map_err(DaeError::PyBlock)?
1460 } else {
1461 instance
1462 .next_sample_hit(t, elapsed, &py_inputs)
1463 .map_err(DaeError::PyBlock)?
1464 };
1465 }
1466 }
1467 for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
1468 outputs.insert(name.clone(), SignalValue::Scalar(*v));
1469 }
1470 SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
1471 }
1472 #[cfg(feature = "python")]
1473 (
1474 BlockKind::PyFunction {
1475 output_names,
1476 sample_time,
1477 ..
1478 },
1479 BlockState::PyFunction {
1480 instance,
1481 time_since_sample,
1482 last_output,
1483 },
1484 ) => {
1485 // Same sample_time gating as every other zero-order-hold block, just for *when*
1486 // this block is due -- unlike every other gated block, the elapsed time itself
1487 // is discarded: PyFunctionInstance::call has no dt parameter at all (a pure
1488 // function has no notion of elapsed time to hand it), so only `due` matters here.
1489 let due = match sample_time {
1490 None => true,
1491 // Variable is unreachable here -- rejected at parse time for PyFunction.
1492 Some(SampleTimeSpec::Variable) => true,
1493 Some(SampleTimeSpec::Periodic { period, .. }) => {
1494 *time_since_sample += dt;
1495 if *time_since_sample + 1e-15 >= *period {
1496 *time_since_sample = 0.0;
1497 true
1498 } else {
1499 false
1500 }
1501 }
1502 };
1503 if due {
1504 let py_inputs: Vec<pyblock_ffi::PyInput> = input_vals
1505 .iter()
1506 .map(|v| match v {
1507 SignalValue::Scalar(x) => pyblock_ffi::PyInput::Scalar(*x),
1508 SignalValue::Vector(xs) => pyblock_ffi::PyInput::Vector(xs),
1509 })
1510 .collect();
1511 *last_output = instance
1512 .call(&py_inputs, output_names.len())
1513 .map_err(DaeError::PyBlock)?;
1514 }
1515 for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
1516 outputs.insert(name.clone(), SignalValue::Scalar(*v));
1517 }
1518 SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
1519 }
1520 (
1521 BlockKind::OctFunc {
1522 output_names,
1523 sample_time,
1524 function,
1525 ..
1526 },
1527 BlockState::OctFunction {
1528 session,
1529 time_since_sample,
1530 last_output,
1531 ..
1532 },
1533 ) => {
1534 // Identical zero-order-hold "due" gating to PyFunction's own arm above -- see
1535 // its own comment for the full rationale. Same discard-elapsed-time rule too:
1536 // OctaveSession::call has no dt parameter, a pure function has no notion of
1537 // elapsed time to hand it.
1538 let due = match sample_time {
1539 None => true,
1540 // Variable is unreachable here -- rejected at parse time for OctFunc.
1541 Some(SampleTimeSpec::Variable) => true,
1542 Some(SampleTimeSpec::Periodic { period, .. }) => {
1543 *time_since_sample += dt;
1544 if *time_since_sample + 1e-15 >= *period {
1545 *time_since_sample = 0.0;
1546 true
1547 } else {
1548 false
1549 }
1550 }
1551 };
1552 if due {
1553 // Unlike PyFunction (which keeps each declared input's own scalar/vector
1554 // shape, via numpy), octave_ffi::OctaveSession::call takes a flat &[f64] of
1555 // literal scalar arguments -- there is no vector-input support for octfunc
1556 // (matching this crate's own scalar-only-outputs restriction, and the
1557 // literal-numeric-argument protocol octave_ffi's own module doc comment
1558 // documents), so every declared input must itself be a Scalar.
1559 let flat_inputs = require_all_scalar(&block.name, &input_vals)?;
1560 *last_output = session
1561 .borrow_mut()
1562 .call(function, &flat_inputs, output_names.len())
1563 .map_err(DaeError::Octave)?;
1564 }
1565 for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
1566 outputs.insert(name.clone(), SignalValue::Scalar(*v));
1567 }
1568 SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
1569 }
1570 (
1571 BlockKind::OctBlock {
1572 output_names,
1573 sample_time,
1574 xc_count,
1575 function,
1576 ..
1577 },
1578 BlockState::OctBlock {
1579 session,
1580 instance,
1581 time_since_sample,
1582 next_hit_dt,
1583 last_output,
1584 xc,
1585 has_update,
1586 },
1587 ) => {
1588 // Identical sample_time/xc "due" gating to CScript's/PyBlock's own arms above --
1589 // unlike OctFunc/PyFunction (stateless, elapsed time discarded), this block's
1590 // own contract functions take `t`/`dt` explicitly (see BlockKind::OctBlock's own
1591 // file-per-function table), so the accumulated `elapsed` matters here.
1592 let threshold = sample_threshold(sample_time.as_ref(), *next_hit_dt);
1593 let (due, elapsed) = match threshold {
1594 None => (true, dt),
1595 Some(threshold) => {
1596 *time_since_sample += dt;
1597 if *time_since_sample + 1e-15 >= threshold {
1598 let elapsed = *time_since_sample;
1599 *time_since_sample = 0.0;
1600 (true, elapsed)
1601 } else {
1602 (false, 0.0)
1603 }
1604 }
1605 };
1606 if due {
1607 // No vector-input support -- same scalar-only restriction OctFunc already
1608 // has (see octave_ffi's own literal-numeric-argument protocol).
1609 let flat_inputs = require_all_scalar(&block.name, &input_vals)?;
1610 // `args` is [t, dt, u0, u1, ...] -- the exact positional shape every
1611 // t/dt-taking contract function expects after its own leading `state`.
1612 let mut args = Vec::with_capacity(2 + flat_inputs.len());
1613 args.push(t);
1614 args.push(elapsed);
1615 args.extend_from_slice(&flat_inputs);
1616
1617 *last_output = if *xc_count > 0 {
1618 // Step xc first (RK4, via <function>_derivative -- pure, never touches
1619 // this instance's own opaque state slot), then compute output from the
1620 // *new* xc -- same "step state, then compute output from the updated
1621 // state" ordering CScript's/PyBlock's own xc arms use. Derivative's own
1622 // args exclude t/dt (see the file-per-function table).
1623 *xc = session
1624 .borrow_mut()
1625 .rk4_step_xc_stateful(
1626 &format!("{function}_derivative"),
1627 instance,
1628 xc,
1629 &flat_inputs,
1630 elapsed,
1631 )
1632 .map_err(DaeError::Octave)?;
1633 session
1634 .borrow_mut()
1635 .call_stateful(
1636 &format!("{function}_output_xc"),
1637 instance,
1638 &args,
1639 Some(xc),
1640 output_names.len(),
1641 )
1642 .map_err(DaeError::Octave)?
1643 } else {
1644 session
1645 .borrow_mut()
1646 .call_stateful(function, instance, &args, None, output_names.len())
1647 .map_err(DaeError::Octave)?
1648 };
1649 // Optional, a no-op if <function>_update.m wasn't found at construction --
1650 // the dedicated place discrete bookkeeping commits forward to the next step,
1651 // same role CScript's/PyBlock's own optional update has.
1652 if *has_update {
1653 session
1654 .borrow_mut()
1655 .call_stateful(&format!("{function}_update"), instance, &args, None, 0)
1656 .map_err(DaeError::Octave)?;
1657 }
1658 if matches!(sample_time, Some(SampleTimeSpec::Variable)) {
1659 *next_hit_dt = session
1660 .borrow_mut()
1661 .call_readonly_stateful(
1662 &format!("{function}_next_sample_hit"),
1663 instance,
1664 &args,
1665 None,
1666 1,
1667 )
1668 .map_err(DaeError::Octave)?[0];
1669 }
1670 }
1671 for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
1672 outputs.insert(name.clone(), SignalValue::Scalar(*v));
1673 }
1674 SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
1675 }
1676 _ => unreachable!("BlockState variant always matches its BlockKind"),
1677 };
1678 outputs.insert(block.name.clone(), value);
1679 }
1680 Ok(outputs)
1681}
1682
1683/// Rejects a `kind=sig2phys` converter that was *wired into* the physical network — i.e. a block
1684/// whose own name is also used as a node on some element line — before any system is built or any
1685/// step is solved. See [`DaeError::Sig2PhysUsedAsCircuitNode`] for the full rationale; the short
1686/// version is that a `Sig2Phys` block has no terminals and stamps nothing, so such a net is an
1687/// ordinary undriven node that silently solves to `0` instead of failing.
1688///
1689/// Call this with the *flattened* statements ([`general_mna::parse_and_flatten`]), so a converter
1690/// wired inside a `.subckt` body is caught under its final, flattened node name too.
1691///
1692/// Node names are compared case-insensitively (ASCII), because the netlist grammar itself treats
1693/// `A` and `a` as one node — writing `R1 vdrv 0 1k` against a converter declared `VDRV` is the
1694/// same mistake, and must produce the same error.
1695pub fn reject_sig2phys_wired_into_circuit(
1696 statements: &[general_spice_core::ast::Statement],
1697 blocks: &[BlockInstance],
1698) -> Result<(), DaeError> {
1699 // Only `Sig2Phys` blocks are checked, not every block kind: it is the only kind that claims
1700 // to drive the physical domain at all, so it is the only one anybody is tempted to draw a
1701 // wire from. (Wiring any *other* block's name as a node is the same silent-zero shape, but
1702 // rejecting every block/node name collision outright would also reject the harmless, and
1703 // plausible, habit of naming a `kind=phys2sig` probe after the node it measures.)
1704 let converters: BTreeMap<String, &str> = blocks
1705 .iter()
1706 .filter(|b| matches!(b.kind, BlockKind::Sig2Phys { .. }))
1707 .map(|b| (b.name.to_ascii_lowercase(), b.name.as_str()))
1708 .collect();
1709 if converters.is_empty() {
1710 return Ok(());
1711 }
1712 for statement in statements {
1713 let general_spice_core::ast::Statement::ElementInstance(element) = statement else {
1714 continue;
1715 };
1716 for node in &element.nodes {
1717 if let Some(declared) = converters.get(&node.to_ascii_lowercase()) {
1718 return Err(DaeError::Sig2PhysUsedAsCircuitNode {
1719 block: (*declared).to_string(),
1720 element: element.name.clone(),
1721 node: node.clone(),
1722 });
1723 }
1724 }
1725 }
1726 Ok(())
1727}
1728
1729fn resolve_gates(
1730 gates: &BTreeMap<String, GateBinding>,
1731 outputs: &BTreeMap<String, SignalValue>,
1732) -> BTreeMap<String, GateState> {
1733 gates
1734 .iter()
1735 .map(|(switch_name, binding)| (switch_name.clone(), binding.resolve(outputs)))
1736 .collect()
1737}
1738
1739/// Runs a transient with every ideal switch's gate resolved from a [`GateBinding`] each step — see
1740/// this module's doc comment for why there's no separate "closed-loop" entry point: a device
1741/// gated by a plain [`BlockKind::Hysteresis`] and one gated by a `Sum`-`Pid`-[`BlockKind::PhaseShiftPwm`]
1742/// chain that happens to read a [`BlockKind::Phys2Sig`] are resolved by exactly the same loop
1743/// below — every [`GateBinding`] is `Block(name)`, reading whatever `name`'s current output
1744/// happens to be. `step` picks fixed or adaptive timing — see [`TimeStep`]/[`AdaptiveConfig`]. Adaptive mode here can't
1745/// reuse [`step_control::adaptive_step`] directly (that assumes a `dt`-independent `system`):
1746/// this circuit's gate states, and so its `system`, are themselves a function of `dt` through
1747/// the block graph, so a rejected trial has to redo block evaluation *and* gate resolution at
1748/// the smaller `dt`, not just re-solve the same system — see the retry loop below.
1749#[allow(clippy::too_many_arguments)]
1750pub fn simulate_transient_with_blocks(
1751 source: &str,
1752 dialect: Dialect,
1753 diodes: &BTreeMap<String, IdealDiode>,
1754 ideal_switches: &BTreeMap<String, IdealSwitch>,
1755 blocks: &[BlockInstance],
1756 gates: &BTreeMap<String, GateBinding>,
1757 shared_r_on: f64,
1758 x_initial: Option<&[f64]>,
1759 t_final: f64,
1760 step: TimeStep,
1761) -> Result<Vec<TransientWithBlocksStep>, DaeError> {
1762 simulate_transient_with_blocks_capped(
1763 source,
1764 dialect,
1765 diodes,
1766 ideal_switches,
1767 blocks,
1768 gates,
1769 shared_r_on,
1770 x_initial,
1771 t_final,
1772 step,
1773 ADAPTIVE_STEP_HARD_CAP,
1774 )
1775}
1776
1777/// Identical to [`simulate_transient_with_blocks`], with one addition: `max_adaptive_steps`
1778/// overrides [`ADAPTIVE_STEP_HARD_CAP`] (see [`DaeError::AdaptiveStepStalled`]'s own doc comment
1779/// for what this guards against) instead of always using the built-in default. A separate
1780/// function, rather than adding a parameter to `simulate_transient_with_blocks` itself, so this
1781/// project's own ~20 existing call sites (mostly tests, positional-argument calls) don't all need
1782/// updating for a cap most of them will never want to change — `general-simulator-cli`'s own
1783/// `--max-steps` flag is the intended caller.
1784///
1785/// Collects the whole run into a `Vec` before returning, exactly like `simulate_transient_with_blocks`
1786/// — a thin wrapper over [`simulate_transient_with_blocks_streamed`], which does the actual work
1787/// and holds nothing in memory beyond what its caller's own callback chooses to keep. Prefer the
1788/// streamed form directly for a run whose row count isn't known to be small (this repo's own
1789/// experience: a single real run drove a 14GB machine to ~11GB RSS / 24GB swap before being
1790/// killed, entirely because of this function's own full-`Vec` buffering — see
1791/// `general-simulator-cli`'s own streaming CSV/raw writer for the fix in practice).
1792#[allow(clippy::too_many_arguments)]
1793pub fn simulate_transient_with_blocks_capped(
1794 source: &str,
1795 dialect: Dialect,
1796 diodes: &BTreeMap<String, IdealDiode>,
1797 ideal_switches: &BTreeMap<String, IdealSwitch>,
1798 blocks: &[BlockInstance],
1799 gates: &BTreeMap<String, GateBinding>,
1800 shared_r_on: f64,
1801 x_initial: Option<&[f64]>,
1802 t_final: f64,
1803 step: TimeStep,
1804 max_adaptive_steps: usize,
1805) -> Result<Vec<TransientWithBlocksStep>, DaeError> {
1806 let mut trace = Vec::new();
1807 simulate_transient_with_blocks_streamed(
1808 source,
1809 dialect,
1810 diodes,
1811 ideal_switches,
1812 blocks,
1813 gates,
1814 shared_r_on,
1815 x_initial,
1816 t_final,
1817 step,
1818 max_adaptive_steps,
1819 |t, point, outputs| {
1820 trace.push((t, point, outputs));
1821 Ok(())
1822 },
1823 )?;
1824 Ok(trace)
1825}
1826
1827/// The actual transient engine — every other `simulate_transient_with_blocks*` function is a
1828/// thin wrapper over this one. Calls `on_step(t, point, outputs)` once per *accepted* step, in
1829/// order, and holds nothing beyond one step's own data itself: a caller that only needs summary
1830/// statistics, or that writes each row straight to a file/stream as it arrives, never pays for a
1831/// full in-memory trace the way `simulate_transient_with_blocks`/`_capped` do by design (they
1832/// exist for exactly the callers — mostly this project's own tests — that want the whole
1833/// `Vec` back). `on_step` returning `Err` aborts the run immediately with that error.
1834#[allow(clippy::too_many_arguments)]
1835pub fn simulate_transient_with_blocks_streamed(
1836 source: &str,
1837 dialect: Dialect,
1838 diodes: &BTreeMap<String, IdealDiode>,
1839 ideal_switches: &BTreeMap<String, IdealSwitch>,
1840 blocks: &[BlockInstance],
1841 gates: &BTreeMap<String, GateBinding>,
1842 shared_r_on: f64,
1843 x_initial: Option<&[f64]>,
1844 t_final: f64,
1845 step: TimeStep,
1846 max_adaptive_steps: usize,
1847 mut on_step: impl FnMut(f64, OperatingPoint, BTreeMap<String, SignalValue>) -> Result<(), DaeError>,
1848) -> Result<(), DaeError> {
1849 let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
1850
1851 // A CScript, CoordinateTransform, or Pmsm block's own `.name` is only its *primary* output
1852 // alias; `output_names` may also register extra named outputs (see evaluate_blocks' arms
1853 // for all three) that a gate binding is just as free to reference directly -- all need to
1854 // count as "known" here, or a valid netlist referencing one of those extra names gets
1855 // rejected before it ever runs.
1856 let block_names = block_index_by_name(blocks)?;
1857
1858 // Structural check first: a `Sig2Phys` converter is a reference *target*, never a device with
1859 // terminals, so wiring one into the netlist as a node is a model error that must be reported
1860 // before anything else is examined -- otherwise it solves silently to `V(<name>) = 0`.
1861 reject_sig2phys_wired_into_circuit(&statements, blocks)?;
1862
1863 for (switch_name, binding) in gates {
1864 for needed in binding.source_blocks().into_iter().flatten() {
1865 let Some(&idx) = block_names.get(needed) else {
1866 return Err(DaeError::UnknownBlockInput(needed.to_string()));
1867 };
1868 // A GateBinding's target must be an explicit domain=voltage Sig2Phys converter,
1869 // never a raw control block directly and never a domain=current Sig2Phys either --
1870 // an ideal switch's gate is itself a voltage, so it shares the same Signal-to-PS
1871 // boundary a V-source's own magnitude uses (see BlockKind::Sig2Phys's own doc
1872 // comment); no separate gate-only converter type exists. This also correctly
1873 // rejects naming a CScript/CoordinateTransform/Pmsm block's own *extra* output
1874 // alias directly (block_names maps those to the same index, whose kind is never
1875 // Sig2Phys), so no separate check is needed for that case.
1876 if !matches!(
1877 blocks[idx].kind,
1878 BlockKind::Sig2Phys {
1879 domain: PhysicalDomain::Voltage
1880 }
1881 ) {
1882 return Err(DaeError::GateTargetNotSig2Voltage {
1883 gate: switch_name.clone(),
1884 block: needed.to_string(),
1885 found_kind: block_kind_name(&blocks[idx].kind),
1886 });
1887 }
1888 }
1889 }
1890
1891 // Derive this step's (every step's -- the graph's shape never changes mid-run) causal
1892 // evaluation order up front, before any block state or circuit system is built: a cycle is
1893 // a model error the caller should hear about immediately, not partway through a possibly
1894 // long transient.
1895 let order = topological_order(blocks)?;
1896
1897 // Only used to learn the system's `unknowns` ordering/count for the pre-first-step
1898 // `point_prev` below and the default `x_initial` — no step is solved with it. Solving one
1899 // would perturb `x_prev` away from `x_initial` before the real first step even runs, a
1900 // real behavioral difference from `simulate_transient_with_ideal_switches` for the plain
1901 // fixed/PWM case (caught by exactly that mismatch: this function must reduce to identical
1902 // numbers as that one whenever no block reads a `BlockKind::Phys2Sig`).
1903 let initial_states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
1904 .iter()
1905 .map(|(name, m)| (name.clone(), (*m, GateState::Off)))
1906 .collect();
1907 let (system0, all_diodes0) = crate::build_with_ideal_switches(
1908 &statements,
1909 dialect,
1910 diodes,
1911 &initial_states,
1912 shared_r_on,
1913 )?;
1914
1915 // Signal-to-PS enforcement for a `V`/`I` source's own literal value: `general-mna` already
1916 // accepts a bare symbol there (`Expression::Symbol`), stamped verbatim into that source's
1917 // own `input_values` entry -- a genuinely time-varying `TransientFunction` source uses this
1918 // too, with the symbol set to the source's *own* element name (`sym == name`, resolved via
1919 // `system.transient_sources`, an entirely separate mechanism this check must not confuse
1920 // with a block-driven source). Any *other* symbol is a block-driven source candidate: it
1921 // must name a declared block, and that block must be a `Sig2Phys` converter of the matching
1922 // domain (never a raw control block directly, and never the wrong domain) -- source element
1923 // names are always their own SPICE device letter (`V`/`I`) by construction, which is what
1924 // picks the expected domain below. V/I source stamps never depend on switch state, so
1925 // checking `system0` once here is representative of every later per-step rebuild.
1926 for (name, expr) in system0.inputs.iter().zip(&system0.input_values) {
1927 let general_mna::Expression::Symbol(sym) = expr else {
1928 continue;
1929 };
1930 if sym == name || system0.transient_sources.contains_key(name) {
1931 continue;
1932 }
1933 let Some(&idx) = block_names.get(sym.as_str()) else {
1934 continue;
1935 };
1936 let expected = match name.chars().next() {
1937 Some('V') | Some('v') => (
1938 BlockKind::Sig2Phys {
1939 domain: PhysicalDomain::Voltage,
1940 },
1941 "sig2phys(domain=voltage)",
1942 ),
1943 Some('I') | Some('i') => (
1944 BlockKind::Sig2Phys {
1945 domain: PhysicalDomain::Current,
1946 },
1947 "sig2phys(domain=current)",
1948 ),
1949 _ => continue,
1950 };
1951 if blocks[idx].kind != expected.0 {
1952 return Err(DaeError::SourceNotSig2PhysicalConverter {
1953 source: name.clone(),
1954 block: sym.clone(),
1955 expected_kind: expected.1,
1956 found_kind: block_kind_name(&blocks[idx].kind),
1957 });
1958 }
1959 }
1960
1961 let mut x_prev = crate::resolve_initial_state(&system0, &all_diodes0, x_initial)?;
1962 let mut point_prev = OperatingPoint {
1963 unknowns: system0.unknowns.clone(),
1964 x: x_prev.clone(),
1965 diode_names: Vec::new(),
1966 diode_z: Vec::new(),
1967 diode_raw_ioff: Vec::new(),
1968 };
1969 let mut x_prev_prev: Option<Vec<f64>> = None;
1970
1971 let mut cscript_registry = CScriptRegistry::new();
1972 #[cfg(feature = "python")]
1973 let mut pyblock_registry = pyblock_ffi::PyBlockRegistry::new();
1974 #[cfg(feature = "python")]
1975 let mut pyfunction_registry = pyblock_ffi::PyFunctionRegistry::new();
1976 // Spawned lazily, the first time a BlockKind::OctFunc block is actually encountered below --
1977 // see octave_ffi's own module doc comment for why paying octave-cli's own real startup cost
1978 // (~158 ms, measured) should never happen for a run that doesn't use kind=octfunc at all.
1979 // Shared (via Rc::clone into every BlockState::OctFunction instance) rather than one process
1980 // per block instance -- this is the stateless/pyfunc-style case, so every octfunc block in
1981 // one run talks to the same octave-cli session.
1982 let mut octave_session: Option<std::rc::Rc<std::cell::RefCell<octave_ffi::OctaveSession>>> =
1983 None;
1984 // Which directories have already been addpath'd into the shared session -- addpath itself
1985 // is harmless to repeat, but there's no reason to pay the round trip twice for two block
1986 // instances whose .m files happen to live in the same directory.
1987 let mut octave_paths_added: std::collections::BTreeSet<std::path::PathBuf> =
1988 std::collections::BTreeSet::new();
1989 let mut block_states: Vec<BlockState> = Vec::with_capacity(blocks.len());
1990 for b in blocks {
1991 let dynamic = |state_space: StateSpace| {
1992 let x = vec![0.0; state_space.states()];
1993 BlockState::Dynamic { state_space, x }
1994 };
1995 let state = match &b.kind {
1996 BlockKind::Pid { pid, .. } => dynamic(pid.to_state_space()),
1997 BlockKind::StateSpace(ss) => dynamic(ss.clone()),
1998 BlockKind::TransferFunction(tf) => dynamic(tf.to_state_space()),
1999 BlockKind::DiscreteStateSpace { ss, sample_time } => {
2000 let (period, offset) = match sample_time {
2001 SampleTimeSpec::Periodic { period, offset } => (*period, *offset),
2002 SampleTimeSpec::Variable => unreachable!(
2003 "general-mna's parse_required_periodic_sample_time already rejected \
2004 ts=variable for kind=discretestatespace"
2005 ),
2006 };
2007 BlockState::DiscreteDynamic {
2008 x: vec![0.0; ss.states()],
2009 last_output: vec![0.0; ss.outputs()],
2010 // Same `period - offset` convention as BlockKind::CScript's own init below
2011 // -- guarantees the first evaluate_blocks call is due at t=offset.
2012 time_since_sample: period - offset,
2013 state_space: ss.clone(),
2014 }
2015 }
2016 BlockKind::DiscreteTransferFunction { tf, sample_time } => {
2017 let (period, offset) = match sample_time {
2018 SampleTimeSpec::Periodic { period, offset } => (*period, *offset),
2019 SampleTimeSpec::Variable => unreachable!(
2020 "general-mna's parse_required_periodic_sample_time already rejected \
2021 ts=variable for kind=discretetf"
2022 ),
2023 };
2024 let state_space = tf.to_state_space();
2025 BlockState::DiscreteDynamic {
2026 x: vec![0.0; state_space.states()],
2027 last_output: vec![0.0],
2028 time_since_sample: period - offset,
2029 state_space,
2030 }
2031 }
2032 BlockKind::DiscretePid { sample_time, .. } => {
2033 let (period, offset) = match sample_time {
2034 SampleTimeSpec::Periodic { period, offset } => (*period, *offset),
2035 SampleTimeSpec::Variable => unreachable!(
2036 "general-mna's parse_required_periodic_sample_time already rejected \
2037 ts=variable for kind=discretepid"
2038 ),
2039 };
2040 BlockState::DiscretePid {
2041 state: DiscretePidState::default(),
2042 time_since_sample: period - offset,
2043 last_output: 0.0,
2044 }
2045 }
2046 BlockKind::Vco(vco) => BlockState::Vco {
2047 vco: *vco,
2048 phase: 0.0,
2049 },
2050 BlockKind::PhaseShiftPwm { osc, .. } => BlockState::PhaseShiftPwm {
2051 osc: *osc,
2052 phase: 0.0,
2053 },
2054 BlockKind::Pmsm { pmsm, .. } => BlockState::Pmsm {
2055 pmsm: *pmsm,
2056 x: [0.0; 4],
2057 },
2058 BlockKind::Hysteresis(hysteresis) => BlockState::Hysteresis {
2059 hysteresis: *hysteresis,
2060 on: false,
2061 },
2062 // LogicGate needs no BlockState at all -- purely combinational, falls through to
2063 // the `_ => BlockState::Stateless` catch-all below, same as Sum/Gain.
2064 BlockKind::SrLatch { .. } => BlockState::SrLatch { q: false },
2065 // prev_clk starts at 0.0 (clk below threshold) -- matches every other dynamic
2066 // block's own "starts at rest" convention, and means a clk that's already high on
2067 // the very first step is correctly treated as a rising edge (0.0 -> high counts),
2068 // not silently missed.
2069 BlockKind::FlipFlop { .. } => BlockState::FlipFlop {
2070 q: false,
2071 prev_clk: 0.0,
2072 },
2073 BlockKind::Counter { .. } => BlockState::Counter {
2074 count: 0,
2075 prev_clk: 0.0,
2076 },
2077 BlockKind::CScript {
2078 lib,
2079 output_names,
2080 sample_time,
2081 xc_count,
2082 } => {
2083 // xc_count == 0: the plain, single-function contract (cscript_output),
2084 // unchanged from before xc existed. xc_count > 0: the continuous-state
2085 // contract (cscript_derivative/cscript_output_xc instead) -- see
2086 // cscript_ffi::CScriptRegistry::{instantiate,instantiate_xc}'s own doc
2087 // comments for exactly which symbols each requires.
2088 let instance = if *xc_count > 0 {
2089 cscript_registry.instantiate_xc(lib)
2090 } else {
2091 cscript_registry.instantiate(lib)
2092 }
2093 .map_err(DaeError::CScript)?;
2094 if matches!(step, TimeStep::Adaptive(_)) && !instance.supports_clone() {
2095 return Err(DaeError::CScriptRequiresCloneForAdaptiveStep {
2096 block_name: b.name.clone(),
2097 });
2098 }
2099 if matches!(sample_time, Some(SampleTimeSpec::Variable))
2100 && !instance.supports_next_sample_hit()
2101 {
2102 return Err(
2103 DaeError::CScriptRequiresNextSampleHitForVariableSampleTime {
2104 block_name: b.name.clone(),
2105 },
2106 );
2107 }
2108 BlockState::CScript {
2109 instance,
2110 // Periodic{period, offset}: initialized to `period - offset` (not 0.0, and
2111 // deliberately not an infinite sentinel -- that would poison the first
2112 // call's `elapsed` value into +inf once `dt` is added to it below) --
2113 // `offset == 0.0` (the default when `to=` is omitted) makes this `period`
2114 // itself, guaranteeing the first evaluate_blocks call is always "due"
2115 // (time_since_sample + dt >= period trivially) exactly like every
2116 // `ts=`/`freq=`-using netlist already behaved before `to=` could exist at
2117 // all; a nonzero `offset` delays that first hit to `t=offset` instead.
2118 // Variable/None: `0.0` -- Variable's own threshold is `next_hit_dt` (itself
2119 // seeded to `0.0` below), so this is unconditionally due on the first call
2120 // too, the same convention.
2121 time_since_sample: match sample_time {
2122 Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
2123 Some(SampleTimeSpec::Variable) | None => 0.0,
2124 },
2125 next_hit_dt: 0.0,
2126 last_output: vec![0.0; output_names.len()],
2127 // Starts at rest, matching every other dynamic block's own convention
2128 // (Pid/StateSpace/TransferFunction/Pmsm/Vco all start their own state at
2129 // zero too).
2130 xc: vec![0.0; *xc_count],
2131 }
2132 }
2133 #[cfg(feature = "python")]
2134 BlockKind::PyBlock {
2135 path,
2136 output_names,
2137 sample_time,
2138 xc_count,
2139 } => {
2140 // Same xc_count == 0 / > 0 contract split as CScript's own arm above; no
2141 // "requires clone" upfront check here -- pyblock_ffi's own clone is generic
2142 // (Python's copy.deepcopy), no author opt-in needed, so it's never missing.
2143 let instance = if *xc_count > 0 {
2144 pyblock_registry.instantiate_xc(path)
2145 } else {
2146 pyblock_registry.instantiate(path)
2147 }
2148 .map_err(DaeError::PyBlock)?;
2149 if matches!(sample_time, Some(SampleTimeSpec::Variable))
2150 && !instance.supports_next_sample_hit()
2151 {
2152 return Err(
2153 DaeError::PyBlockRequiresNextSampleHitForVariableSampleTime {
2154 block_name: b.name.clone(),
2155 },
2156 );
2157 }
2158 BlockState::PyBlock {
2159 instance,
2160 // Same rationale as CScript's own construction arm above.
2161 time_since_sample: match sample_time {
2162 Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
2163 Some(SampleTimeSpec::Variable) | None => 0.0,
2164 },
2165 next_hit_dt: 0.0,
2166 last_output: vec![0.0; output_names.len()],
2167 xc: vec![0.0; *xc_count],
2168 }
2169 }
2170 // A netlist declaring kind=pyblock against a build with the `python` feature off --
2171 // see DaeError::PythonSupportNotCompiledIn's own doc comment.
2172 #[cfg(not(feature = "python"))]
2173 BlockKind::PyBlock { .. } => {
2174 return Err(DaeError::PythonSupportNotCompiledIn {
2175 block_name: b.name.clone(),
2176 });
2177 }
2178 #[cfg(feature = "python")]
2179 BlockKind::PyFunction {
2180 path,
2181 function,
2182 output_names,
2183 sample_time,
2184 } => {
2185 // Genuinely separate registry from pyblock's own -- see
2186 // BlockKind::PyFunction's own doc comment for why this isn't just PyBlock with
2187 // xc_count implicitly 0.
2188 let instance = pyfunction_registry
2189 .instantiate(path, function)
2190 .map_err(DaeError::PyBlock)?;
2191 BlockState::PyFunction {
2192 instance,
2193 // Variable is unreachable here -- rejected at parse time for PyFunction
2194 // (see BlockKind::PyFunction's own doc comment) -- so only Periodic/None
2195 // ever appear; same rationale as CScript's own construction arm above.
2196 time_since_sample: match sample_time {
2197 Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
2198 Some(SampleTimeSpec::Variable) | None => 0.0,
2199 },
2200 last_output: vec![0.0; output_names.len()],
2201 }
2202 }
2203 #[cfg(not(feature = "python"))]
2204 BlockKind::PyFunction { .. } => {
2205 return Err(DaeError::PythonSupportNotCompiledIn {
2206 block_name: b.name.clone(),
2207 });
2208 }
2209 BlockKind::OctFunc {
2210 path,
2211 output_names,
2212 sample_time,
2213 ..
2214 } => {
2215 // Spawn the shared session on first use, not eagerly -- see its own `let mut
2216 // octave_session` declaration above.
2217 let session = match &octave_session {
2218 Some(s) => s.clone(),
2219 None => {
2220 let s = octave_ffi::OctaveSession::spawn().map_err(DaeError::Octave)?;
2221 let s = std::rc::Rc::new(std::cell::RefCell::new(s));
2222 octave_session = Some(s.clone());
2223 s
2224 }
2225 };
2226 // Octave requires the .m file to be on its own path and the file name to match
2227 // the function name (see octave_ffi's own module doc comment) -- addpath once
2228 // per unique containing directory, not once per block instance.
2229 let dir = match path.canonicalize() {
2230 Ok(abs_file) => abs_file
2231 .parent()
2232 .map(std::path::Path::to_path_buf)
2233 .unwrap_or_else(|| std::path::PathBuf::from(".")),
2234 // A .m file that doesn't (yet) resolve via canonicalize -- fall back to its
2235 // own literal parent, relative to this process's own current directory
2236 // (which octave-cli inherits unchanged, since it's spawned with no explicit
2237 // current_dir override). Calling into a function this session genuinely
2238 // can't find then surfaces naturally as an ordinary Octave-side "undefined
2239 // function" DaeError::Octave(OctaveError::Runtime) at call time, rather than
2240 // failing here at construction time.
2241 Err(_) => path
2242 .parent()
2243 .map(std::path::Path::to_path_buf)
2244 .unwrap_or_else(|| std::path::PathBuf::from(".")),
2245 };
2246 if octave_paths_added.insert(dir.clone()) {
2247 session
2248 .borrow_mut()
2249 .add_path(&dir)
2250 .map_err(DaeError::Octave)?;
2251 }
2252 BlockState::OctFunction {
2253 session,
2254 // Same rationale as PyFunction's own construction arm above.
2255 time_since_sample: match sample_time {
2256 Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
2257 Some(SampleTimeSpec::Variable) | None => 0.0,
2258 },
2259 last_output: vec![0.0; output_names.len()],
2260 }
2261 }
2262 BlockKind::OctBlock {
2263 path,
2264 function,
2265 output_names,
2266 sample_time,
2267 xc_count,
2268 } => {
2269 // OctBlock's own per-instance state genuinely lives inside the shared Octave
2270 // session (see BlockState::OctBlock's own doc comment) -- a rejected trial step
2271 // under TimeStep::Adaptive would silently persist its own state-mutating calls
2272 // with no way to roll them back, since block_states.clone() never clones the
2273 // Octave-side state at all. Unconditional restriction; see
2274 // DaeError::OctBlockDoesNotSupportAdaptiveStep's own doc comment.
2275 if matches!(step, TimeStep::Adaptive(_)) {
2276 return Err(DaeError::OctBlockDoesNotSupportAdaptiveStep {
2277 block_name: b.name.clone(),
2278 });
2279 }
2280 // Spawn the shared session on first use, not eagerly -- same shared session
2281 // every other Octave-hosted block kind in this run uses (see OctFunc's own
2282 // construction arm above for the full rationale).
2283 let session = match &octave_session {
2284 Some(s) => s.clone(),
2285 None => {
2286 let s = octave_ffi::OctaveSession::spawn().map_err(DaeError::Octave)?;
2287 let s = std::rc::Rc::new(std::cell::RefCell::new(s));
2288 octave_session = Some(s.clone());
2289 s
2290 }
2291 };
2292 // Unlike OctFunc's own `path` (a single .m file), OctBlock's `path` is already
2293 // the directory containing every `<function>_<role>.m` file (see
2294 // BlockKind::OctBlock's own doc comment, the file-per-function table) -- addpath
2295 // this directory itself, once per unique directory, not once per instance.
2296 let dir = match path.canonicalize() {
2297 Ok(abs_dir) => abs_dir,
2298 // A directory that doesn't (yet) resolve via canonicalize -- fall back to
2299 // its own literal path, relative to this process's own current directory.
2300 // Any file this session genuinely can't find then surfaces as a clear
2301 // OctBlockMissingRequiredFile error below (checked directly against the
2302 // filesystem, not deferred to Octave's own "undefined function").
2303 Err(_) => path.clone(),
2304 };
2305 let required = |role: &str| -> Result<(), DaeError> {
2306 let expected_path = dir.join(format!("{function}_{role}.m"));
2307 if expected_path.is_file() {
2308 Ok(())
2309 } else {
2310 Err(DaeError::OctBlockMissingRequiredFile {
2311 block_name: b.name.clone(),
2312 expected_path,
2313 })
2314 }
2315 };
2316 // <function>_start.m is always required.
2317 required("start")?;
2318 if *xc_count > 0 {
2319 // The xc_count > 0 contract: <function>_derivative.m/_output_xc.m instead
2320 // of the plain <function>.m -- same split CScript's own xc_count has.
2321 required("derivative")?;
2322 required("output_xc")?;
2323 } else {
2324 // The plain contract's own output function is named exactly `<function>.m`,
2325 // not `<function>_output.m` -- checked directly rather than via the
2326 // `required` closure above (which always appends a `_<role>` suffix).
2327 let expected_path = dir.join(format!("{function}.m"));
2328 if !expected_path.is_file() {
2329 return Err(DaeError::OctBlockMissingRequiredFile {
2330 block_name: b.name.clone(),
2331 expected_path,
2332 });
2333 }
2334 }
2335 if matches!(sample_time, Some(SampleTimeSpec::Variable))
2336 && !dir.join(format!("{function}_next_sample_hit.m")).is_file()
2337 {
2338 return Err(
2339 DaeError::OctBlockRequiresNextSampleHitForVariableSampleTime {
2340 block_name: b.name.clone(),
2341 },
2342 );
2343 }
2344 let has_update = dir.join(format!("{function}_update.m")).is_file();
2345
2346 if octave_paths_added.insert(dir.clone()) {
2347 session
2348 .borrow_mut()
2349 .add_path(&dir)
2350 .map_err(DaeError::Octave)?;
2351 }
2352 // Initialize this instance's own state slot once, at construction -- the same
2353 // "first-touch" convention PyBlock's own instantiate() already uses (calling
2354 // `start()` immediately, not deferred to the first evaluate_blocks call).
2355 session
2356 .borrow_mut()
2357 .call_start(function, &b.name)
2358 .map_err(DaeError::Octave)?;
2359 BlockState::OctBlock {
2360 session,
2361 instance: b.name.clone(),
2362 // Same rationale as CScript's/PyBlock's own construction arms above.
2363 time_since_sample: match sample_time {
2364 Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
2365 Some(SampleTimeSpec::Variable) | None => 0.0,
2366 },
2367 next_hit_dt: 0.0,
2368 last_output: vec![0.0; output_names.len()],
2369 xc: vec![0.0; *xc_count],
2370 has_update,
2371 }
2372 }
2373 _ => BlockState::Stateless,
2374 };
2375 block_states.push(state);
2376 }
2377
2378 let mut prev_diode_raw_ioff: BTreeMap<String, f64> = BTreeMap::new();
2379 let mut prev_segments: Option<Vec<Segment>> = None;
2380 let mut prev_gate_states: Option<BTreeMap<String, GateState>> = None;
2381 let mut ringing_cooldown: u32 = 0;
2382 // Empty on the first step, matching every dynamic block's own "starts at rest" convention
2383 // -- any Signal::BlockPrev reference resolves to 0.0 before any block has ever produced an
2384 // output.
2385 let mut prev_outputs: BTreeMap<String, SignalValue> = BTreeMap::new();
2386
2387 let mut accepted_steps: usize = 0;
2388 let mut t = 0.0;
2389
2390 match step {
2391 TimeStep::Fixed(dt) => {
2392 let steps = (t_final / dt).round() as usize;
2393 for step_index in 0..steps {
2394 t += dt;
2395
2396 let outputs = evaluate_blocks(
2397 blocks,
2398 &order,
2399 &mut block_states,
2400 &point_prev,
2401 &prev_outputs,
2402 t,
2403 dt,
2404 )?;
2405 let gate_states = resolve_gates(gates, &outputs);
2406 let states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
2407 .iter()
2408 .map(|(name, m)| {
2409 (
2410 name.clone(),
2411 (*m, *gate_states.get(name).unwrap_or(&GateState::Off)),
2412 )
2413 })
2414 .collect();
2415 let gate_changed = prev_gate_states.as_ref() != Some(&gate_states);
2416 let forced = step_index == 0 || gate_changed || ringing_cooldown > 0;
2417
2418 let (system, all_diodes) = crate::build_with_ideal_switches(
2419 &statements,
2420 dialect,
2421 diodes,
2422 &states,
2423 shared_r_on,
2424 )?;
2425 let (point, used_backward_euler) = step_with_fallback(
2426 &system,
2427 &statements,
2428 &all_diodes,
2429 x_prev_prev.as_deref(),
2430 &x_prev,
2431 dt,
2432 &prev_diode_raw_ioff,
2433 &prev_segments,
2434 forced,
2435 t,
2436 &scalar_only(&outputs),
2437 &scalar_only(&prev_outputs),
2438 )?;
2439 if used_backward_euler && !forced {
2440 ringing_cooldown = RINGING_COOLDOWN_STEPS;
2441 } else if ringing_cooldown > 0 {
2442 ringing_cooldown = ringing_cooldown.saturating_sub(1);
2443 }
2444
2445 prev_segments = Some(classify_segments(&point));
2446 prev_gate_states = Some(gate_states);
2447 prev_diode_raw_ioff = point
2448 .diode_names
2449 .iter()
2450 .cloned()
2451 .zip(point.diode_raw_ioff.iter().copied())
2452 .collect();
2453 x_prev_prev = Some(std::mem::replace(&mut x_prev, point.x.clone()));
2454 point_prev = point.clone();
2455 prev_outputs = outputs.clone();
2456 on_step(t, point, outputs)?;
2457 }
2458 }
2459 TimeStep::Adaptive(config) => {
2460 let mut dt_next = config.dt_init;
2461 let mut step_index = 0usize;
2462 while t < t_final {
2463 let mut dt = dt_next.min(t_final - t);
2464 // Clamp to the earliest predicted discrete-block/gate-edge event so a trial step
2465 // lands (approximately) exactly on it, instead of stepping past it and only
2466 // detecting the change after the fact via `gate_changed` -- the fix for silently
2467 // missed edges when `dt_max` approaches or exceeds the switching period (see
2468 // `earliest_next_event_dt`'s own doc comment). This can only shrink `dt` here;
2469 // the inner LTE-retry loop below may shrink it further via
2470 // `attempt.suggested_dt_next` on rejection, but never grows it back past this
2471 // clamp within the same outer iteration. Landing exactly on a predicted event
2472 // takes priority over `config.dt_min` -- missing an edge is worse than one small
2473 // out-of-target step; the `1e-15` floor just avoids a zero/negative-dt retry loop
2474 // from float noise when we're already sitting on the event.
2475 if let Some(event_dt) =
2476 earliest_next_event_dt(blocks, &block_states, &prev_outputs, t)
2477 {
2478 dt = dt.min(event_dt.max(1e-15));
2479 }
2480 loop {
2481 let mut trial_block_states = block_states.clone();
2482 let t_candidate = t + dt;
2483 let outputs = evaluate_blocks(
2484 blocks,
2485 &order,
2486 &mut trial_block_states,
2487 &point_prev,
2488 &prev_outputs,
2489 t_candidate,
2490 dt,
2491 )?;
2492 let gate_states = resolve_gates(gates, &outputs);
2493 let states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
2494 .iter()
2495 .map(|(name, m)| {
2496 (
2497 name.clone(),
2498 (*m, *gate_states.get(name).unwrap_or(&GateState::Off)),
2499 )
2500 })
2501 .collect();
2502 let gate_changed = prev_gate_states.as_ref() != Some(&gate_states);
2503 let forced = step_index == 0 || gate_changed || ringing_cooldown > 0;
2504
2505 let (system, all_diodes) = crate::build_with_ideal_switches(
2506 &statements,
2507 dialect,
2508 diodes,
2509 &states,
2510 shared_r_on,
2511 )?;
2512 let attempt = step_control::lte_attempt(
2513 &system,
2514 &statements,
2515 &all_diodes,
2516 x_prev_prev.as_deref(),
2517 &x_prev,
2518 dt,
2519 &prev_diode_raw_ioff,
2520 &prev_segments,
2521 forced,
2522 &config,
2523 t,
2524 &scalar_only(&outputs),
2525 &scalar_only(&prev_outputs),
2526 )?;
2527
2528 if !attempt.accept {
2529 dt = attempt.suggested_dt_next;
2530 continue;
2531 }
2532
2533 if attempt.used_backward_euler && !forced {
2534 ringing_cooldown = RINGING_COOLDOWN_STEPS;
2535 } else if ringing_cooldown > 0 {
2536 ringing_cooldown = ringing_cooldown.saturating_sub(1);
2537 }
2538
2539 block_states = trial_block_states;
2540 t = t_candidate;
2541 dt_next = attempt.suggested_dt_next;
2542 prev_outputs = outputs.clone();
2543 prev_segments = Some(classify_segments(&attempt.point));
2544 prev_gate_states = Some(gate_states);
2545 prev_diode_raw_ioff = attempt
2546 .point
2547 .diode_names
2548 .iter()
2549 .cloned()
2550 .zip(attempt.point.diode_raw_ioff.iter().copied())
2551 .collect();
2552 x_prev_prev = Some(std::mem::replace(&mut x_prev, attempt.point.x.clone()));
2553 point_prev = attempt.point.clone();
2554 on_step(t, attempt.point, outputs)?;
2555 accepted_steps += 1;
2556 step_index += 1;
2557 if accepted_steps > max_adaptive_steps {
2558 return Err(DaeError::AdaptiveStepStalled {
2559 steps_taken: accepted_steps,
2560 t_reached: t,
2561 t_final,
2562 });
2563 }
2564 break;
2565 }
2566 }
2567 }
2568 }
2569 Ok(())
2570}
2571
2572#[cfg(test)]
2573mod next_pwm_edge_dt_tests {
2574 use super::next_pwm_edge_dt;
2575
2576 /// The exact bug this guards against: once the adaptive loop lands a step precisely on a
2577 /// threshold (the whole point of `earliest_next_event_dt`), `theta_now == threshold` to
2578 /// float precision on the very next call. Naively that reads as "0 away," which an outer
2579 /// `.max(1e-15)` clamp turns into a real near-zero step instead of an error -- and since
2580 /// theta barely advances in a step that small, the SAME threshold reads as ~0 again next
2581 /// call too: an unbounded near-zero-dt stall that grows the in-memory row buffer without
2582 /// limit until the process (and, in the real run that found this, the whole machine) runs
2583 /// out of memory. Asserts the fixed behavior directly: landing exactly on `duty` must report
2584 /// "a full period away," not "already there."
2585 #[test]
2586 fn landing_exactly_on_a_threshold_reports_a_full_period_not_zero() {
2587 let freq = 600_000.0;
2588 let duty = 0.4;
2589 let red_frac = 0.0;
2590 let fed_frac = 0.0;
2591 let dt = next_pwm_edge_dt(duty, duty, red_frac, fed_frac, freq)
2592 .expect("finite freq must always report a next-edge estimate");
2593 let half_period = 0.5 / freq;
2594 assert!(
2595 dt > half_period,
2596 "landing exactly on duty's own threshold must report ~a full period away \
2597 ({half_period:.3e}s expected), not ~0 (got {dt:.3e}s) -- ~0 is exactly the bug \
2598 that stalled the adaptive loop and exhausted memory on a real run",
2599 );
2600 }
2601
2602 /// Same case for the `red_frac` threshold (the other edge `Pwm`/`PhaseShiftPwm` compare
2603 /// against), landed a few `f64::EPSILON`-scale ULPs *past* the exact instant (real
2604 /// floating-point accumulation can produce this just as easily as landing exactly on it) --
2605 /// with `duty` set to the SAME threshold so there's only one edge in play, isolating this
2606 /// from the (correct, separately-tested) case where a genuinely different, nearer threshold
2607 /// exists.
2608 #[test]
2609 fn landing_a_few_ulps_past_a_threshold_also_reports_a_full_period_not_zero() {
2610 let freq = 300_000.0;
2611 let red_frac = 0.1;
2612 let theta_now = red_frac + 4.0 * f64::EPSILON;
2613 let dt = next_pwm_edge_dt(theta_now, red_frac, red_frac, 0.0, freq)
2614 .expect("finite freq must always report a next-edge estimate");
2615 let half_period = 0.5 / freq;
2616 assert!(
2617 dt > half_period,
2618 "landing a few ULPs past red_frac must report ~a full period away \
2619 ({half_period:.3e}s expected), not ~0 (got {dt:.3e}s)",
2620 );
2621 }
2622
2623 /// Normal, non-degenerate cases stay essentially unchanged: a threshold genuinely ahead of
2624 /// `theta_now` reports (approximately) the real distance to it, not a full period.
2625 #[test]
2626 fn a_threshold_genuinely_ahead_reports_the_real_distance() {
2627 let freq = 100_000.0; // period = 10us
2628 let theta_now = 0.1;
2629 let duty = 0.4; // 0.3 of a period ahead
2630 let dt = next_pwm_edge_dt(theta_now, duty, 0.0, 0.0, freq).unwrap();
2631 let expected = 0.3 / freq;
2632 assert!(
2633 (dt - expected).abs() < 1e-9 / freq,
2634 "expected ~{expected:.3e}s, got {dt:.3e}s"
2635 );
2636 }
2637}