Skip to main content

autoeq_core/
param_utils.rs

1//! Parameter vector utilities for handling different PEQ models
2//!
3//! This module provides utilities for working with parameter vectors that may have
4//! different layouts depending on the PEQ model being used.
5
6use crate::PeqModel;
7use crate::iir::BiquadFilterType;
8
9/// Position of each parameter inside a filter's parameter group.
10#[derive(Debug, Clone, Copy)]
11pub struct ParamLayout {
12    /// Index of the encoded filter type, if present.
13    pub type_idx: Option<usize>,
14    /// Index of the log10 frequency parameter.
15    pub freq_idx: usize,
16    /// Index of the Q parameter.
17    pub q_idx: usize,
18    /// Index of the gain parameter.
19    pub gain_idx: usize,
20}
21
22/// Strategy trait that encapsulates the parameter-vector layout for a PEQ model.
23///
24/// Implementations describe how many parameters each filter consumes, where each
25/// semantic parameter lives, and how to convert between the flat vector and filter
26/// descriptors.
27pub trait PeqLayout {
28    /// Number of scalar parameters stored for each filter.
29    fn params_per_filter(&self) -> usize;
30
31    /// Position of each semantic parameter within a filter group.
32    fn layout(&self) -> ParamLayout;
33
34    /// Number of filters represented by a parameter vector.
35    fn num_filters(&self, x: &[f64]) -> usize {
36        x.len() / self.params_per_filter()
37    }
38
39    /// Extract the parameters for the `i`-th filter.
40    fn get_filter_params(&self, x: &[f64], i: usize) -> FilterParams;
41
42    /// Write the parameters for the `i`-th filter into an existing vector.
43    fn set_filter_params(&self, x: &mut [f64], i: usize, params: &FilterParams);
44
45    /// Append a filter's parameters to a vector (used when building a vector from
46    /// scratch, e.g. `peq2x`).
47    fn append_filter_params(&self, x: &mut Vec<f64>, params: &FilterParams) {
48        let l = self.layout();
49        if let Some(type_idx) = l.type_idx {
50            x.push(params.filter_type.unwrap_or(0.0));
51            // Only fixed/free layout is supported; assert indices line up.
52            assert_eq!(l.freq_idx, type_idx + 1);
53        }
54        x.push(params.freq);
55        x.push(params.q);
56        x.push(params.gain);
57    }
58
59    /// Determine the biquad type for filter `i` given the model and optional type
60    /// parameter.
61    fn determine_filter_type(
62        &self,
63        i: usize,
64        num_filters: usize,
65        type_param: Option<f64>,
66    ) -> BiquadFilterType;
67
68    /// Build an initial-guess parameter group for filter `i`.
69    fn initial_guess_filter(
70        &self,
71        i: usize,
72        num_filters: usize,
73        lower_bounds: &[f64],
74        upper_bounds: &[f64],
75        min_db: f64,
76        max_freq: f64,
77    ) -> Vec<f64>;
78}
79
80impl PeqLayout for PeqModel {
81    fn params_per_filter(&self) -> usize {
82        match self {
83            PeqModel::Pk
84            | PeqModel::HpPk
85            | PeqModel::HpPkLp
86            | PeqModel::LsPk
87            | PeqModel::LsPkHs => 3,
88            PeqModel::FreePkFree | PeqModel::Free => 4,
89        }
90    }
91
92    fn layout(&self) -> ParamLayout {
93        match self {
94            PeqModel::Pk
95            | PeqModel::HpPk
96            | PeqModel::HpPkLp
97            | PeqModel::LsPk
98            | PeqModel::LsPkHs => ParamLayout {
99                type_idx: None,
100                freq_idx: 0,
101                q_idx: 1,
102                gain_idx: 2,
103            },
104            PeqModel::FreePkFree | PeqModel::Free => ParamLayout {
105                type_idx: Some(0),
106                freq_idx: 1,
107                q_idx: 2,
108                gain_idx: 3,
109            },
110        }
111    }
112
113    fn get_filter_params(&self, x: &[f64], i: usize) -> FilterParams {
114        let l = self.layout();
115        let offset = i * self.params_per_filter();
116        FilterParams {
117            filter_type: l.type_idx.map(|idx| x[offset + idx]),
118            freq: x[offset + l.freq_idx],
119            q: x[offset + l.q_idx],
120            gain: x[offset + l.gain_idx],
121        }
122    }
123
124    fn set_filter_params(&self, x: &mut [f64], i: usize, params: &FilterParams) {
125        let l = self.layout();
126        let offset = i * self.params_per_filter();
127        if let Some(type_idx) = l.type_idx {
128            x[offset + type_idx] = params.filter_type.unwrap_or(0.0);
129        }
130        x[offset + l.freq_idx] = params.freq;
131        x[offset + l.q_idx] = params.q;
132        x[offset + l.gain_idx] = params.gain;
133    }
134
135    fn determine_filter_type(
136        &self,
137        i: usize,
138        num_filters: usize,
139        type_param: Option<f64>,
140    ) -> BiquadFilterType {
141        match self {
142            PeqModel::Pk => BiquadFilterType::Peak,
143            PeqModel::HpPk => {
144                if i == 0 {
145                    BiquadFilterType::HighpassVariableQ
146                } else {
147                    BiquadFilterType::Peak
148                }
149            }
150            PeqModel::HpPkLp => {
151                if i == 0 {
152                    BiquadFilterType::HighpassVariableQ
153                } else if i == num_filters - 1 {
154                    BiquadFilterType::Lowpass
155                } else {
156                    BiquadFilterType::Peak
157                }
158            }
159            PeqModel::LsPk => {
160                if i == 0 {
161                    BiquadFilterType::Lowshelf
162                } else {
163                    BiquadFilterType::Peak
164                }
165            }
166            PeqModel::LsPkHs => {
167                if i == 0 {
168                    BiquadFilterType::Lowshelf
169                } else if i == num_filters - 1 {
170                    BiquadFilterType::Highshelf
171                } else {
172                    BiquadFilterType::Peak
173                }
174            }
175            PeqModel::FreePkFree => {
176                if i == 0 || i == num_filters - 1 {
177                    decode_filter_type(type_param.unwrap_or(0.0))
178                } else {
179                    BiquadFilterType::Peak
180                }
181            }
182            PeqModel::Free => decode_filter_type(type_param.unwrap_or(0.0)),
183        }
184    }
185
186    fn initial_guess_filter(
187        &self,
188        i: usize,
189        num_filters: usize,
190        lower_bounds: &[f64],
191        upper_bounds: &[f64],
192        min_db: f64,
193        max_freq: f64,
194    ) -> Vec<f64> {
195        let l = self.layout();
196        let mut group = Vec::with_capacity(self.params_per_filter());
197        let sign = if i.is_multiple_of(2) { 0.5 } else { -0.5 };
198
199        if let Some(type_idx) = l.type_idx {
200            group.push(0.0_f64.clamp(lower_bounds[type_idx], upper_bounds[type_idx]));
201        }
202
203        let upper_frequency = upper_bounds[l.freq_idx].min(max_freq.log10());
204        let fraction = (i + 1) as f64 / (num_filters + 1).max(2) as f64;
205        let freq = (lower_bounds[l.freq_idx]
206            + fraction * (upper_frequency - lower_bounds[l.freq_idx]))
207            .clamp(lower_bounds[l.freq_idx], upper_bounds[l.freq_idx]);
208        group.push(freq);
209
210        let q = (upper_bounds[l.q_idx] * lower_bounds[l.q_idx])
211            .sqrt()
212            .clamp(lower_bounds[l.q_idx], upper_bounds[l.q_idx]);
213        group.push(q);
214
215        let gain = (sign * upper_bounds[l.gain_idx].max(min_db))
216            .clamp(lower_bounds[l.gain_idx], upper_bounds[l.gain_idx]);
217        group.push(gain);
218
219        group
220    }
221}
222
223/// Get the number of parameters per filter for a given PEQ model
224pub fn params_per_filter(peq_model: PeqModel) -> usize {
225    peq_model.params_per_filter()
226}
227
228/// Get the number of filters from a parameter vector
229pub fn num_filters(x: &[f64], peq_model: PeqModel) -> usize {
230    peq_model.num_filters(x)
231}
232
233/// Extract filter parameters for the i-th filter
234pub fn get_filter_params(x: &[f64], i: usize, peq_model: PeqModel) -> FilterParams {
235    peq_model.get_filter_params(x, i)
236}
237
238/// Set filter parameters for the i-th filter
239pub fn set_filter_params(x: &mut [f64], i: usize, params: &FilterParams, peq_model: PeqModel) {
240    peq_model.set_filter_params(x, i, params);
241}
242
243/// Container for filter parameters
244#[derive(Debug, Clone)]
245pub struct FilterParams {
246    /// Filter type (encoded as f64 for free filter models)
247    pub filter_type: Option<f64>,
248    /// Frequency (as log10 for optimization)
249    pub freq: f64,
250    /// Q factor
251    pub q: f64,
252    /// Gain in dB
253    pub gain: f64,
254}
255
256/// Determine the filter type based on model and position
257pub fn determine_filter_type(
258    i: usize,
259    num_filters: usize,
260    peq_model: PeqModel,
261    type_param: Option<f64>,
262) -> BiquadFilterType {
263    peq_model.determine_filter_type(i, num_filters, type_param)
264}
265
266/// Decode filter type from parameter value
267/// Maps continuous parameter to discrete filter types for optimization
268pub fn decode_filter_type(type_value: f64) -> BiquadFilterType {
269    assert!(
270        type_value.is_finite() && (0.0..12.0).contains(&type_value),
271        "invalid free-filter topology value {type_value}; expected a finite value in [0, 12)"
272    );
273    // Map [0, 1) -> Peak
274    // Map [1, 2) -> Lowpass
275    // Map [2, 3) -> Highpass
276    // Map [3, 4) -> Lowshelf
277    // Map [4, 5) -> Highshelf
278    // Map [5, 6) -> HighpassVariableQ
279    // Map [6, 7) -> Bandpass
280    // Map [7, 8) -> Notch
281    // Map [8, 9) -> AllPass
282    // Map [9, 10) -> Orfanidis low shelf
283    // Map [10, 11) -> Orfanidis high shelf
284    // Map [11, 12) -> matched peak
285
286    let idx = type_value.floor() as i32;
287    match idx {
288        0 => BiquadFilterType::Peak,
289        1 => BiquadFilterType::Lowpass,
290        2 => BiquadFilterType::Highpass,
291        3 => BiquadFilterType::Lowshelf,
292        4 => BiquadFilterType::Highshelf,
293        5 => BiquadFilterType::HighpassVariableQ,
294        6 => BiquadFilterType::Bandpass,
295        7 => BiquadFilterType::Notch,
296        8 => BiquadFilterType::AllPass,
297        9 => BiquadFilterType::LowshelfOrf,
298        10 => BiquadFilterType::HighshelfOrf,
299        11 => BiquadFilterType::PeakMatched,
300        _ => unreachable!("validated free-filter topology index"),
301    }
302}
303
304/// Encode filter type to parameter value
305pub fn encode_filter_type(filter_type: BiquadFilterType) -> f64 {
306    match filter_type {
307        BiquadFilterType::Peak => 0.0,
308        BiquadFilterType::Lowpass => 1.0,
309        BiquadFilterType::Highpass => 2.0,
310        BiquadFilterType::Lowshelf => 3.0,
311        BiquadFilterType::Highshelf => 4.0,
312        BiquadFilterType::HighpassVariableQ => 5.0,
313        BiquadFilterType::Bandpass => 6.0,
314        BiquadFilterType::Notch => 7.0,
315        BiquadFilterType::AllPass => 8.0,
316        BiquadFilterType::LowshelfOrf => 9.0,
317        BiquadFilterType::HighshelfOrf => 10.0,
318        BiquadFilterType::PeakMatched => 11.0,
319    }
320}
321
322/// Get bounds for filter type parameter
323pub fn filter_type_bounds() -> (f64, f64) {
324    (0.0, 11.999)
325}
326
327/// Convert log10 frequency parameter to Hz
328///
329/// Filter frequencies are stored as log10(Hz) in the optimization parameter vector.
330/// This function converts back to linear Hz.
331#[inline]
332pub fn freq_from_log10(log_freq: f64) -> f64 {
333    10f64.powf(log_freq)
334}
335
336/// Convert log10 frequency parameter to Hz with minimum value clamping
337///
338/// Like `freq_from_log10` but clamps the result to avoid numerical issues
339/// with very small or negative frequencies.
340#[inline]
341pub fn freq_from_log10_clamped(log_freq: f64, min_freq: f64) -> f64 {
342    10f64.powf(log_freq).max(min_freq)
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use crate::PeqModel;
349    use crate::iir::BiquadFilterType;
350
351    #[test]
352    fn get_filter_params_fixed() {
353        let x = vec![2.0, 1.5, 3.0];
354        let p = get_filter_params(&x, 0, PeqModel::Pk);
355        assert_eq!(p.freq, 2.0);
356        assert_eq!(p.q, 1.5);
357        assert_eq!(p.gain, 3.0);
358        assert!(p.filter_type.is_none());
359    }
360
361    #[test]
362    fn get_filter_params_free() {
363        let x = vec![1.0, 2.0, 1.5, 3.0];
364        let p = get_filter_params(&x, 0, PeqModel::Free);
365        assert_eq!(p.filter_type, Some(1.0));
366        assert_eq!(p.freq, 2.0);
367        assert_eq!(p.q, 1.5);
368        assert_eq!(p.gain, 3.0);
369    }
370
371    #[test]
372    fn set_filter_params_round_trip() {
373        let mut x = vec![0.0; 3];
374        let params = FilterParams {
375            filter_type: None,
376            freq: 2.0,
377            q: 1.5,
378            gain: 3.0,
379        };
380        set_filter_params(&mut x, 0, &params, PeqModel::Pk);
381        assert_eq!(x, vec![2.0, 1.5, 3.0]);
382    }
383
384    #[test]
385    fn determine_filter_type_pk() {
386        assert_eq!(
387            determine_filter_type(0, 3, PeqModel::Pk, None),
388            BiquadFilterType::Peak
389        );
390    }
391
392    #[test]
393    fn determine_filter_type_hp_pk() {
394        assert_eq!(
395            determine_filter_type(0, 3, PeqModel::HpPk, None),
396            BiquadFilterType::HighpassVariableQ
397        );
398        assert_eq!(
399            determine_filter_type(1, 3, PeqModel::HpPk, None),
400            BiquadFilterType::Peak
401        );
402    }
403
404    #[test]
405    fn determine_filter_type_ls_pk_hs() {
406        assert_eq!(
407            determine_filter_type(0, 3, PeqModel::LsPkHs, None),
408            BiquadFilterType::Lowshelf
409        );
410        assert_eq!(
411            determine_filter_type(1, 3, PeqModel::LsPkHs, None),
412            BiquadFilterType::Peak
413        );
414        assert_eq!(
415            determine_filter_type(2, 3, PeqModel::LsPkHs, None),
416            BiquadFilterType::Highshelf
417        );
418    }
419
420    #[test]
421    fn filter_type_bounds_range() {
422        let (min, max) = filter_type_bounds();
423        assert_eq!(min, 0.0);
424        assert_eq!(max, 11.999);
425    }
426
427    #[test]
428    fn audit_every_encoded_filter_type_is_decodable_and_in_bounds() {
429        let filter_types = [
430            BiquadFilterType::Peak,
431            BiquadFilterType::Lowpass,
432            BiquadFilterType::Highpass,
433            BiquadFilterType::Lowshelf,
434            BiquadFilterType::Highshelf,
435            BiquadFilterType::HighpassVariableQ,
436            BiquadFilterType::Bandpass,
437            BiquadFilterType::Notch,
438            BiquadFilterType::AllPass,
439            BiquadFilterType::LowshelfOrf,
440            BiquadFilterType::HighshelfOrf,
441            BiquadFilterType::PeakMatched,
442        ];
443        let (lower, upper) = filter_type_bounds();
444
445        for filter_type in filter_types {
446            let encoded = encode_filter_type(filter_type);
447            assert!(encoded >= lower && encoded <= upper);
448            assert_eq!(decode_filter_type(encoded), filter_type);
449        }
450    }
451
452    #[test]
453    fn freq_from_log10_basic() {
454        assert!((freq_from_log10(2.0) - 100.0).abs() < 1e-12);
455    }
456
457    #[test]
458    fn freq_from_log10_clamped_respects_min() {
459        assert_eq!(freq_from_log10_clamped(-10.0, 20.0), 20.0);
460    }
461
462    #[test]
463    fn invalid_free_filter_topology_is_rejected() {
464        for invalid in [f64::NAN, f64::INFINITY, -0.1, 12.0, f64::MAX] {
465            assert!(std::panic::catch_unwind(|| decode_filter_type(invalid)).is_err());
466        }
467    }
468
469    #[test]
470    fn initial_filter_centers_are_distributed_in_log_frequency() {
471        let lower = [20.0_f64.log10(), 0.5, -12.0];
472        let upper = [20_000.0_f64.log10(), 10.0, 6.0];
473        let centers: Vec<f64> = (0..5)
474            .map(|index| {
475                PeqModel::Pk.initial_guess_filter(index, 5, &lower, &upper, -12.0, 20_000.0)[0]
476            })
477            .collect();
478        assert!(centers.windows(2).all(|pair| pair[0] < pair[1]));
479        let step = centers[1] - centers[0];
480        assert!(
481            centers
482                .windows(2)
483                .all(|pair| ((pair[1] - pair[0]) - step).abs() < 1e-12)
484        );
485    }
486}