boost_pid_closed_loop/
boost_pid_closed_loop.rs1use std::collections::BTreeMap;
9use std::io::Write;
10
11use continuous_blocks::Pid;
12use dae_runtime::{sawtooth_carrier, simulate_closed_loop, GateState};
13use general_spice_core::Dialect;
14use pwl_devices::{IdealDiode, IdealSwitch};
15
16fn main() {
17 let netlist = "V1 vin 0 12\nD1 vx 0 idealswitchmodel\nD2 vx vout dmodel\nL1 vin vx 100u\nC1 vout 0 100u\nR1 vout 0 50";
18 let switch = IdealSwitch::new(0.01, IdealDiode::new(0.0, -1e6, 0.0, 1e6, 0.0));
19 let mut ideal_switches = BTreeMap::new();
20 ideal_switches.insert("D1".to_string(), switch);
21 let mut diodes = BTreeMap::new();
22 diodes.insert(
23 "D2".to_string(),
24 IdealDiode::new(0.0, -100.0, 0.0, 0.6, 100.0),
25 );
26
27 let reference = 24.0;
28 let pid = Pid::new(0.01, 20.0, 0.0, 1000.0).unwrap();
29 let controller = pid.to_state_space();
30
31 let switching_freq = 100_000.0;
32 let measure = |point: &dae_runtime::OperatingPoint| point.value("V(vout)").unwrap();
33 let pwm = move |duty: f64, t: f64| {
34 let duty = duty.clamp(0.0, 1.0);
35 let carrier = sawtooth_carrier(t, switching_freq);
36 let state = if carrier < duty {
37 GateState::On
38 } else {
39 GateState::Off
40 };
41 BTreeMap::from([("D1".to_string(), state)])
42 };
43
44 let dt = 1e-7;
45 let t_final = 0.010;
46
47 let trace = simulate_closed_loop(
48 netlist,
49 Dialect::Ngspice,
50 &diodes,
51 &ideal_switches,
52 &controller,
53 move |_| reference,
54 measure,
55 pwm,
56 (0.0, 1.0),
57 0.01,
58 None,
59 t_final,
60 dt,
61 )
62 .unwrap();
63
64 let out_path = "boost_pid_elspice_pwl_out.csv";
65 let mut f = std::fs::File::create(out_path).unwrap();
66 writeln!(f, "t,V(vout),duty").unwrap();
67 for (t, point, duty) in &trace {
68 writeln!(f, "{t},{},{}", point.value("V(vout)").unwrap(), duty).unwrap();
69 }
70 println!("wrote {out_path}");
71}