mod block_graph;
pub mod checkpoint;
mod closed_loop;
mod linsolve;
mod step_control;
mod topology;
pub use block_graph::{
reject_sig2phys_wired_into_circuit, simulate_transient_with_blocks,
simulate_transient_with_blocks_capped, simulate_transient_with_blocks_checkpointed,
simulate_transient_with_blocks_streamed, BlockInstance, BlockKind, CheckpointControl,
CheckpointSink, ConstValue, GainValue, GateBinding, Phys2SigTarget, PhysicalDomain, PidClamp,
SampleTimeSpec, Signal, SignalValue, TransientWithBlocksStep, ADAPTIVE_STEP_HARD_CAP,
};
pub use closed_loop::{sawtooth_carrier, simulate_closed_loop};
pub use step_control::{AdaptiveConfig, TimeStep};
use std::collections::BTreeMap;
use general_mna::{
BuildError, BuildOptions, EvaluationError, Expression, InitialStateError, MnaBuilder, MnaSystem,
};
use general_spice_core::ast::Statement;
use general_spice_core::Dialect;
use lcp_solver::LcpError;
use linsolve::{dense_solve, SingularMatrix};
use pwl_devices::{IdealDiode, IdealSwitch};
pub use general_mna::SwitchState as GateState;
pub use general_mna::TransientFunction;
#[derive(Debug, Clone, PartialEq)]
pub struct OperatingPoint {
pub unknowns: Vec<String>,
pub x: Vec<f64>,
pub diode_names: Vec<String>,
pub diode_z: Vec<(f64, f64)>,
pub diode_raw_ioff: Vec<f64>,
}
impl OperatingPoint {
pub fn value(&self, unknown: &str) -> Option<f64> {
self.unknowns
.iter()
.position(|name| name == unknown)
.map(|index| self.x[index])
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum DaeError {
Parse(String),
Io(String),
StopRequested,
Build(BuildError),
InitialCondition(InitialStateError),
Evaluate(EvaluationError),
Linear(SingularMatrix),
Lcp(LcpError),
UnknownDiodeInput(String),
UnknownBlockInput(String),
AlgebraicLoop {
cycle: Vec<String>,
},
CScript(cscript_ffi::CScriptError),
CScriptRequiresCloneForAdaptiveStep {
block_name: String,
},
CScriptRequiresNextSampleHitForVariableSampleTime {
block_name: String,
},
CScriptArityMismatch {
block_name: String,
declared_inputs: Option<usize>,
declared_outputs: Option<usize>,
netlist_inputs: usize,
netlist_outputs: usize,
},
#[cfg(feature = "python")]
PyBlockRequiresNextSampleHitForVariableSampleTime {
block_name: String,
},
#[cfg(feature = "python")]
PyBlock(pyblock_ffi::PyBlockError),
PythonSupportNotCompiledIn {
block_name: String,
},
Octave(octave_ffi::OctaveError),
OctBlockMissingRequiredFile {
block_name: String,
expected_path: std::path::PathBuf,
},
OctBlockRequiresNextSampleHitForVariableSampleTime {
block_name: String,
},
OctBlockDoesNotSupportAdaptiveStep {
block_name: String,
},
AdaptiveStepStalled {
steps_taken: usize,
t_reached: f64,
t_final: f64,
},
GateTargetNotSig2Voltage {
gate: String,
block: String,
found_kind: &'static str,
},
SourceNotSig2PhysicalConverter {
source: String,
block: String,
expected_kind: &'static str,
found_kind: &'static str,
},
Sig2PhysUsedAsCircuitNode {
block: String,
element: String,
node: String,
},
DuplicateBlockName(String),
CheckpointFormat(String),
CheckpointIo {
path: std::path::PathBuf,
message: String,
},
CheckpointDeckMismatch {
unknowns_in_checkpoint: Vec<String>,
unknowns_in_deck: Vec<String>,
},
CheckpointUnsupportedBlock {
block: String,
kind: &'static str,
},
BlockInitialConditionLength {
block: String,
expected: usize,
got: usize,
},
VectorSignalNotSupported {
block: String,
},
VectorSignalSizeMismatch {
block: String,
expected: usize,
got: usize,
},
}
pub fn solve_dc(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
) -> Result<OperatingPoint, DaeError> {
let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
let system = MnaBuilder::new(dialect)
.build_statements(&statements)
.map_err(DaeError::Build)?;
fold_and_solve(
&system,
&statements,
diodes,
&Scheme::Dc,
0.0,
&BTreeMap::new(),
&BTreeMap::new(),
)
}
enum Scheme<'a> {
Dc,
BackwardEuler { x_prev: &'a [f64], dt: f64 },
Trapezoidal {
x_prev: &'a [f64],
dt: f64,
prev_diode_raw_ioff: &'a BTreeMap<String, f64>,
},
}
pub(crate) fn resolve_initial_state(
system: &MnaSystem,
diodes: &BTreeMap<String, IdealDiode>,
x_initial: Option<&[f64]>,
) -> Result<Vec<f64>, DaeError> {
if let Some(x) = x_initial {
return Ok(x.to_vec());
}
let mut values = BTreeMap::new();
for (name, diode) in diodes {
values.insert(format!("{name}_G"), diode.g_off);
values.insert(format!("{name}_Ioff"), 0.0);
}
for (name, transient_fn) in &system.transient_sources {
values.insert(name.clone(), transient_fn.value_at(0.0));
}
match system
.initial_state(&values, general_mna::DEFAULT_INITIAL_STATE_TOLERANCE)
.map_err(DaeError::InitialCondition)?
{
Some(x) => Ok(x),
None => Ok(vec![0.0; system.order()]),
}
}
pub fn simulate_transient(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
x_initial: Option<&[f64]>,
t_final: f64,
step: TimeStep,
) -> Result<Vec<(f64, OperatingPoint)>, DaeError> {
let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
let system = MnaBuilder::new(dialect)
.build_statements(&statements)
.map_err(DaeError::Build)?;
let mut x_prev = resolve_initial_state(&system, diodes, x_initial)?;
let mut x_prev_prev: Option<Vec<f64>> = None;
let mut prev_diode_raw_ioff: BTreeMap<String, f64> = BTreeMap::new();
let mut prev_segments: Option<Vec<Segment>> = None;
let mut ringing_cooldown: u32 = 0;
let mut trace = Vec::new();
let mut t = 0.0;
match step {
TimeStep::Fixed(dt) => {
let steps = (t_final / dt).round() as usize;
trace.reserve(steps);
for step_index in 0..steps {
t += dt;
let forced = step_index == 0 || ringing_cooldown > 0;
let (point, used_backward_euler) = step_with_fallback(
&system,
&statements,
diodes,
x_prev_prev.as_deref(),
&x_prev,
dt,
&prev_diode_raw_ioff,
&prev_segments,
forced,
t,
&BTreeMap::new(),
&BTreeMap::new(),
)?;
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_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()));
trace.push((t, point));
}
}
TimeStep::Adaptive(config) => {
let mut dt_next = config.dt_init;
let mut step_index = 0usize;
while t < t_final {
let dt_trial = dt_next.min(t_final - t);
let forced = step_index == 0 || ringing_cooldown > 0;
let (point, used_backward_euler, dt_used, next_dt) = step_control::adaptive_step(
&system,
&statements,
diodes,
x_prev_prev.as_deref(),
&x_prev,
dt_trial,
&prev_diode_raw_ioff,
&prev_segments,
forced,
&config,
t,
)?;
if used_backward_euler && !forced {
ringing_cooldown = RINGING_COOLDOWN_STEPS;
} else if ringing_cooldown > 0 {
ringing_cooldown = ringing_cooldown.saturating_sub(1);
}
t += dt_used;
dt_next = next_dt;
prev_segments = Some(classify_segments(&point));
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()));
trace.push((t, point));
step_index += 1;
}
}
}
Ok(trace)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Segment {
Breakdown,
Leakage,
Forward,
}
fn classify_segments(point: &OperatingPoint) -> Vec<Segment> {
point
.diode_z
.iter()
.map(|&(z1, z2)| {
if z1 > 1e-9 {
Segment::Breakdown
} else if z2 > 1e-9 {
Segment::Forward
} else {
Segment::Leakage
}
})
.collect()
}
fn is_ringing(x_prev_prev: &[f64], x_prev: &[f64], trial: &[f64]) -> bool {
const NOISE_FLOOR: f64 = 1e-9;
x_prev_prev
.iter()
.zip(x_prev)
.zip(trial)
.any(|((&a, &b), &c)| {
if a.abs() < NOISE_FLOOR || b.abs() < NOISE_FLOOR || c.abs() < NOISE_FLOOR {
return false;
}
let alternating = (a > 0.0) == (c > 0.0) && (a > 0.0) != (b > 0.0);
alternating && c.abs() >= b.abs() * 0.9
})
}
const RINGING_COOLDOWN_STEPS: u32 = 3;
#[allow(clippy::too_many_arguments)]
fn step_with_fallback(
system: &MnaSystem,
statements: &[Statement],
diodes: &BTreeMap<String, IdealDiode>,
x_prev_prev: Option<&[f64]>,
x_prev: &[f64],
dt: f64,
prev_diode_raw_ioff: &BTreeMap<String, f64>,
prev_segments: &Option<Vec<Segment>>,
force_backward_euler: bool,
t: f64,
extra_values: &BTreeMap<String, f64>,
extra_values_prev: &BTreeMap<String, f64>,
) -> Result<(OperatingPoint, bool), DaeError> {
if force_backward_euler {
return fold_and_solve(
system,
statements,
diodes,
&Scheme::BackwardEuler { x_prev, dt },
t,
extra_values,
extra_values_prev,
)
.map(|point| (point, true));
}
let trial = fold_and_solve(
system,
statements,
diodes,
&Scheme::Trapezoidal {
x_prev,
dt,
prev_diode_raw_ioff,
},
t,
extra_values,
extra_values_prev,
)?;
let trial_segments = classify_segments(&trial);
let segments_changed = Some(&trial_segments) != prev_segments.as_ref();
let ringing = x_prev_prev.is_some_and(|xpp| is_ringing(xpp, x_prev, &trial.x));
if segments_changed || ringing {
fold_and_solve(
system,
statements,
diodes,
&Scheme::BackwardEuler { x_prev, dt },
t,
extra_values,
extra_values_prev,
)
.map(|point| (point, true))
} else {
Ok((trial, false))
}
}
pub fn solve_dc_with_ideal_switches(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, (IdealSwitch, GateState)>,
shared_r_on: f64,
) -> Result<OperatingPoint, DaeError> {
let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
let (system, all_diodes) =
build_with_ideal_switches(&statements, dialect, diodes, ideal_switches, shared_r_on)?;
fold_and_solve(
&system,
&statements,
&all_diodes,
&Scheme::Dc,
0.0,
&BTreeMap::new(),
&BTreeMap::new(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn simulate_transient_with_ideal_switches(
source: &str,
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, IdealSwitch>,
gate_signal: impl Fn(&str, f64) -> GateState,
shared_r_on: f64,
x_initial: Option<&[f64]>,
t_final: f64,
dt: f64,
) -> Result<Vec<(f64, OperatingPoint)>, DaeError> {
let states_at = |t: f64| -> BTreeMap<String, (IdealSwitch, GateState)> {
ideal_switches
.iter()
.map(|(name, m)| (name.clone(), (*m, gate_signal(name, t))))
.collect()
};
let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
let (system0, _) =
build_with_ideal_switches(&statements, dialect, diodes, &states_at(0.0), shared_r_on)?;
let mut x_prev = resolve_initial_state(&system0, diodes, x_initial)?;
let mut x_prev_prev: Option<Vec<f64>> = None;
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 steps = (t_final / dt).round() as usize;
let mut trace = Vec::with_capacity(steps);
let mut t = 0.0;
for step_index in 0..steps {
t += dt;
let states = states_at(t);
let gate_states: BTreeMap<String, GateState> = states
.iter()
.map(|(name, (_, state))| (name.clone(), *state))
.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) =
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,
&BTreeMap::new(),
&BTreeMap::new(),
)?;
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()));
trace.push((t, point));
}
Ok(trace)
}
fn build_with_ideal_switches(
statements: &[Statement],
dialect: Dialect,
diodes: &BTreeMap<String, IdealDiode>,
ideal_switches: &BTreeMap<String, (IdealSwitch, GateState)>,
shared_r_on: f64,
) -> Result<(MnaSystem, BTreeMap<String, IdealDiode>), DaeError> {
let mut options = BuildOptions {
on_resistance: Expression::Constant(shared_r_on),
..BuildOptions::default()
};
let mut all_diodes = diodes.clone();
for (name, (switch, state)) in ideal_switches {
match state {
GateState::On => options.set_switch(name, GateState::On),
GateState::Off => {
all_diodes.insert(name.clone(), switch.body_diode_for_drain_source_stamping());
}
}
}
let system = MnaBuilder::with_options(dialect, options)
.build_statements(statements)
.map_err(DaeError::Build)?;
Ok((system, all_diodes))
}
#[allow(clippy::too_many_arguments)]
fn fold_and_solve(
system: &MnaSystem,
statements: &[Statement],
diodes: &BTreeMap<String, IdealDiode>,
scheme: &Scheme,
t: f64,
extra_values: &BTreeMap<String, f64>,
extra_values_prev: &BTreeMap<String, f64>,
) -> Result<OperatingPoint, DaeError> {
let nodes = topology::diode_nodes(statements);
let order = system.order();
let mut base_values = BTreeMap::new();
for (name, diode) in diodes {
base_values.insert(format!("{name}_G"), diode.g_off);
base_values.insert(format!("{name}_Ioff"), 0.0);
}
for (name, transient_fn) in &system.transient_sources {
base_values.insert(name.clone(), transient_fn.value_at(t));
}
for (name, value) in extra_values {
base_values.insert(name.clone(), *value);
}
let numeric0 = system.evaluate(&base_values).map_err(DaeError::Evaluate)?;
let (a_eff, u_eff_base, coupling_scale): (general_mna::Matrix<f64>, Vec<f64>, f64) =
match scheme {
Scheme::Dc => (numeric0.a.clone(), numeric0.u.clone(), 1.0),
Scheme::BackwardEuler { x_prev, dt } => {
let mut a_eff = numeric0.a.clone();
for row in 0..order {
for col in 0..order {
a_eff[(row, col)] += numeric0.k[(row, col)] / dt;
}
}
let u_eff: Vec<f64> = (0..order)
.map(|row| {
let k_x: f64 = (0..order)
.map(|col| numeric0.k[(row, col)] * x_prev[col])
.sum();
numeric0.u[row] + k_x / dt
})
.collect();
(a_eff, u_eff, 1.0)
}
Scheme::Trapezoidal { x_prev, dt, .. } => {
let mut a_eff = numeric0.a.clone();
for row in 0..order {
for col in 0..order {
a_eff[(row, col)] = a_eff[(row, col)] / 2.0 + numeric0.k[(row, col)] / dt;
}
}
let u_prev: Vec<f64> =
if system.transient_sources.is_empty() && extra_values_prev.is_empty() {
numeric0.u.clone()
} else {
let mut base_values_prev = base_values.clone();
for (name, transient_fn) in &system.transient_sources {
base_values_prev.insert(name.clone(), transient_fn.value_at(t - dt));
}
for (name, value) in extra_values_prev {
base_values_prev.insert(name.clone(), *value);
}
system
.evaluate(&base_values_prev)
.map_err(DaeError::Evaluate)?
.u
};
let u_eff: Vec<f64> = (0..order)
.map(|row| {
let k_x: f64 = (0..order)
.map(|col| numeric0.k[(row, col)] * x_prev[col])
.sum();
let a_x: f64 = (0..order)
.map(|col| numeric0.a[(row, col)] * x_prev[col])
.sum();
(numeric0.u[row] + u_prev[row]) / 2.0 + k_x / dt - a_x / 2.0
})
.collect();
(a_eff, u_eff, 0.5)
}
};
struct DiodeInfo {
name: String,
canonical: pwl_devices::IdealDiodeCanonical,
p: Option<usize>,
n: Option<usize>,
w: Vec<f64>,
}
let mut u_eff = u_eff_base;
let mut infos = Vec::with_capacity(diodes.len());
for (name, diode) in diodes {
let column = system
.inputs
.iter()
.position(|input| input == name)
.ok_or_else(|| DaeError::UnknownDiodeInput(name.clone()))?;
let b_col: Vec<f64> = (0..order).map(|row| numeric0.b[(row, column)]).collect();
if let Scheme::Trapezoidal {
prev_diode_raw_ioff,
..
} = scheme
{
if let Some(&prev_ioff) = prev_diode_raw_ioff.get(name) {
for (row, &b) in b_col.iter().enumerate() {
u_eff[row] += 0.5 * b * prev_ioff;
}
}
}
let w = dense_solve(&a_eff, &b_col).map_err(DaeError::Linear)?;
let terminals = &nodes[name];
let p = topology::node_index(&system.unknowns, &terminals.positive);
let n = topology::node_index(&system.unknowns, &terminals.negative);
infos.push(DiodeInfo {
name: name.clone(),
canonical: diode.canonical(),
p,
n,
w,
});
}
let x0 = dense_solve(&a_eff, &u_eff).map_err(DaeError::Linear)?;
let get = |x: &[f64], index: Option<usize>| index.map(|i| x[i]).unwrap_or(0.0);
let n_diodes = infos.len();
let v0: Vec<f64> = infos
.iter()
.map(|d| get(&x0, d.p) - get(&x0, d.n))
.collect();
let gamma: Vec<Vec<f64>> = infos
.iter()
.map(|k| {
infos
.iter()
.map(|j| get(&j.w, k.p) - get(&j.w, k.n))
.collect()
})
.collect();
let dim = 2 * n_diodes;
let mut m = vec![vec![0.0; dim]; dim];
let mut q = vec![0.0; dim];
for k in 0..n_diodes {
let row_w1 = 2 * k;
q[row_w1] = v0[k] - infos[k].canonical.v_breakdown;
for (j, info_j) in infos.iter().enumerate() {
m[row_w1][2 * j] += -gamma[k][j] * info_j.canonical.delta_br * coupling_scale;
m[row_w1][2 * j + 1] += gamma[k][j] * info_j.canonical.delta_on * coupling_scale;
}
m[row_w1][2 * k] += 1.0;
let row_w2 = 2 * k + 1;
q[row_w2] = infos[k].canonical.v_f - v0[k];
for (j, info_j) in infos.iter().enumerate() {
m[row_w2][2 * j] += gamma[k][j] * info_j.canonical.delta_br * coupling_scale;
m[row_w2][2 * j + 1] += -gamma[k][j] * info_j.canonical.delta_on * coupling_scale;
}
m[row_w2][2 * k + 1] += 1.0;
}
let sol = lcp_solver::solve(&m, &q).map_err(DaeError::Lcp)?;
let mut x = x0;
let mut diode_z = Vec::with_capacity(n_diodes);
let mut diode_raw_ioff = Vec::with_capacity(n_diodes);
for (k, info) in infos.iter().enumerate() {
let z1 = sol.z[2 * k];
let z2 = sol.z[2 * k + 1];
let raw_ioff = info.canonical.delta_on * z2 - info.canonical.delta_br * z1;
let x_contribution = raw_ioff * coupling_scale;
for (xi, wi) in x.iter_mut().zip(info.w.iter()) {
*xi += wi * x_contribution;
}
diode_z.push((z1, z2));
diode_raw_ioff.push(raw_ioff);
}
Ok(OperatingPoint {
unknowns: system.unknowns.clone(),
x,
diode_names: infos.into_iter().map(|d| d.name).collect(),
diode_z,
diode_raw_ioff,
})
}
#[cfg(test)]
mod scheme_tests {
use super::*;
enum Kind {
BackwardEuler,
Trapezoidal,
}
fn rc_final_error(kind: &Kind, dt: f64, t_final: f64) -> f64 {
let source = "V1 a 0 5\nR1 a b 1\nC1 b 0 1";
let statements = general_mna::parse_and_flatten(source, Dialect::Ngspice).unwrap();
let system = MnaBuilder::new(Dialect::Ngspice)
.build_statements(&statements)
.unwrap();
let diodes = BTreeMap::new();
let steps = (t_final / dt).round() as usize;
let mut x = vec![0.0; system.order()];
for step in 0..steps {
let t = (step + 1) as f64 * dt;
let use_be = matches!(kind, Kind::BackwardEuler) || step == 0;
let point = if use_be {
fold_and_solve(
&system,
&statements,
&diodes,
&Scheme::BackwardEuler { x_prev: &x, dt },
t,
&BTreeMap::new(),
&BTreeMap::new(),
)
} else {
fold_and_solve(
&system,
&statements,
&diodes,
&Scheme::Trapezoidal {
x_prev: &x,
dt,
prev_diode_raw_ioff: &BTreeMap::new(),
},
t,
&BTreeMap::new(),
&BTreeMap::new(),
)
}
.unwrap();
x = point.x;
}
let vb_index = system.unknowns.iter().position(|u| u == "V(b)").unwrap();
let expected = 5.0 * (1.0 - (-t_final).exp());
(x[vb_index] - expected).abs()
}
#[test]
fn backward_euler_error_roughly_halves_when_dt_halves() {
let t_final = 2.0;
let error_coarse = rc_final_error(&Kind::BackwardEuler, 0.1, t_final);
let error_fine = rc_final_error(&Kind::BackwardEuler, 0.05, t_final);
let ratio = error_coarse / error_fine;
assert!(
(1.7..=2.3).contains(&ratio),
"backward-Euler error ratio (dt vs dt/2) = {ratio}, expected close to 2.0 (first-order)"
);
}
#[test]
fn trapezoidal_error_roughly_quarters_when_dt_halves() {
let t_final = 2.0;
let error_coarse = rc_final_error(&Kind::Trapezoidal, 0.1, t_final);
let error_fine = rc_final_error(&Kind::Trapezoidal, 0.05, t_final);
let ratio = error_coarse / error_fine;
assert!(
(3.0..=5.5).contains(&ratio),
"trapezoidal error ratio (dt vs dt/2) = {ratio}, expected close to 4.0 (second-order)"
);
}
#[test]
fn trapezoidal_is_more_accurate_than_backward_euler_at_the_same_dt() {
let t_final = 2.0;
let dt = 0.1;
let error_be = rc_final_error(&Kind::BackwardEuler, dt, t_final);
let error_tr = rc_final_error(&Kind::Trapezoidal, dt, t_final);
assert!(
error_tr < error_be / 10.0,
"trapezoidal error {error_tr} should be well under backward-Euler error {error_be} at dt={dt}"
);
}
}