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