Skip to main content

lib_jsl_dsp/discrete/controls/
pid.rs

1//! A PID controller with derivative filtering, output limits and anti-windup.
2//!
3//! See the book entry [Control: state-space models, PID controllers and the Kalman filter](https://jwkunz.github.io/lib_jsl/book/comms/controls.html#pid-control).
4
5use crate::{
6    dsp::discrete::{
7        filters::biquad::BiquadFilter,
8        stream_operator::{StreamOperator, StreamOperatorManagement},
9    },
10    prelude::ErrorsJSL,
11};
12
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct PidOutput {
15    pub control: f64,
16    pub error: f64,
17}
18
19/// Runtime-programmable PID controller for scalar (`f64`) streams.
20///
21/// - Setpoint and coefficients can be updated at runtime.
22/// - `kp`, `ki`, `kd` are optional; `None` means that term is skipped.
23/// - Derivative is taken on a low-pass-filtered measurement using a
24///   biquad low-pass filter with normalized cutoff 0.1.\
25///   This reduces noise sensitivity and avoids derivative kick from setpoint changes.
26/// - Optional output limits with anti-windup that prevents integral growth when the controller is saturated and pushing further in the same direction.
27/// - `dt` is the time step for integration and differentiation, and can be set at initialization. It does not have to match the actual sample rate, but should be chosen based on the expected dynamics of the system being controlled.
28/// - The controller maintains internal state for the integral term and the previous filtered measurement for the derivative term, and provides a `reset_integral` method to reset the integral state without affecting the derivative state.
29/// - The `process` method takes a slice of measurements and returns a vector of `PidOutput` containing the control output and error for each input measurement.
30/// - The `flush` method does nothing and returns `None`, as the PID controller does not have any buffered output that needs to be flushed.
31/// - The `reset` method resets the integral state and derivative state, and also resets the internal state of the biquad filter used for the derivative term.
32/// - The `finalize` method does nothing, as there are no resources that need to be cleaned up when the controller is finalized.
33pub struct PidController {
34    setpoint: f64,
35    kp: Option<f64>,
36    ki: Option<f64>,
37    kd: Option<f64>,
38    // High and low limits for the control output. If None, output is not limited.
39    output_limits: Option<(f64, f64)>,
40    anti_windup: Option<bool>,
41    dt: f64,
42    integral_state: f64,
43    prev_filtered_measurement: f64,
44    deriv_lpf: BiquadFilter,
45}
46
47impl PidController {
48    pub fn new(
49        setpoint: Option<f64>,
50        kp: Option<f64>,
51        ki: Option<f64>,
52        kd: Option<f64>,
53        output_limits: Option<(f64, f64)>,
54        anti_windup: Option<bool>,
55    ) -> Result<Self, ErrorsJSL> {
56        Self::new_with_dt(setpoint, kp, ki, kd, output_limits, anti_windup, 1.0)
57    }
58
59    pub fn new_with_dt(
60        setpoint: Option<f64>,
61        kp: Option<f64>,
62        ki: Option<f64>,
63        kd: Option<f64>,
64        output_limits: Option<(f64, f64)>,
65        anti_windup: Option<bool>,
66        dt: f64,
67    ) -> Result<Self, ErrorsJSL> {
68        if !dt.is_finite() || dt <= 0.0 {
69            return Err(ErrorsJSL::InvalidInputRange("dt must be finite and > 0"));
70        }
71        if let Some((lo, hi)) = output_limits
72            && (!lo.is_finite() || !hi.is_finite() || lo > hi)
73        {
74            return Err(ErrorsJSL::InvalidInputRange(
75                "output_limits must be finite and satisfy min <= max",
76            ));
77        }
78        Ok(Self {
79            setpoint: setpoint.unwrap_or(0.0),
80            kp,
81            ki,
82            kd,
83            output_limits,
84            anti_windup,
85            dt,
86            integral_state: 0.0,
87            prev_filtered_measurement: 0.0,
88            deriv_lpf: BiquadFilter::lowpass(0.1)?,
89        })
90    }
91
92    pub fn set_setpoint(&mut self, setpoint: f64) {
93        self.setpoint = setpoint;
94    }
95
96    pub fn set_coefficients(&mut self, kp: Option<f64>, ki: Option<f64>, kd: Option<f64>) {
97        self.kp = kp;
98        self.ki = ki;
99        self.kd = kd;
100    }
101
102    pub fn set_output_limits(&mut self, output_limits: Option<(f64, f64)>) -> Result<(), ErrorsJSL> {
103        if let Some((lo, hi)) = output_limits
104            && (!lo.is_finite() || !hi.is_finite() || lo > hi)
105        {
106            return Err(ErrorsJSL::InvalidInputRange(
107                "output_limits must be finite and satisfy min <= max",
108            ));
109        }
110        self.output_limits = output_limits;
111        Ok(())
112    }
113
114    pub fn set_anti_windup(&mut self, anti_windup: Option<bool>) {
115        self.anti_windup = anti_windup;
116    }
117
118    pub fn set_kp(&mut self, kp: Option<f64>) {
119        self.kp = kp;
120    }
121
122    pub fn set_ki(&mut self, ki: Option<f64>) {
123        self.ki = ki;
124    }
125
126    pub fn set_kd(&mut self, kd: Option<f64>) {
127        self.kd = kd;
128    }
129
130    pub fn reset_integral(&mut self) {
131        self.integral_state = 0.0;
132    }
133
134    // ANCHOR: pid
135    fn step(&mut self, measurement: f64) -> PidOutput {
136        let error = self.setpoint - measurement;
137
138        let p_term = self.kp.unwrap_or(0.0) * error;
139
140        let i_prev = self.integral_state;
141        self.integral_state += error * self.dt;
142        let i_term = self.ki.unwrap_or(0.0) * self.integral_state;
143
144        // Derivative on filtered measurement to reduce noise sensitivity and
145        // avoid setpoint-derivative kick.
146        let filtered = self.deriv_lpf.step(measurement);
147        let d_meas = (filtered - self.prev_filtered_measurement) / self.dt;
148        self.prev_filtered_measurement = filtered;
149        let d_term = self.kd.unwrap_or(0.0) * (-d_meas);
150
151        let mut control = p_term + i_term + d_term;
152        let mut saturated = false;
153        if let Some((lo, hi)) = self.output_limits {
154            if control < lo {
155                control = lo;
156                saturated = true;
157            } else if control > hi {
158                control = hi;
159                saturated = true;
160            }
161        }
162
163        if self.anti_windup.unwrap_or(false) && saturated {
164            let pushing_further = if let Some((lo, hi)) = self.output_limits {
165                (control >= hi && error > 0.0) || (control <= lo && error < 0.0)
166            } else {
167                false
168            };
169            if pushing_further {
170                self.integral_state = i_prev;
171            }
172        }
173
174        PidOutput {
175            control,
176            error,
177        }
178    }
179    // ANCHOR_END: pid
180}
181
182impl StreamOperatorManagement for PidController {
183    fn reset(&mut self) -> Result<(), ErrorsJSL> {
184        self.integral_state = 0.0;
185        self.prev_filtered_measurement = 0.0;
186        self.deriv_lpf.reset()?;
187        Ok(())
188    }
189
190    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
191        Ok(())
192    }
193}
194
195impl StreamOperator<f64, PidOutput> for PidController {
196    fn process(&mut self, data_in: &[f64]) -> Result<Option<Vec<PidOutput>>, ErrorsJSL> {
197        if data_in.is_empty() {
198            return Ok(None);
199        }
200        Ok(Some(data_in.iter().map(|&x| self.step(x)).collect()))
201    }
202
203    fn flush(&mut self) -> Result<Option<Vec<PidOutput>>, ErrorsJSL> {
204        Ok(None)
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn test_pid_p_only() {
214        let mut pid = PidController::new(Some(1.0), Some(2.0), None, None, None, None).unwrap();
215        let y = pid.process(&[0.0, 0.5, 1.0]).unwrap().unwrap();
216        assert!((y[0].control - 2.0).abs() < 1e-12);
217        assert!((y[1].control - 1.0).abs() < 1e-12);
218        assert!((y[2].control - 0.0).abs() < 1e-12);
219    }
220
221    #[test]
222    fn test_pid_integral_accumulates() {
223        let mut pid = PidController::new(Some(1.0), None, Some(1.0), None, None, None).unwrap();
224        let y = pid.process(&[0.0, 0.0, 0.0]).unwrap().unwrap();
225        assert!(y[1].control > y[0].control);
226        assert!(y[2].control > y[1].control);
227    }
228
229    #[test]
230    fn test_pid_runtime_programming() {
231        let mut pid = PidController::new(Some(0.0), Some(1.0), None, None, None, None).unwrap();
232        let a = pid.process(&[1.0]).unwrap().unwrap()[0];
233        pid.set_setpoint(2.0);
234        pid.set_coefficients(Some(0.5), None, None);
235        let b = pid.process(&[1.0]).unwrap().unwrap()[0];
236        assert!((a.error + 1.0).abs() < 1e-12);
237        assert!((b.error - 1.0).abs() < 1e-12);
238        assert!((b.control - 0.5).abs() < 1e-12);
239    }
240
241    #[test]
242    fn test_pid_output_limiting() {
243        let mut pid =
244            PidController::new(Some(10.0), Some(10.0), None, None, Some((-1.0, 1.0)), None)
245                .unwrap();
246        let y = pid.process(&[0.0]).unwrap().unwrap();
247        assert!((y[0].control - 1.0).abs() < 1e-12);
248    }
249
250    #[test]
251    fn test_pid_anti_windup_prevents_integral_growth_on_saturation() {
252        let mut pid = PidController::new(
253            Some(10.0),
254            None,
255            Some(1.0),
256            None,
257            Some((-0.5, 0.5)),
258            Some(true),
259        )
260        .unwrap();
261        let y = pid.process(&[0.0, 0.0, 0.0, 0.0]).unwrap().unwrap();
262        for yi in y {
263            assert!((yi.control - 0.5).abs() < 1e-12);
264        }
265    }
266}