idsp 0.23.0

DSP algorithms for embedded, mostly integer math
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Control-plane configuration types.

use core::any::Any;

use miniconf::{Tree, leaf};
use num_traits::{AsPrimitive, Float, FloatConst};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned};

use crate::{
    Build,
    iir::{
        BiquadClamp, Error,
        coefficients::{Filter, Shape, Type},
        pid::{Gains, Order, Pid, Units},
    },
};

/// Output bounds `[min, max]`.
///
/// Serde maps an unbounded endpoint between `null` and the corresponding infinity.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ClampConfig<T>([T; 2]);

impl<T> Serialize for ClampConfig<T>
where
    T: Serialize + Float,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        [
            (self.0[0] != T::neg_infinity()).then_some(self.0[0]),
            (self.0[1] != T::infinity()).then_some(self.0[1]),
        ]
        .serialize(serializer)
    }
}

impl<T> ClampConfig<T> {
    /// Create an output range from lower and upper bounds.
    pub const fn new(min: T, max: T) -> Self {
        Self([min, max])
    }
}

impl<T: Copy> ClampConfig<T> {
    /// Return `[min, max]`.
    pub const fn bounds(&self) -> [T; 2] {
        self.0
    }
}

impl<T: Float> Default for ClampConfig<T> {
    fn default() -> Self {
        Self([T::neg_infinity(), T::infinity()])
    }
}

impl<T: Float> ClampConfig<T> {
    fn validate(&self) -> Result<(), Error> {
        let [min, max] = self.0;
        if !(min.is_finite() || min == T::neg_infinity())
            || !(max.is_finite() || max == T::infinity())
        {
            return Err(Error::NonFinite("output_clamp"));
        }
        if min > max {
            return Err(Error::InvertedRange("output_clamp"));
        }
        Ok(())
    }
}

impl<'de, T> Deserialize<'de> for ClampConfig<T>
where
    T: Deserialize<'de> + Float,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let bounds = <[Option<T>; 2]>::deserialize(deserializer)?;
        let clamp = Self([
            bounds[0].unwrap_or_else(T::neg_infinity),
            bounds[1].unwrap_or_else(T::infinity),
        ]);
        clamp.validate().map_err(serde::de::Error::custom)?;
        Ok(clamp)
    }
}

/// Floating point BA coefficients before quantization.
#[derive(Debug, Clone, Tree)]
#[tree(meta(doc, typename))]
pub struct BaConfig<T> {
    /// Coefficient array: [[b0, b1, b2], [a0, a1, a2]]
    #[tree(with=leaf, bounds(serialize="T: Serialize", deserialize="T: DeserializeOwned", any="T: Any"))]
    pub ba: [[T; 3]; 2],
    /// Summing junction offset.
    pub offset: T,
    /// Output clamp.
    #[tree(with=leaf, bounds(serialize="T: Serialize + Float", deserialize="T: DeserializeOwned + Float", any="T: Any"))]
    pub clamp: ClampConfig<T>,
}

impl<T: Float> Default for BaConfig<T> {
    fn default() -> Self {
        Self {
            ba: [[T::zero(); 3], [T::one(), T::zero(), T::zero()]],
            offset: T::zero(),
            clamp: ClampConfig::default(),
        }
    }
}

/// Standard biquad filter parameters.
#[derive(Clone, Debug, Tree)]
#[tree(meta(doc, typename))]
pub struct FilterConfig<T> {
    /// Filter style.
    #[tree(with=leaf)]
    pub typ: Type,
    /// Relative critical frequency in units of the sample rate.
    pub frequency: T,
    /// Passband gain in dB.
    pub gain_db: T,
    /// Shelf gain in dB.
    ///
    /// Used for peaking, low shelf, and high shelf filters.
    pub shelf_db: T,
    /// Q, bandwidth, or slope.
    #[tree(with=leaf, bounds(serialize="T: Serialize", deserialize="T: DeserializeOwned", any="T: Any"))]
    pub shape: Shape<T>,
    /// Summing junction offset.
    pub offset: T,
    /// Output clamp.
    #[tree(with=leaf, bounds(serialize="T: Serialize + Float", deserialize="T: DeserializeOwned + Float", any="T: Any"))]
    pub clamp: ClampConfig<T>,
}

impl<T: Float + FloatConst> Default for FilterConfig<T> {
    fn default() -> Self {
        Self {
            typ: Type::default(),
            frequency: T::zero(),
            gain_db: T::zero(),
            shelf_db: T::zero(),
            shape: Shape::default(),
            offset: T::zero(),
            clamp: ClampConfig::default(),
        }
    }
}

