use std::fs;
use std::path::PathBuf;
use std::process::Command;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("gs-rules-{}", std::process::id()));
fs::create_dir_all(&dir).expect("scratch dir");
dir.join(name)
}
fn write(name: &str, contents: &str) -> PathBuf {
let path = scratch(name);
fs::write(&path, contents).expect("writing the netlist");
path
}
fn run(args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_general-simulator"))
.args(args)
.output()
.expect("failed to run general-simulator binary")
}
const BUCK: &str = "\
VIN vin 0 12
DSW vin sw idealswitchmodel
DSW kind=ideal_switch r_on=0.05 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=5 gate=block ctrl=GATE
D1 0 sw dmodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=5
L1 sw out 22e-6
C1 out 0 47e-6 ic=3
RL out 0 4
VOUT kind=phys2sig node=out
REF kind=const value=5
ERR kind=sum inputs=REF,VOUT signs=1,-1
PI kind=pid in=ERR kp=0.02 ki=50 kd=0 n=100 clamp_lo=0.05 clamp_hi=0.95 ic=0.4
PWM1 kind=pwm freq=100000 in=PI
GATE kind=sig2phys domain=voltage in=PWM1
";
const SHOOT_THROUGH_LEG: &str = "\
VIN vin 0 400
DSH vin mid idealswitchmodel
DSH kind=ideal_switch r_on=0.01 body_g_breakdown=0 body_v_breakdown=-1000 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GH
DSL mid 0 idealswitchmodel
DSL kind=ideal_switch r_on=0.01 body_g_breakdown=0 body_v_breakdown=-1000 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GL
L1 mid out 1e-3
R1 out 0 10
DUTY kind=const value=0.4
ONE kind=const value=1
COMP kind=sum inputs=ONE,DUTY signs=1,-1
PWMH kind=pwm freq=20000 in=DUTY
PWML kind=pwm freq=20000 in=COMP
GH kind=sig2phys domain=voltage in=PWMH
GL kind=sig2phys domain=voltage in=PWML
";
#[test]
fn a_violated_rule_logs_edges_and_reports_through_the_exit_code() {
let netlist = write(
"edges.cir",
&format!("{BUCK}\nR_isat kind=rule type=above target=I(L1) max=3 unit=A severity=error\n"),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(2), "a rule at error severity");
let events = fs::read_to_string(netlist.with_extension("events.jsonl")).expect("the log");
let enters = events.matches("\"kind\":\"enter\"").count();
let leaves = events.matches("\"kind\":\"leave\"").count();
assert!(
enters > 0 && enters == leaves,
"{enters} enters, {leaves} leaves"
);
assert!(
enters < 50,
"{enters} enters is per-sample logging, not per-edge"
);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(text.contains("--- rules ---"), "{text}");
}
#[test]
fn two_switches_of_a_leg_conducting_together_stops_the_run() {
let netlist = write(
"leg.cir",
&format!(
"{SHOOT_THROUGH_LEG}\n\
R_leg kind=rule type=forbidden_state switches=DSH,DSL severity=fatal action=stop\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(3), "stopped by a rule");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("stopped by rule 'DSH+DSL.R_leg'"),
"{stderr}"
);
assert!(stderr.contains("DSH") && stderr.contains("DSL"), "{stderr}");
}
#[test]
fn a_correctly_gated_leg_raises_nothing() {
let good = SHOOT_THROUGH_LEG.replace(
"PWML kind=pwm freq=20000 in=COMP",
"PWML kind=sum inputs=ONE,PWMH signs=1,-1",
);
let netlist = write(
"leg_ok.cir",
&format!(
"{good}\n\
R_leg kind=rule type=forbidden_state switches=DSH,DSL severity=fatal action=stop\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(0), "a clean leg must pass");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("0 violated, 1 passed"), "{stderr}");
}
#[test]
fn a_run_a_rule_stopped_resumes_after_the_rule_is_adjusted() {
let whole_netlist = write("whole.cir", BUCK);
let whole = run(&[
whole_netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
assert!(whole.status.success());
let whole_csv = String::from_utf8_lossy(&whole.stdout).to_string();
let stopping = write(
"stop.cir",
&format!(
"{BUCK}\nR_isat kind=rule type=above target=I(L1) max=3 unit=A severity=fatal action=stop\n"
),
);
let checkpoint = scratch("stop.ckpt");
let first = run(&[
stopping.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
"--checkpoint-out",
checkpoint.to_str().unwrap(),
]);
assert_eq!(first.status.code(), Some(3), "the rule should stop it");
assert!(
checkpoint.exists(),
"a stopped run must still leave its state"
);
let part1 = String::from_utf8_lossy(&first.stdout).to_string();
assert!(
part1.lines().count() > 1 && part1.lines().count() < whole_csv.lines().count(),
"it should stop partway, not at once or not at all"
);
let relaxed = write(
"relaxed.cir",
&format!(
"{BUCK}\nR_isat kind=rule type=above target=I(L1) max=50 unit=A severity=warning\n"
),
);
let second = run(&[
relaxed.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
"--resume",
checkpoint.to_str().unwrap(),
]);
assert_eq!(
second.status.code(),
Some(0),
"the resume must load -- editing a rule is not editing the deck.\nstderr: {}",
String::from_utf8_lossy(&second.stderr)
);
let part2 = String::from_utf8_lossy(&second.stdout).to_string();
let rejoined: String = part1
.lines()
.chain(part2.lines().skip(1))
.map(|line| format!("{line}\n"))
.collect();
assert_eq!(
rejoined, whole_csv,
"stopping on a rule and resuming must reproduce the uninterrupted run exactly"
);
}
fn buck_rated(rating: &str) -> String {
BUCK.replace("L1 sw out 22e-6", &format!("L1 sw out 22e-6 {rating}"))
}
#[test]
fn a_rating_on_the_device_line_reports_exactly_as_a_card_does() {
let netlist = write("rated.cir", &buck_rated("i_max=3.5"));
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
assert_eq!(
output.status.code(),
Some(2),
"a rating is an error by default"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("L1.i_max"), "{stderr}");
let events = fs::read_to_string(netlist.with_extension("events.jsonl")).expect("the log");
assert!(
events.contains("\"rule\":\"i_max\"") && events.contains("\"target\":\"L1\""),
"{events}"
);
assert!(events.contains("\"kind\":\"enter\""), "{events}");
}
#[test]
fn an_unexceeded_rating_passes_rather_than_being_ignored() {
let netlist = write("rated_ok.cir", &buck_rated("i_max=50"));
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(0));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("0 violated, 1 passed"), "{stderr}");
}
#[test]
fn two_ratings_on_one_line_are_two_independent_thresholds() {
let netlist = write("rated_two.cir", &buck_rated("i_max=3.5 i_sat=50"));
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("2 rule(s): 1 violated, 1 passed"),
"{stderr}"
);
assert!(stderr.contains("L1.i_sat"), "{stderr}");
}
#[test]
fn a_rating_is_a_limit_on_magnitude_not_on_signed_value() {
let netlist = write(
"reversed.cir",
"VIN vin 0 12\nR1 vin a 1\nL1 0 a 22e-6 i_max=3.5\n",
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-5",
"--dt",
"1e-7",
]);
assert_eq!(
output.status.code(),
Some(2),
"a reverse overload is an overload"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("-4.3831 A"), "{stderr}");
}
#[test]
fn on_violation_stops_the_run_and_the_message_names_the_component() {
let netlist = write("rated_stop.cir", &buck_rated("i_max=3.5 on_violation=stop"));
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(3), "stopped by a rating");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("stopped by rule 'L1.i_max'"), "{stderr}");
}
#[test]
fn a_rating_on_a_device_with_no_branch_current_is_refused_at_load() {
let netlist = write("rated_r.cir", "VIN vin 0 12\nR1 vin 0 50 i_max=2\n");
let output = run(&[netlist.to_str().unwrap(), "--mode", "transient"]);
assert_ne!(output.status.code(), Some(0));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("device R does not have one"), "{stderr}");
assert!(stderr.contains("only V, L, E and H"), "{stderr}");
}
#[test]
fn raising_a_rating_still_loads_the_checkpoint_of_the_run_it_stopped() {
let whole_netlist = write("rating_whole.cir", BUCK);
let whole = run(&[
whole_netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
assert!(whole.status.success());
let whole_csv = String::from_utf8_lossy(&whole.stdout).to_string();
let stopping = write("rating_stop.cir", &buck_rated("i_max=3 on_violation=stop"));
let checkpoint = scratch("rating.ckpt");
let first = run(&[
stopping.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
"--checkpoint-out",
checkpoint.to_str().unwrap(),
]);
assert_eq!(first.status.code(), Some(3), "the rating should stop it");
let part1 = String::from_utf8_lossy(&first.stdout).to_string();
assert!(
part1.lines().count() > 1 && part1.lines().count() < whole_csv.lines().count(),
"it should stop partway, not at once or not at all"
);
let relaxed = write("rating_relaxed.cir", &buck_rated("i_max=50"));
let second = run(&[
relaxed.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
"--resume",
checkpoint.to_str().unwrap(),
]);
assert_eq!(
second.status.code(),
Some(0),
"editing a rating is not editing the deck.\nstderr: {}",
String::from_utf8_lossy(&second.stderr)
);
let rejoined: String = part1
.lines()
.chain(String::from_utf8_lossy(&second.stdout).lines().skip(1))
.map(|line| format!("{line}\n"))
.collect();
assert_eq!(
rejoined, whole_csv,
"stopping on a rating and resuming must reproduce the uninterrupted run exactly"
);
}
const DEAD_GATE: &str = "\
VIN vin 0 12
DSW vin sw idealswitchmodel
DSW kind=ideal_switch r_on=0.05 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=5 gate=block ctrl=GATE
D1 0 sw dmodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=5
L1 sw out 22e-6
C1 out 0 47e-6 ic=3
RL out 0 4
DEAD kind=const value=0
GATE kind=sig2phys domain=voltage in=DEAD
";
#[test]
fn a_switch_that_never_commutated_is_reported() {
let netlist = write(
"dead_gate.cir",
&format!("{DEAD_GATE}T_sw kind=rule type=switch_timing switches=DSW severity=error\n"),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(2), "a dead gate is an error");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("never commutated"), "{stderr}");
assert!(stderr.contains("stayed open"), "{stderr}");
}
#[test]
fn a_switch_that_does_commutate_passes_the_same_rule() {
let netlist = write(
"live_gate.cir",
&format!("{BUCK}T_sw kind=rule type=switch_timing switches=DSW severity=error\n"),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(0));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("0 violated, 1 passed"), "{stderr}");
}
#[test]
fn an_on_pulse_shorter_than_the_device_allows_is_reported_with_its_length() {
let netlist = write(
"min_on.cir",
&format!(
"{BUCK}T_sw kind=rule type=switch_timing switches=DSW min_on=6u severity=warning\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"5e-5",
"--dt",
"1e-7",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("DSW was on for"), "{stderr}");
assert!(stderr.contains("6.0000e-6 s required"), "{stderr}");
let events = fs::read_to_string(netlist.with_extension("events.jsonl")).expect("the log");
assert!(events.contains("\"kind\":\"instant\""), "{events}");
assert!(events.contains("\"unit\":\"s\""), "{events}");
}
#[test]
fn a_switching_frequency_is_measured_and_held_to_its_band() {
let netlist = write(
"freq.cir",
&format!(
"{BUCK}T_f kind=rule type=switch_timing switches=DSW f_min=200k \
require_commutation=no severity=warning\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("below 2.0000e5 Hz"), "{stderr}");
assert!(
stderr.contains("1.0003e5 Hz") || stderr.contains("1.0000e5 Hz"),
"{stderr}"
);
let ok = write(
"freq_ok.cir",
&format!(
"{BUCK}T_f kind=rule type=switch_timing switches=DSW f_min=90k f_max=110k \
severity=warning\n"
),
);
let output = run(&[
ok.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-4",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(0));
assert!(
String::from_utf8_lossy(&output.stderr).contains("0 violated, 1 passed"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn require_commutation_rejects_a_value_that_is_not_yes_or_no() {
let netlist = write(
"bad_flag.cir",
&format!(
"{BUCK}T_sw kind=rule type=switch_timing switches=DSW require_commutation=maybe\n"
),
);
let output = run(&[netlist.to_str().unwrap(), "--mode", "transient"]);
assert_ne!(output.status.code(), Some(0));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("require_commutation must be yes or no"),
"{stderr}"
);
}
#[test]
fn a_gate_pinned_at_zero_is_reported_without_any_rule_being_written() {
let netlist = write("static_dead.cir", DEAD_GATE);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-5",
"--dt",
"1e-7",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("can never conduct"), "{stderr}");
assert!(stderr.contains("fixed at 0 by 'DEAD'"), "{stderr}");
assert_eq!(
output.status.code(),
Some(0),
"a warning does not fail a run"
);
}
#[test]
fn a_deck_whose_gates_are_driven_by_a_modulator_says_nothing() {
let netlist = write("static_live.cir", BUCK);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-5",
"--dt",
"1e-7",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.contains("can never conduct"),
"a working buck must be silent: {stderr}"
);
}
const SYNC_BUCK: &str = "\
VIN vin 0 12
VSH vin sh 0
DSH sh mid idealswitchmodel
DSH kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.4 body_g_on=50 gate=block ctrl=GH
VSL mid sl 0
DSL sl 0 idealswitchmodel
DSL kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.4 body_g_on=50 gate=block ctrl=GL
L1 mid out 22e-6
C1 out 0 47e-6 ic=5
RL out 0 4
DUTY kind=const value=0.45
PWM1 kind=pwm freq=100000 in=DUTY red=300e-9 fed=300e-9
GH kind=sig2phys domain=voltage in=PWM1
GL kind=sig2phys domain=voltage in=PWM1_comp
";
#[test]
fn a_body_diode_carrying_the_dead_time_current_is_reported_with_its_duration() {
let netlist = write(
"sync_body.cir",
&format!(
"{SYNC_BUCK}B_dsl kind=rule type=body_diode switches=DSL currents=I(VSL) \
i_min=0.5 severity=warning\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-5",
"--dt",
"1e-8",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("body diode conducting in DSL"), "{stderr}");
assert!(
stderr.contains("302.3458 ns") || stderr.contains("302."),
"the measured interval should be the 300 ns dead time: {stderr}"
);
}
#[test]
fn a_threshold_above_the_dead_time_current_keeps_ordinary_freewheeling_quiet() {
let netlist = write(
"sync_body_ok.cir",
&format!(
"{SYNC_BUCK}B_dsl kind=rule type=body_diode switches=DSL currents=I(VSL) \
i_min=50 severity=warning\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-5",
"--dt",
"1e-8",
]);
assert_eq!(output.status.code(), Some(0));
assert!(
String::from_utf8_lossy(&output.stderr).contains("0 violated, 1 passed"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn a_slope_bound_reports_the_slope_the_circuit_actually_produced() {
let netlist = write(
"slew.cir",
&format!(
"{BUCK}R_slew kind=rule type=rate_of_change target=I(L1) max_slope=2e5 \
unit=A/s severity=warning\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-5",
"--dt",
"1e-7",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("limit 200000.0000A/s"), "{stderr}");
assert!(stderr.contains("40"), "about 4.1e5 A/s expected: {stderr}");
let ok = write(
"slew_ok.cir",
&format!(
"{BUCK}R_slew kind=rule type=rate_of_change target=I(L1) max_slope=1e9 \
unit=A/s severity=warning\n"
),
);
let output = run(&[
ok.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-5",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(0));
}
#[test]
fn a_commutation_order_the_bridge_keeps_passes() {
let netlist = write(
"order_ok.cir",
&format!("{SYNC_BUCK}C_ord kind=rule type=commutation_order sequence=DSH,DSL\n"),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"3e-5",
"--dt",
"1e-8",
]);
assert_eq!(output.status.code(), Some(0));
assert!(
String::from_utf8_lossy(&output.stderr).contains("0 violated, 1 passed"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn the_conduction_cards_reject_what_they_cannot_act_on() {
let mismatched = write(
"order_bad.cir",
&format!(
"{SYNC_BUCK}B_x kind=rule type=body_diode switches=DSH,DSL currents=I(VSH) i_min=1\n"
),
);
let output = run(&[mismatched.to_str().unwrap(), "--mode", "transient"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("lists 1 name(s) for 2 switch(es)"),
"{stderr}"
);
let single = write(
"order_one.cir",
&format!("{SYNC_BUCK}C_ord kind=rule type=commutation_order sequence=DSH\n"),
);
let output = run(&[single.to_str().unwrap(), "--mode", "transient"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("needs at least two switches"), "{stderr}");
}
#[test]
fn a_run_that_goes_non_finite_is_abandoned_and_says_which_quantity_went_first() {
let netlist = write(
"nan.cir",
"VIN vin 0 12\nR1 vin a 1\nL1 a 0 22e-6\nNEG kind=const value=-1\nBAD kind=sqrt in=NEG\n",
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-5",
"--dt",
"1e-7",
]);
assert_eq!(
output.status.code(),
Some(4),
"a non-finite run has its own code"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("'BAD' is not a finite number"), "{stderr}");
assert!(stderr.contains("not a number"), "{stderr}");
assert!(stderr.contains("abandoned at step 0"), "{stderr}");
}
#[test]
fn a_healthy_run_is_not_touched_by_the_finite_check() {
let netlist = write("finite_ok.cir", "VIN vin 0 12\nR1 vin a 1\nL1 a 0 22e-6\n");
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-5",
"--dt",
"1e-7",
]);
assert_eq!(output.status.code(), Some(0));
assert!(
String::from_utf8_lossy(&output.stderr).is_empty(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn a_rule_on_a_non_finite_run_is_not_reported_as_passed() {
let netlist = write(
"nan_rule.cir",
"VIN vin 0 12\nR1 vin a 1\nL1 a 0 22e-6\nNEG kind=const value=-1\n\
BAD kind=sqrt in=NEG\n\
R_bad kind=rule type=above target=BAD max=1 severity=error\n",
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-5",
"--dt",
"1e-7",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.contains("1 passed"),
"a rule that could not read its quantity must not pass: {stderr}"
);
}
#[test]
fn a_volt_second_imbalance_is_reported_and_decays_as_the_converter_settles() {
let netlist = write(
"vs.cir",
&format!(
"{BUCK}P_vs kind=rule type=per_period target=V(sw,out) measure=integral \
period=10e-6 min=-2e-6 max=2e-6 unit=Vs severity=warning\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"6e-4",
"--dt",
"1e-8",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
let found: Vec<f64> = stderr
.lines()
.filter(|line| line.contains("P_vs") && line.contains("at "))
.filter_map(|line| {
let after = line.split("at ").nth(1)?;
after.trim().split("Vs").next()?.trim().parse::<f64>().ok()
})
.collect();
assert!(found.len() >= 5, "several periods expected: {stderr}");
assert!(
found[0] > found[found.len() - 1] * 3.0,
"the imbalance must shrink as the converter settles: {found:?}"
);
assert!(
stderr.contains("e-5Vs") || stderr.contains("e-6Vs"),
"{stderr}"
);
}
#[test]
fn a_per_period_rms_reports_the_rms_and_not_the_peak() {
let netlist = write(
"prms.cir",
&format!(
"{BUCK}P_rms kind=rule type=per_period target=I(L1) measure=rms period=10e-6 \
max=1.0 unit=A severity=warning\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"5e-5",
"--dt",
"1e-8",
]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("RMS of I(L1)"), "{stderr}");
assert!(stderr.contains("limit 1.0000A"), "{stderr}");
}
#[test]
fn a_per_period_card_insists_on_knowing_what_a_period_is() {
for (card, expected) in [
(
"P kind=rule type=per_period target=I(L1) measure=rms max=1",
"needs 'period=<seconds>' or 'sync=<switch>'",
),
(
"P kind=rule type=per_period target=I(L1) measure=rms period=10u sync=DSW max=1",
"'period' and 'sync' both given",
),
(
"P kind=rule type=per_period target=I(L1) measure=rms period=10u",
"needs 'min' or 'max'",
),
(
"P kind=rule type=per_period target=I(L1) measure=median period=10u max=1",
"unknown measure 'median'",
),
] {
let netlist = write("pbad.cir", &format!("{BUCK}{card}\n"));
let output = run(&[netlist.to_str().unwrap(), "--mode", "transient"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(expected), "for {card}:\n{stderr}");
}
}
const BUCK_WITH_PORTS: &str = "\
VIN in 0 12
DSW in sw idealswitchmodel
DSW kind=ideal_switch r_on=0.01 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
D1 0 sw idealdiodemodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=100
L1 sw out 1e-3
C1 out 0 1e-4
VSENSE out load 0
R1 load 0 5
DUTY kind=const value=0.4
PWM1 kind=pwm freq=50000 in=DUTY
GATE kind=sig2phys domain=voltage in=PWM1
P_IN kind=port v=(in,0) i=-VIN
P_OUT kind=port v=(out,0) i=VSENSE
";
const OVER_UNITY: &str = "\
VIN in 0 12
R1 in mid 1
R3 mid 0 100
E1 out 0 mid 0 2
R2 out 0 10
P_IN kind=port v=(in,0) i=-VIN
P_OUT kind=port v=(out,0) i=-E1
";
#[test]
fn a_real_converter_efficiency_sits_inside_its_band() {
let netlist = write(
"eta_pass.cir",
&format!(
"{BUCK_WITH_PORTS}\
ETA kind=rule type=efficiency in=P_IN out=P_OUT min=0 max=1 period=2e-3 severity=error\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"8e-3",
"--dt",
"2e-7",
"--out-every",
"1000000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("P_OUT/P_IN.ETA passed"),
"a buck averaged over its ring period should never look over-unity:\n{text}"
);
assert_eq!(output.status.code(), Some(0), "{text}");
}
#[test]
fn a_window_shorter_than_the_output_ring_exceeds_unity_legitimately() {
let netlist = write(
"eta_short_window.cir",
&format!(
"{BUCK_WITH_PORTS}\
ETA kind=rule type=efficiency in=P_IN out=P_OUT max=1 period=1e-3 severity=error\n"
),
);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2.2e-3",
"--dt",
"2e-7",
"--out-every",
"1000000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("ERROR P_OUT/P_IN.ETA"),
"half a ring period should report the capacitor's discharge as over-unity:\n{text}"
);
assert!(
text.contains("mean P_OUT / mean P_IN ="),
"the finding should show both averages:\n{text}"
);
}
#[test]
fn a_stamp_that_creates_energy_is_caught_and_stops_the_run() {
let netlist = write(
"eta_over_unity.cir",
&format!(
"{OVER_UNITY}\
ETA kind=rule type=efficiency in=P_IN out=P_OUT max=1 period=1e-5 severity=error action=stop\n"
),
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-4",
"--dt",
"1e-6",
"--out-every",
"100000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
let console = String::from_utf8_lossy(&output.stderr);
assert!(
console.contains("stopped by rule 'P_OUT/P_IN.ETA'"),
"an over-unity stamp should stop the run:\n{console}"
);
assert!(
text.contains("ERROR P_OUT/P_IN.ETA") && text.contains("limit 1.0000"),
"the finding should name the ratio and the limit:\n{text}"
);
assert_eq!(output.status.code(), Some(3), "stopped by a rule:\n{text}");
}
#[test]
fn a_port_declared_backwards_reports_a_negative_efficiency_rather_than_inverting_it() {
let netlist = write(
"eta_backwards.cir",
&format!(
"{}\
ETA kind=rule type=efficiency in=P_IN out=P_OUT min=0 sync=DSW severity=error\n",
BUCK_WITH_PORTS.replace("i=-VIN", "i=VIN")
),
);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"5e-4",
"--dt",
"2e-7",
"--out-every",
"100000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("ERROR P_OUT/P_IN.ETA")
&& text.contains("mean P_IN = ")
&& text.contains("/ -"),
"a backwards port should report a negative input power:\n{text}"
);
}
#[test]
fn a_period_whose_input_power_averages_to_zero_is_skipped_not_reported() {
let netlist = write(
"eta_zero.cir",
"VIN in 0 0
R1 in mid 1
R2 mid 0 10
P_IN kind=port v=(in,0) i=-VIN
P_OUT kind=port v=(mid,0) i=-VIN
ETA kind=rule type=efficiency in=P_IN out=P_OUT max=1 min=0 period=1e-5 severity=error
",
);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-4",
"--dt",
"1e-6",
"--out-every",
"100000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("P_OUT/P_IN.ETA passed"),
"a zero denominator should be skipped, not reported:\n{text}"
);
}
#[test]
fn a_port_power_converges_to_the_product_the_netlist_can_compute() {
let deck = "\
VIN in 0 12
DSW in sw idealswitchmodel
DSW kind=ideal_switch r_on=0.01 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
D1 0 sw idealdiodemodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=100
L1 sw out 1e-3
C1 out 0 1e-4
R1 out 0 5
DUTY kind=const value=0.4
PWM1 kind=pwm freq=50000 in=DUTY
GATE kind=sig2phys domain=voltage in=PWM1
VPROBE kind=phys2sig node=in
IPROBE kind=phys2sig branch=VIN
NEG kind=const value=-1
P_PRODUCT kind=product inputs=VPROBE,IPROBE,NEG
P_IN kind=port v=(in,0) i=-VIN
";
let netlist = write(
"eta_agree.cir",
&format!(
"{deck}\
CHK kind=rule type=efficiency in=P_PRODUCT out=P_IN min=0.99 max=1.01 \
period=1e-5 after=8e-5 severity=error\n"
),
);
let at = |dt: &str| -> String {
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
dt,
"--out-every",
"2000000",
]);
let _ = output;
fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log")
};
let coarse = at("4e-7");
assert!(
coarse.contains("ERROR P_IN/P_PRODUCT.CHK"),
"at dt=4e-7 the lagging product should sit outside a 1% band:\n{coarse}"
);
let fine = at("1e-7");
assert!(
fine.contains("P_IN/P_PRODUCT.CHK") && fine.contains("passed"),
"at dt=1e-7 the product should have converged into the 1% band:\n{fine}"
);
}
const SYNC_BUCK_CHANNELS: &str = "\
VIN in 0 12
DSH in mid idealswitchmodel
DSH kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GH
DSL mid 0 idealswitchmodel
DSL kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GL
L1 mid out 1e-3
C1 out 0 1e-4
R1 out 0 5
DUTY kind=const value=0.4
PWMH kind=pwm freq=50000 in=DUTY red=200e-9 fed=200e-9
GH kind=sig2phys domain=voltage in=PWMH
GL kind=sig2phys domain=voltage in=PWMH_comp
";
#[test]
fn a_switchs_computed_current_agrees_with_a_measured_one() {
let netlist = write(
"i_switch.cir",
"VIN in 0 12
DSW in mid idealswitchmodel
DSW kind=ideal_switch r_on=0.01 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
VS1 mid sw 0
D1 0 sw idealdiodemodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=100
L1 sw out 1e-3
C1 out 0 1e-4
R1 out 0 5
DUTY kind=const value=0.4
PWM1 kind=pwm freq=50000 in=DUTY
GATE kind=sig2phys domain=voltage in=PWM1
",
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-4",
"--dt",
"1e-7",
]);
let csv = String::from_utf8_lossy(&output.stdout);
let mut lines = csv.lines();
let header: Vec<&str> = lines.next().expect("a header").split(',').collect();
let column = |name: &str| -> usize {
header
.iter()
.position(|h| *h == name)
.unwrap_or_else(|| panic!("no column {name} in {header:?}"))
};
let (v_in, v_mid, i_sense, gate) = (
column("V(in)"),
column("V(mid)"),
column("I(VS1)"),
column("GATE"),
);
let mut worst = 0.0_f64;
let mut checked = 0usize;
let mut off_rows = 0usize;
for line in lines {
let f: Vec<f64> = line
.split(',')
.map(|v| v.parse().unwrap_or(f64::NAN))
.collect();
let computed = (f[v_in] - f[v_mid]) / 0.01;
if f[gate] >= 0.5 {
let measured = f[i_sense];
worst = worst.max((computed - measured).abs() / measured.abs().max(1e-12));
checked += 1;
} else {
assert!(
computed.abs() > 100.0 && f[i_sense].abs() < 1e-9,
"off-state row should show a true 0 A and an absurd computed current: {line}"
);
off_rows += 1;
}
}
assert!(
checked > 100 && off_rows > 100,
"{checked} on, {off_rows} off"
);
assert!(
worst < 1e-7,
"computed and measured switch current should agree: worst relative error {worst:e}"
);
}
#[test]
fn conduction_loss_follows_the_duty_split_across_a_synchronous_leg() {
let netlist = write(
"cond_split.cir",
&format!(
"{SYNC_BUCK_CHANNELS}\
LOSS_H kind=rule type=per_period target=P_cond(DSH) measure=mean period=2e-3 max=0 severity=info\n\
LOSS_L kind=rule type=per_period target=P_cond(DSL) measure=mean period=2e-3 max=0 severity=info\n"
),
);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"6e-3",
"--dt",
"1e-7",
"--out-every",
"2000000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
let last = |rule: &str| -> f64 {
text.lines()
.rfind(|l| l.contains(rule) && l.contains(" at "))
.and_then(|l| {
let after = l.split(" at ").nth(1)?;
after.split_whitespace().next()?.parse().ok()
})
.unwrap_or_else(|| panic!("no finding for {rule} in:\n{text}"))
};
let (high, low) = (last("P_cond(DSH)"), last("P_cond(DSL)"));
assert!(
(0.005..0.009).contains(&high) && (0.008..0.013).contains(&low),
"losses out of the expected range: high {high} W, low {low} W"
);
let ratio = low / high;
assert!(
(ratio - 1.5).abs() < 0.1,
"the low-side should carry (1-D)/D = 1.5 times the high-side's conduction loss, got {ratio}"
);
}
#[test]
fn a_switch_that_is_never_commanded_on_reports_no_conduction_loss() {
let netlist = write(
"cond_off.cir",
"VIN in 0 12
DSW in mid idealswitchmodel
DSW kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
R1 mid 0 1e6
OFF kind=const value=0
GATE kind=sig2phys domain=voltage in=OFF
NO_LOSS kind=rule type=per_period target=P_cond(DSW) measure=mean period=1e-5 max=1e-9 severity=error
",
);
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-4",
"--dt",
"1e-6",
"--out-every",
"100000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("P_cond(DSW).NO_LOSS") && text.contains("passed"),
"a switch that never turns on dissipates nothing in its channel:\n{text}"
);
assert_eq!(output.status.code(), Some(0), "{text}");
}
#[test]
fn a_synchronous_leg_reports_its_hard_switching_edge_and_passes_its_soft_one() {
let netlist = write(
"zvs_leg.cir",
&format!(
"{SYNC_BUCK_CHANNELS}\
ZVS_H kind=rule type=zvs switches=DSH v_max=5 severity=error\n\
ZVS_L kind=rule type=zvs switches=DSL v_max=5 severity=error\n"
),
);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-8",
"--out-every",
"1000000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("ERROR DSH.ZVS_H") && text.contains("DSH turned on with V(in,mid)"),
"the high-side switch hard-switches and should be reported:\n{text}"
);
assert!(
text.contains("at 12.5"),
"the reported voltage should be the bus it switched into:\n{text}"
);
assert!(
text.contains("DSL.ZVS_L") && text.contains("passed"),
"the low-side switch commutates behind its body diode and should pass:\n{text}"
);
}
#[test]
fn the_low_sides_pass_is_a_measured_diode_drop_and_not_a_skipped_measurement() {
let netlist = write(
"zvs_tight.cir",
&format!(
"{SYNC_BUCK_CHANNELS}\
ZVS_L kind=rule type=zvs switches=DSL v_max=0.01 severity=error\n"
),
);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-8",
"--out-every",
"1000000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("ERROR DSL.ZVS_L") && text.contains("at 0.50"),
"the low-side's turn-on voltage is its body diode's drop, and it is measured:\n{text}"
);
}
#[test]
fn the_reported_voltage_is_the_one_before_the_transition_not_after_it() {
let netlist = write(
"zvs_400.cir",
"VIN in 0 400
DSW in mid idealswitchmodel
DSW kind=ideal_switch r_on=0.01 body_g_breakdown=0 body_v_breakdown=-1000 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
L1 mid out 1e-3
R1 out 0 40
D1 0 mid idealdiodemodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-1000 g_off=0 v_f=0.4 g_on=100
DUTY kind=const value=0.5
PWM1 kind=pwm freq=20000 in=DUTY
GATE kind=sig2phys domain=voltage in=PWM1
ZVS kind=rule type=zvs switches=DSW v_max=5 severity=error
",
);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"6e-5",
"--dt",
"1e-8",
"--out-every",
"1000000",
]);
let text = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("ERROR DSW.ZVS") && text.contains("at 400."),
"the blocking voltage, not the post-commutation drop:\n{text}"
);
}
#[test]
fn a_gate_threshold_above_the_signal_keeps_the_switch_off_through_the_whole_run() {
let deck = |v_gs_th: &str| {
format!(
"VIN in 0 12
DSW in mid idealswitchmodel
DSW kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 \
body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE{v_gs_th}
R1 mid 0 5
DUTY kind=const value=0.5
PWM1 kind=pwm freq=50000 in=DUTY
GATE kind=sig2phys domain=voltage in=PWM1
TIMING kind=rule type=switch_timing switches=DSW f_min=1000 f_max=100000 severity=error
"
)
};
let normal = write("vgsth_default.cir", &deck(""));
run(&[
normal.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"5e-4",
"--dt",
"1e-7",
"--out-every",
"100000",
]);
let text = fs::read_to_string(normal.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("DSW.TIMING") && text.contains("passed"),
"with the default threshold the switch should commutate:\n{text}"
);
let high = write("vgsth_five.cir", &deck(" v_gs_th=5"));
run(&[
high.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"5e-4",
"--dt",
"1e-7",
"--out-every",
"100000",
]);
let text = fs::read_to_string(high.with_extension("events.txt")).expect("the text log");
assert!(
text.contains("ERROR DSW.TIMING"),
"a 5 V gate threshold must keep a logic-level-driven switch off:\n{text}"
);
}
#[test]
fn the_old_device_field_names_are_refused_with_the_replacement_named() {
let cases: [(&str, &str, &str); 3] = [
("body_v_f=0.5", "v_th=0.5", "v_gs_th"),
("body_g_on=100", "g_on=100", "body_g_on"),
(
"body_v_breakdown=-100",
"v_breakdown=-100",
"body_v_breakdown",
),
];
for (correct, old, expected) in cases {
let deck = "VIN in 0 12
DSW in mid idealswitchmodel
DSW kind=ideal_switch r_on=0.02 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 \
body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
R1 mid 0 5
ONE kind=const value=1
GATE kind=sig2phys domain=voltage in=ONE
"
.replace(correct, old);
let netlist = write("old_vocab.cir", &deck);
let output = run(&[netlist.to_str().unwrap(), "--mode", "dc"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("no longer exists") && stderr.contains(expected),
"writing '{old}' should be refused and should name '{expected}':\n{stderr}"
);
assert_ne!(output.status.code(), Some(0), "{stderr}");
}
}
#[test]
fn an_expectation_decides_the_exit_code_so_a_deck_is_its_own_regression_test() {
let deck = |low: &str, high: &str| {
format!(
"VIN in 0 12
DSW in sw idealswitchmodel
DSW kind=ideal_switch r_on=0.01 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 \
body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
D1 0 sw idealdiodemodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=100
L1 sw out 1e-3
C1 out 0 1e-4
R1 out 0 5
DUTY kind=const value=0.4
PWM1 kind=pwm freq=50000 in=DUTY
GATE kind=sig2phys domain=voltage in=PWM1
EXPECT kind=rule type=outside target=V(out) min={low} max={high} after=3e-3 severity=error
"
)
};
let at = |name: &str, low: &str, high: &str| {
let netlist = write(name, &deck(low, high));
let output = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"5e-3",
"--dt",
"2e-7",
"--out-every",
"1000000",
]);
let log = fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log");
(output.status.code(), log)
};
let (code, log) = at("expect_true.cir", "4.0", "5.0");
assert_eq!(code, Some(0), "a met expectation must exit 0:\n{log}");
assert!(
log.contains("V(out).EXPECT") && log.contains("passed"),
"{log}"
);
let (code, log) = at("expect_false.cir", "9.0", "10.0");
assert_eq!(code, Some(2), "a failed expectation must exit 2:\n{log}");
assert!(
log.contains("ERROR V(out).EXPECT") && log.contains("worst"),
"the report should carry the worst value and when it happened:\n{log}"
);
}
const BUCK_FOR_CLOSURE: &str = "\
VIN in 0 12
DSW in sw idealswitchmodel
DSW kind=ideal_switch r_on=0.05 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=100 gate=block ctrl=GATE
D1 0 sw idealdiodemodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=100
L1 sw out 1e-3
C1 out 0 1e-4
VSENSE out load 0
R1 load 0 5
DUTY kind=const value=0.4
PWM1 kind=pwm freq=50000 in=DUTY
GATE kind=sig2phys domain=voltage in=PWM1
P_IN kind=port v=(in,0) i=-VIN
P_OUT kind=port v=(out,0) i=VSENSE
";
fn closure_run(name: &str, card: &str) -> String {
let netlist = write(name, &format!("{BUCK_FOR_CLOSURE}{card}"));
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"1e-2",
"--dt",
"1e-7",
"--out-every",
"2000000",
]);
fs::read_to_string(netlist.with_extension("events.txt")).expect("the text log")
}
#[test]
fn a_fully_modelled_converter_closes_its_loss_budget() {
let text = closure_run(
"closure_good.cir",
"CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT devices=DSW,D1 max=0.002 \
period=2e-3 after=6e-3 severity=error\n",
);
assert!(
text.contains("P_OUT/P_IN.CLOSE") && text.contains("passed"),
"a buck whose only losses are conduction should close to better than 0.2%:\n{text}"
);
}
#[test]
fn omitting_the_freewheeling_diode_shows_up_as_unaccounted_power() {
let text = closure_run(
"closure_missing.cir",
"CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT devices=DSW max=0.002 \
period=2e-3 after=6e-3 severity=error\n",
);
assert!(
text.contains("ERROR P_OUT/P_IN.CLOSE"),
"a loss model missing the dominant device should be reported:\n{text}"
);
assert!(
text.contains("deficit, model accounts for"),
"the finding should show both sides of the comparison:\n{text}"
);
}
#[test]
fn the_unaccounted_fraction_is_far_larger_with_the_diode_left_out() {
let with_both = closure_run(
"closure_cmp_both.cir",
"CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT devices=DSW,D1 max=0.0 \
period=2e-3 after=6e-3 severity=info\n",
);
let switch_only = closure_run(
"closure_cmp_one.cir",
"CLOSE kind=rule type=loss_closure in=P_IN out=P_OUT devices=DSW max=0.0 \
period=2e-3 after=6e-3 severity=info\n",
);
let fraction = |text: &str| -> f64 {
text.lines()
.rfind(|l| l.contains("P_OUT/P_IN.CLOSE") && l.contains(" at "))
.and_then(|l| {
l.split(" at ")
.nth(1)?
.split_whitespace()
.next()?
.parse()
.ok()
})
.unwrap_or_else(|| panic!("no finding in:\n{text}"))
};
let (both, one) = (fraction(&with_both), fraction(&switch_only));
assert!(
both < 0.002,
"with both devices modelled the residual should be small, got {both}"
);
assert!(
one > 20.0 * both,
"leaving out 93% of the loss should be unmistakable: {one} vs {both}"
);
}
const BUCK_WITH_RATING: &str = "\
VIN vin 0 12
DSW vin sw idealswitchmodel
DSW kind=ideal_switch r_on=0.05 body_g_breakdown=0 body_v_breakdown=-100 body_g_off=0 body_v_f=0.5 body_g_on=5 gate=block ctrl=GATE
D1 0 sw dmodel
D1 kind=ideal_diode g_breakdown=0 v_breakdown=-100 g_off=0 v_f=0.4 g_on=5
L1 sw out 22e-6
C1 out 0 47e-6 ic=3
RL out 0 4
VOUT kind=phys2sig node=out
REF kind=const value=5
ERR kind=sum inputs=REF,VOUT signs=1,-1
PI kind=pid in=ERR kp=0.02 ki=50 kd=0 n=100 clamp_lo=0.05 clamp_hi=0.95 ic=0.4
PWM1 kind=pwm freq=100000 in=PI
GATE kind=sig2phys domain=voltage in=PWM1
R_vout kind=rule type=above target=V(out) max=1 unit=V severity=warning action=console
";
#[test]
fn the_event_stream_goes_where_it_is_asked_for() {
let netlist = write("redirected.cir", BUCK_WITH_RATING);
let jsonl = scratch("asked-for.jsonl");
let text = scratch("asked-for.txt");
let _ = fs::remove_file(&jsonl);
let _ = fs::remove_file(&text);
let _ = fs::remove_file(netlist.with_extension("events.jsonl"));
let _ = fs::remove_file(netlist.with_extension("events.txt"));
let out = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-7",
"--events",
jsonl.to_str().unwrap(),
"--events-text",
text.to_str().unwrap(),
]);
let log = fs::read_to_string(&jsonl).expect("the redirected JSONL log");
assert!(log.contains("\"rule\":"), "{log}");
assert!(fs::read_to_string(&text).is_ok(), "the redirected text log");
assert!(
!netlist.with_extension("events.jsonl").exists(),
"a log was still written beside the netlist"
);
assert!(!netlist.with_extension("events.txt").exists());
assert!(
out.status.code() == Some(0) || out.status.code() == Some(2),
"{:?}: {}",
out.status.code(),
String::from_utf8_lossy(&out.stderr)
);
}
#[test]
fn either_file_moves_without_the_other() {
let netlist = write("one-moved.cir", BUCK_WITH_RATING);
let jsonl = scratch("only-this-one.jsonl");
let _ = fs::remove_file(&jsonl);
let _ = fs::remove_file(netlist.with_extension("events.txt"));
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-7",
"--events",
jsonl.to_str().unwrap(),
]);
assert!(fs::read_to_string(&jsonl).is_ok(), "the redirected JSONL");
assert!(
netlist.with_extension("events.txt").exists(),
"the text log kept its default path"
);
assert!(!netlist.with_extension("events.jsonl").exists());
}
#[test]
fn without_the_flags_the_files_keep_their_old_paths() {
let netlist = write("default-paths.cir", BUCK_WITH_RATING);
let _ = fs::remove_file(netlist.with_extension("events.jsonl"));
let _ = fs::remove_file(netlist.with_extension("events.txt"));
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-7",
]);
assert!(netlist.with_extension("events.jsonl").exists());
assert!(netlist.with_extension("events.txt").exists());
}
#[test]
fn a_log_path_that_cannot_be_created_is_an_error_and_not_a_silently_skipped_log() {
let netlist = write("bad-log-path.cir", BUCK_WITH_RATING);
let missing = scratch("no-such-directory").join("run.jsonl");
let out = run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-7",
"--events",
missing.to_str().unwrap(),
]);
assert_eq!(out.status.code(), Some(1));
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("creating the event log"), "{stderr}");
assert!(stderr.contains("run.jsonl"), "{stderr}");
}
#[test]
fn every_line_of_the_log_says_which_shape_it_is() {
let netlist = write("tagged-lines.cir", BUCK_WITH_RATING);
let jsonl = scratch("tagged-lines.jsonl");
let _ = fs::remove_file(&jsonl);
run(&[
netlist.to_str().unwrap(),
"--mode",
"transient",
"--tfinal",
"2e-4",
"--dt",
"1e-7",
"--events",
jsonl.to_str().unwrap(),
]);
let log = fs::read_to_string(&jsonl).expect("the log");
let lines: Vec<&str> = log.lines().filter(|l| !l.trim().is_empty()).collect();
assert!(!lines.is_empty(), "the rule fired, so there are lines");
for line in &lines {
let value: serde_json::Value = serde_json::from_str(line).expect("one JSON object");
let record = value["record"].as_str().unwrap_or_default();
assert!(
record == "event" || record == "summary",
"untagged line: {line}"
);
}
let (events, summaries): (Vec<&&str>, Vec<&&str>) = lines
.iter()
.partition(|l| l.contains("\"record\":\"event\""));
assert!(!events.is_empty(), "{log}");
assert_eq!(summaries.len(), 1, "{log}");
for line in events {
assert!(line.contains("\"kind\":"), "{line}");
}
assert!(summaries[0].contains("\"entries\":"), "{}", summaries[0]);
}