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