/// Named PID gains.
#[derive(Clone, Debug, Tree, Default)]
pub struct GainsConfig<T> {
    /// Double integral.
    pub i2: T,
    /// Integral.
    pub i: T,
    /// Proportional.
    pub p: T,
    /// Derivative.
    pub d: T,
    /// Double derivative.
    pub d2: T,
}

impl<T> GainsConfig<T> {
    /// Create named gain configuration.
    pub const fn new(i2: T, i: T, p: T, d: T, d2: T) -> Self {
        Self { i2, i, p, d, d2 }
    }
}

impl<T: Copy> GainsConfig<T> {
    /// Create gain configuration with the same value for all actions.
    pub const fn splat(value: T) -> Self {
        Self::new(value, value, value, value, value)
    }
}

impl<T: Copy> From<&GainsConfig<T>> for Gains<T> {
    fn from(config: &GainsConfig<T>) -> Self {
        Self::new([config.i2, config.i, config.p, config.d, config.d2])
    }
}

/// PID controller configuration.
#[derive(Clone, Debug, Tree)]
#[tree(meta(doc, typename))]
pub struct PidConfig<T> {
    /// Feedback term order.
    #[tree(with=leaf)]
    pub order: Order,
    /// Gain.
    ///
    /// * Sequence: [I², I, P, D, D²]
    /// * Units: output/input * second**order where `Action::I2` has order=-2
    /// * Gains outside the range `order..=order + 3` are ignored
    /// * P gain sign determines sign of all gains
    pub gain: GainsConfig<T>,
    /// Gain limit.
    ///
    /// * Sequence: [I², I, P, D, D²]
    /// * Units: output/input
    /// * P gain limit is ignored
    /// * Limits outside the range `order..order + 3` are ignored
    /// * P gain sign determines sign of all gain limits
    /// * `null` selects an unbounded limit
    pub limit: GainsConfig<T>,
    /// Setpoint.
    ///
    /// Units: input.
    pub setpoint: T,
    /// Output clamp.
    ///
    /// Units: output.
    #[tree(with=leaf, bounds(serialize="T: Serialize + Float", deserialize="T: DeserializeOwned + Float", any="T: Any"))]
    pub clamp: ClampConfig<T>,
}

