use std::collections::BTreeMap;
use continuous_blocks::logic::{as_bool, from_bool, rising_edge, srlatch_next};
use continuous_blocks::{math_ops, DiscretePidState, Hysteresis, Pmsm, StateSpace, Vco};
use cscript_ffi::CScriptRegistry;
use general_spice_core::Dialect;
use pwl_devices::{IdealDiode, IdealSwitch};
use crate::checkpoint::{BlockSnapshot, Checkpoint, PointSnapshot, SignalSnapshot};
use crate::{
classify_segments, sawtooth_carrier, step_control, step_with_fallback, DaeError, GateState,
OperatingPoint, Segment, TimeStep, RINGING_COOLDOWN_STEPS,
};
use general_mna::block_graph::block_kind_name;
pub use general_mna::block_graph::{
BlockInstance, BlockKind, ConstValue, GainValue, GateBinding, Phys2SigTarget, PhysicalDomain,
PidClamp, SampleTimeSpec, Signal, SignalValue,
};
pub const ADAPTIVE_STEP_HARD_CAP: usize = 10_000_000;
fn require_all_scalar(block_name: &str, input_vals: &[SignalValue]) -> Result<Vec<f64>, DaeError> {
input_vals
.iter()
.map(|v| {
v.as_scalar()
.ok_or_else(|| DaeError::VectorSignalNotSupported {
block: block_name.to_string(),
})
})
.collect()
}
fn flatten(input_vals: &[SignalValue]) -> Vec<f64> {
input_vals
.iter()
.flat_map(|v| v.as_slice().iter().copied())
.collect()
}
fn common_vector_len(
block_name: &str,
operands: &[&SignalValue],
) -> Result<Option<usize>, DaeError> {
let mut common: Option<usize> = None;
for v in operands {
if let SignalValue::Vector(xs) = v {
match common {
None => common = Some(xs.len()),
Some(n) if n == xs.len() => {}
Some(n) => {
return Err(DaeError::VectorSignalSizeMismatch {
block: block_name.to_string(),
expected: n,
got: xs.len(),
})
}
}
}
}
Ok(common)
}
fn broadcast_at(v: &SignalValue, i: usize) -> f64 {
match v {
SignalValue::Scalar(x) => *x,
SignalValue::Vector(xs) => xs[i],
}
}
fn require_uniform_vectors(
block_name: &str,
input_vals: &[SignalValue],
) -> Result<usize, DaeError> {
let mut common: Option<usize> = None;
for v in input_vals {
let SignalValue::Vector(xs) = v else {
return Err(DaeError::VectorSignalNotSupported {
block: block_name.to_string(),
});
};
match common {
None => common = Some(xs.len()),
Some(n) if n == xs.len() => {}
Some(n) => {
return Err(DaeError::VectorSignalSizeMismatch {
block: block_name.to_string(),
expected: n,
got: xs.len(),
})
}
}
}
Ok(common.unwrap_or(0))
}
fn scalar_only(outputs: &BTreeMap<String, SignalValue>) -> BTreeMap<String, f64> {
outputs
.iter()
.filter_map(|(k, v)| v.as_scalar().map(|x| (k.clone(), x)))
.collect()
}
#[derive(Clone)]
enum BlockState {
Stateless,
Dynamic {
state_space: continuous_blocks::StateSpace,
x: Vec<f64>,
},
DiscreteDynamic {
state_space: continuous_blocks::StateSpace,
x: Vec<f64>,
time_since_sample: f64,
last_output: Vec<f64>,
},
DiscretePid {
state: continuous_blocks::DiscretePidState,
time_since_sample: f64,
last_output: f64,
},
Vco {
vco: Vco,
phase: f64,
},
PhaseShiftPwm {
osc: Vco,
phase: f64,
},
Pmsm {
pmsm: Pmsm,
x: [f64; 4],
},
Hysteresis {
hysteresis: Hysteresis,
on: bool,
},
SrLatch {
q: bool,
},
FlipFlop {
q: bool,
prev_clk: f64,
},
Counter {
count: i64,
prev_clk: f64,
},
CScript {
instance: cscript_ffi::CScriptInstance,
time_since_sample: f64,
next_hit_dt: f64,
last_output: Vec<f64>,
xc: Vec<f64>,
},
#[cfg(feature = "python")]
PyBlock {
instance: pyblock_ffi::PyBlockInstance,
time_since_sample: f64,
next_hit_dt: f64,
last_output: Vec<f64>,
xc: Vec<f64>,
},
#[cfg(feature = "python")]
PyFunction {
instance: pyblock_ffi::PyFunctionInstance,
time_since_sample: f64,
last_output: Vec<f64>,
},
OctFunction {
session: std::rc::Rc<std::cell::RefCell<octave_ffi::OctaveSession>>,
time_since_sample: f64,
last_output: Vec<f64>,
},
OctBlock {
session: std::rc::Rc<std::cell::RefCell<octave_ffi::OctaveSession>>,
instance: String,
time_since_sample: f64,
next_hit_dt: f64,
last_output: Vec<f64>,
xc: Vec<f64>,
has_update: bool,
},
}
pub type TransientWithBlocksStep = (f64, OperatingPoint, BTreeMap<String, SignalValue>);
fn block_index_by_name(blocks: &[BlockInstance]) -> Result<BTreeMap<&str, usize>, DaeError> {
let mut index_of = BTreeMap::new();
for (i, b) in blocks.iter().enumerate() {
if index_of.insert(b.name.as_str(), i).is_some() {
return Err(DaeError::DuplicateBlockName(b.name.clone()));
}
let extra: &[String] = match &b.kind {
BlockKind::CScript { output_names, .. }
| BlockKind::PyBlock { output_names, .. }
| BlockKind::PyFunction { output_names, .. }
| BlockKind::OctFunc { output_names, .. }
| BlockKind::OctBlock { output_names, .. }
| BlockKind::CoordinateTransform { output_names, .. }
| BlockKind::Pmsm { output_names, .. }
| BlockKind::Pwm { output_names, .. }
| BlockKind::PhaseShiftPwm { output_names, .. } => output_names,
_ => &[],
};
for name in extra.iter().skip(1) {
if index_of.insert(name.as_str(), i).is_some() {
return Err(DaeError::DuplicateBlockName(name.clone()));
}
}
}
Ok(index_of)
}
fn topological_order(blocks: &[BlockInstance]) -> Result<Vec<usize>, DaeError> {
#[derive(Clone, Copy, PartialEq)]
enum Color {
White,
Gray,
Black,
}
fn visit(
i: usize,
blocks: &[BlockInstance],
index_of: &BTreeMap<&str, usize>,
color: &mut [Color],
stack: &mut Vec<usize>,
order: &mut Vec<usize>,
) -> Result<(), DaeError> {
match color[i] {
Color::Black => return Ok(()),
Color::Gray => {
let start = stack.iter().position(|&s| s == i).expect(
"a Gray node is always still on the stack by this function's own invariant",
);
let mut cycle: Vec<String> = stack[start..]
.iter()
.map(|&idx| blocks[idx].name.clone())
.collect();
cycle.push(blocks[i].name.clone());
return Err(DaeError::AlgebraicLoop { cycle });
}
Color::White => {}
}
color[i] = Color::Gray;
stack.push(i);
for signal in &blocks[i].inputs {
if let Signal::Block(name) = signal {
if let Some(&dep) = index_of.get(name.as_str()) {
visit(dep, blocks, index_of, color, stack, order)?;
}
}
}
stack.pop();
color[i] = Color::Black;
order.push(i);
Ok(())
}
let index_of = block_index_by_name(blocks)?;
let mut color = vec![Color::White; blocks.len()];
let mut order = Vec::with_capacity(blocks.len());
let mut stack = Vec::new();
for i in 0..blocks.len() {
if color[i] == Color::White {
visit(i, blocks, &index_of, &mut color, &mut stack, &mut order)?;
}
}
Ok(order)
}
fn periodic_time(t: f64, points: &[(f64, f64)], repeat: bool) -> f64 {
if !repeat || points.len() < 2 {
return t;
}
let t0 = points[0].0;
let t_last = points[points.len() - 1].0;
let period = t_last - t0;
if period <= 0.0 || t < t_last {
return t;
}
t0 + (t - t0) % period
}
fn phys2sig_value(target: &Phys2SigTarget, point_prev: &OperatingPoint) -> f64 {
match target {
Phys2SigTarget::Voltage(node) => point_prev.value(&format!("V({node})")).unwrap_or(0.0),
Phys2SigTarget::Current(branch) => point_prev.value(&format!("I({branch})")).unwrap_or(0.0),
}
}
fn emit_complementary_pair(
outputs: &mut BTreeMap<String, SignalValue>,
output_names: &[String],
main: bool,
complement: bool,
) -> f64 {
if let Some(name) = output_names.get(1) {
outputs.insert(
name.clone(),
SignalValue::Scalar(if complement { 1.0 } else { 0.0 }),
);
}
if main {
1.0
} else {
0.0
}
}
fn sample_threshold(sample_time: Option<&SampleTimeSpec>, next_hit_dt: f64) -> Option<f64> {
match sample_time {
None => None,
Some(SampleTimeSpec::Periodic { period, .. }) => Some(*period),
Some(SampleTimeSpec::Variable) => Some(next_hit_dt),
}
}
fn time_until_due(threshold: Option<f64>, time_since_sample: f64) -> Option<f64> {
threshold.map(|th| (th - time_since_sample).max(0.0))
}
fn next_pwm_edge_dt(
theta_now: f64,
duty: f64,
red_frac: f64,
fed_frac: f64,
freq: f64,
) -> Option<f64> {
const THETA_EPS: f64 = 1e-9;
if !freq.is_finite() || freq <= 0.0 {
return None;
}
let thresholds = [red_frac, duty, duty + fed_frac];
let delta_theta = thresholds
.iter()
.map(|&r| (r - theta_now - THETA_EPS).rem_euclid(1.0) + THETA_EPS)
.fold(f64::INFINITY, f64::min);
if !delta_theta.is_finite() {
return None;
}
Some(delta_theta / freq)
}
fn resolve_prev_scalar(
prev_outputs: &BTreeMap<String, SignalValue>,
signal: &Signal,
) -> Option<f64> {
let name = match signal {
Signal::Block(n) | Signal::BlockPrev(n) => n,
};
prev_outputs.get(name).and_then(|v| v.as_scalar())
}
fn earliest_next_event_dt(
blocks: &[BlockInstance],
block_states: &[BlockState],
prev_outputs: &BTreeMap<String, SignalValue>,
t: f64,
) -> Option<f64> {
blocks
.iter()
.zip(block_states.iter())
.filter_map(|(block, state)| match (&block.kind, state) {
(
BlockKind::Pwm {
freq_hz, red, fed, ..
},
_,
) => {
let theta_now = sawtooth_carrier(t, *freq_hz);
let duty = resolve_prev_scalar(prev_outputs, block.inputs.first()?)?;
next_pwm_edge_dt(theta_now, duty, red * freq_hz, fed * freq_hz, *freq_hz)
}
(
BlockKind::PhaseShiftPwm { red, fed, .. },
BlockState::PhaseShiftPwm { osc, phase },
) => {
let freq_command = resolve_prev_scalar(prev_outputs, block.inputs.first()?)?;
let phase_offset = resolve_prev_scalar(prev_outputs, block.inputs.get(1)?)?;
let duty = resolve_prev_scalar(prev_outputs, block.inputs.get(2)?)?;
let actual_freq = freq_command.clamp(osc.f_min, osc.f_max);
let theta_now = (*phase + phase_offset).rem_euclid(1.0);
next_pwm_edge_dt(
theta_now,
duty,
red * actual_freq,
fed * actual_freq,
actual_freq,
)
}
(
BlockKind::CScript { sample_time, .. },
BlockState::CScript {
time_since_sample,
next_hit_dt,
..
},
) => time_until_due(
sample_threshold(sample_time.as_ref(), *next_hit_dt),
*time_since_sample,
),
#[cfg(feature = "python")]
(
BlockKind::PyBlock { sample_time, .. },
BlockState::PyBlock {
time_since_sample,
next_hit_dt,
..
},
) => time_until_due(
sample_threshold(sample_time.as_ref(), *next_hit_dt),
*time_since_sample,
),
#[cfg(feature = "python")]
(
BlockKind::PyFunction { sample_time, .. },
BlockState::PyFunction {
time_since_sample, ..
},
) => match sample_time {
None | Some(SampleTimeSpec::Variable) => None,
Some(SampleTimeSpec::Periodic { period, .. }) => {
Some((period - time_since_sample).max(0.0))
}
},
(
BlockKind::OctFunc { sample_time, .. },
BlockState::OctFunction {
time_since_sample, ..
},
) => match sample_time {
None | Some(SampleTimeSpec::Variable) => None,
Some(SampleTimeSpec::Periodic { period, .. }) => {
Some((period - time_since_sample).max(0.0))
}
},
(
BlockKind::OctBlock { sample_time, .. },
BlockState::OctBlock {
time_since_sample,
next_hit_dt,
..
},
) => time_until_due(
sample_threshold(sample_time.as_ref(), *next_hit_dt),
*time_since_sample,
),
(
BlockKind::DiscreteStateSpace { sample_time, .. }
| BlockKind::DiscreteTransferFunction { sample_time, .. },
BlockState::DiscreteDynamic {
time_since_sample, ..
},
) => match sample_time {
SampleTimeSpec::Periodic { period, .. } => {
Some((period - time_since_sample).max(0.0))
}
SampleTimeSpec::Variable => None, },
(
BlockKind::DiscretePid { sample_time, .. },
BlockState::DiscretePid {
time_since_sample, ..
},
) => match sample_time {
SampleTimeSpec::Periodic { period, .. } => {
Some((period - time_since_sample).max(0.0))
}
SampleTimeSpec::Variable => None, },
_ => None,
})
.fold(None, |acc, dt| match acc {
None => Some(dt),
Some(best) => Some(best.min(dt)),
})
}
fn evaluate_blocks(
blocks: &[BlockInstance],
order: &[usize],
block_states: &mut [BlockState],
point_prev: &OperatingPoint,
prev_outputs: &BTreeMap<String, SignalValue>,
t: f64,
dt: f64,
) -> Result<BTreeMap<String, SignalValue>, DaeError> {
let mut outputs: BTreeMap<String, SignalValue> = BTreeMap::new();
let resolve = |outputs: &BTreeMap<String, SignalValue>,
signal: &Signal|
-> Result<SignalValue, DaeError> {
match signal {
Signal::Block(name) => outputs
.get(name)
.cloned()
.ok_or_else(|| DaeError::UnknownBlockInput(name.clone())),
Signal::BlockPrev(name) => Ok(prev_outputs
.get(name)
.cloned()
.unwrap_or(SignalValue::Scalar(0.0))),
}
};
for &i in order {
let block = &blocks[i];
let state = &mut block_states[i];
let input_vals: Vec<SignalValue> = block
.inputs
.iter()
.map(|s| resolve(&outputs, s))
.collect::<Result<_, _>>()?;
let value: SignalValue = match (&block.kind, state) {
(BlockKind::Const(v), _) => match v {
ConstValue::Scalar(x) => SignalValue::Scalar(*x),
ConstValue::Vector(xs) => SignalValue::Vector(xs.clone()),
},
(BlockKind::Time, _) => SignalValue::Scalar(t),
(BlockKind::Phys2Sig(target), _) => {
SignalValue::Scalar(phys2sig_value(target, point_prev))
}
(BlockKind::Sig2Phys { .. }, _) => {
SignalValue::Scalar(require_all_scalar(&block.name, &input_vals)?[0])
}
(BlockKind::Pwc { points, repeat }, _) => {
let t_eval = periodic_time(t, points, *repeat);
let mut v = points.first().map(|(_, v)| *v).unwrap_or(0.0);
for &(t_i, v_i) in points {
if t_i <= t_eval {
v = v_i;
} else {
break;
}
}
SignalValue::Scalar(v)
}
(BlockKind::Pwl { points, repeat }, _) => {
let t_eval = periodic_time(t, points, *repeat);
SignalValue::Scalar(match points.as_slice() {
[] => 0.0,
[(_, v)] => *v,
_ if t_eval <= points[0].0 => points[0].1,
_ if t_eval >= points[points.len() - 1].0 => points[points.len() - 1].1,
_ => {
let mut v = points[points.len() - 1].1;
for window in points.windows(2) {
let (t0, v0) = window[0];
let (t1, v1) = window[1];
if t_eval >= t0 && t_eval <= t1 {
v = if (t1 - t0).abs() < f64::EPSILON {
v1
} else {
v0 + (v1 - v0) * ((t_eval - t0) / (t1 - t0))
};
break;
}
}
v
}
})
}
(BlockKind::Waveform(f), _) => SignalValue::Scalar(f.value_at(t)),
(BlockKind::Sum(signs), _) => {
if input_vals
.iter()
.all(|v| matches!(v, SignalValue::Scalar(_)))
{
let scalars = require_all_scalar(&block.name, &input_vals)?;
SignalValue::Scalar(math_ops::sum(&scalars, signs))
} else {
let n = require_uniform_vectors(&block.name, &input_vals)?;
let out: Vec<f64> = (0..n)
.map(|i| {
let elems: Vec<f64> =
input_vals.iter().map(|v| broadcast_at(v, i)).collect();
math_ops::sum(&elems, signs)
})
.collect();
SignalValue::Vector(out)
}
}
(BlockKind::Gain(k), _) => match k {
GainValue::Scalar(k) => match &input_vals[0] {
SignalValue::Scalar(x) => SignalValue::Scalar(math_ops::gain(*k, *x)),
SignalValue::Vector(xs) => {
SignalValue::Vector(xs.iter().map(|&x| math_ops::gain(*k, x)).collect())
}
},
GainValue::Matrix(mat) => {
let n = mat.first().map_or(0, |row| row.len());
let SignalValue::Vector(x) = &input_vals[0] else {
return Err(DaeError::VectorSignalNotSupported {
block: block.name.clone(),
});
};
if x.len() != n {
return Err(DaeError::VectorSignalSizeMismatch {
block: block.name.clone(),
expected: n,
got: x.len(),
});
}
let y: Vec<f64> = mat
.iter()
.map(|row| row.iter().zip(x).map(|(a, b)| a * b).sum())
.collect();
SignalValue::Vector(y)
}
},
(BlockKind::Product, _) => {
if input_vals
.iter()
.all(|v| matches!(v, SignalValue::Scalar(_)))
{
let scalars = require_all_scalar(&block.name, &input_vals)?;
SignalValue::Scalar(math_ops::product(&scalars))
} else {
let n = require_uniform_vectors(&block.name, &input_vals)?;
let out: Vec<f64> = (0..n)
.map(|i| {
let elems: Vec<f64> =
input_vals.iter().map(|v| broadcast_at(v, i)).collect();
math_ops::product(&elems)
})
.collect();
SignalValue::Vector(out)
}
}
(
BlockKind::Pwm {
freq_hz,
red,
fed,
output_names,
},
_,
) => {
let theta = sawtooth_carrier(t, *freq_hz);
let duty = require_all_scalar(&block.name, &input_vals)?[0];
let (main, complement) = math_ops::complementary_pwm_with_deadtime(
theta,
duty,
red * freq_hz,
fed * freq_hz,
);
SignalValue::Scalar(emit_complementary_pair(
&mut outputs,
output_names,
main,
complement,
))
}
(BlockKind::Saturation(limit), _) => match &input_vals[0] {
SignalValue::Scalar(x) => SignalValue::Scalar(math_ops::saturation(*x, *limit)),
SignalValue::Vector(xs) => SignalValue::Vector(
xs.iter()
.map(|&x| math_ops::saturation(x, *limit))
.collect(),
),
},
(BlockKind::Table(points), _) => match &input_vals[0] {
SignalValue::Scalar(x) => {
SignalValue::Scalar(continuous_blocks::waveform_arithmetic::table(*x, points))
}
SignalValue::Vector(xs) => SignalValue::Vector(
xs.iter()
.map(|&x| continuous_blocks::waveform_arithmetic::table(x, points))
.collect(),
),
},
(BlockKind::MathFn1(f), _) => match &input_vals[0] {
SignalValue::Scalar(x) => SignalValue::Scalar(f.call(*x)),
SignalValue::Vector(xs) => {
SignalValue::Vector(xs.iter().map(|&x| f.call(x)).collect())
}
},
(BlockKind::MathFn2(f), _) => {
match common_vector_len(&block.name, &[&input_vals[0], &input_vals[1]])? {
None => SignalValue::Scalar(f.call(
input_vals[0].as_scalar().expect("checked Scalar above"),
input_vals[1].as_scalar().expect("checked Scalar above"),
)),
Some(n) => SignalValue::Vector(
(0..n)
.map(|i| {
f.call(
broadcast_at(&input_vals[0], i),
broadcast_at(&input_vals[1], i),
)
})
.collect(),
),
}
}
(BlockKind::MathFn3(f), _) => {
match common_vector_len(
&block.name,
&[&input_vals[0], &input_vals[1], &input_vals[2]],
)? {
None => SignalValue::Scalar(f.call(
input_vals[0].as_scalar().expect("checked Scalar above"),
input_vals[1].as_scalar().expect("checked Scalar above"),
input_vals[2].as_scalar().expect("checked Scalar above"),
)),
Some(n) => SignalValue::Vector(
(0..n)
.map(|i| {
f.call(
broadcast_at(&input_vals[0], i),
broadcast_at(&input_vals[1], i),
broadcast_at(&input_vals[2], i),
)
})
.collect(),
),
}
}
(BlockKind::CoordinateTransform { kind, output_names }, _) => {
let flat = flatten(&input_vals);
let outs = kind.call(&flat);
for (name, v) in output_names.iter().zip(outs.iter()).skip(1) {
outputs.insert(name.clone(), SignalValue::Scalar(*v));
}
SignalValue::Scalar(outs[0])
}
(BlockKind::Pid { clamp, .. }, BlockState::Dynamic { state_space, x }) => {
let scalars = require_all_scalar(&block.name, &input_vals)?;
let (lo, hi) = match clamp {
PidClamp::Fixed(lo, hi) => (*lo, *hi),
PidClamp::Dynamic => (scalars[1], scalars[2]),
};
let error = [scalars[0]];
let tentative_x = state_space.rk4_step(x, &error, dt);
let tentative_output = state_space.output(&tentative_x, &error)[0];
let saturating_further = (tentative_output >= hi && error[0] > 0.0)
|| (tentative_output <= lo && error[0] < 0.0);
SignalValue::Scalar(if saturating_further {
state_space.output(x, &error)[0].clamp(lo, hi)
} else {
*x = tentative_x;
tentative_output
})
}
(BlockKind::TransferFunction(_), BlockState::Dynamic { state_space, x }) => {
let u = require_all_scalar(&block.name, &input_vals)?;
*x = state_space.rk4_step(x, &u, dt);
SignalValue::Scalar(state_space.output(x, &u)[0])
}
(BlockKind::StateSpace(_), BlockState::Dynamic { state_space, x }) => {
let u = flatten(&input_vals);
let expected = state_space.inputs();
if u.len() != expected {
return Err(DaeError::VectorSignalSizeMismatch {
block: block.name.clone(),
expected,
got: u.len(),
});
}
*x = state_space.rk4_step(x, &u, dt);
let y = state_space.output(x, &u);
if y.len() == 1 {
SignalValue::Scalar(y[0])
} else {
SignalValue::Vector(y)
}
}
(
BlockKind::DiscreteStateSpace { sample_time, .. },
BlockState::DiscreteDynamic {
state_space,
x,
time_since_sample,
last_output,
},
) => {
let period = match sample_time {
SampleTimeSpec::Periodic { period, .. } => *period,
SampleTimeSpec::Variable => unreachable!(
"general-mna's parse_required_periodic_sample_time already rejected \
ts=variable for kind=discretestatespace"
),
};
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= period {
*time_since_sample = 0.0;
let u = flatten(&input_vals);
let expected = state_space.inputs();
if u.len() != expected {
return Err(DaeError::VectorSignalSizeMismatch {
block: block.name.clone(),
expected,
got: u.len(),
});
}
*x = state_space.discrete_step(x, &u);
*last_output = state_space.output(x, &u);
}
if last_output.len() == 1 {
SignalValue::Scalar(last_output[0])
} else {
SignalValue::Vector(last_output.clone())
}
}
(
BlockKind::DiscreteTransferFunction { sample_time, .. },
BlockState::DiscreteDynamic {
state_space,
x,
time_since_sample,
last_output,
},
) => {
let period = match sample_time {
SampleTimeSpec::Periodic { period, .. } => *period,
SampleTimeSpec::Variable => unreachable!(
"general-mna's parse_required_periodic_sample_time already rejected \
ts=variable for kind=discretetf"
),
};
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= period {
*time_since_sample = 0.0;
let u = require_all_scalar(&block.name, &input_vals)?;
*x = state_space.discrete_step(x, &u);
*last_output = state_space.output(x, &u);
}
SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
}
(
BlockKind::DiscretePid {
pid,
clamp,
sample_time,
},
BlockState::DiscretePid {
state,
time_since_sample,
last_output,
},
) => {
let period = match sample_time {
SampleTimeSpec::Periodic { period, .. } => *period,
SampleTimeSpec::Variable => unreachable!(
"general-mna's parse_required_periodic_sample_time already rejected \
ts=variable for kind=discretepid"
),
};
let scalars = require_all_scalar(&block.name, &input_vals)?;
let (lo, hi) = match clamp {
PidClamp::Fixed(lo, hi) => (*lo, *hi),
PidClamp::Dynamic => (scalars[1], scalars[2]),
};
let error = scalars[0];
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= period {
*time_since_sample = 0.0;
let mut tentative_state = *state;
let tentative_output = pid.step(&mut tentative_state, error);
let saturating_further = (tentative_output >= hi && error > 0.0)
|| (tentative_output <= lo && error < 0.0);
*last_output = if saturating_further {
tentative_output.clamp(lo, hi)
} else {
*state = tentative_state;
tentative_output
};
}
SignalValue::Scalar(*last_output)
}
(BlockKind::Vco(_), BlockState::Vco { vco, phase }) => {
let u = require_all_scalar(&block.name, &input_vals)?;
*phase = vco.step(*phase, u[0], dt);
SignalValue::Scalar(*phase)
}
(
BlockKind::PhaseShiftPwm {
red,
fed,
output_names,
..
},
BlockState::PhaseShiftPwm { osc, phase },
) => {
let u = require_all_scalar(&block.name, &input_vals)?;
let freq_command = u[0];
let phase_offset = u[1];
let duty = u[2];
*phase = osc.step(*phase, freq_command, dt);
let actual_freq = freq_command.clamp(osc.f_min, osc.f_max);
let theta = (*phase + phase_offset).rem_euclid(1.0);
let (main, complement) = math_ops::complementary_pwm_with_deadtime(
theta,
duty,
red * actual_freq,
fed * actual_freq,
);
SignalValue::Scalar(emit_complementary_pair(
&mut outputs,
output_names,
main,
complement,
))
}
(BlockKind::Pmsm { output_names, .. }, BlockState::Pmsm { pmsm, x }) => {
let flat = flatten(&input_vals);
*x = pmsm.step(*x, flat[0], flat[1], flat[2], dt);
let [id, iq, omega_m, theta_e] = *x;
let full = [id, iq, omega_m, Pmsm::theta_e_wrapped(theta_e)];
for (name, v) in output_names.iter().zip(full.iter()).skip(1) {
outputs.insert(name.clone(), SignalValue::Scalar(*v));
}
SignalValue::Scalar(full[0])
}
(BlockKind::Hysteresis(_), BlockState::Hysteresis { hysteresis, on }) => {
let u = require_all_scalar(&block.name, &input_vals)?;
*on = hysteresis.step(*on, u[0]);
SignalValue::Scalar(if *on { 1.0 } else { 0.0 })
}
(BlockKind::LogicGate(op), _) => {
let u = require_all_scalar(&block.name, &input_vals)?;
let bits: Vec<bool> = u.iter().map(|&x| as_bool(x)).collect();
SignalValue::Scalar(from_bool(op.call(&bits)))
}
(BlockKind::SrLatch { priority }, BlockState::SrLatch { q }) => {
let u = require_all_scalar(&block.name, &input_vals)?;
let (set, reset) = (as_bool(u[0]), as_bool(u[1]));
*q = srlatch_next(*q, set, reset, *priority);
SignalValue::Scalar(from_bool(*q))
}
(BlockKind::FlipFlop { kind, .. }, BlockState::FlipFlop { q, prev_clk }) => {
let u = require_all_scalar(&block.name, &input_vals)?;
let clk = u[0];
let data = &u[1..1 + kind.input_count()];
let reset_asserted = u.get(1 + kind.input_count()).is_some_and(|&r| as_bool(r));
if rising_edge(clk, *prev_clk) {
let bits: Vec<bool> = data.iter().map(|&x| as_bool(x)).collect();
*q = if reset_asserted {
false
} else {
kind.next_state(*q, &bits)
};
}
*prev_clk = clk;
SignalValue::Scalar(from_bool(*q))
}
(
BlockKind::Counter {
up_down, modulus, ..
},
BlockState::Counter { count, prev_clk },
) => {
let u = require_all_scalar(&block.name, &input_vals)?;
let clk = u[0];
let mut idx = 1;
let up_down_asserted = if *up_down {
let v = as_bool(u[idx]);
idx += 1;
v
} else {
true };
let reset_asserted = u.get(idx).is_some_and(|&r| as_bool(r));
if rising_edge(clk, *prev_clk) {
if reset_asserted {
*count = 0;
} else if up_down_asserted {
*count += 1;
} else {
*count -= 1;
}
if let Some(m) = modulus {
*count = count.rem_euclid(*m as i64);
}
}
*prev_clk = clk;
SignalValue::Scalar(*count as f64)
}
(
BlockKind::CScript {
output_names,
sample_time,
xc_count,
..
},
BlockState::CScript {
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
},
) => {
let threshold = sample_threshold(sample_time.as_ref(), *next_hit_dt);
let (due, elapsed) = match threshold {
None => (true, dt),
Some(threshold) => {
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= threshold {
let elapsed = *time_since_sample;
*time_since_sample = 0.0;
(true, elapsed)
} else {
(false, 0.0)
}
}
};
if due {
let flat = flatten(&input_vals);
*last_output = if *xc_count > 0 {
*xc = instance.rk4_step_xc(xc, &flat, elapsed);
instance.call_xc(&flat, elapsed, xc, output_names.len())
} else {
instance.call(&flat, elapsed, output_names.len())
};
instance.update(&flat, elapsed, xc);
if matches!(sample_time, Some(SampleTimeSpec::Variable)) {
*next_hit_dt = instance.next_sample_hit(&flat, xc);
}
}
for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
outputs.insert(name.clone(), SignalValue::Scalar(*v));
}
SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
}
#[cfg(feature = "python")]
(
BlockKind::PyBlock {
output_names,
sample_time,
xc_count,
..
},
BlockState::PyBlock {
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
},
) => {
let threshold = sample_threshold(sample_time.as_ref(), *next_hit_dt);
let (due, elapsed) = match threshold {
None => (true, dt),
Some(threshold) => {
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= threshold {
let elapsed = *time_since_sample;
*time_since_sample = 0.0;
(true, elapsed)
} else {
(false, 0.0)
}
}
};
if due {
let py_inputs: Vec<pyblock_ffi::PyInput> = input_vals
.iter()
.map(|v| match v {
SignalValue::Scalar(x) => pyblock_ffi::PyInput::Scalar(*x),
SignalValue::Vector(xs) => pyblock_ffi::PyInput::Vector(xs),
})
.collect();
*last_output = if *xc_count > 0 {
*xc = instance
.rk4_step_xc(xc, t, &py_inputs, elapsed)
.map_err(DaeError::PyBlock)?;
instance
.call_xc(t, elapsed, &py_inputs, xc, output_names.len())
.map_err(DaeError::PyBlock)?
} else {
instance
.call(t, elapsed, &py_inputs, output_names.len())
.map_err(DaeError::PyBlock)?
};
if *xc_count > 0 {
instance
.update_xc(t, elapsed, &py_inputs, xc)
.map_err(DaeError::PyBlock)?;
} else {
instance
.update(t, elapsed, &py_inputs)
.map_err(DaeError::PyBlock)?;
}
if matches!(sample_time, Some(SampleTimeSpec::Variable)) {
*next_hit_dt = if *xc_count > 0 {
instance
.next_sample_hit_xc(t, elapsed, &py_inputs, xc)
.map_err(DaeError::PyBlock)?
} else {
instance
.next_sample_hit(t, elapsed, &py_inputs)
.map_err(DaeError::PyBlock)?
};
}
}
for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
outputs.insert(name.clone(), SignalValue::Scalar(*v));
}
SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
}
#[cfg(feature = "python")]
(
BlockKind::PyFunction {
output_names,
sample_time,
..
},
BlockState::PyFunction {
instance,
time_since_sample,
last_output,
},
) => {
let due = match sample_time {
None => true,
Some(SampleTimeSpec::Variable) => true,
Some(SampleTimeSpec::Periodic { period, .. }) => {
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= *period {
*time_since_sample = 0.0;
true
} else {
false
}
}
};
if due {
let py_inputs: Vec<pyblock_ffi::PyInput> = input_vals
.iter()
.map(|v| match v {
SignalValue::Scalar(x) => pyblock_ffi::PyInput::Scalar(*x),
SignalValue::Vector(xs) => pyblock_ffi::PyInput::Vector(xs),
})
.collect();
*last_output = instance
.call(&py_inputs, output_names.len())
.map_err(DaeError::PyBlock)?;
}
for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
outputs.insert(name.clone(), SignalValue::Scalar(*v));
}
SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
}
(
BlockKind::OctFunc {
output_names,
sample_time,
function,
..
},
BlockState::OctFunction {
session,
time_since_sample,
last_output,
..
},
) => {
let due = match sample_time {
None => true,
Some(SampleTimeSpec::Variable) => true,
Some(SampleTimeSpec::Periodic { period, .. }) => {
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= *period {
*time_since_sample = 0.0;
true
} else {
false
}
}
};
if due {
let flat_inputs = require_all_scalar(&block.name, &input_vals)?;
*last_output = session
.borrow_mut()
.call(function, &flat_inputs, output_names.len())
.map_err(DaeError::Octave)?;
}
for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
outputs.insert(name.clone(), SignalValue::Scalar(*v));
}
SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
}
(
BlockKind::OctBlock {
output_names,
sample_time,
xc_count,
function,
..
},
BlockState::OctBlock {
session,
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
has_update,
},
) => {
let threshold = sample_threshold(sample_time.as_ref(), *next_hit_dt);
let (due, elapsed) = match threshold {
None => (true, dt),
Some(threshold) => {
*time_since_sample += dt;
if *time_since_sample + 1e-15 >= threshold {
let elapsed = *time_since_sample;
*time_since_sample = 0.0;
(true, elapsed)
} else {
(false, 0.0)
}
}
};
if due {
let flat_inputs = require_all_scalar(&block.name, &input_vals)?;
let mut args = Vec::with_capacity(2 + flat_inputs.len());
args.push(t);
args.push(elapsed);
args.extend_from_slice(&flat_inputs);
*last_output = if *xc_count > 0 {
*xc = session
.borrow_mut()
.rk4_step_xc_stateful(
&format!("{function}_derivative"),
instance,
xc,
&flat_inputs,
elapsed,
)
.map_err(DaeError::Octave)?;
session
.borrow_mut()
.call_stateful(
&format!("{function}_output_xc"),
instance,
&args,
Some(xc),
output_names.len(),
)
.map_err(DaeError::Octave)?
} else {
session
.borrow_mut()
.call_stateful(function, instance, &args, None, output_names.len())
.map_err(DaeError::Octave)?
};
if *has_update {
session
.borrow_mut()
.call_stateful(&format!("{function}_update"), instance, &args, None, 0)
.map_err(DaeError::Octave)?;
}
if matches!(sample_time, Some(SampleTimeSpec::Variable)) {
*next_hit_dt = session
.borrow_mut()
.call_readonly_stateful(
&format!("{function}_next_sample_hit"),
instance,
&args,
None,
1,
)
.map_err(DaeError::Octave)?[0];
}
}
for (name, v) in output_names.iter().zip(last_output.iter()).skip(1) {
outputs.insert(name.clone(), SignalValue::Scalar(*v));
}
SignalValue::Scalar(last_output.first().copied().unwrap_or(0.0))
}
_ => unreachable!("BlockState variant always matches its BlockKind"),
};
outputs.insert(block.name.clone(), value);
}
Ok(outputs)
}
pub fn reject_sig2phys_wired_into_circuit(
statements: &[general_spice_core::ast::Statement],
blocks: &[BlockInstance],
) -> Result<(), DaeError> {
let converters: BTreeMap<String, &str> = blocks
.iter()
.filter(|b| matches!(b.kind, BlockKind::Sig2Phys { .. }))
.map(|b| (b.name.to_ascii_lowercase(), b.name.as_str()))
.collect();
if converters.is_empty() {
return Ok(());
}
for statement in statements {
let general_spice_core::ast::Statement::ElementInstance(element) = statement else {
continue;
};
for node in &element.nodes {
if let Some(declared) = converters.get(&node.to_ascii_lowercase()) {
return Err(DaeError::Sig2PhysUsedAsCircuitNode {
block: (*declared).to_string(),
element: element.name.clone(),
node: node.clone(),
});
}
}
}
Ok(())
}
fn resolve_gates(
gates: &BTreeMap<String, GateBinding>,
outputs: &BTreeMap<String, SignalValue>,
) -> BTreeMap<String, GateState> {
gates
.iter()
.map(|(switch_name, binding)| (switch_name.clone(), binding.resolve(outputs)))
.collect()
}
#[allow(clippy::too_many_arguments)]
pub fn simulate_transient_with_blocks(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, IdealSwitch>,
blocks: &[BlockInstance],
gates: &BTreeMap<String, GateBinding>,
shared_r_on: f64,
x_initial: Option<&[f64]>,
t_final: f64,
step: TimeStep,
) -> Result<Vec<TransientWithBlocksStep>, DaeError> {
simulate_transient_with_blocks_capped(
source,
dialect,
diodes,
ideal_switches,
blocks,
gates,
shared_r_on,
x_initial,
t_final,
step,
ADAPTIVE_STEP_HARD_CAP,
)
}
#[allow(clippy::too_many_arguments)]
pub fn simulate_transient_with_blocks_capped(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, IdealSwitch>,
blocks: &[BlockInstance],
gates: &BTreeMap<String, GateBinding>,
shared_r_on: f64,
x_initial: Option<&[f64]>,
t_final: f64,
step: TimeStep,
max_adaptive_steps: usize,
) -> Result<Vec<TransientWithBlocksStep>, DaeError> {
let mut trace = Vec::new();
simulate_transient_with_blocks_streamed(
source,
dialect,
diodes,
ideal_switches,
blocks,
gates,
shared_r_on,
x_initial,
t_final,
step,
max_adaptive_steps,
|t, point, outputs| {
trace.push((t, point, outputs));
Ok(())
},
)?;
Ok(trace)
}
#[allow(clippy::too_many_arguments)]
pub fn simulate_transient_with_blocks_streamed(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, IdealSwitch>,
blocks: &[BlockInstance],
gates: &BTreeMap<String, GateBinding>,
shared_r_on: f64,
x_initial: Option<&[f64]>,
t_final: f64,
step: TimeStep,
max_adaptive_steps: usize,
on_step: impl FnMut(f64, OperatingPoint, BTreeMap<String, SignalValue>) -> Result<(), DaeError>,
) -> Result<(), DaeError> {
simulate_transient_with_blocks_checkpointed(
source,
dialect,
diodes,
ideal_switches,
blocks,
gates,
shared_r_on,
x_initial,
t_final,
step,
max_adaptive_steps,
CheckpointControl::default(),
on_step,
)
.map(|_| ())
}
#[derive(Default)]
pub struct CheckpointControl<'a> {
pub resume: Option<&'a Checkpoint>,
pub every: Option<f64>,
pub on_checkpoint: Option<&'a mut CheckpointSink<'a>>,
pub final_snapshot: bool,
}
pub type CheckpointSink<'a> = dyn FnMut(&Checkpoint) -> Result<(), DaeError> + 'a;
#[allow(clippy::too_many_arguments)]
pub fn simulate_transient_with_blocks_checkpointed(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, IdealSwitch>,
blocks: &[BlockInstance],
gates: &BTreeMap<String, GateBinding>,
shared_r_on: f64,
x_initial: Option<&[f64]>,
t_final: f64,
step: TimeStep,
max_adaptive_steps: usize,
mut checkpoints: CheckpointControl<'_>,
mut on_step: impl FnMut(f64, OperatingPoint, BTreeMap<String, SignalValue>) -> Result<(), DaeError>,
) -> Result<Option<Checkpoint>, DaeError> {
let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
let deck_hash = crate::checkpoint::deck_hash(&[
&statements,
&dialect,
&blocks,
&diodes,
&ideal_switches,
&gates,
&shared_r_on,
]);
let block_names = block_index_by_name(blocks)?;
reject_sig2phys_wired_into_circuit(&statements, blocks)?;
for (switch_name, binding) in gates {
for needed in binding.source_blocks().into_iter().flatten() {
let Some(&idx) = block_names.get(needed) else {
return Err(DaeError::UnknownBlockInput(needed.to_string()));
};
if !matches!(
blocks[idx].kind,
BlockKind::Sig2Phys {
domain: PhysicalDomain::Voltage
}
) {
return Err(DaeError::GateTargetNotSig2Voltage {
gate: switch_name.clone(),
block: needed.to_string(),
found_kind: block_kind_name(&blocks[idx].kind),
});
}
}
}
let order = topological_order(blocks)?;
let initial_states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
.iter()
.map(|(name, m)| (name.clone(), (*m, GateState::Off)))
.collect();
let (system0, all_diodes0) = crate::build_with_ideal_switches(
&statements,
dialect,
diodes,
&initial_states,
shared_r_on,
)?;
for (name, expr) in system0.inputs.iter().zip(&system0.input_values) {
let general_mna::Expression::Symbol(sym) = expr else {
continue;
};
if sym == name || system0.transient_sources.contains_key(name) {
continue;
}
let Some(&idx) = block_names.get(sym.as_str()) else {
continue;
};
let expected = match name.chars().next() {
Some('V') | Some('v') => (
BlockKind::Sig2Phys {
domain: PhysicalDomain::Voltage,
},
"sig2phys(domain=voltage)",
),
Some('I') | Some('i') => (
BlockKind::Sig2Phys {
domain: PhysicalDomain::Current,
},
"sig2phys(domain=current)",
),
_ => continue,
};
if blocks[idx].kind != expected.0 {
return Err(DaeError::SourceNotSig2PhysicalConverter {
source: name.clone(),
block: sym.clone(),
expected_kind: expected.1,
found_kind: block_kind_name(&blocks[idx].kind),
});
}
}
let mut x_prev = crate::resolve_initial_state(&system0, &all_diodes0, x_initial)?;
let mut point_prev = OperatingPoint {
unknowns: system0.unknowns.clone(),
x: x_prev.clone(),
diode_names: Vec::new(),
diode_z: Vec::new(),
diode_raw_ioff: Vec::new(),
};
let mut x_prev_prev: Option<Vec<f64>> = None;
let mut cscript_registry = CScriptRegistry::new();
#[cfg(feature = "python")]
let mut pyblock_registry = pyblock_ffi::PyBlockRegistry::new();
#[cfg(feature = "python")]
let mut pyfunction_registry = pyblock_ffi::PyFunctionRegistry::new();
let mut octave_session: Option<std::rc::Rc<std::cell::RefCell<octave_ffi::OctaveSession>>> =
None;
let mut octave_paths_added: std::collections::BTreeSet<std::path::PathBuf> =
std::collections::BTreeSet::new();
let mut block_states: Vec<BlockState> = Vec::with_capacity(blocks.len());
for b in blocks {
let initial_state = |states: usize| -> Result<Vec<f64>, DaeError> {
match &b.ic {
None => Ok(vec![0.0; states]),
Some(ic) if ic.len() == states => Ok(ic.clone()),
Some(ic) => Err(DaeError::BlockInitialConditionLength {
block: b.name.clone(),
expected: states,
got: ic.len(),
}),
}
};
let dynamic = |state_space: StateSpace| -> Result<BlockState, DaeError> {
let x = initial_state(state_space.states())?;
Ok(BlockState::Dynamic { state_space, x })
};
let state = match &b.kind {
BlockKind::Pid { pid, .. } => dynamic(pid.to_state_space())?,
BlockKind::StateSpace(ss) => dynamic(ss.clone())?,
BlockKind::TransferFunction(tf) => dynamic(tf.to_state_space())?,
BlockKind::DiscreteStateSpace { ss, sample_time } => {
let (period, offset) = match sample_time {
SampleTimeSpec::Periodic { period, offset } => (*period, *offset),
SampleTimeSpec::Variable => unreachable!(
"general-mna's parse_required_periodic_sample_time already rejected \
ts=variable for kind=discretestatespace"
),
};
let x = initial_state(ss.states())?;
BlockState::DiscreteDynamic {
last_output: ss.output(&x, &vec![0.0; ss.inputs()]),
x,
time_since_sample: period - offset,
state_space: ss.clone(),
}
}
BlockKind::DiscreteTransferFunction { tf, sample_time } => {
let (period, offset) = match sample_time {
SampleTimeSpec::Periodic { period, offset } => (*period, *offset),
SampleTimeSpec::Variable => unreachable!(
"general-mna's parse_required_periodic_sample_time already rejected \
ts=variable for kind=discretetf"
),
};
let state_space = tf.to_state_space();
let x = initial_state(state_space.states())?;
BlockState::DiscreteDynamic {
last_output: state_space.output(&x, &[0.0]),
x,
time_since_sample: period - offset,
state_space,
}
}
BlockKind::DiscretePid {
pid, sample_time, ..
} => {
let (period, offset) = match sample_time {
SampleTimeSpec::Periodic { period, offset } => (*period, *offset),
SampleTimeSpec::Variable => unreachable!(
"general-mna's parse_required_periodic_sample_time already rejected \
ts=variable for kind=discretepid"
),
};
let int_state = initial_state(1)?[0];
BlockState::DiscretePid {
state: DiscretePidState {
int_state,
..DiscretePidState::default()
},
time_since_sample: period - offset,
last_output: pid.ki * int_state,
}
}
BlockKind::Vco(vco) => BlockState::Vco {
vco: *vco,
phase: initial_state(1)?[0],
},
BlockKind::PhaseShiftPwm { osc, .. } => BlockState::PhaseShiftPwm {
osc: *osc,
phase: initial_state(1)?[0],
},
BlockKind::Pmsm { pmsm, .. } => {
let x0 = initial_state(4)?;
BlockState::Pmsm {
pmsm: *pmsm,
x: [x0[0], x0[1], x0[2], x0[3]],
}
}
BlockKind::Hysteresis(hysteresis) => BlockState::Hysteresis {
hysteresis: *hysteresis,
on: initial_state(1)?[0] >= 0.5,
},
BlockKind::SrLatch { .. } => BlockState::SrLatch {
q: initial_state(1)?[0] >= 0.5,
},
BlockKind::FlipFlop { .. } => BlockState::FlipFlop {
q: initial_state(1)?[0] >= 0.5,
prev_clk: 0.0,
},
BlockKind::Counter { .. } => BlockState::Counter {
count: initial_state(1)?[0] as i64,
prev_clk: 0.0,
},
BlockKind::CScript {
lib,
output_names,
sample_time,
xc_count,
} => {
let instance = if *xc_count > 0 {
cscript_registry.instantiate_xc(lib)
} else {
cscript_registry.instantiate(lib)
}
.map_err(DaeError::CScript)?;
if matches!(step, TimeStep::Adaptive(_)) && !instance.supports_clone() {
return Err(DaeError::CScriptRequiresCloneForAdaptiveStep {
block_name: b.name.clone(),
});
}
if matches!(sample_time, Some(SampleTimeSpec::Variable))
&& !instance.supports_next_sample_hit()
{
return Err(
DaeError::CScriptRequiresNextSampleHitForVariableSampleTime {
block_name: b.name.clone(),
},
);
}
if let Some(declared) = instance.declared_arity() {
let netlist_inputs = b.inputs.len();
let netlist_outputs = output_names.len();
let inputs_disagree = declared.inputs.is_some_and(|n| n != netlist_inputs);
let outputs_disagree = declared.outputs.is_some_and(|n| n != netlist_outputs);
if inputs_disagree || outputs_disagree {
return Err(DaeError::CScriptArityMismatch {
block_name: b.name.clone(),
declared_inputs: declared.inputs,
declared_outputs: declared.outputs,
netlist_inputs,
netlist_outputs,
});
}
}
BlockState::CScript {
instance,
time_since_sample: match sample_time {
Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
Some(SampleTimeSpec::Variable) | None => 0.0,
},
next_hit_dt: 0.0,
last_output: vec![0.0; output_names.len()],
xc: vec![0.0; *xc_count],
}
}
#[cfg(feature = "python")]
BlockKind::PyBlock {
path,
output_names,
sample_time,
xc_count,
} => {
let instance = if *xc_count > 0 {
pyblock_registry.instantiate_xc(path)
} else {
pyblock_registry.instantiate(path)
}
.map_err(DaeError::PyBlock)?;
if matches!(sample_time, Some(SampleTimeSpec::Variable))
&& !instance.supports_next_sample_hit()
{
return Err(
DaeError::PyBlockRequiresNextSampleHitForVariableSampleTime {
block_name: b.name.clone(),
},
);
}
BlockState::PyBlock {
instance,
time_since_sample: match sample_time {
Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
Some(SampleTimeSpec::Variable) | None => 0.0,
},
next_hit_dt: 0.0,
last_output: vec![0.0; output_names.len()],
xc: vec![0.0; *xc_count],
}
}
#[cfg(not(feature = "python"))]
BlockKind::PyBlock { .. } => {
return Err(DaeError::PythonSupportNotCompiledIn {
block_name: b.name.clone(),
});
}
#[cfg(feature = "python")]
BlockKind::PyFunction {
path,
function,
output_names,
sample_time,
} => {
let instance = pyfunction_registry
.instantiate(path, function)
.map_err(DaeError::PyBlock)?;
BlockState::PyFunction {
instance,
time_since_sample: match sample_time {
Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
Some(SampleTimeSpec::Variable) | None => 0.0,
},
last_output: vec![0.0; output_names.len()],
}
}
#[cfg(not(feature = "python"))]
BlockKind::PyFunction { .. } => {
return Err(DaeError::PythonSupportNotCompiledIn {
block_name: b.name.clone(),
});
}
BlockKind::OctFunc {
path,
output_names,
sample_time,
..
} => {
let session = match &octave_session {
Some(s) => s.clone(),
None => {
let s = octave_ffi::OctaveSession::spawn().map_err(DaeError::Octave)?;
let s = std::rc::Rc::new(std::cell::RefCell::new(s));
octave_session = Some(s.clone());
s
}
};
let dir = match path.canonicalize() {
Ok(abs_file) => abs_file
.parent()
.map(std::path::Path::to_path_buf)
.unwrap_or_else(|| std::path::PathBuf::from(".")),
Err(_) => path
.parent()
.map(std::path::Path::to_path_buf)
.unwrap_or_else(|| std::path::PathBuf::from(".")),
};
if octave_paths_added.insert(dir.clone()) {
session
.borrow_mut()
.add_path(&dir)
.map_err(DaeError::Octave)?;
}
BlockState::OctFunction {
session,
time_since_sample: match sample_time {
Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
Some(SampleTimeSpec::Variable) | None => 0.0,
},
last_output: vec![0.0; output_names.len()],
}
}
BlockKind::OctBlock {
path,
function,
output_names,
sample_time,
xc_count,
} => {
if matches!(step, TimeStep::Adaptive(_)) {
return Err(DaeError::OctBlockDoesNotSupportAdaptiveStep {
block_name: b.name.clone(),
});
}
let session = match &octave_session {
Some(s) => s.clone(),
None => {
let s = octave_ffi::OctaveSession::spawn().map_err(DaeError::Octave)?;
let s = std::rc::Rc::new(std::cell::RefCell::new(s));
octave_session = Some(s.clone());
s
}
};
let dir = match path.canonicalize() {
Ok(abs_dir) => abs_dir,
Err(_) => path.clone(),
};
let required = |role: &str| -> Result<(), DaeError> {
let expected_path = dir.join(format!("{function}_{role}.m"));
if expected_path.is_file() {
Ok(())
} else {
Err(DaeError::OctBlockMissingRequiredFile {
block_name: b.name.clone(),
expected_path,
})
}
};
required("start")?;
if *xc_count > 0 {
required("derivative")?;
required("output_xc")?;
} else {
let expected_path = dir.join(format!("{function}.m"));
if !expected_path.is_file() {
return Err(DaeError::OctBlockMissingRequiredFile {
block_name: b.name.clone(),
expected_path,
});
}
}
if matches!(sample_time, Some(SampleTimeSpec::Variable))
&& !dir.join(format!("{function}_next_sample_hit.m")).is_file()
{
return Err(
DaeError::OctBlockRequiresNextSampleHitForVariableSampleTime {
block_name: b.name.clone(),
},
);
}
let has_update = dir.join(format!("{function}_update.m")).is_file();
if octave_paths_added.insert(dir.clone()) {
session
.borrow_mut()
.add_path(&dir)
.map_err(DaeError::Octave)?;
}
session
.borrow_mut()
.call_start(function, &b.name)
.map_err(DaeError::Octave)?;
BlockState::OctBlock {
session,
instance: b.name.clone(),
time_since_sample: match sample_time {
Some(SampleTimeSpec::Periodic { period, offset }) => period - offset,
Some(SampleTimeSpec::Variable) | None => 0.0,
},
next_hit_dt: 0.0,
last_output: vec![0.0; output_names.len()],
xc: vec![0.0; *xc_count],
has_update,
}
}
_ => BlockState::Stateless,
};
block_states.push(state);
}
let mut prev_diode_raw_ioff: BTreeMap<String, f64> = BTreeMap::new();
let mut prev_segments: Option<Vec<Segment>> = None;
let mut prev_gate_states: Option<BTreeMap<String, GateState>> = None;
let mut ringing_cooldown: u32 = 0;
let mut prev_outputs: BTreeMap<String, SignalValue> = BTreeMap::new();
let mut accepted_steps: usize = 0;
let mut t = 0.0;
let mut step_index = 0usize;
let mut dt_next: Option<f64> = None;
let mut dt_next_final: Option<f64> = None;
if let Some(ckpt) = checkpoints.resume {
if ckpt.deck_hash != deck_hash || ckpt.unknowns != system0.unknowns {
return Err(DaeError::CheckpointDeckMismatch {
unknowns_in_checkpoint: ckpt.unknowns.clone(),
unknowns_in_deck: system0.unknowns.clone(),
});
}
restore_block_states(blocks, &mut block_states, ckpt)?;
x_prev = ckpt.x_prev.clone();
x_prev_prev = ckpt.x_prev_prev.clone();
point_prev = OperatingPoint {
unknowns: system0.unknowns.clone(),
x: ckpt.point_prev.x.clone(),
diode_names: ckpt.point_prev.diode_names.clone(),
diode_z: ckpt.point_prev.diode_z.clone(),
diode_raw_ioff: ckpt.point_prev.diode_raw_ioff.clone(),
};
prev_diode_raw_ioff = ckpt.prev_diode_raw_ioff.clone();
prev_segments = ckpt.prev_segments.as_ref().map(|v| {
v.iter()
.map(|s| match s {
0 => Segment::Breakdown,
1 => Segment::Leakage,
_ => Segment::Forward,
})
.collect()
});
prev_gate_states = ckpt.prev_gate_states.as_ref().map(|m| {
m.iter()
.map(|(k, on)| (k.clone(), if *on { GateState::On } else { GateState::Off }))
.collect()
});
ringing_cooldown = ckpt.ringing_cooldown;
prev_outputs = ckpt
.prev_outputs
.iter()
.map(|(k, v)| {
(
k.clone(),
match v {
SignalSnapshot::Scalar(x) => SignalValue::Scalar(*x),
SignalSnapshot::Vector(x) => SignalValue::Vector(x.clone()),
},
)
})
.collect();
accepted_steps = ckpt.accepted_steps;
step_index = ckpt.step_index;
dt_next = ckpt.dt_next;
t = ckpt.t;
}
let snapshot = |block_states: &[BlockState],
t: f64,
accepted_steps: usize,
step_index: usize,
dt_next: Option<f64>,
ringing_cooldown: u32,
x_prev: &[f64],
x_prev_prev: &Option<Vec<f64>>,
point_prev: &OperatingPoint,
prev_diode_raw_ioff: &BTreeMap<String, f64>,
prev_segments: &Option<Vec<Segment>>,
prev_gate_states: &Option<BTreeMap<String, GateState>>,
prev_outputs: &BTreeMap<String, SignalValue>|
-> Result<Checkpoint, DaeError> {
Ok(Checkpoint {
deck_hash,
unknowns: system0.unknowns.clone(),
t,
accepted_steps,
step_index,
dt_next,
ringing_cooldown,
x_prev: x_prev.to_vec(),
x_prev_prev: x_prev_prev.clone(),
point_prev: PointSnapshot {
x: point_prev.x.clone(),
diode_names: point_prev.diode_names.clone(),
diode_z: point_prev.diode_z.clone(),
diode_raw_ioff: point_prev.diode_raw_ioff.clone(),
},
prev_diode_raw_ioff: prev_diode_raw_ioff.clone(),
prev_segments: prev_segments.as_ref().map(|v| {
v.iter()
.map(|s| match s {
Segment::Breakdown => 0,
Segment::Leakage => 1,
Segment::Forward => 2,
})
.collect()
}),
prev_gate_states: prev_gate_states.as_ref().map(|m| {
m.iter()
.map(|(k, g)| (k.clone(), *g == GateState::On))
.collect()
}),
prev_outputs: prev_outputs
.iter()
.map(|(k, v)| {
(
k.clone(),
match v {
SignalValue::Scalar(x) => SignalSnapshot::Scalar(*x),
SignalValue::Vector(x) => SignalSnapshot::Vector(x.clone()),
},
)
})
.collect(),
blocks: snapshot_block_states(blocks, block_states)?,
})
};
let mut last_checkpoint_t = t;
match step {
TimeStep::Fixed(dt) => {
let steps = ((t_final - t) / dt).round() as usize;
for _ in 0..steps {
t += dt;
let outputs = evaluate_blocks(
blocks,
&order,
&mut block_states,
&point_prev,
&prev_outputs,
t,
dt,
)?;
let gate_states = resolve_gates(gates, &outputs);
let states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
.iter()
.map(|(name, m)| {
(
name.clone(),
(*m, *gate_states.get(name).unwrap_or(&GateState::Off)),
)
})
.collect();
let gate_changed = prev_gate_states.as_ref() != Some(&gate_states);
let forced = step_index == 0 || gate_changed || ringing_cooldown > 0;
let (system, all_diodes) = crate::build_with_ideal_switches(
&statements,
dialect,
diodes,
&states,
shared_r_on,
)?;
let (point, used_backward_euler) = step_with_fallback(
&system,
&statements,
&all_diodes,
x_prev_prev.as_deref(),
&x_prev,
dt,
&prev_diode_raw_ioff,
&prev_segments,
forced,
t,
&scalar_only(&outputs),
&scalar_only(&prev_outputs),
)?;
if used_backward_euler && !forced {
ringing_cooldown = RINGING_COOLDOWN_STEPS;
} else if ringing_cooldown > 0 {
ringing_cooldown = ringing_cooldown.saturating_sub(1);
}
prev_segments = Some(classify_segments(&point));
prev_gate_states = Some(gate_states);
prev_diode_raw_ioff = point
.diode_names
.iter()
.cloned()
.zip(point.diode_raw_ioff.iter().copied())
.collect();
x_prev_prev = Some(std::mem::replace(&mut x_prev, point.x.clone()));
point_prev = point.clone();
prev_outputs = outputs.clone();
match on_step(t, point, outputs) {
Ok(()) => {}
Err(DaeError::StopRequested) => {
step_index += 1;
break;
}
Err(other) => return Err(other),
}
step_index += 1;
if let (Some(every), Some(on_checkpoint)) =
(checkpoints.every, checkpoints.on_checkpoint.as_deref_mut())
{
if t - last_checkpoint_t >= every {
last_checkpoint_t = t;
on_checkpoint(&snapshot(
&block_states,
t,
accepted_steps,
step_index,
None,
ringing_cooldown,
&x_prev,
&x_prev_prev,
&point_prev,
&prev_diode_raw_ioff,
&prev_segments,
&prev_gate_states,
&prev_outputs,
)?)?;
}
}
}
}
TimeStep::Adaptive(config) => {
let mut dt_next = dt_next.unwrap_or(config.dt_init);
while t < t_final {
let mut dt = dt_next.min(t_final - t);
if let Some(event_dt) =
earliest_next_event_dt(blocks, &block_states, &prev_outputs, t)
{
dt = dt.min(event_dt.max(1e-15));
}
loop {
let mut trial_block_states = block_states.clone();
let t_candidate = t + dt;
let outputs = evaluate_blocks(
blocks,
&order,
&mut trial_block_states,
&point_prev,
&prev_outputs,
t_candidate,
dt,
)?;
let gate_states = resolve_gates(gates, &outputs);
let states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
.iter()
.map(|(name, m)| {
(
name.clone(),
(*m, *gate_states.get(name).unwrap_or(&GateState::Off)),
)
})
.collect();
let gate_changed = prev_gate_states.as_ref() != Some(&gate_states);
let forced = step_index == 0 || gate_changed || ringing_cooldown > 0;
let (system, all_diodes) = crate::build_with_ideal_switches(
&statements,
dialect,
diodes,
&states,
shared_r_on,
)?;
let attempt = step_control::lte_attempt(
&system,
&statements,
&all_diodes,
x_prev_prev.as_deref(),
&x_prev,
dt,
&prev_diode_raw_ioff,
&prev_segments,
forced,
&config,
t,
&scalar_only(&outputs),
&scalar_only(&prev_outputs),
)?;
if !attempt.accept {
dt = attempt.suggested_dt_next;
continue;
}
if attempt.used_backward_euler && !forced {
ringing_cooldown = RINGING_COOLDOWN_STEPS;
} else if ringing_cooldown > 0 {
ringing_cooldown = ringing_cooldown.saturating_sub(1);
}
block_states = trial_block_states;
t = t_candidate;
dt_next = attempt.suggested_dt_next;
prev_outputs = outputs.clone();
prev_segments = Some(classify_segments(&attempt.point));
prev_gate_states = Some(gate_states);
prev_diode_raw_ioff = attempt
.point
.diode_names
.iter()
.cloned()
.zip(attempt.point.diode_raw_ioff.iter().copied())
.collect();
x_prev_prev = Some(std::mem::replace(&mut x_prev, attempt.point.x.clone()));
point_prev = attempt.point.clone();
match on_step(t, attempt.point, outputs) {
Ok(()) => {}
Err(DaeError::StopRequested) => {
accepted_steps += 1;
step_index += 1;
break;
}
Err(other) => return Err(other),
}
accepted_steps += 1;
step_index += 1;
if accepted_steps > max_adaptive_steps {
return Err(DaeError::AdaptiveStepStalled {
steps_taken: accepted_steps,
t_reached: t,
t_final,
});
}
if let (Some(every), Some(on_checkpoint)) =
(checkpoints.every, checkpoints.on_checkpoint.as_deref_mut())
{
if t - last_checkpoint_t >= every {
last_checkpoint_t = t;
on_checkpoint(&snapshot(
&block_states,
t,
accepted_steps,
step_index,
Some(dt_next),
ringing_cooldown,
&x_prev,
&x_prev_prev,
&point_prev,
&prev_diode_raw_ioff,
&prev_segments,
&prev_gate_states,
&prev_outputs,
)?)?;
}
}
break;
}
}
dt_next_final = Some(dt_next);
}
}
if !checkpoints.final_snapshot {
return Ok(None);
}
snapshot(
&block_states,
t,
accepted_steps,
step_index,
dt_next_final,
ringing_cooldown,
&x_prev,
&x_prev_prev,
&point_prev,
&prev_diode_raw_ioff,
&prev_segments,
&prev_gate_states,
&prev_outputs,
)
.map(Some)
}
fn snapshot_block_states(
blocks: &[BlockInstance],
block_states: &[BlockState],
) -> Result<Vec<(String, BlockSnapshot)>, DaeError> {
blocks
.iter()
.zip(block_states)
.map(|(b, state)| {
let snap = match state {
BlockState::Stateless => BlockSnapshot::Stateless,
BlockState::Dynamic { x, .. } => BlockSnapshot::Dynamic { x: x.clone() },
BlockState::DiscreteDynamic {
x,
time_since_sample,
last_output,
..
} => BlockSnapshot::DiscreteDynamic {
x: x.clone(),
time_since_sample: *time_since_sample,
last_output: last_output.clone(),
},
BlockState::DiscretePid {
state,
time_since_sample,
last_output,
} => BlockSnapshot::DiscretePid {
int_state: state.int_state,
int_prev_e: state.int_prev_e,
filt_state: state.filt_state,
filt_prev_v: state.filt_prev_v,
time_since_sample: *time_since_sample,
last_output: *last_output,
},
BlockState::Vco { phase, .. } | BlockState::PhaseShiftPwm { phase, .. } => {
BlockSnapshot::Phase(*phase)
}
BlockState::Pmsm { x, .. } => BlockSnapshot::Pmsm { x: x.to_vec() },
BlockState::Hysteresis { on, .. } => BlockSnapshot::Bit(*on),
BlockState::SrLatch { q } => BlockSnapshot::Bit(*q),
BlockState::FlipFlop { q, prev_clk } => BlockSnapshot::FlipFlop {
q: *q,
prev_clk: *prev_clk,
},
BlockState::Counter { count, prev_clk } => BlockSnapshot::Counter {
count: *count,
prev_clk: *prev_clk,
},
BlockState::CScript {
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
} => {
if !instance.supports_state_io() {
return Err(DaeError::CheckpointUnsupportedBlock {
block: b.name.clone(),
kind: "cscript",
});
}
BlockSnapshot::CScript {
time_since_sample: *time_since_sample,
next_hit_dt: *next_hit_dt,
last_output: last_output.clone(),
xc: xc.clone(),
state: instance.state_bytes().map_err(DaeError::CScript)?,
}
}
BlockState::OctBlock {
session,
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
..
} => BlockSnapshot::OctBlock {
time_since_sample: *time_since_sample,
next_hit_dt: *next_hit_dt,
last_output: last_output.clone(),
xc: xc.clone(),
state: session
.borrow_mut()
.save_state(instance)
.map_err(DaeError::Octave)?,
},
BlockState::OctFunction {
time_since_sample,
last_output,
..
} => BlockSnapshot::SampledFunction {
time_since_sample: *time_since_sample,
last_output: last_output.clone(),
},
#[cfg(feature = "python")]
BlockState::PyFunction {
time_since_sample,
last_output,
..
} => BlockSnapshot::SampledFunction {
time_since_sample: *time_since_sample,
last_output: last_output.clone(),
},
#[cfg(feature = "python")]
BlockState::PyBlock {
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
} => BlockSnapshot::PyBlock {
time_since_sample: *time_since_sample,
next_hit_dt: *next_hit_dt,
last_output: last_output.clone(),
xc: xc.clone(),
state: instance.pickle_state().map_err(DaeError::PyBlock)?,
},
};
Ok((b.name.clone(), snap))
})
.collect()
}
fn restore_block_states(
blocks: &[BlockInstance],
block_states: &mut [BlockState],
ckpt: &Checkpoint,
) -> Result<(), DaeError> {
let corrupt = |name: &str| {
DaeError::CheckpointFormat(format!(
"block '{name}': the checkpoint's state does not match this block's kind"
))
};
if ckpt.blocks.len() != blocks.len() {
return Err(DaeError::CheckpointFormat(format!(
"checkpoint holds {} block state(s), deck declares {}",
ckpt.blocks.len(),
blocks.len()
)));
}
for ((b, state), (name, snap)) in blocks.iter().zip(block_states).zip(&ckpt.blocks) {
if *name != b.name {
return Err(corrupt(&b.name));
}
match (state, snap) {
(BlockState::Stateless, BlockSnapshot::Stateless) => {}
(BlockState::Dynamic { x, .. }, BlockSnapshot::Dynamic { x: sx })
if x.len() == sx.len() =>
{
x.clone_from(sx);
}
(
BlockState::DiscreteDynamic {
x,
time_since_sample,
last_output,
..
},
BlockSnapshot::DiscreteDynamic {
x: sx,
time_since_sample: st,
last_output: so,
},
) if x.len() == sx.len() => {
x.clone_from(sx);
*time_since_sample = *st;
last_output.clone_from(so);
}
(
BlockState::DiscretePid {
state,
time_since_sample,
last_output,
},
BlockSnapshot::DiscretePid {
int_state,
int_prev_e,
filt_state,
filt_prev_v,
time_since_sample: st,
last_output: so,
},
) => {
*state = DiscretePidState {
int_state: *int_state,
int_prev_e: *int_prev_e,
filt_state: *filt_state,
filt_prev_v: *filt_prev_v,
};
*time_since_sample = *st;
*last_output = *so;
}
(BlockState::Vco { phase, .. }, BlockSnapshot::Phase(p))
| (BlockState::PhaseShiftPwm { phase, .. }, BlockSnapshot::Phase(p)) => {
*phase = *p;
}
(BlockState::Pmsm { x, .. }, BlockSnapshot::Pmsm { x: sx }) if sx.len() == 4 => {
x.copy_from_slice(sx);
}
(BlockState::Hysteresis { on, .. }, BlockSnapshot::Bit(b)) => *on = *b,
(BlockState::SrLatch { q }, BlockSnapshot::Bit(b)) => *q = *b,
(
BlockState::FlipFlop { q, prev_clk },
BlockSnapshot::FlipFlop {
q: sq,
prev_clk: sp,
},
) => {
*q = *sq;
*prev_clk = *sp;
}
(
BlockState::Counter { count, prev_clk },
BlockSnapshot::Counter {
count: sc,
prev_clk: sp,
},
) => {
*count = *sc;
*prev_clk = *sp;
}
(
BlockState::OctFunction {
time_since_sample,
last_output,
..
},
BlockSnapshot::SampledFunction {
time_since_sample: st,
last_output: so,
},
) => {
*time_since_sample = *st;
last_output.clone_from(so);
}
#[cfg(feature = "python")]
(
BlockState::PyFunction {
time_since_sample,
last_output,
..
},
BlockSnapshot::SampledFunction {
time_since_sample: st,
last_output: so,
},
) => {
*time_since_sample = *st;
last_output.clone_from(so);
}
#[cfg(feature = "python")]
(
BlockState::PyBlock {
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
},
BlockSnapshot::PyBlock {
time_since_sample: st,
next_hit_dt: sn,
last_output: so,
xc: sxc,
state: bytes,
},
) => {
instance.restore_state(bytes).map_err(DaeError::PyBlock)?;
*time_since_sample = *st;
*next_hit_dt = *sn;
last_output.clone_from(so);
xc.clone_from(sxc);
}
(
BlockState::CScript {
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
},
BlockSnapshot::CScript {
time_since_sample: st,
next_hit_dt: sn,
last_output: so,
xc: sxc,
state: bytes,
},
) => {
if !instance.supports_state_io() {
return Err(DaeError::CheckpointUnsupportedBlock {
block: b.name.clone(),
kind: "cscript",
});
}
instance.restore_state(bytes).map_err(DaeError::CScript)?;
*time_since_sample = *st;
*next_hit_dt = *sn;
last_output.clone_from(so);
xc.clone_from(sxc);
}
(
BlockState::OctBlock {
session,
instance,
time_since_sample,
next_hit_dt,
last_output,
xc,
..
},
BlockSnapshot::OctBlock {
time_since_sample: st,
next_hit_dt: sn,
last_output: so,
xc: sxc,
state: bytes,
},
) => {
session
.borrow_mut()
.load_state(instance, bytes)
.map_err(DaeError::Octave)?;
*time_since_sample = *st;
*next_hit_dt = *sn;
last_output.clone_from(so);
xc.clone_from(sxc);
}
_ => return Err(corrupt(&b.name)),
}
}
Ok(())
}
#[cfg(test)]
mod next_pwm_edge_dt_tests {
use super::next_pwm_edge_dt;
#[test]
fn landing_exactly_on_a_threshold_reports_a_full_period_not_zero() {
let freq = 600_000.0;
let duty = 0.4;
let red_frac = 0.0;
let fed_frac = 0.0;
let dt = next_pwm_edge_dt(duty, duty, red_frac, fed_frac, freq)
.expect("finite freq must always report a next-edge estimate");
let half_period = 0.5 / freq;
assert!(
dt > half_period,
"landing exactly on duty's own threshold must report ~a full period away \
({half_period:.3e}s expected), not ~0 (got {dt:.3e}s) -- ~0 is exactly the bug \
that stalled the adaptive loop and exhausted memory on a real run",
);
}
#[test]
fn landing_a_few_ulps_past_a_threshold_also_reports_a_full_period_not_zero() {
let freq = 300_000.0;
let red_frac = 0.1;
let theta_now = red_frac + 4.0 * f64::EPSILON;
let dt = next_pwm_edge_dt(theta_now, red_frac, red_frac, 0.0, freq)
.expect("finite freq must always report a next-edge estimate");
let half_period = 0.5 / freq;
assert!(
dt > half_period,
"landing a few ULPs past red_frac must report ~a full period away \
({half_period:.3e}s expected), not ~0 (got {dt:.3e}s)",
);
}
#[test]
fn a_threshold_genuinely_ahead_reports_the_real_distance() {
let freq = 100_000.0; let theta_now = 0.1;
let duty = 0.4; let dt = next_pwm_edge_dt(theta_now, duty, 0.0, 0.0, freq).unwrap();
let expected = 0.3 / freq;
assert!(
(dt - expected).abs() < 1e-9 / freq,
"expected ~{expected:.3e}s, got {dt:.3e}s"
);
}
}