Skip to main content

stable_flight/controllers/
notch.rs

1//! Notch filter for the copter's gyro path: see [`NotchConfig`].
2
3use core::f32::consts::PI;
4
5use nalgebra::Complex;
6
7use super::biquad::{Biquad, Section};
8use super::{InvalidConfig, check};
9
10/// Highest center a notch takes, as a share of the sample rate: past it the filter passes the
11/// signal through (ArduPilot's `HARMONIC_NYQUIST_CUTOFF`).
12const MAX_CENTER_SHARE: f32 = 0.48;
13
14/// Lowest center a notch takes, as a share of its bandwidth: a lower one is raised to it, so
15/// the band's lower edge stays above 0 Hz, as ArduPilot's `HarmonicNotchFilter::init` does.
16const MIN_CENTER_PER_BANDWIDTH: f32 = 0.52;
17
18/// Where a gyro notch cuts and how deep: one vibration tone, such as a motor's, removed from
19/// the body rates before the low-pass, so the rate loop's D doesn't amplify it into the
20/// moments. A low-pass alone barely touches a tone just above its cutoff.
21///
22/// ArduPilot's harmonic notch in its fixed mode (`INS_HNTCH_FREQ`, `INS_HNTCH_BW`,
23/// `INS_HNTCH_ATT`, `NotchFilter`), described, not copied: a biquad whose band edges sit
24/// geometrically about the center, `center − bandwidth/2` below it, with a finite depth.
25///
26/// # Examples
27///
28/// ```
29/// use stable_flight::controllers::NotchConfig;
30///
31/// assert!(!NotchConfig::default().is_on());
32/// let notch = NotchConfig { center_hz: 90.0, bandwidth_hz: 45.0, attenuation_db: 40.0 };
33/// assert!(notch.validate().is_ok());
34/// ```
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub struct NotchConfig {
37    /// The tone cut, in Hz; 0 turns the notch off, and so does one at or past 0.48 of the
38    /// sample rate. One under 0.52 of the bandwidth cuts at 0.52 of it. Non-negative and
39    /// finite.
40    pub center_hz: f32,
41    /// Width of the band cut, in Hz: wider takes a tone that wanders, at more lag below the
42    /// center (ArduPilot suggests half the center); 0 cuts nothing. Non-negative and finite.
43    pub bandwidth_hz: f32,
44    /// How deep the notch cuts at its center, in dB. Positive and finite: past 40 dB it cuts
45    /// hard rather than attenuating (ArduPilot's `INS_HNTCH_ATT` default is 40).
46    pub attenuation_db: f32,
47}
48
49impl Default for NotchConfig {
50    /// Off, with ArduPilot's width and depth (`INS_HNTCH_BW` 40 Hz, `INS_HNTCH_ATT` 40 dB)
51    /// ready for a center.
52    fn default() -> Self {
53        Self {
54            center_hz: 0.0,
55            bandwidth_hz: 40.0,
56            attenuation_db: 40.0,
57        }
58    }
59}
60
61impl NotchConfig {
62    /// Whether the notch cuts anything: a positive center.
63    pub fn is_on(&self) -> bool {
64        self.center_hz > 0.0
65    }
66
67    /// Checks each field's stated requirement; each stands alone, so a param can change any
68    /// one of them.
69    pub fn validate(&self) -> Result<(), InvalidConfig> {
70        check(
71            "center_hz",
72            self.center_hz >= 0.0 && self.center_hz.is_finite(),
73            "non-negative and finite",
74        )?;
75        check(
76            "bandwidth_hz",
77            self.bandwidth_hz >= 0.0 && self.bandwidth_hz.is_finite(),
78            "non-negative and finite",
79        )?;
80        check(
81            "attenuation_db",
82            self.attenuation_db > 0.0 && self.attenuation_db.is_finite(),
83            "positive and finite",
84        )
85    }
86
87    /// The notch's response at `unit_delay` for samples `dt_s` apart, `(b₀ + b₁·z⁻¹ + b₂·z⁻²)
88    /// / (a₀ + a₁·z⁻¹ + a₂·z⁻²)`: 1 where the filter passes the signal through. The
89    /// autotune's design models it, as it does the low-pass.
90    pub fn response(&self, dt_s: f32, unit_delay: Complex<f32>) -> Complex<f32> {
91        let one = Complex::new(1.0, 0.0);
92        let Some(Coefficients { b, a }) = Coefficients::new(self, dt_s) else {
93            return one;
94        };
95        let z1 = unit_delay;
96        (one * b[0] + z1 * b[1] + z1 * z1 * b[2]) / (one + z1 * a[0] + z1 * z1 * a[1])
97    }
98}
99
100/// Cuts one tone out of a signal ([`NotchConfig`]), on the shared two-pole state
101/// ([`Biquad`]): the first sample fills the history, so the output starts at the input, and a
102/// non-finite sample passes through and leaves the history as it was.
103#[derive(Clone, Copy, Debug, Default, PartialEq)]
104pub(crate) struct Notch(Biquad<Coefficients>);
105
106impl Notch {
107    /// Filters `value`, sampled `dt` s after the last, through `config`'s notch. The
108    /// coefficients are recomputed only when `config` or `dt` changes.
109    pub(crate) fn apply(&mut self, value: f32, dt: f32, config: &NotchConfig) -> f32 {
110        self.0.apply(value, dt, config)
111    }
112}
113
114/// A [`Notch`]'s weights, normalized so `a₀` is 1: numerator `b` for `z⁰`, `z⁻¹`, `z⁻²`, and
115/// denominator `a` for `z⁻¹`, `z⁻²`.
116#[derive(Clone, Copy, Debug, PartialEq)]
117struct Coefficients {
118    b: [f32; 3],
119    a: [f32; 2],
120}
121
122impl Section for Coefficients {
123    type Settings = NotchConfig;
124
125    /// `None` when the notch passes the signal through: off, no width, at or past
126    /// [`MAX_CENTER_SHARE`] of the sample rate, or not a valid config. A center under
127    /// [`MIN_CENTER_PER_BANDWIDTH`] of the bandwidth is raised to it.
128    ///
129    /// The band's lower edge is `center − bandwidth/2`; its width in octaves, `n = 2·log₂(center
130    /// / lower)`, gives `Q = √(2ⁿ) / (2ⁿ − 1)`, and with `ω = 2π·center·dt`, `α = sin ω / 2Q`
131    /// and the depth `g = 10^(−attenuation/20)`: `b = [1 + α·g, −2·cos ω, 1 − α·g]` and
132    /// `a = [−2·cos ω, 1 − α]`, each over `a₀ = 1 + α`. At the center the gain is `g`; far from
133    /// it, 1.
134    fn new(config: &NotchConfig, dt_s: f32) -> Option<Self> {
135        let center_hz = config
136            .center_hz
137            .max(MIN_CENTER_PER_BANDWIDTH * config.bandwidth_hz);
138        let center_share = center_hz * dt_s;
139        let cuts = config.is_on()
140            && config.bandwidth_hz > 0.0
141            && center_share < MAX_CENTER_SHARE
142            && config.validate().is_ok();
143        if !cuts {
144            return None;
145        }
146        let lower_hz = center_hz - 0.5 * config.bandwidth_hz;
147        let octaves = 2.0 * libm::log2f(center_hz / lower_hz);
148        let ratio = libm::exp2f(octaves);
149        let q = libm::sqrtf(ratio) / (ratio - 1.0);
150        let omega = 2.0 * PI * center_share;
151        let alpha = libm::sinf(omega) / (2.0 * q);
152        let depth = libm::powf(10.0, -config.attenuation_db / 20.0);
153        let cos_omega = libm::cosf(omega);
154        let a0 = 1.0 + alpha;
155        Some(Self {
156            b: [1.0 + alpha * depth, -2.0 * cos_omega, 1.0 - alpha * depth].map(|b| b / a0),
157            a: [-2.0 * cos_omega, 1.0 - alpha].map(|a| a / a0),
158        })
159    }
160
161    fn step(&self, value: f32, inputs: [f32; 2], outputs: [f32; 2]) -> f32 {
162        let Self { b, a } = *self;
163        b[0] * value + b[1] * inputs[0] + b[2] * inputs[1] - a[0] * outputs[0] - a[1] * outputs[1]
164    }
165}
166
167#[cfg(test)]
168mod tests;