impl<T: Float + Default> Default for PidConfig<T> {
    fn default() -> Self {
        Self {
            order: Order::default(),
            gain: GainsConfig::default(),
            limit: GainsConfig::splat(T::infinity()),
            setpoint: T::zero(),
            clamp: ClampConfig::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use miniconf::json_core;

    #[test]
    fn biquad_config_tag_conversion() {
        let config = BiquadConfig::<f32>::try_from("Filter").unwrap();
        assert_eq!(config.as_ref(), "Filter");
        assert!(BiquadConfig::<f32>::try_from("Unknown").is_err());
    }

    #[test]
    fn biquad_config_try_build_rejects_invalid_ba_config() {
        let ba = BaConfig {
            clamp: ClampConfig::new(1.0, 0.0),
            ..Default::default()
        };
        let config = BiquadConfig::<f32>::Ba(ba);

        assert_eq!(
            config.try_build(&Units::default()),
            Err(Error::InvertedRange("output_clamp"))
        );
    }

    #[test]
    fn clamp_miniconf_leaf_requires_a_complete_valid_range() {
        let mut config = BaConfig::<f32> {
            clamp: ClampConfig::new(-1.0, 1.0),
            ..Default::default()
        };

        json_core::set(&mut config, "/clamp", br#"[-2.0,2.0]"#).unwrap();
        assert_eq!(config.clamp, ClampConfig::new(-2.0, 2.0));

        for value in [
            br#"[-3.0]"#.as_slice(),
            br#"[-3.0,3.0,4.0]"#,
            br#"[3.0,-3.0]"#,
            br#"{"min":-3.0,"max":3.0}"#,
        ] {
            assert!(json_core::set(&mut config, "/clamp", value).is_err());
            assert_eq!(config.clamp, ClampConfig::new(-2.0, 2.0));
        }

        json_core::set(&mut config, "/clamp", br#"[null,2.0]"#).unwrap();
        assert_eq!(config.clamp, ClampConfig::new(f32::NEG_INFINITY, 2.0));

        let mut data = [0; 64];
        let len = json_core::get(&config, "/clamp", &mut data).unwrap();
        assert_eq!(&data[..len], br#"[null,2.0]"#);
        let mut copy = BaConfig::<f32>::default();
        json_core::set(&mut copy, "/clamp", &data[..len]).unwrap();
        assert_eq!(copy.clamp, config.clamp);
        assert!(json_core::set(&mut copy, "/clamp/0", b"-1.0").is_err());
    }

    #[test]
    fn raw_biquad_config_try_build_does_not_validate_units() {
        let config = BiquadConfig::<f32>::Raw(Default::default());
        let units = Units {
            t: 0.0,
            x: 0.0,
            y: 0.0,
        };

        assert!(config.try_build(&units).is_ok());
    }

    #[test]
    fn pid_null_gain_limit_is_unbounded() {
        let mut pid = PidConfig::<f32>::default();
        json_core::set(&mut pid, "/limit/i", b"null").unwrap();
        let runtime = Pid::from(&pid);

        let mut data = [0; 8];
        let len = json_core::get(&pid, "/limit/i", &mut data).unwrap();
        assert_eq!(&data[..len], b"null");
        assert_eq!(
            runtime.limit.value[crate::iir::pid::Action::I as usize],
            f32::INFINITY
        );
        let config: BiquadConfig<f32> = BiquadConfig::Pid(pid);
        assert!(config.try_build(&Units::default()).is_ok());
    }
}

impl<T: Float> From<&PidConfig<T>> for Pid<T> {
    fn from(config: &PidConfig<T>) -> Self {
        let [min, max] = config.clamp.bounds();
        let mut limit = Gains::from(&config.limit);
        limit.value = limit
            .value
            .map(|value| if value.is_nan() { T::infinity() } else { value });
        Self {
            order: config.order,
            gain: Gains::from(&config.gain),
            limit,
            setpoint: config.setpoint,
            min,
            max,
        }
    }
}

/// Configurable representation of a biquad.
///
/// `miniconf::Tree` can expose the selected variant as a string:
///
/// ```
/// use miniconf::{Tree, str_leaf};
///
/// #[derive(Tree)]
/// struct Foo {
///     #[tree(typ="&str", with=str_leaf, defer=self.config)]
///     typ: (),
///     config: idsp::iir::config::BiquadConfig<f32>,
/// }
/// ```
#[derive(Debug, Clone, Tree)]
#[tree(meta(doc = "Configurable representation of a biquad", typename))]
pub enum BiquadConfig<T, C = T, Y = T>
where
    BaConfig<T>: Default,
    PidConfig<T>: Default,
    BiquadClamp<C, Y>: Default,
    FilterConfig<T>: Default,
{
    /// Normalized SI unit coefficients.
    Ba(BaConfig<T>),
    /// Raw, unscaled, possibly fixed-point machine-unit coefficients.
    Raw(
        #[tree(with=leaf, bounds(
            serialize="C: Serialize, Y: Serialize",
            deserialize="C: DeserializeOwned, Y: DeserializeOwned",
            any="C: Any, Y: Any"))]
        BiquadClamp<C, Y>,
    ),
    /// PID controller parameters.
    Pid(PidConfig<T>),
    /// Standard biquad filters: notch, lowpass, highpass, shelf, and similar.
    Filter(FilterConfig<T>),
}

impl<T, C, Y> AsRef<str> for BiquadConfig<T, C, Y>
where
    BaConfig<T>: Default,
    PidConfig<T>: Default,
    BiquadClamp<C, Y>: Default,
    FilterConfig<T>: Default,
{
    fn as_ref(&self) -> &str {
        match self {
            Self::Ba(_) => "Ba",
            Self::Raw(_) => "Raw",
            Self::Pid(_) => "Pid",
            Self::Filter(_) => "Filter",
        }
    }
}

impl<'a, T, C, Y> TryFrom<&'a str> for BiquadConfig<T, C, Y>
where
    BaConfig<T>: Default,
    PidConfig<T>: Default,
    BiquadClamp<C, Y>: Default,
    FilterConfig<T>: Default,
{
    type Error = ();

    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        match value {
            "Ba" => Ok(Self::Ba(Default::default())),
            "Raw" => Ok(Self::Raw(Default::default())),
            "Pid" => Ok(Self::Pid(Default::default())),
            "Filter" => Ok(Self::Filter(Default::default())),
            _ => Err(()),
        }
    }
}

impl<T, C, Y> Default for BiquadConfig<T, C, Y>
where
    BaConfig<T>: Default,
    PidConfig<T>: Default,
    BiquadClamp<C, Y>: Default,
    FilterConfig<T>: Default,
{
    fn default() -> Self {
        Self::Ba(Default::default())
    }
}

fn check_offset<T: Float>(offset: T) -> Result<(), Error> {
    if !offset.is_finite() {
        return Err(Error::NonFinite("offset"));
    }
    Ok(())
}

fn check_units<T: Float>(units: &Units<T>, check_t: bool) -> Result<(), Error> {
    for (name, value) in [("x", units.x), ("y", units.y)] {
        if !value.is_finite() {
            return Err(Error::NonFinite(name));
        }
        if value <= T::zero() {
            return Err(Error::NonPositive(name));
        }
    }
    if check_t {
        if !units.t.is_finite() {
            return Err(Error::NonFinite("t"));
        }
        if units.t <= T::zero() {
            return Err(Error::NonPositive("t"));
        }
    }
    Ok(())
}

impl<T, C, Y> BiquadConfig<T, C, Y>
where
    BiquadClamp<C, Y>: Default + Clone,
    Y: 'static + Copy,
    T: 'static + Float + FloatConst + Default + AsPrimitive<Y>,
    f32: AsPrimitive<T>,
    Pid<T>: Build<BiquadClamp<C, Y>, Context = Units<T>>,
    [[T; 3]; 2]: Into<BiquadClamp<C, Y>>,
{
    /// Build a biquad from this configuration.
    pub fn build(&self, units: &Units<T>) -> BiquadClamp<C, Y> {
        let yu = units.y.recip();
        let yx = units.x * yu;
        match self {
            Self::Ba(ba) => {
                let [min, max] = ba.clamp.bounds();
                let mut bba = ba.ba;
                bba[0] = bba[0].map(|b| b * yx);
                let mut b: BiquadClamp<C, Y> = bba.into();
                b.u = (ba.offset * yu).as_();
                b.min = (min * yu).as_();
                b.max = (max * yu).as_();
                b
            }
            Self::Raw(raw) => raw.clone(),
            Self::Pid(pid) => Pid::from(pid).build(units),
            Self::Filter(filter) => {
                let [min, max] = filter.clamp.bounds();
                let mut f = Filter::default();
                f.gain_db(filter.gain_db);
                f.critical_frequency(filter.frequency * units.t);
                f.shelf_db(filter.shelf_db);
                f.set_shape(filter.shape);
                let mut ba = f.build(filter.typ);
                ba[0] = ba[0].map(|b| b * yx);
                let mut b: BiquadClamp<C, Y> = ba.into();
                b.u = (filter.offset * yu).as_();
                b.min = (min * yu).as_();
                b.max = (max * yu).as_();
                b
            }
        }
    }

    /// Build a biquad from this configuration after validation.
    pub fn try_build(&self, units: &Units<T>) -> Result<BiquadClamp<C, Y>, Error> {
        match self {
            Self::Ba(ba) => {
                check_units(units, false)?;
                check_offset(ba.offset)?;
                ba.clamp.validate()?;
                let [min, max] = ba.clamp.bounds();
                let yu = units.y.recip();
                let yx = units.x * yu;
                for row in ba.ba {
                    for coefficient in row {
                        if !coefficient.is_finite() {
                            return Err(Error::NonFinite("ba"));
                        }
                    }
                }
                let mut bba = ba.ba;
                bba[0] = bba[0].map(|b| b * yx);
                let mut b: BiquadClamp<C, Y> = bba.into();
                b.u = (ba.offset * yu).as_();
                b.min = (min * yu).as_();
                b.max = (max * yu).as_();
                Ok(b)
            }
            Self::Raw(raw) => Ok(raw.clone()),
            Self::Pid(pid) => {
                pid.clamp.validate()?;
                Pid::from(pid).try_build(units)
            }
            Self::Filter(filter) => {
                check_units(units, true)?;
                check_offset(filter.offset)?;
                filter.clamp.validate()?;
                let [min, max] = filter.clamp.bounds();
                let yu = units.y.recip();
                let yx = units.x * yu;
                let mut f = Filter::default();
                f.gain_db(filter.gain_db);
                f.critical_frequency(filter.frequency * units.t);
                f.shelf_db(filter.shelf_db);
                f.set_shape(filter.shape);
                let mut ba = f.try_build(filter.typ)?;
                ba[0] = ba[0].map(|b| b * yx);
                let mut b: BiquadClamp<C, Y> = ba.into();
                b.u = (filter.offset * yu).as_();
                b.min = (min * yu).as_();
                b.max = (max * yu).as_();
                Ok(b)
            }
        }
    }
}