Skip to main content

dae_runtime/
closed_loop.rs

1//! Wires a `continuous_blocks::StateSpace` controller (typically a compiled [`Pid`
2//! ](continuous_blocks::Pid)) into a closed loop around a circuit's ideal switch(s), replacing
3//! Xyce/SPICE's `tanh`-smoothed comparator workaround (documented in an internal gotcha note
4//! on Xyce PID-timestep collapse needing a smoothed comparator)
5//! with an ordinary PWM comparator — no smoothing hack needed, since gate switching is just
6//! another LCP-resolved mode here, not a Newton-Raphson convergence hazard. See
7//! `docs/architecture.md`.
8//!
9//! This is deliberately a **sampled-data co-simulation**, not a fully implicit unified system:
10//! the controller reads the circuit's measured output from the *previous* timestep, steps its
11//! own dynamics forward with its own RK4 integrator, and the result (compared against a PWM
12//! carrier) decides this step's gate states before the circuit step is solved. This is not a
13//! shortcut — it is literally how a real digital PID+PWM controller in an actual converter
14//! works: it samples state, computes, and updates PWM at discrete instants. Fully folding a
15//! controller's `(A, K, B)` into the circuit's own global descriptor system (implicit,
16//! zero-sample-delay coupling) remains a possible future refinement, not a correctness gap in
17//! what's implemented here.
18
19use std::collections::BTreeMap;
20
21use continuous_blocks::StateSpace;
22use general_spice_core::Dialect;
23use pwl_devices::{IdealDiode, IdealSwitch};
24
25use crate::{
26    classify_segments, step_with_fallback, DaeError, GateState, OperatingPoint, Segment,
27    RINGING_COOLDOWN_STEPS,
28};
29
30/// A free-running sawtooth PWM carrier in `[0, 1)` at frequency `freq_hz`. Compare a duty
31/// command (also `[0, 1]`) against this to decide gate state: on while the carrier is below
32/// the duty command, off otherwise (a standard trailing-edge PWM comparator).
33pub fn sawtooth_carrier(t: f64, freq_hz: f64) -> f64 {
34    let phase = t * freq_hz;
35    phase - phase.floor()
36}
37
38/// Runs a closed-loop transient: at each timestep, `measure` reads a scalar from the
39/// *previous* step's [`OperatingPoint`] (e.g. an output node voltage), `controller` (its own
40/// state carried forward internally) is stepped with `reference(t) - measured` as its input
41/// via RK4, and `pwm(controller_output, t)` decides every ideal switch's gate state for this step
42/// from that controller output. Everything else matches
43/// [`crate::simulate_transient_with_ideal_switches`] (system rebuilt per step, trapezoidal with
44/// backward-Euler fallback on any diode-segment or gate-state change).
45///
46/// `reference` is a function of time rather than a fixed value so a reference-step robustness
47/// test (settle at one setpoint, then step to another mid-run) is just `move |t| if t < t_step
48/// { v1 } else { v2 }` — no separate code path needed. Pass `move |_| v` for a fixed setpoint.
49///
50/// `output_clamp = (lo, hi)` is the controller output's valid (unsaturated) range — typically
51/// `(0.0, 1.0)` for a duty command. **Two-sided conditional-integration anti-windup** is
52/// applied against it: if a tentative controller step would push the output further past
53/// `lo` or `hi` while the current error is still driving it that direction, the controller's
54/// internal state is *not* advanced that step (frozen at its previous value) rather than
55/// integrating further into a saturation it may struggle to recover from. This directly
56/// addresses a documented real failure mode this project validated against: an internal
57/// Xyce/ngspice closed-loop boost-PI benchmark (its own gotcha note on nonlinear
58/// integrator-windup failure) used *one-sided*
59/// anti-windup and, per that benchmark's own conclusion, never actually achieved working
60/// closed-loop regulation — the integrator wound down past the point of recovery during
61/// startup overshoot, the PWM output floored at zero, and the converter stopped switching for
62/// the rest of the run, with the misleadingly-plausible final voltage reading being nothing
63/// more than the output capacitor passively discharging through the load. Symmetric
64/// (two-sided) anti-windup is the standard, well-known fix for exactly this failure mode.
65///
66/// Returns, per step: `(t, OperatingPoint, controller_output)`.
67#[allow(clippy::too_many_arguments)]
68pub fn simulate_closed_loop(
69    source: &str,
70    dialect: Dialect,
71    diodes: &BTreeMap<String, IdealDiode>,
72    ideal_switches: &BTreeMap<String, IdealSwitch>,
73    controller: &StateSpace,
74    reference: impl Fn(f64) -> f64,
75    measure: impl Fn(&OperatingPoint) -> f64,
76    pwm: impl Fn(f64, f64) -> BTreeMap<String, GateState>,
77    output_clamp: (f64, f64),
78    shared_r_on: f64,
79    x_initial: Option<&[f64]>,
80    t_final: f64,
81    dt: f64,
82) -> Result<Vec<(f64, OperatingPoint, f64)>, DaeError> {
83    let statements = general_mna::parse_and_flatten(source, dialect).map_err(DaeError::Parse)?;
84
85    // A zero initial gate assignment (no measurement exists yet) just to learn `order` for the
86    // default x_initial and to get a first OperatingPoint to seed `measure`/the loop with.
87    let initial_states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
88        .iter()
89        .map(|(name, m)| (name.clone(), (*m, GateState::Off)))
90        .collect();
91    let (system0, all_diodes0) = crate::build_with_ideal_switches(
92        &statements,
93        dialect,
94        diodes,
95        &initial_states,
96        shared_r_on,
97    )?;
98    let mut x_prev = crate::resolve_initial_state(&system0, &all_diodes0, x_initial)?;
99    let (mut point_prev, _) = step_with_fallback(
100        &system0,
101        &statements,
102        &all_diodes0,
103        None,
104        &x_prev,
105        dt,
106        &BTreeMap::new(),
107        &None,
108        true,
109        0.0,
110        &BTreeMap::new(),
111        &BTreeMap::new(),
112    )?;
113    let mut x_prev_prev: Option<Vec<f64>> =
114        Some(std::mem::replace(&mut x_prev, point_prev.x.clone()));
115
116    let mut controller_x = vec![0.0; controller.states()];
117    let mut prev_diode_raw_ioff: BTreeMap<String, f64> = BTreeMap::new();
118    let mut prev_segments: Option<Vec<Segment>> = None;
119    let mut prev_gate_states: Option<BTreeMap<String, GateState>> = None;
120    let mut ringing_cooldown: u32 = 0;
121
122    let steps = (t_final / dt).round() as usize;
123    let mut trace = Vec::with_capacity(steps);
124    let mut t = 0.0;
125    for step_index in 0..steps {
126        t += dt;
127
128        let measured = measure(&point_prev);
129        let error = [reference(t) - measured];
130
131        let (lo, hi) = output_clamp;
132        let tentative_x = controller.rk4_step(&controller_x, &error, dt);
133        let tentative_output = controller.output(&tentative_x, &error)[0];
134        let saturating_further = (tentative_output >= hi && error[0] > 0.0)
135            || (tentative_output <= lo && error[0] < 0.0);
136        let controller_output = if saturating_further {
137            // Freeze: don't advance the controller's state further into a saturation the
138            // current error is still driving it toward (two-sided conditional-integration
139            // anti-windup -- see this function's doc comment for why one-sided isn't enough).
140            controller.output(&controller_x, &error)[0].clamp(lo, hi)
141        } else {
142            controller_x = tentative_x;
143            tentative_output
144        };
145
146        let gate_states = pwm(controller_output, t);
147        let states: BTreeMap<String, (IdealSwitch, GateState)> = ideal_switches
148            .iter()
149            .map(|(name, m)| {
150                (
151                    name.clone(),
152                    (*m, *gate_states.get(name).unwrap_or(&GateState::Off)),
153                )
154            })
155            .collect();
156        let gate_changed = prev_gate_states.as_ref() != Some(&gate_states);
157        let forced = step_index == 0 || gate_changed || ringing_cooldown > 0;
158
159        let (system, all_diodes) =
160            crate::build_with_ideal_switches(&statements, dialect, diodes, &states, shared_r_on)?;
161        let (point, used_backward_euler) = step_with_fallback(
162            &system,
163            &statements,
164            &all_diodes,
165            x_prev_prev.as_deref(),
166            &x_prev,
167            dt,
168            &prev_diode_raw_ioff,
169            &prev_segments,
170            forced,
171            t,
172            &BTreeMap::new(),
173            &BTreeMap::new(),
174        )?;
175        if used_backward_euler && !forced {
176            ringing_cooldown = RINGING_COOLDOWN_STEPS;
177        } else if ringing_cooldown > 0 {
178            ringing_cooldown = ringing_cooldown.saturating_sub(1);
179        }
180
181        prev_segments = Some(classify_segments(&point));
182        prev_gate_states = Some(gate_states);
183        prev_diode_raw_ioff = point
184            .diode_names
185            .iter()
186            .cloned()
187            .zip(point.diode_raw_ioff.iter().copied())
188            .collect();
189        x_prev_prev = Some(std::mem::replace(&mut x_prev, point.x.clone()));
190        point_prev = point.clone();
191        trace.push((t, point, controller_output));
192    }
193    Ok(trace)
194}