llc_validation/llc_validation.rs
1//! Open-loop LLC resonant converter (400V bus, half-bridge, series resonant tank, coupled-
2//! inductor transformer, full-wave rectified output) -- the same specification as an internal
3//! open-loop-topologies benchmark (`code/llc/`), used as a cross-simulator validation and
4//! timing comparison against ngspice and Xyce on the hardest topology in that benchmark (two
5//! switches, a resonant tank near the switching frequency, and a coupled-inductor transformer
6//! via `general-mna`'s `K` stamp -- not just a single ideal switch and diode like the
7//! buck/boost cases). An example, not a `#[test]`
8//! fixture: unlike buck/boost, there is no simple hand-derivable closed-form target for an
9//! LLC resonant converter's steady-state output, so this is exploratory validation against
10//! the other simulators' numbers, not a pass/fail assertion.
11//!
12//! Result recorded when this was last run (see an internal boost/LLC-vs-Xyce/ngspice
13//! validation experiment's own writeup for the full account): avg `Vout` (last 90% of the run) = 33.70V, a ~6.3% spread against
14//! ngspice/Xyce's own (tightly mutually agreeing, <0.03% apart) ~31.69V, down from ~8.7% before
15//! the fix below. The fix resolves the dead-time spike itself; the remaining spread is a
16//! separate, pre-existing parameter-fitting gap (see this file's PWL device comments below and
17//! the README's Next Steps) unrelated to the spike.
18//!
19//! ## Dead-time voltage spike -- root-caused and fixed
20//!
21//! During dead time (both switches gated off simultaneously, twice per switching period),
22//! node `vx` had essentially zero conductance to any reference from the switch stamps
23//! themselves (only the resonant tank's `Cr` coupled to it at all) -- a genuinely
24//! near-floating node. Under [`dae_runtime::simulate_transient_with_ideal_switches`]'s trapezoidal
25//! integration, that near-zero damping triggered classic **trapezoidal ringing** (A-stable
26//! but not L-stable: `V(vx)` oscillated between roughly +/-3000V, sign-flipping every single
27//! step, while every other tracked quantity stayed smooth throughout).
28//!
29//! Two things fixed this, one at each level:
30//! 1. **Circuit level (the actual fix)**: added the `Rs1`/`Cs1`, `Rs2`/`Cs2` RC snubbers --
31//! the *same* ones the reference Xyce/ngspice decks already have and this translation had
32//! originally dropped. A real ideal switch always has nonzero output capacitance (`Coss`); an
33//! RC snubber approximates it, giving the switching node a genuine charge-storage anchor
34//! during dead time (the capacitor) plus real damping to dissipate the resulting ringing
35//! (the resistor) -- exactly why real converters use snubbers in hardware, not just in
36//! simulation. With them in place, `V(vx)` transitions *smoothly and monotonically*
37//! between rails during dead time (a physically correct RC-discharge-shaped ramp), no
38//! oscillation at all.
39//! 2. **Solver level (defense in depth, not a substitute for the above)**: `dae-runtime` now
40//! detects trapezoidal ringing directly (three consecutive values of the same unknown
41//! alternating in sign without shrinking in magnitude) and falls back to backward Euler
42//! for a short cooldown when it happens, the same way it already does for a diode-segment
43//! or gate-state change. This bounds the damage for any circuit that still lacks adequate
44//! damping at some node, but a circuit with real snubbers/parasitic capacitance (like this
45//! one, now) shouldn't need to lean on it.
46
47use std::collections::BTreeMap;
48use std::io::Write;
49use std::time::Instant;
50
51use dae_runtime::{simulate_transient_with_ideal_switches, GateState};
52use general_spice_core::Dialect;
53use pwl_devices::{IdealDiode, IdealSwitch};
54
55fn main() {
56 let netlist = "V1 vin 0 400\n\
57 D1 vin vx idealswitchmodel\n\
58 D2 vx 0 idealswitchmodel\n\
59 Rs1 vin vx 1k\n\
60 Cs1 vin vx 1n\n\
61 Rs2 vx 0 1k\n\
62 Cs2 vx 0 1n\n\
63 Cr vx vr 22n\n\
64 Lr vr vp 100u\n\
65 Lm vp 0 400u\n\
66 Lpri vp 0 1000u\n\
67 Lsec1 vy 0 10u\n\
68 Lsec2 0 vz 10u\n\
69 K1 Lpri Lsec1 0.99\n\
70 K2 Lpri Lsec2 0.99\n\
71 K3 Lsec1 Lsec2 0.99\n\
72 D3 vy vout dmodel\n\
73 D4 vz vout dmodel\n\
74 Cout vout 0 470u\n\
75 Rout vout 0 20";
76
77 // D1/D2 stand in for the ideal half-bridge switches S1/S2 (RON=10m, no body diode of
78 // their own in the reference decks): body-diode threshold set unreachably high so
79 // gate=off means true full blocking, with a tiny nonzero g_off (see module doc, the
80 // dead-time spike finding).
81 let ideal_switch = IdealSwitch::new(0.01, IdealDiode::new(0.0, -1e6, 1e-6, 1e6, 0.0));
82 let mut ideal_switches = BTreeMap::new();
83 ideal_switches.insert("D1".to_string(), ideal_switch);
84 ideal_switches.insert("D2".to_string(), ideal_switch);
85 // D3/D4 are the real rectifier diodes (D_IDEAL: IS=1e-14, N=1, RS=10m); g_on=1/RS=100.
86 let mut diodes = BTreeMap::new();
87 diodes.insert(
88 "D3".to_string(),
89 IdealDiode::new(0.0, -100.0, 0.0, 0.6, 100.0),
90 );
91 diodes.insert(
92 "D4".to_string(),
93 IdealDiode::new(0.0, -100.0, 0.0, 0.6, 100.0),
94 );
95
96 // Matches the Xyce/ngspice decks' PULSE sources: S1 (D1) on for the first 4.8us of each
97 // 10us period; S2 (D2) on for the complementary window, phase-shifted by 5us -- ~0.2us
98 // dead time on each edge.
99 let period = 10e-6;
100 let on_width = 4.8e-6;
101 let gate_signal = move |name: &str, t: f64| {
102 let phase_offset = if name == "D2" { 5e-6 } else { 0.0 };
103 let tau = (t - phase_offset).rem_euclid(period);
104 if tau < on_width {
105 GateState::On
106 } else {
107 GateState::Off
108 }
109 };
110
111 let dt = 1e-8; // matches the .tran 10n step in both reference decks
112 let t_final = 1e-3; // 100 switching periods, matches both reference decks
113
114 let start = Instant::now();
115 let trace = simulate_transient_with_ideal_switches(
116 netlist,
117 Dialect::Ngspice,
118 &diodes,
119 &ideal_switches,
120 gate_signal,
121 0.01,
122 None,
123 t_final,
124 dt,
125 )
126 .unwrap();
127 let elapsed = start.elapsed();
128
129 println!(
130 "general-simulator LLC open-loop: {} steps in {:.3}s ({:.0} steps/s)",
131 trace.len(),
132 elapsed.as_secs_f64(),
133 trace.len() as f64 / elapsed.as_secs_f64()
134 );
135
136 let tail = &trace[trace.len() / 10..]; // last 90% (skip only the initial transient)
137 let avg_vout: f64 = tail
138 .iter()
139 .map(|(_, p)| p.value("V(vout)").unwrap())
140 .sum::<f64>()
141 / tail.len() as f64;
142 println!("avg Vout (last 90%): {avg_vout:.4}");
143
144 // CSV export (t, V(vout), V(vx)) for the cross-simulator waveform plot -- see the internal
145 // boost/LLC-vs-Xyce/ngspice validation experiment's own writeup.
146 // Same `t,unknown1,unknown2,...` column convention as general-simulator-cli's own CSV output.
147 let out_path = "llc_elspice_pwl_out.csv";
148 let mut f = std::fs::File::create(out_path).unwrap();
149 writeln!(f, "t,V(vout),V(vx)").unwrap();
150 for (t, point) in &trace {
151 writeln!(
152 f,
153 "{t},{},{}",
154 point.value("V(vout)").unwrap(),
155 point.value("V(vx)").unwrap()
156 )
157 .unwrap();
158 }
159 println!("wrote {out_path}");
160}