use crate::PeqModel;
use crate::param_utils;
#[derive(Clone, Copy)]
pub struct MinGainConstraintData {
pub min_db: f64,
pub peq_model: PeqModel,
}
pub fn constraint_min_gain(
x: &[f64],
_grad: Option<&mut [f64]>,
data: &MinGainConstraintData,
) -> f64 {
viol_min_gain_from_xs(x, data.peq_model, data.min_db)
}
pub fn viol_min_gain_from_xs(xs: &[f64], peq_model: PeqModel, min_db: f64) -> f64 {
let n = param_utils::num_filters(xs, peq_model);
if n == 0 {
return 0.0;
}
let mut worst_short = 0.0_f64;
for i in 0..n {
let params = param_utils::get_filter_params(xs, i, peq_model);
let filter_type = param_utils::determine_filter_type(i, n, peq_model, params.filter_type);
use crate::iir::BiquadFilterType;
let is_peak = matches!(filter_type, BiquadFilterType::Peak);
if !is_peak {
continue;
}
let g_abs = params.gain.abs();
let short = if g_abs < 0.1 {
0.0 } else {
(min_db - g_abs).max(0.0) };
if short > worst_short {
worst_short = short;
}
}
worst_short
}
#[cfg(test)]
mod tests {
use super::*;
use crate::PeqModel;
#[test]
fn viol_min_gain_no_filters() {
let xs: Vec<f64> = vec![];
assert_eq!(viol_min_gain_from_xs(&xs, PeqModel::Pk, 3.0), 0.0);
}
#[test]
fn viol_min_gain_all_above_threshold() {
let xs = vec![2.0, 1.0, 5.0, 3.0, 1.0, 5.0];
assert_eq!(viol_min_gain_from_xs(&xs, PeqModel::Pk, 3.0), 0.0);
}
#[test]
fn viol_min_gain_one_below_threshold() {
let xs = vec![2.0, 1.0, 2.0, 3.0, 1.0, 5.0];
let v = viol_min_gain_from_xs(&xs, PeqModel::Pk, 3.0);
assert!((v - 1.0).abs() < 1e-12, "expected 1.0, got {}", v);
}
#[test]
fn viol_min_gain_allows_zero_gain_removal() {
let xs = vec![2.0, 1.0, 0.0];
assert_eq!(viol_min_gain_from_xs(&xs, PeqModel::Pk, 3.0), 0.0);
}
#[test]
fn viol_min_gain_skips_non_peak_filters() {
let xs = vec![2.0, 0.5, 0.0, 3.0, 1.0, 2.0];
let v = viol_min_gain_from_xs(&xs, PeqModel::HpPk, 3.0);
assert!((v - 1.0).abs() < 1e-12, "expected 1.0, got {}", v);
}
}