Skip to main content

secs_engine/mimo/
iir.rs

1//! Port of SECS 2 `src/secs/mimo_iir.py` (GPL-3.0).
2//! Default joint TRF accumulates position blocks; the opt-in solver applies
3//! Jv/Jᵀv directly. Neither stacks a dense residual Jacobian (ADR 0007).
4
5use std::{cell::RefCell, f64::consts::PI};
6
7use faer::{Accum, Mat, Par, linalg::matmul::matmul};
8use secs_compute::Context;
9use secs_dsp::{
10    DspError, fft, optimize,
11    optimize::{JacobianOperator, NormalEquations, NormalOptions, OperatorOptions, XScale},
12    pairwise_sum, response,
13};
14
15use super::{MimoDesign, MimoRequest, design::third_octave_bands, support_path};
16use crate::{
17    C, Design, EngineConfig, EngineError, MeasurementSet, Note, Tuning, decay,
18    fit::{FitRequest, PeqDerivatives, fit_peq_with},
19    grid::design_freqs,
20};
21
22const FS: f64 = 600.0;
23/// Residuals of one support's seed fit: 160 frequencies, real and imaginary.
24const SEED_RESIDUALS: usize = 320;
25const N: usize = 720;
26const MU: f64 = 10.0;
27
28#[derive(Debug, Clone, PartialEq)]
29pub struct IirSupport {
30    pub gain_db: f64,
31    pub delay_ms: f64,
32    pub polarity: i8,
33    pub peq: Vec<(f64, f64, f64)>,
34    pub allpass: Vec<(f64, f64)>,
35}
36
37impl IirSupport {
38    pub fn response(&self, f: &[f64]) -> Vec<C> {
39        self.response_z(f, &frequency_z(f))
40    }
41
42    fn response_z(&self, f: &[f64], z: &[C]) -> Vec<C> {
43        let gain = 10f64.powf(self.gain_db / 20.0) * f64::from(self.polarity);
44        let mut out: Vec<_> = f
45            .iter()
46            .map(|&f| C::from_polar(1.0, -2.0 * PI * f * self.delay_ms / 1000.0) * gain)
47            .collect();
48        for &(f0, q, g) in &self.peq {
49            for (h, p) in out
50                .iter_mut()
51                .zip(response::peaking_response_z(z, f0, q, g, 48000.0))
52            {
53                *h *= p;
54            }
55        }
56        for &(f0, q) in &self.allpass {
57            for (h, p) in out.iter_mut().zip(response::allpass2(f, f0, q)) {
58                *h *= p;
59            }
60        }
61        out
62    }
63}
64
65fn frequency_z(f: &[f64]) -> Vec<C> {
66    f.iter()
67        .map(|&f| C::from_polar(1.0, (-2.0 * PI * f) * (1.0 / 48000.0)))
68        .collect()
69}
70
71#[derive(Debug, Clone, PartialEq, Default)]
72pub struct MimoIir {
73    pub supports: Vec<(String, Vec<(String, IirSupport)>)>,
74    pub removed: Vec<(String, Vec<String>)>,
75    pub notes: Vec<Note>,
76}
77
78/// Joint IIR optimizer. The matrix-free path is explicit because an iterative
79/// trust-region subproblem follows a different numerical trajectory.
80#[derive(Debug, Clone, Copy, Default, PartialEq)]
81pub enum IirSolver {
82    #[default]
83    Dense,
84    MatrixFree {
85        max_cg_iterations: usize,
86        cg_rtol: f64,
87    },
88}
89
90/// How MIMO IIR fits differentiate the complex seed refinement and joint fit.
91/// Gain and delay columns are exact either way; the initial PEQ fit is selected
92/// independently by [`IirSolveOptions::seed_peq_derivatives`].
93#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94pub enum IirDerivatives {
95    /// Upstream central differences (step 1e-4). Reproduces SECS 2.
96    #[default]
97    CentralDifference,
98    /// Closed-form logarithmic derivatives (experimental; results leave SECS 2).
99    Analytic,
100}
101
102#[derive(Debug, Clone, Copy)]
103pub struct IirSolveOptions {
104    pub solver: IirSolver,
105    /// Retry the original dense Jac/Unit solvers after an operator error. The
106    /// memory permit also includes dense workspaces when this is enabled.
107    pub dense_fallback: bool,
108    pub derivatives: IirDerivatives,
109    pub seed_peq_derivatives: PeqDerivatives,
110}
111
112impl Default for IirSolveOptions {
113    fn default() -> Self {
114        Self {
115            solver: IirSolver::Dense,
116            dense_fallback: true,
117            derivatives: IirDerivatives::CentralDifference,
118            seed_peq_derivatives: PeqDerivatives::TwoPoint,
119        }
120    }
121}
122
123impl IirSolveOptions {
124    fn validate(&self) -> Result<(), EngineError> {
125        if let IirSolver::MatrixFree {
126            max_cg_iterations,
127            cg_rtol,
128        } = self.solver
129            && (max_cg_iterations == 0 || !cg_rtol.is_finite() || cg_rtol <= 0.0 || cg_rtol >= 1.0)
130        {
131            return Err(EngineError::Input("invalid matrix-free IIR options".into()));
132        }
133        Ok(())
134    }
135}
136
137fn check(ctx: &Context) -> Result<(), EngineError> {
138    ctx.cancel().check().map_err(|_| EngineError::Cancelled)
139}
140
141fn per(t: &Tuning) -> usize {
142    2 + 3 * t.mimo_k_bands + 2 * t.mimo_a_bands
143}
144
145pub(crate) fn band_of(lo: f64, hi: f64, fsiso: f64, t: &Tuning) -> (f64, f64) {
146    let low = 15f64.max(lo * 0.9);
147    let high = 300f64.min(hi.min(fsiso) * 1.1);
148    if t.mimo_in_band && high > low * 1.5 {
149        (low, high)
150    } else {
151        (15.0, 300.0)
152    }
153}
154
155pub(crate) fn bounds(band: (f64, f64), t: &Tuning) -> (Vec<f64>, Vec<f64>) {
156    let mut lb = vec![-80.0, 0.0];
157    let mut ub = vec![t.mimo_gain_max_db, 250.0];
158    for _ in 0..t.mimo_k_bands {
159        lb.extend([band.0.ln(), 0.5f64.ln(), -t.mimo_band_db]);
160        ub.extend([band.1.ln(), t.mimo_q_max.ln(), t.mimo_band_db]);
161    }
162    for _ in 0..t.mimo_a_bands {
163        lb.extend([band.0.ln(), 0.3f64.ln()]);
164        ub.extend([band.1.ln(), 20f64.ln()]);
165    }
166    (lb, ub)
167}
168
169pub(crate) fn unpack(x: &[f64], pols: &[i8], t: &Tuning) -> Vec<IirSupport> {
170    x.chunks_exact(per(t))
171        .zip(pols)
172        .map(|(v, &polarity)| IirSupport {
173            gain_db: v[0],
174            delay_ms: v[1],
175            polarity,
176            peq: (0..t.mimo_k_bands)
177                .map(|k| (v[2 + 3 * k].exp(), v[3 + 3 * k].exp(), v[4 + 3 * k]))
178                .collect(),
179            allpass: (0..t.mimo_a_bands)
180                .map(|a| {
181                    let b = 2 + 3 * t.mimo_k_bands + 2 * a;
182                    (v[b].exp(), v[b + 1].exp())
183                })
184                .collect(),
185        })
186        .collect()
187}
188
189pub(crate) fn late_modes(xs: &[Vec<f64>], count: usize, lo: f64, hi: f64) -> Vec<f64> {
190    let mut spec = vec![0.0; 2049];
191    for x in xs {
192        let mut late = vec![0.0; 4096];
193        let begin = (decay::onset(x) + 90).min(x.len().min(4096));
194        let end = x.len().min(4096);
195        late[begin..end].copy_from_slice(&x[begin..end]);
196        for (s, h) in spec.iter_mut().zip(fft::rfft(&late)) {
197            let a = response::magnitude(h);
198            *s += a * a;
199        }
200    }
201    let f = secs_dsp::grid::freqs(4096, FS).expect("MIMO grid");
202    let masked: Vec<_> = spec
203        .iter()
204        .zip(&f)
205        .map(|(&s, &f)| if (lo..=hi).contains(&f) { s } else { 0.0 })
206        .collect();
207    let mut indices = secs_dsp::peaks::find_peaks(&masked, None);
208    indices.sort_by(|&a, &b| spec[b].total_cmp(&spec[a]));
209    indices.into_iter().take(count).map(|i| f[i]).collect()
210}
211
212pub(crate) struct SeedResult {
213    pub x: Vec<f64>,
214    pub polarity: i8,
215    pub cost: f64,
216    pub nfev: usize,
217    pub status: i32,
218}
219
220#[allow(clippy::too_many_arguments)]
221pub(crate) fn fit_one(
222    s: &[f64],
223    lo: f64,
224    hi: f64,
225    modes: &[f64],
226    band: (f64, f64),
227    t: &Tuning,
228    derivatives: IirDerivatives,
229    seed_peq_derivatives: PeqDerivatives,
230    ctx: &Context,
231) -> Result<SeedResult, EngineError> {
232    check(ctx)?;
233    let lo = lo.max(15.0);
234    let step = (hi.log10() - lo.log10()) / 159.0;
235    let mut f: Vec<_> = (0..160)
236        .map(|k| 10f64.powf(lo.log10() + k as f64 * step))
237        .collect();
238    f[0] = lo;
239    f[159] = hi;
240    let target: Vec<C> = f
241        .iter()
242        .map(|&f| {
243            s.iter()
244                .enumerate()
245                .map(|(k, &s)| C::from_polar(1.0, -2.0 * PI * f * k as f64 / FS) * s)
246                .sum()
247        })
248        .collect();
249    let k = decay::first_max(&s.iter().map(|v| v.abs()).collect::<Vec<_>>());
250    let polarity = if s[k] >= 0.0 { 1 } else { -1 };
251    let db: Vec<_> = target
252        .iter()
253        .map(|&h| 20.0 * (response::magnitude(h) + 1e-12).log10())
254        .collect();
255    let base = decay::median(&db);
256    let corr: Vec<_> = db.iter().map(|v| v - base).collect();
257    let mut peq = fit_peq_with(
258        &FitRequest {
259            g: &f,
260            corr_db: &corr,
261            n: t.mimo_k_bands,
262            lo,
263            hi,
264            boost: t.mimo_band_db,
265            ring_ms: None,
266            f_max: None,
267            bands: None,
268        },
269        &|| ctx.cancel().is_cancelled(),
270        seed_peq_derivatives,
271    );
272    check(ctx)?;
273    let middle = (lo * hi).sqrt();
274    peq.resize(t.mimo_k_bands, (middle, 1.0, 0.0));
275    let mut x0 = vec![base, 1000.0 * k as f64 / FS];
276    for (f, q, g) in peq {
277        x0.extend([f.ln(), q.ln(), g]);
278    }
279    for a in 0..t.mimo_a_bands {
280        x0.extend([
281            modes
282                .get(a)
283                .copied()
284                .unwrap_or(middle)
285                .clamp(band.0 * 1.03, band.1 * 0.97)
286                .ln(),
287            2f64.ln(),
288        ]);
289    }
290    let (lb, ub) = bounds(band, t);
291    for (k, v) in x0.iter_mut().enumerate() {
292        *v = v.clamp(lb[k] + 1e-6, ub[k] - 1e-6);
293    }
294    let norm = pairwise_sum(
295        &target
296            .iter()
297            .map(|&h| response::magnitude(h))
298            .collect::<Vec<_>>(),
299    ) / 160.0
300        + 1e-12;
301    let z = frequency_z(&f);
302    let cache = RefCell::new(Parts::default());
303    let residual = |x: &[f64]| {
304        if ctx.cancel().is_cancelled() {
305            return vec![0.0; SEED_RESIDUALS];
306        }
307        let mut cache = cache.borrow_mut();
308        cache.response(x, polarity, &f, &z, t);
309        let r: Vec<_> = cache
310            .s
311            .iter()
312            .zip(&target)
313            .map(|(&h, &v)| (h - v) / norm)
314            .collect();
315        r.iter()
316            .map(|v| v.re)
317            .chain(r.iter().map(|v| v.im))
318            .collect::<Vec<_>>()
319    };
320    let result = match derivatives {
321        IirDerivatives::CentralDifference => optimize::least_squares(residual, &x0, &lb, &ub, 300),
322        IirDerivatives::Analytic => {
323            let jacobian = |x: &[f64]| {
324                if ctx.cancel().is_cancelled() {
325                    return Mat::zeros(SEED_RESIDUALS, x.len());
326                }
327                let mut cache = cache.borrow_mut();
328                cache.derivatives(x, polarity, &f, &z, t, IirDerivatives::Analytic);
329                let half = SEED_RESIDUALS / 2;
330                Mat::from_fn(SEED_RESIDUALS, x.len(), |i, j| {
331                    if i < half {
332                        cache.d[j][i].re / norm
333                    } else {
334                        cache.d[j][i - half].im / norm
335                    }
336                })
337            };
338            optimize::least_squares_analytic(
339                residual,
340                jacobian,
341                &x0,
342                &lb,
343                &ub,
344                optimize::Options {
345                    max_nfev: 300,
346                    ..optimize::Options::default()
347                },
348                None,
349            )
350        }
351    };
352    check(ctx)?;
353    Ok(match result {
354        Ok(sol) => SeedResult {
355            x: sol.x,
356            polarity,
357            cost: sol.cost,
358            nfev: sol.nfev,
359            status: sol.status,
360        },
361        Err(_) => SeedResult {
362            cost: decay::energy(&residual(&x0)) * 0.5,
363            x: x0,
364            polarity,
365            nfev: 0,
366            status: -1,
367        },
368    })
369}
370
371#[derive(Clone)]
372pub(crate) struct Problem {
373    pub roles: Vec<String>,
374    pub f: Vec<f64>,
375    pub lp: Vec<C>,
376    pub n: usize,
377    pub nf: usize,
378    pub xs: Vec<Vec<f64>>,
379    pub wl: Vec<Vec<f64>>,
380    pub we: Vec<Vec<f64>>,
381    pub g: Vec<Vec<Vec<C>>>,
382    pub fir: Vec<Vec<f64>>,
383    pub ranges: Vec<(f64, f64)>,
384    pub modes: Vec<f64>,
385    pub fsiso: f64,
386    pub direct: f64,
387    pub level_db: f64,
388    pub seat_guard: bool,
389}
390
391#[derive(Default)]
392struct Parts {
393    key: Vec<u64>,
394    s: Vec<C>,
395    d: Vec<Vec<C>>,
396}
397
398impl Parts {
399    fn response(&mut self, v: &[f64], pol: i8, f: &[f64], z: &[C], t: &Tuning) {
400        if self.key.len() == v.len() && self.key.iter().zip(v).all(|(&a, &b)| a == b.to_bits()) {
401            return;
402        }
403        self.s = unpack(v, &[pol], t).remove(0).response_z(f, z);
404        self.key.clear();
405        self.key.extend(v.iter().map(|v| v.to_bits()));
406        self.d.clear();
407    }
408
409    fn derivatives(
410        &mut self,
411        v: &[f64],
412        pol: i8,
413        f: &[f64],
414        z: &[C],
415        t: &Tuning,
416        derivatives: IirDerivatives,
417    ) {
418        self.response(v, pol, f, z, t);
419        if !self.d.is_empty() {
420            return;
421        }
422        if derivatives == IirDerivatives::CentralDifference {
423            self.d = finite_difference_derivatives(v, &self.s, f, t);
424            return;
425        }
426        self.d = vec![vec![C::new(0.0, 0.0); f.len()]; per(t)];
427        for (k, &f) in f.iter().enumerate() {
428            self.d[0][k] = self.s[k] * 10f64.ln() / 20.0;
429            self.d[1][k] = self.s[k] * C::new(0.0, -2.0 * PI * f / 1000.0);
430        }
431        for k in 0..t.mimo_k_bands {
432            let base = 2 + 3 * k;
433            let derivatives = response::peaking_log_derivatives_z(
434                z,
435                v[base].exp(),
436                v[base + 1].exp(),
437                v[base + 2],
438                48000.0,
439            );
440            for (c, derivative) in derivatives.into_iter().enumerate() {
441                for (i, value) in derivative.into_iter().enumerate() {
442                    self.d[base + c][i] = self.s[i] * value;
443                }
444            }
445        }
446        for a in 0..t.mimo_a_bands {
447            let base = 2 + 3 * t.mimo_k_bands + 2 * a;
448            let derivatives =
449                response::allpass_log_derivatives(f, v[base].exp(), v[base + 1].exp());
450            for (c, derivative) in derivatives.into_iter().enumerate() {
451                for (i, value) in derivative.into_iter().enumerate() {
452                    self.d[base + c][i] = self.s[i] * value;
453                }
454            }
455        }
456    }
457}
458
459/// Upstream's central differences (step 1e-4) for the support factors. The
460/// gain and delay columns are exact. Analytic factor derivatives moved the
461/// joint fit outside SECS 2's spread (ADR 0012), so the port keeps these.
462fn finite_difference_derivatives(v: &[f64], s: &[C], f: &[f64], t: &Tuning) -> Vec<Vec<C>> {
463    let mut d = vec![vec![C::new(0.0, 0.0); f.len()]; per(t)];
464    for (k, &f) in f.iter().enumerate() {
465        d[0][k] = s[k] * 10f64.ln() / 20.0;
466        d[1][k] = s[k] * C::new(0.0, -2.0 * PI * f / 1000.0);
467    }
468    let h = 1e-4;
469    for k in 0..t.mimo_k_bands {
470        let base = 2 + 3 * k;
471        let factor =
472            response::peaking_response(f, v[base].exp(), v[base + 1].exp(), v[base + 2], 48000.0);
473        for c in 0..3 {
474            let mut up = [v[base], v[base + 1], v[base + 2]];
475            let mut dn = up;
476            up[c] += h;
477            dn[c] -= h;
478            let u = response::peaking_response(f, up[0].exp(), up[1].exp(), up[2], 48000.0);
479            let l = response::peaking_response(f, dn[0].exp(), dn[1].exp(), dn[2], 48000.0);
480            for i in 0..f.len() {
481                d[base + c][i] = secs_dsp::complex_div(s[i] * (u[i] - l[i]) / (2.0 * h), factor[i]);
482            }
483        }
484    }
485    for a in 0..t.mimo_a_bands {
486        let base = 2 + 3 * t.mimo_k_bands + 2 * a;
487        let factor = response::allpass2(f, v[base].exp(), v[base + 1].exp());
488        for c in 0..2 {
489            let mut up = [v[base], v[base + 1]];
490            let mut dn = up;
491            up[c] += h;
492            dn[c] -= h;
493            let u = response::allpass2(f, up[0].exp(), up[1].exp());
494            let l = response::allpass2(f, dn[0].exp(), dn[1].exp());
495            for i in 0..f.len() {
496                d[base + c][i] = secs_dsp::complex_div(s[i] * (u[i] - l[i]) / (2.0 * h), factor[i]);
497            }
498        }
499    }
500    d
501}
502
503fn time_product(a: &[C], b: &[C], nf: usize, n: usize) -> Vec<f64> {
504    let mut out = fft::irfft(&a.iter().zip(b).map(|(a, b)| a * b).collect::<Vec<_>>(), nf);
505    out.truncate(n);
506    out
507}
508
509pub(crate) struct Objective<'a> {
510    pb: &'a Problem,
511    t: &'a Tuning,
512    ctx: &'a Context,
513    pols: &'a [i8],
514    weff: Vec<Vec<f64>>,
515    scale: f64,
516    z: Vec<C>,
517    cache: Vec<Parts>,
518    derivatives: IirDerivatives,
519    operator: Option<OperatorState>,
520}
521
522struct OperatorState {
523    /// Per support, parameter and frequency. Retained independently of trial
524    /// response caches, so a rejected residual cannot change Jv or Jᵀv.
525    derivatives: Vec<Vec<Vec<C>>>,
526    level: Vec<f64>,
527}
528
529impl<'a> Objective<'a> {
530    pub(crate) fn new(pb: &'a Problem, t: &'a Tuning, ctx: &'a Context, pols: &'a [i8]) -> Self {
531        let band: Vec<_> =
532            pb.f.iter()
533                .map(|&f| f >= 15.0 && f <= pb.fsiso * 1.2)
534                .collect();
535        let count = band.iter().filter(|&&b| b).count().max(1);
536        let energy = decay::energy(&pb.xs[0]);
537        let weff = (0..pb.roles.len())
538            .map(|r| {
539                let mut gbar = vec![0.0; pb.f.len()];
540                for g in &pb.g {
541                    for (sum, &h) in gbar.iter_mut().zip(&g[r]) {
542                        *sum += response::magnitude(h);
543                    }
544                }
545                for v in &mut gbar {
546                    *v /= pb.xs.len() as f64;
547                }
548                let reference = decay::median(
549                    &gbar
550                        .iter()
551                        .zip(&band)
552                        .filter(|(_, b)| **b)
553                        .map(|(&v, _)| v)
554                        .collect::<Vec<_>>(),
555                );
556                let factor = t.mimo_effort * (energy / count as f64).sqrt();
557                gbar.iter()
558                    .zip(&band)
559                    .map(|(&g, &b)| {
560                        factor
561                            * if b {
562                                reference / (g + 0.05 * reference)
563                            } else {
564                                0.0
565                            }
566                    })
567                    .collect()
568            })
569            .collect();
570        Self {
571            pb,
572            t,
573            ctx,
574            pols,
575            weff,
576            scale: energy.sqrt(),
577            z: frequency_z(&pb.f),
578            cache: (0..pb.roles.len()).map(|_| Parts::default()).collect(),
579            derivatives: IirDerivatives::CentralDifference,
580            operator: None,
581        }
582    }
583
584    pub(crate) fn set_derivatives(&mut self, derivatives: IirDerivatives) {
585        self.derivatives = derivatives;
586        for part in &mut self.cache {
587            part.d.clear();
588        }
589        self.operator = None;
590    }
591
592    fn evaluate(&mut self, x: &[f64]) {
593        for ((part, v), &pol) in self
594            .cache
595            .iter_mut()
596            .zip(x.chunks_exact(per(self.t)))
597            .zip(self.pols)
598        {
599            part.response(v, pol, &self.pb.f, &self.z, self.t);
600        }
601    }
602
603    fn derivatives(&mut self, x: &[f64]) {
604        for ((part, v), &pol) in self
605            .cache
606            .iter_mut()
607            .zip(x.chunks_exact(per(self.t)))
608            .zip(self.pols)
609        {
610            part.derivatives(v, pol, &self.pb.f, &self.z, self.t, self.derivatives);
611        }
612    }
613
614    fn level(&self) -> (Vec<Vec<f64>>, f64, f64) {
615        let st: Vec<_> = self
616            .cache
617            .iter()
618            .map(|p| time_product(&p.s, &self.pb.lp, self.pb.nf, self.pb.n))
619            .collect();
620        let lvl = st.iter().map(|s| decay::energy(s)).sum::<f64>() / self.pb.direct.max(1e-30);
621        let over = 10.0 * (lvl + 1e-30).log10() - self.pb.level_db;
622        (st, lvl, over)
623    }
624
625    fn rows(&self) -> usize {
626        2 * self.pb.xs.len() * self.pb.n
627            + 1
628            + 2 * self.pb.roles.len() * self.pb.f.len()
629            + if self.t.mimo_band_reg > 0.0 {
630                self.pb.roles.len() * self.t.mimo_k_bands
631            } else {
632                0
633            }
634    }
635}
636
637pub(crate) fn solve_joint(
638    pb: &Problem,
639    t: &Tuning,
640    ctx: &Context,
641    x0: &[f64],
642    pols: &[i8],
643) -> Result<optimize::LeastSquaresResult, EngineError> {
644    solve_joint_with_options(pb, t, ctx, x0, pols, &IirSolveOptions::default())
645}
646
647pub(crate) fn solve_joint_with_options(
648    pb: &Problem,
649    t: &Tuning,
650    ctx: &Context,
651    x0: &[f64],
652    pols: &[i8],
653    options: &IirSolveOptions,
654) -> Result<optimize::LeastSquaresResult, EngineError> {
655    check(ctx)?;
656    let mut lb = Vec::new();
657    let mut ub = Vec::new();
658    for &(lo, hi) in &pb.ranges {
659        let (l, u) = bounds(band_of(lo, hi, pb.fsiso, t), t);
660        lb.extend(l);
661        ub.extend(u);
662    }
663    let x0: Vec<_> = x0
664        .iter()
665        .enumerate()
666        .map(|(k, &v)| v.clamp(lb[k] + 1e-6, ub[k] - 1e-6))
667        .collect();
668    let mut objective = Objective::new(pb, t, ctx, pols);
669    objective.derivatives = options.derivatives;
670    if let IirSolver::MatrixFree {
671        max_cg_iterations,
672        cg_rtol,
673    } = options.solver
674    {
675        let result = optimize::least_squares_operator(
676            &mut objective,
677            &x0,
678            &lb,
679            &ub,
680            &OperatorOptions {
681                max_nfev: t.mimo_max_nfev,
682                max_cg_iterations,
683                cg_rtol,
684                ..OperatorOptions::default()
685            },
686        );
687        check(ctx)?;
688        match result {
689            Ok(solution) => return Ok(solution),
690            Err(error) if !options.dense_fallback => return Err(error.into()),
691            Err(_) => objective.operator = None,
692        }
693    }
694    for x_scale in [XScale::Jac, XScale::Unit] {
695        let result = optimize::least_squares_normal(
696            &mut objective,
697            &x0,
698            &lb,
699            &ub,
700            &NormalOptions {
701                max_nfev: t.mimo_max_nfev,
702                x_scale,
703                ..NormalOptions::default()
704            },
705        );
706        check(ctx)?;
707        if let Ok(sol) = result {
708            return Ok(sol);
709        }
710    }
711    let cost = 0.5 * decay::energy(&NormalEquations::residual(&mut objective, &x0));
712    Ok(optimize::LeastSquaresResult {
713        x: x0,
714        cost,
715        nfev: 0,
716        njev: 0,
717        status: -1,
718        optimality: f64::NAN,
719    })
720}
721
722pub(crate) fn solve_problem(
723    pb: &Problem,
724    t: &Tuning,
725    ctx: &Context,
726) -> Result<(Vec<f64>, Vec<i8>), EngineError> {
727    solve_problem_with_options(pb, t, ctx, &IirSolveOptions::default())
728}
729
730fn solve_problem_with_options(
731    pb: &Problem,
732    t: &Tuning,
733    ctx: &Context,
734    options: &IirSolveOptions,
735) -> Result<(Vec<f64>, Vec<i8>), EngineError> {
736    let mut starts = Vec::new();
737    let mut pols = Vec::new();
738    for (r, &(lo, hi)) in pb.ranges.iter().enumerate() {
739        let modes: Vec<_> = pb
740            .modes
741            .iter()
742            .copied()
743            .filter(|m| (lo..=hi).contains(m))
744            .collect();
745        let modes = if modes.is_empty() { &pb.modes } else { &modes };
746        let seed = fit_one(
747            &pb.fir[r],
748            lo,
749            hi.min(pb.fsiso),
750            modes,
751            band_of(lo, hi, pb.fsiso, t),
752            t,
753            options.derivatives,
754            options.seed_peq_derivatives,
755            ctx,
756        )?;
757        starts.extend(seed.x);
758        pols.push(seed.polarity);
759    }
760    Ok((
761        solve_joint_with_options(pb, t, ctx, &starts, &pols, options)?.x,
762        pols,
763    ))
764}
765
766pub(crate) fn applied(pb: &Problem, supports: &[(usize, IirSupport)]) -> Vec<Vec<f64>> {
767    let ss: Vec<_> = supports.iter().map(|(_, s)| s.response(&pb.f)).collect();
768    pb.xs
769        .iter()
770        .enumerate()
771        .map(|(p, x)| {
772            let mut sum = vec![C::new(0.0, 0.0); pb.f.len()];
773            for ((r, _), s) in supports.iter().zip(&ss) {
774                for (k, v) in sum.iter_mut().enumerate() {
775                    *v += pb.g[p][*r][k] * s[k];
776                }
777            }
778            let add = fft::irfft(&sum, pb.nf);
779            x.iter().zip(add).map(|(x, a)| x + a).collect()
780        })
781        .collect()
782}
783
784struct BandGuard {
785    bounds: Vec<(usize, usize)>,
786    before: Vec<f64>,
787    before_by_position: Option<Vec<Vec<f64>>>,
788}
789
790impl BandGuard {
791    fn new(pb: &Problem) -> Self {
792        let mut bands = third_octave_bands(pb.fsiso);
793        bands.extend(
794            late_modes(&pb.xs, 6, 20.0, 160.0)
795                .iter()
796                .map(|f| (f - 1.5, f + 1.5)),
797        );
798        let bounds = bands
799            .into_iter()
800            .map(|(lo, hi)| {
801                (
802                    pb.f.partition_point(|&f| f < lo),
803                    pb.f.partition_point(|&f| f < hi),
804                )
805            })
806            .collect::<Vec<_>>();
807        let (before, before_by_position) = if pb.seat_guard {
808            (
809                Vec::new(),
810                Some(Self::power_by_position(pb, &pb.xs, &bounds)),
811            )
812        } else {
813            (Self::power(pb, &pb.xs, &bounds), None)
814        };
815        Self {
816            bounds,
817            before,
818            before_by_position,
819        }
820    }
821
822    fn power(pb: &Problem, ys: &[Vec<f64>], bounds: &[(usize, usize)]) -> Vec<f64> {
823        let mut total = vec![0.0; bounds.len()];
824        for (p, y) in ys.iter().enumerate() {
825            let mut windowed: Vec<_> = y.iter().zip(&pb.wl[p]).map(|(y, w)| y * w).collect();
826            windowed.resize(pb.nf, 0.0);
827            let power: Vec<_> = fft::rfft(&windowed)
828                .iter()
829                .map(|&h| {
830                    let a = response::magnitude(h);
831                    a * a
832                })
833                .collect();
834            for (total, &(a, b)) in total.iter_mut().zip(bounds) {
835                *total += pairwise_sum(&power[a..b]);
836            }
837        }
838        total
839    }
840
841    fn power_by_position(
842        pb: &Problem,
843        ys: &[Vec<f64>],
844        bounds: &[(usize, usize)],
845    ) -> Vec<Vec<f64>> {
846        ys.iter()
847            .enumerate()
848            .map(|(p, y)| {
849                let mut windowed: Vec<_> = y.iter().zip(&pb.wl[p]).map(|(y, w)| y * w).collect();
850                windowed.resize(pb.nf, 0.0);
851                let power: Vec<_> = fft::rfft(&windowed)
852                    .iter()
853                    .map(|&h| {
854                        let a = response::magnitude(h);
855                        a * a
856                    })
857                    .collect();
858                bounds
859                    .iter()
860                    .map(|&(a, b)| pairwise_sum(&power[a..b]))
861                    .collect()
862            })
863            .collect()
864    }
865
866    fn evaluate(&self, pb: &Problem, ys: &[Vec<f64>]) -> f64 {
867        if let Some(before) = &self.before_by_position {
868            return before
869                .iter()
870                .zip(Self::power_by_position(pb, ys, &self.bounds))
871                .flat_map(|(before, after)| before.iter().copied().zip(after))
872                .filter_map(|(b, a)| super::design::seat_change(b, a))
873                .reduce(f64::max)
874                .unwrap_or(-99.0);
875        }
876        self.before
877            .iter()
878            .zip(Self::power(pb, ys, &self.bounds))
879            .filter(|(b, _)| **b > 0.0)
880            .map(|(b, a)| 10.0 * ((a + 1e-30) / b).log10())
881            .reduce(f64::max)
882            .unwrap_or(-99.0)
883    }
884}
885
886pub(crate) fn worst_band_db(pb: &Problem, supports: &[(usize, IirSupport)]) -> f64 {
887    BandGuard::new(pb).evaluate(pb, &applied(pb, supports))
888}
889
890struct OutcomeGuard<'a> {
891    pb: &'a Problem,
892    band: BandGuard,
893    tail: super::design::T60Guard<'a>,
894}
895
896impl<'a> OutcomeGuard<'a> {
897    fn new(pb: &'a Problem) -> Self {
898        Self {
899            pb,
900            band: BandGuard::new(pb),
901            tail: super::design::T60Guard::new(&pb.xs, 6, pb.seat_guard),
902        }
903    }
904
905    fn evaluate(&mut self, supports: &[(usize, IirSupport)]) -> Result<(f64, f64), EngineError> {
906        // Both guards consume the same candidate waveform, while baseline
907        // windows, bands, modal filters and original tails survive all trials.
908        let ys = applied(self.pb, supports);
909        Ok((
910            if supports.is_empty() {
911                -99.0
912            } else {
913                self.band.evaluate(self.pb, &ys)
914            },
915            self.tail.evaluate(&ys)?,
916        ))
917    }
918}
919
920pub(crate) fn outcome(
921    pb: &Problem,
922    supports: &[(usize, IirSupport)],
923) -> Result<(f64, f64), EngineError> {
924    OutcomeGuard::new(pb).evaluate(supports)
925}
926
927#[derive(Debug)]
928pub(crate) struct PostResult {
929    pub supports: Vec<(usize, IirSupport)>,
930    pub removed: Vec<String>,
931    pub level_cut: f64,
932    pub violations: Vec<f64>,
933    pub gain_steps: usize,
934}
935
936pub(crate) fn postprocess(
937    pb: &Problem,
938    x: &[f64],
939    pols: &[i8],
940    t: &Tuning,
941    ctx: &Context,
942) -> Result<PostResult, EngineError> {
943    let mut sups = unpack(x, pols, t);
944    let lvl = sups
945        .iter()
946        .map(|s| decay::energy(&time_product(&s.response(&pb.f), &pb.lp, pb.nf, pb.n)))
947        .sum::<f64>()
948        / pb.direct.max(1e-30);
949    let target = 10f64.powf(pb.level_db / 10.0);
950    let level_cut = if lvl > target {
951        10.0 * (lvl / target).log10()
952    } else {
953        0.0
954    };
955    for s in &mut sups {
956        s.gain_db -= level_cut;
957    }
958    let mut cur: Vec<_> = sups.into_iter().enumerate().collect();
959    let mut violations = Vec::new();
960    let mut guard = OutcomeGuard::new(pb);
961    let mut violation = |s: &[(usize, IirSupport)]| -> Result<f64, EngineError> {
962        check(ctx)?;
963        let (band, tail) = guard.evaluate(s)?;
964        let v = (band - t.mimo_worse_db).max(tail - 0.15 * t.mimo_worse_db);
965        violations.push(v);
966        Ok(v)
967    };
968    let mut v = violation(&cur)?;
969    let mut removed = Vec::new();
970    while v > 0.0 && removed.len() < (pb.roles.len() / 2).max(1) && cur.len() > 1 {
971        let mut best = (0, f64::INFINITY);
972        for index in 0..cur.len() {
973            let trial: Vec<_> = cur
974                .iter()
975                .enumerate()
976                .filter(|(k, _)| *k != index)
977                .map(|(_, s)| s.clone())
978                .collect();
979            let value = violation(&trial)?;
980            if value < best.1 {
981                best = (index, value);
982            }
983        }
984        if best.1 >= v {
985            break;
986        }
987        removed.push(pb.roles[cur.remove(best.0).0].clone());
988        v = best.1;
989    }
990    let mut gain_steps = 0;
991    for step in 0..5 {
992        if v <= 0.0 {
993            break;
994        }
995        if step == 4 {
996            cur.clear();
997            break;
998        }
999        for (_, s) in &mut cur {
1000            s.gain_db -= 3.0;
1001        }
1002        gain_steps += 1;
1003        v = violation(&cur)?;
1004    }
1005    Ok(PostResult {
1006        supports: cur,
1007        removed,
1008        level_cut,
1009        violations,
1010        gain_steps,
1011    })
1012}
1013
1014#[allow(clippy::too_many_arguments)]
1015pub(crate) fn build_problem(
1016    design: &Design,
1017    spectra: &crate::Spectra,
1018    align_delay_ms: &[(String, f64)],
1019    ideal: &MimoDesign,
1020    input: &str,
1021    supports: &[(String, Vec<f64>)],
1022    req: &MimoRequest,
1023    t: &Tuning,
1024    ctx: &Context,
1025) -> Result<Problem, EngineError> {
1026    let f = secs_dsp::grid::freqs(2 * N, FS)?;
1027    let lp = response::lr4(&f, req.fsiso, "LP");
1028    let roles: Vec<_> = supports.iter().map(|(r, _)| r.clone()).collect();
1029    let mut pb = Problem {
1030        roles,
1031        f,
1032        lp,
1033        n: N,
1034        nf: 2 * N,
1035        xs: Vec::new(),
1036        wl: Vec::new(),
1037        we: Vec::new(),
1038        g: Vec::new(),
1039        fir: supports.iter().map(|(_, s)| s.clone()).collect(),
1040        ranges: Vec::new(),
1041        modes: Vec::new(),
1042        fsiso: req.fsiso,
1043        direct: 0.0,
1044        level_db: req.level_db,
1045        seat_guard: req.seat_guard,
1046    };
1047    for role in &pb.roles {
1048        pb.ranges.push(
1049            ideal
1050                .ranges
1051                .iter()
1052                .find(|(r, _)| r == role)
1053                .and_then(|(_, v)| *v)
1054                .ok_or_else(|| EngineError::Input(format!("missing MIMO range {role}")))?,
1055        );
1056    }
1057    for &p in &design.spectra.positions {
1058        check(ctx)?;
1059        let h = crate::input_response(design, input, spectra, p)
1060            .ok_or_else(|| EngineError::Input(format!("missing MIMO input {p}/{input}")))?;
1061        let x = secs_dsp::lowrate::to_low(&h, design_freqs(), N)?;
1062        let onset = decay::onset(&x) + 36;
1063        pb.wl
1064            .push((0..N).map(|i| if i >= onset { 1.0 } else { 0.0 }).collect());
1065        pb.we
1066            .push(pb.wl.last().unwrap().iter().map(|w| 1.0 - w).collect());
1067        pb.xs.push(x);
1068        let mut paths = Vec::new();
1069        for role in &pb.roles {
1070            let h = support_path(ideal, role, spectra, p, align_delay_ms)?;
1071            let mut low = secs_dsp::lowrate::to_low(&h, design_freqs(), N)?;
1072            low.resize(2 * N, 0.0);
1073            paths.push(
1074                fft::rfft(&low)
1075                    .iter()
1076                    .zip(&pb.lp)
1077                    .map(|(h, l)| h * l)
1078                    .collect(),
1079            );
1080        }
1081        pb.g.push(paths);
1082    }
1083    let main = design
1084        .mains
1085        .iter()
1086        .find(|m| m.role == input)
1087        .ok_or_else(|| EngineError::Input(format!("missing MIMO main {input}")))?;
1088    pb.direct = decay::energy(&secs_dsp::lowrate::to_low(
1089        &main.response,
1090        design_freqs(),
1091        N,
1092    )?);
1093    pb.modes = late_modes(&pb.xs, t.mimo_a_bands, 20.0, req.fsiso);
1094    Ok(pb)
1095}
1096
1097fn validate_request(req: &MimoRequest, t: &Tuning) -> Result<(), EngineError> {
1098    if !(0.0..300.0).contains(&req.fsiso)
1099        || req.fsiso == 0.0
1100        || !req.level_db.is_finite()
1101        || !t.mimo_band_db.is_finite()
1102        || t.mimo_band_db <= 0.0
1103        || !t.mimo_q_max.is_finite()
1104        || t.mimo_q_max <= 0.5
1105        || !t.mimo_gain_max_db.is_finite()
1106        || t.mimo_gain_max_db <= -80.0
1107        || t.mimo_max_nfev == 0
1108        || [t.mimo_band_reg, t.mimo_effort, t.mimo_worse_db]
1109            .iter()
1110            .any(|v| !v.is_finite() || *v < 0.0)
1111    {
1112        return Err(EngineError::Input("invalid MIMO IIR tuning".into()));
1113    }
1114    // Each support's seed fit solves `per(t)` = 2 + 3·K + 2·A parameters from
1115    // its SEED_RESIDUALS residuals; more unknowns than that is not a fit the
1116    // design supports, and the count must not overflow (TD-104).
1117    let parameters = t
1118        .mimo_k_bands
1119        .checked_mul(3)
1120        .zip(t.mimo_a_bands.checked_mul(2))
1121        .and_then(|(k, a)| k.checked_add(a)?.checked_add(2));
1122    if parameters.is_none_or(|n| n > SEED_RESIDUALS) {
1123        return Err(EngineError::Input(format!(
1124            "invalid MIMO IIR tuning: {} peaking and {} all-pass bands exceed {SEED_RESIDUALS} parameters per support",
1125            t.mimo_k_bands, t.mimo_a_bands
1126        )));
1127    }
1128    // The seed and joint fits clamp their start into [lb + 1e-6, ub - 1e-6],
1129    // which needs every interval wider than 2e-6. The tuning sets the gain, Q
1130    // and band-gain intervals; the frequency ones are at least ln 1.5 wide
1131    // for any band `band_of` returns, so one representative band suffices.
1132    // Every bound is finite after the checks above.
1133    let (lb, ub) = bounds((15.0, 300.0), t);
1134    if lb
1135        .iter()
1136        .zip(&ub)
1137        .any(|(&l, &u)| u - l <= 2e-6 || l + 1e-6 > u - 1e-6)
1138    {
1139        return Err(EngineError::Input(
1140            "invalid MIMO IIR tuning: a parameter range is not wider than 2e-6".into(),
1141        ));
1142    }
1143    Ok(())
1144}
1145
1146#[allow(clippy::too_many_arguments)]
1147pub fn design_mimo_iir(
1148    design: &Design,
1149    measurements: &MeasurementSet,
1150    config: &EngineConfig,
1151    ideal: &MimoDesign,
1152    req: &MimoRequest,
1153    t: &Tuning,
1154    ctx: &Context,
1155) -> Result<MimoIir, EngineError> {
1156    design_mimo_iir_with_options(
1157        design,
1158        measurements,
1159        config,
1160        ideal,
1161        req,
1162        t,
1163        &IirSolveOptions::default(),
1164        ctx,
1165    )
1166}
1167
1168/// Designs IIR supports with an explicit joint-solver choice. Existing callers
1169/// use `design_mimo_iir`, which retains the dense solver. Setting
1170/// `IirSolver::MatrixFree { max_cg_iterations: 64, cg_rtol: 1e-3 }` enables the
1171/// f64 operator solver without changing project files or IPC tuning values.
1172#[allow(clippy::too_many_arguments)]
1173pub fn design_mimo_iir_with_options(
1174    design: &Design,
1175    measurements: &MeasurementSet,
1176    config: &EngineConfig,
1177    ideal: &MimoDesign,
1178    req: &MimoRequest,
1179    t: &Tuning,
1180    options: &IirSolveOptions,
1181    ctx: &Context,
1182) -> Result<MimoIir, EngineError> {
1183    check(ctx)?;
1184    validate_request(req, t)?;
1185    options.validate()?;
1186    if ideal.supports.iter().all(|(_, s)| s.is_empty()) {
1187        let _progress = ctx.stage("engine.mimo_iir", 0);
1188        return Ok(MimoIir::default());
1189    }
1190    let prepared = super::prepared::Prepared::new(design, measurements, config, ctx)?;
1191    design_mimo_iir_prepared_with_options(design, &prepared, ideal, req, t, options, ctx)
1192}
1193
1194pub(crate) fn design_mimo_iir_prepared(
1195    design: &Design,
1196    prepared: &super::prepared::Prepared<'_>,
1197    ideal: &MimoDesign,
1198    req: &MimoRequest,
1199    t: &Tuning,
1200    ctx: &Context,
1201) -> Result<MimoIir, EngineError> {
1202    design_mimo_iir_prepared_with_options(
1203        design,
1204        prepared,
1205        ideal,
1206        req,
1207        t,
1208        &IirSolveOptions::default(),
1209        ctx,
1210    )
1211}
1212
1213#[allow(clippy::too_many_arguments)]
1214pub(crate) fn design_mimo_iir_prepared_with_options(
1215    design: &Design,
1216    prepared: &super::prepared::Prepared<'_>,
1217    ideal: &MimoDesign,
1218    req: &MimoRequest,
1219    t: &Tuning,
1220    options: &IirSolveOptions,
1221    ctx: &Context,
1222) -> Result<MimoIir, EngineError> {
1223    check(ctx)?;
1224    validate_request(req, t)?;
1225    options.validate()?;
1226    let inputs: Vec<_> = ideal
1227        .supports
1228        .iter()
1229        .filter(|(_, s)| !s.is_empty())
1230        .collect();
1231    let progress = ctx.stage("engine.mimo_iir", inputs.len() as u64);
1232    if inputs.is_empty() {
1233        return Ok(MimoIir::default());
1234    }
1235    let spectra = &prepared.spectra;
1236    let positions = &design.spectra.positions;
1237    let results = crate::memory::try_map(
1238        ctx,
1239        inputs,
1240        prepared.reserved,
1241        |(_, supports)| {
1242            let r = supports.len();
1243            let dim = r * per(t);
1244            let rows = 2 * positions.len() * N + 1 + 2 * r * (N + 1) + r * t.mimo_k_bands;
1245            let solver_bytes = if options.solver == IirSolver::Dense || options.dense_fallback {
1246                4 * N * dim + 12 * dim * dim
1247            } else {
1248                8 * rows + 24 * dim + 8 * r * (N + 1)
1249            };
1250            // Problem X/WL/WE/G, derivative cache, one position's time columns,
1251            // weighted columns, normal/eigen/TRF workspaces, seed Jacobian and
1252            // design-grid response temporaries. Reserve before per-input allocation.
1253            let bytes = 8
1254                * (positions.len() * N * (3 + 4 * r)
1255                    + 4 * dim * (N + 1)
1256                    + solver_bytes
1257                    + 320 * per(t) * 4
1258                    + 32 * design_freqs().len()
1259                    + 32768);
1260            bytes as u64
1261        },
1262        |(input, supports)| {
1263            let pb = build_problem(
1264                design,
1265                spectra,
1266                &prepared.align_delay_ms,
1267                ideal,
1268                input,
1269                supports,
1270                req,
1271                t,
1272                ctx,
1273            )?;
1274            let (x, pols) = solve_problem_with_options(&pb, t, ctx, options)?;
1275            let post = postprocess(&pb, &x, &pols, t, ctx)?;
1276            let paths = post
1277                .supports
1278                .into_iter()
1279                .map(|(r, s)| (pb.roles[r].clone(), s))
1280                .collect();
1281            progress.advance(1);
1282            Ok((input.clone(), paths, post.removed))
1283        },
1284    )?;
1285    let mut out = MimoIir::default();
1286    for (input, paths, removed) in results {
1287        out.supports.push((input.clone(), paths));
1288        out.removed.push((input, removed));
1289    }
1290    Ok(out)
1291}
1292
1293impl NormalEquations for Objective<'_> {
1294    fn residual(&mut self, x: &[f64]) -> Vec<f64> {
1295        if self.ctx.cancel().is_cancelled() {
1296            return vec![0.0; self.rows()];
1297        }
1298        self.evaluate(x);
1299        let pb = self.pb;
1300        let mut out = Vec::with_capacity(self.rows());
1301        for p in 0..pb.xs.len() {
1302            let mut sum = vec![C::new(0.0, 0.0); pb.f.len()];
1303            for (r, part) in self.cache.iter().enumerate() {
1304                for (k, v) in sum.iter_mut().enumerate() {
1305                    *v += pb.g[p][r][k] * part.s[k];
1306                }
1307            }
1308            let add = fft::irfft(&sum, pb.nf);
1309            out.extend((0..pb.n).map(|i| pb.wl[p][i] * (pb.xs[p][i] + add[i])));
1310            out.extend((0..pb.n).map(|i| MU.sqrt() * pb.we[p][i] * add[i]));
1311        }
1312        out.push(self.level().2.max(0.0) * self.scale);
1313        for (r, part) in self.cache.iter().enumerate() {
1314            out.extend(part.s.iter().zip(&self.weff[r]).map(|(h, w)| w * h.re));
1315            out.extend(part.s.iter().zip(&self.weff[r]).map(|(h, w)| w * h.im));
1316        }
1317        if self.t.mimo_band_reg > 0.0 {
1318            for r in 0..pb.roles.len() {
1319                for k in 0..self.t.mimo_k_bands {
1320                    out.push(
1321                        self.t.mimo_band_reg * self.scale * x[r * per(self.t) + 4 + 3 * k] / 30.0,
1322                    );
1323                }
1324            }
1325        }
1326        out
1327    }
1328
1329    fn normal(&mut self, x: &[f64], f: &[f64]) -> Result<(Mat<f64>, Vec<f64>), DspError> {
1330        let dim = x.len();
1331        if self.ctx.cancel().is_cancelled() {
1332            return Ok((Mat::zeros(dim, dim), vec![0.0; dim]));
1333        }
1334        self.derivatives(x);
1335        let pb = self.pb;
1336        let width = per(self.t);
1337        let mut h = Mat::zeros(dim, dim);
1338        let mut grad = vec![0.0; dim];
1339        // One position's unweighted time columns, not the stacked residual Jacobian.
1340        // Each position is accumulated in input order; faer never spawns threads.
1341        for p in 0..pb.xs.len() {
1342            let mut c = Mat::zeros(pb.n, dim);
1343            for (r, part) in self.cache.iter().enumerate() {
1344                for (a, d) in part.d.iter().enumerate() {
1345                    let column = time_product(&pb.g[p][r], d, pb.nf, pb.n);
1346                    for (i, &v) in column.iter().enumerate() {
1347                        c[(i, r * width + a)] = v;
1348                    }
1349                }
1350            }
1351            let weighted = Mat::from_fn(pb.n, dim, |i, j| {
1352                c[(i, j)] * (pb.wl[p][i] * pb.wl[p][i] + MU * pb.we[p][i] * pb.we[p][i])
1353            });
1354            matmul(
1355                h.as_mut(),
1356                Accum::Add,
1357                c.transpose(),
1358                &weighted,
1359                1.0,
1360                Par::Seq,
1361            );
1362            for j in 0..dim {
1363                for i in 0..pb.n {
1364                    grad[j] += c[(i, j)]
1365                        * (pb.wl[p][i] * f[2 * p * pb.n + i]
1366                            + MU.sqrt() * pb.we[p][i] * f[(2 * p + 1) * pb.n + i]);
1367                }
1368            }
1369        }
1370        let (st, lvl, over) = self.level();
1371        let mut level = vec![0.0; dim];
1372        for (r, part) in self.cache.iter().enumerate() {
1373            let effort = Mat::from_fn(2 * pb.f.len(), width, |i, j| {
1374                let k = i % pb.f.len();
1375                self.weff[r][k]
1376                    * if i < pb.f.len() {
1377                        part.d[j][k].re
1378                    } else {
1379                        part.d[j][k].im
1380                    }
1381            });
1382            let e0 = 2 * pb.xs.len() * pb.n + 1 + 2 * r * pb.f.len();
1383            let mut block = Mat::zeros(width, width);
1384            matmul(
1385                &mut block,
1386                Accum::Replace,
1387                effort.transpose(),
1388                &effort,
1389                1.0,
1390                Par::Seq,
1391            );
1392            for a in 0..width {
1393                for b in 0..width {
1394                    h[(r * width + a, r * width + b)] += block[(a, b)];
1395                }
1396                for i in 0..2 * pb.f.len() {
1397                    grad[r * width + a] += effort[(i, a)] * f[e0 + i];
1398                }
1399                if over > 0.0 {
1400                    let ct = time_product(&part.d[a], &pb.lp, pb.nf, pb.n);
1401                    let dot = ct.iter().zip(&st[r]).map(|(a, b)| a * b).sum::<f64>();
1402                    level[r * width + a] = self.scale * 10.0 / (10f64.ln() * (lvl + 1e-30))
1403                        * (2.0 * dot / pb.direct.max(1e-30));
1404                }
1405            }
1406        }
1407        if over > 0.0 {
1408            for a in 0..dim {
1409                grad[a] += level[a] * f[2 * pb.xs.len() * pb.n];
1410                for b in 0..dim {
1411                    h[(a, b)] += level[a] * level[b];
1412                }
1413            }
1414        }
1415        if self.t.mimo_band_reg > 0.0 {
1416            let factor = self.t.mimo_band_reg * self.scale / 30.0;
1417            let row = 2 * pb.xs.len() * pb.n + 1 + 2 * pb.roles.len() * pb.f.len();
1418            for r in 0..pb.roles.len() {
1419                for k in 0..self.t.mimo_k_bands {
1420                    let a = r * width + 4 + 3 * k;
1421                    h[(a, a)] += factor * factor;
1422                    grad[a] += factor * f[row + r * self.t.mimo_k_bands + k];
1423                }
1424            }
1425        }
1426        Ok((h, grad))
1427    }
1428}
1429
1430/// Adjoint of the normalized real inverse transform after truncation to n.
1431/// Interior bins carry both conjugate frequencies (2/nf); DC and an even
1432/// Nyquist bin carry one (1/nf), with imaginary endpoint derivatives ignored.
1433fn inverse_adjoint(time: &[f64], nf: usize) -> Vec<C> {
1434    let mut padded = time.to_vec();
1435    padded.resize(nf, 0.0);
1436    let mut spectrum = fft::rfft(&padded);
1437    for (k, h) in spectrum.iter_mut().enumerate() {
1438        let endpoint = k == 0 || (nf.is_multiple_of(2) && k == nf / 2);
1439        *h *= if endpoint {
1440            1.0 / nf as f64
1441        } else {
1442            2.0 / nf as f64
1443        };
1444        if endpoint {
1445            h.im = 0.0;
1446        }
1447    }
1448    spectrum
1449}
1450
1451impl JacobianOperator for Objective<'_> {
1452    fn residual(&mut self, x: &[f64]) -> Vec<f64> {
1453        NormalEquations::residual(self, x)
1454    }
1455
1456    fn linearize(&mut self, x: &[f64]) -> Result<Vec<f64>, DspError> {
1457        let width = per(self.t);
1458        let dim = x.len();
1459        if self.ctx.cancel().is_cancelled() {
1460            self.operator = Some(OperatorState {
1461                derivatives: Vec::new(),
1462                level: vec![0.0; dim],
1463            });
1464            return Ok(vec![0.0; dim]);
1465        }
1466        self.derivatives(x);
1467        let pb = self.pb;
1468        let mut diagonal = vec![0.0; dim];
1469        // Exact column norms need one time column at a time, never an n×dim
1470        // block and never a Gram matrix. They supply scaling/preconditioning.
1471        for p in 0..pb.xs.len() {
1472            for (r, part) in self.cache.iter().enumerate() {
1473                for (a, d) in part.d.iter().enumerate() {
1474                    let column = time_product(&pb.g[p][r], d, pb.nf, pb.n);
1475                    for (i, value) in column.into_iter().enumerate() {
1476                        diagonal[r * width + a] += value
1477                            * value
1478                            * (pb.wl[p][i] * pb.wl[p][i] + MU * pb.we[p][i] * pb.we[p][i]);
1479                    }
1480                }
1481            }
1482        }
1483        let (st, lvl, over) = self.level();
1484        let mut level = vec![0.0; dim];
1485        for (r, part) in self.cache.iter().enumerate() {
1486            for (a, derivative) in part.d.iter().enumerate() {
1487                let j = r * width + a;
1488                for component in [false, true] {
1489                    for (k, d) in derivative.iter().enumerate() {
1490                        let v = self.weff[r][k] * if component { d.im } else { d.re };
1491                        diagonal[j] += v * v;
1492                    }
1493                }
1494                if over > 0.0 {
1495                    let ct = time_product(derivative, &pb.lp, pb.nf, pb.n);
1496                    let dot = ct.iter().zip(&st[r]).map(|(a, b)| a * b).sum::<f64>();
1497                    level[j] = self.scale * 10.0 / (10f64.ln() * (lvl + 1e-30))
1498                        * (2.0 * dot / pb.direct.max(1e-30));
1499                    diagonal[j] += level[j] * level[j];
1500                }
1501            }
1502        }
1503        if self.t.mimo_band_reg > 0.0 {
1504            let factor = self.t.mimo_band_reg * self.scale / 30.0;
1505            for r in 0..pb.roles.len() {
1506                for k in 0..self.t.mimo_k_bands {
1507                    diagonal[r * width + 4 + 3 * k] += factor * factor;
1508                }
1509            }
1510        }
1511        // Moving derivatives into the retained base point avoids a second full
1512        // cache and lets every rejected trial remain response-only.
1513        self.operator = Some(OperatorState {
1514            derivatives: self
1515                .cache
1516                .iter_mut()
1517                .map(|part| std::mem::take(&mut part.d))
1518                .collect(),
1519            level,
1520        });
1521        Ok(diagonal)
1522    }
1523
1524    fn jvp(&self, direction: &[f64], out: &mut [f64]) -> Result<(), DspError> {
1525        let pb = self.pb;
1526        let width = per(self.t);
1527        if direction.len() != width * pb.roles.len() || out.len() != self.rows() {
1528            return Err(DspError::InvalidArgument(
1529                "invalid IIR Jacobian product shape".into(),
1530            ));
1531        }
1532        out.fill(0.0);
1533        if self.ctx.cancel().is_cancelled() {
1534            return Ok(());
1535        }
1536        let state = self
1537            .operator
1538            .as_ref()
1539            .ok_or_else(|| DspError::InvalidArgument("IIR operator has no linearization".into()))?;
1540        let mut responses = vec![vec![C::new(0.0, 0.0); pb.f.len()]; pb.roles.len()];
1541        for (r, derivatives) in state.derivatives.iter().enumerate() {
1542            for (a, derivative) in derivatives.iter().enumerate() {
1543                for (k, d) in derivative.iter().enumerate() {
1544                    responses[r][k] += d * direction[r * width + a];
1545                }
1546            }
1547        }
1548        for p in 0..pb.xs.len() {
1549            let mut sum = vec![C::new(0.0, 0.0); pb.f.len()];
1550            for (r, response) in responses.iter().enumerate() {
1551                for (k, value) in sum.iter_mut().enumerate() {
1552                    *value += pb.g[p][r][k] * response[k];
1553                }
1554            }
1555            let time = fft::irfft(&sum, pb.nf);
1556            for i in 0..pb.n {
1557                out[2 * p * pb.n + i] = pb.wl[p][i] * time[i];
1558                out[(2 * p + 1) * pb.n + i] = MU.sqrt() * pb.we[p][i] * time[i];
1559            }
1560        }
1561        let level_row = 2 * pb.xs.len() * pb.n;
1562        out[level_row] = state.level.iter().zip(direction).map(|(g, v)| g * v).sum();
1563        for (r, response) in responses.iter().enumerate() {
1564            let base = level_row + 1 + 2 * r * pb.f.len();
1565            for (k, h) in response.iter().enumerate() {
1566                out[base + k] = self.weff[r][k] * h.re;
1567                out[base + pb.f.len() + k] = self.weff[r][k] * h.im;
1568            }
1569        }
1570        if self.t.mimo_band_reg > 0.0 {
1571            let base = level_row + 1 + 2 * pb.roles.len() * pb.f.len();
1572            let factor = self.t.mimo_band_reg * self.scale / 30.0;
1573            for r in 0..pb.roles.len() {
1574                for k in 0..self.t.mimo_k_bands {
1575                    out[base + r * self.t.mimo_k_bands + k] =
1576                        factor * direction[r * width + 4 + 3 * k];
1577                }
1578            }
1579        }
1580        Ok(())
1581    }
1582
1583    fn vjp(&self, residual_direction: &[f64], out: &mut [f64]) -> Result<(), DspError> {
1584        let pb = self.pb;
1585        let width = per(self.t);
1586        if out.len() != width * pb.roles.len() || residual_direction.len() != self.rows() {
1587            return Err(DspError::InvalidArgument(
1588                "invalid IIR transpose product shape".into(),
1589            ));
1590        }
1591        out.fill(0.0);
1592        if self.ctx.cancel().is_cancelled() {
1593            return Ok(());
1594        }
1595        let state = self
1596            .operator
1597            .as_ref()
1598            .ok_or_else(|| DspError::InvalidArgument("IIR operator has no linearization".into()))?;
1599        let mut adjoints = vec![vec![C::new(0.0, 0.0); pb.f.len()]; pb.roles.len()];
1600        for p in 0..pb.xs.len() {
1601            let time: Vec<_> = (0..pb.n)
1602                .map(|i| {
1603                    pb.wl[p][i] * residual_direction[2 * p * pb.n + i]
1604                        + MU.sqrt() * pb.we[p][i] * residual_direction[(2 * p + 1) * pb.n + i]
1605                })
1606                .collect();
1607            let spectrum = inverse_adjoint(&time, pb.nf);
1608            for (r, adjoint) in adjoints.iter_mut().enumerate() {
1609                for (k, value) in adjoint.iter_mut().enumerate() {
1610                    *value += pb.g[p][r][k].conj() * spectrum[k];
1611                }
1612            }
1613        }
1614        let level_row = 2 * pb.xs.len() * pb.n;
1615        for (r, adjoint) in adjoints.iter_mut().enumerate() {
1616            let base = level_row + 1 + 2 * r * pb.f.len();
1617            for (k, value) in adjoint.iter_mut().enumerate() {
1618                *value += C::new(
1619                    self.weff[r][k] * residual_direction[base + k],
1620                    self.weff[r][k] * residual_direction[base + pb.f.len() + k],
1621                );
1622            }
1623            for (a, derivative) in state.derivatives[r].iter().enumerate() {
1624                let j = r * width + a;
1625                out[j] = derivative
1626                    .iter()
1627                    .zip(&*adjoint)
1628                    .map(|(d, a)| d.re * a.re + d.im * a.im)
1629                    .sum::<f64>()
1630                    + state.level[j] * residual_direction[level_row];
1631            }
1632        }
1633        if self.t.mimo_band_reg > 0.0 {
1634            let base = level_row + 1 + 2 * pb.roles.len() * pb.f.len();
1635            let factor = self.t.mimo_band_reg * self.scale / 30.0;
1636            for r in 0..pb.roles.len() {
1637                for k in 0..self.t.mimo_k_bands {
1638                    out[r * width + 4 + 3 * k] +=
1639                        factor * residual_direction[base + r * self.t.mimo_k_bands + k];
1640                }
1641            }
1642        }
1643        Ok(())
1644    }
1645}
1646
1647#[cfg(test)]
1648mod operator_tests {
1649    use super::*;
1650
1651    fn fixture(level_db: f64) -> (Problem, Tuning, Vec<f64>, Vec<i8>) {
1652        let (n, nf) = (64, 128);
1653        let f = secs_dsp::grid::freqs(nf, FS).unwrap();
1654        let t = Tuning {
1655            mimo_k_bands: 2,
1656            mimo_a_bands: 1,
1657            mimo_max_nfev: 25,
1658            ..Tuning::default()
1659        };
1660        let lp = response::lr4(&f, 100.0, "LP");
1661        let xs: Vec<Vec<f64>> = (0..2)
1662            .map(|p| {
1663                (0..n)
1664                    .map(|i| {
1665                        let time = i as f64;
1666                        (time * 0.6 + p as f64 * 0.1).cos() * (-time / 40.0).exp()
1667                    })
1668                    .collect()
1669            })
1670            .collect();
1671        let wl: Vec<Vec<f64>> = (0..2)
1672            .map(|p| (0..n).map(|i| if i >= 8 + p { 1.0 } else { 0.0 }).collect())
1673            .collect();
1674        let we = wl
1675            .iter()
1676            .map(|w| w.iter().map(|w| 1.0 - w).collect())
1677            .collect();
1678        let g = (0..2)
1679            .map(|p| {
1680                (0..2)
1681                    .map(|r| {
1682                        let mut ir = vec![0.0; nf];
1683                        for (i, value) in ir.iter_mut().enumerate().take(n).skip(2 + p + r) {
1684                            *value = (-((i - 2 - p - r) as f64) / 12.0).exp()
1685                                * (i as f64 * (0.4 + r as f64 * 0.1)).cos();
1686                        }
1687                        fft::rfft(&ir).iter().zip(&lp).map(|(a, b)| a * b).collect()
1688                    })
1689                    .collect()
1690            })
1691            .collect();
1692        let x = (0..2)
1693            .flat_map(|r| {
1694                [
1695                    -6.0 - r as f64,
1696                    12.0 + r as f64,
1697                    50.0_f64.ln(),
1698                    2.0_f64.ln(),
1699                    3.0,
1700                    110.0_f64.ln(),
1701                    1.3_f64.ln(),
1702                    -4.0,
1703                    70.0_f64.ln(),
1704                    1.5_f64.ln(),
1705                ]
1706            })
1707            .collect();
1708        (
1709            Problem {
1710                roles: vec!["SW1".into(), "SW2".into()],
1711                f,
1712                lp,
1713                n,
1714                nf,
1715                xs,
1716                wl,
1717                we,
1718                g,
1719                fir: vec![vec![0.0; n]; 2],
1720                ranges: vec![(20.0, 150.0); 2],
1721                modes: vec![50.0, 80.0],
1722                fsiso: 100.0,
1723                direct: 1.0,
1724                level_db,
1725                seat_guard: false,
1726            },
1727            t,
1728            x,
1729            vec![1, -1],
1730        )
1731    }
1732
1733    fn dot(a: &[f64], b: &[f64]) -> f64 {
1734        a.iter().zip(b).map(|(a, b)| a * b).sum()
1735    }
1736
1737    #[test]
1738    fn real_inverse_adjoint_handles_dc_nyquist_and_truncation() {
1739        for nf in [63, 64] {
1740            let spectrum: Vec<_> = (0..nf / 2 + 1)
1741                .map(|k| C::new((k as f64 * 0.3).sin(), (k as f64 * 0.7).cos()))
1742                .collect();
1743            let time: Vec<_> = (0..17).map(|i| (i as f64 * 0.5).cos()).collect();
1744            let transformed = fft::irfft(&spectrum, nf);
1745            let lhs = dot(&transformed[..time.len()], &time);
1746            let adjoint = inverse_adjoint(&time, nf);
1747            let rhs: f64 = spectrum
1748                .iter()
1749                .zip(&adjoint)
1750                .map(|(a, b)| a.re * b.re + a.im * b.im)
1751                .sum();
1752            assert!((lhs - rhs).abs() < 1e-12 * lhs.abs().max(rhs.abs()).max(1.0));
1753        }
1754    }
1755
1756    #[test]
1757    fn iir_operator_matches_derivatives_normal_equations_and_adjoint() {
1758        for level_db in [-80.0, 80.0] {
1759            let (pb, tuning, x, pols) = fixture(level_db);
1760            let ctx = Context::serial();
1761            let mut objective = Objective::new(&pb, &tuning, &ctx, &pols);
1762            let f = NormalEquations::residual(&mut objective, &x);
1763            assert!(
1764                objective.cache.iter().all(|part| part.d.is_empty()),
1765                "residual calculated unused derivatives"
1766            );
1767            let (normal, gradient) = objective.normal(&x, &f).unwrap();
1768            let diagonal = objective.linearize(&x).unwrap();
1769            let direction: Vec<_> = (0..x.len()).map(|i| (i as f64 * 0.4).sin()).collect();
1770            let row_direction: Vec<_> = (0..f.len()).map(|i| (i as f64 * 0.13).cos()).collect();
1771            let mut jv = vec![0.0; f.len()];
1772            objective.jvp(&direction, &mut jv).unwrap();
1773            let mut jtu = vec![0.0; x.len()];
1774            objective.vjp(&row_direction, &mut jtu).unwrap();
1775            let lhs = dot(&jv, &row_direction);
1776            let rhs = dot(&direction, &jtu);
1777            assert!((lhs - rhs).abs() < 1e-10 * lhs.abs().max(rhs.abs()).max(1.0));
1778            let mut jt_jv = vec![0.0; x.len()];
1779            objective.vjp(&jv, &mut jt_jv).unwrap();
1780            let mut jt_f = vec![0.0; x.len()];
1781            objective.vjp(&f, &mut jt_f).unwrap();
1782            for j in 0..x.len() {
1783                let expected: f64 = (0..x.len()).map(|k| normal[(j, k)] * direction[k]).sum();
1784                assert!((jt_jv[j] - expected).abs() < 2e-10 * expected.abs().max(1.0));
1785                assert!((jt_f[j] - gradient[j]).abs() < 2e-10 * gradient[j].abs().max(1.0));
1786                assert!(
1787                    (diagonal[j] - normal[(j, j)]).abs() < 2e-10 * normal[(j, j)].abs().max(1.0)
1788                );
1789            }
1790            let up: Vec<_> = x
1791                .iter()
1792                .zip(&direction)
1793                .map(|(x, v)| x + 1e-5 * v)
1794                .collect();
1795            let down: Vec<_> = x
1796                .iter()
1797                .zip(&direction)
1798                .map(|(x, v)| x - 1e-5 * v)
1799                .collect();
1800            let up = NormalEquations::residual(&mut objective, &up);
1801            let down = NormalEquations::residual(&mut objective, &down);
1802            let error = jv
1803                .iter()
1804                .zip(up.iter().zip(down))
1805                .map(|(d, (u, l))| (d - (u - l) / 2e-5).abs())
1806                .fold(0.0_f64, f64::max);
1807            let scale = jv.iter().map(|v| v.abs()).fold(1.0_f64, f64::max);
1808            assert!(
1809                error < 5e-6 * scale,
1810                "analytic directional derivative {error}/{scale}"
1811            );
1812            let mut unchanged = vec![0.0; f.len()];
1813            objective.jvp(&direction, &mut unchanged).unwrap();
1814            assert!(
1815                unchanged
1816                    .iter()
1817                    .zip(&jv)
1818                    .all(|(a, b)| a.to_bits() == b.to_bits()),
1819                "trial residual invalidated the retained operator"
1820            );
1821        }
1822    }
1823
1824    #[test]
1825    fn iir_matrix_free_solve_is_reachable_and_reduces_the_same_objective() {
1826        let (pb, tuning, x, pols) = fixture(80.0);
1827        let ctx = Context::serial();
1828        let mut objective = Objective::new(&pb, &tuning, &ctx, &pols);
1829        let initial = 0.5 * decay::energy(&NormalEquations::residual(&mut objective, &x));
1830        let options = IirSolveOptions {
1831            solver: IirSolver::MatrixFree {
1832                max_cg_iterations: 20,
1833                cg_rtol: 1e-4,
1834            },
1835            dense_fallback: false,
1836            ..IirSolveOptions::default()
1837        };
1838        let result = solve_joint_with_options(&pb, &tuning, &ctx, &x, &pols, &options).unwrap();
1839        assert!(result.cost < initial * 0.95, "{initial} -> {}", result.cost);
1840        assert!(result.nfev > 1 && result.nfev <= tuning.mimo_max_nfev);
1841        for (r, &(lo, hi)) in pb.ranges.iter().enumerate() {
1842            let (lb, ub) = bounds(band_of(lo, hi, pb.fsiso, &tuning), &tuning);
1843            assert!(
1844                result.x[r * per(&tuning)..(r + 1) * per(&tuning)]
1845                    .iter()
1846                    .zip(lb)
1847                    .zip(ub)
1848                    .all(|((&x, l), u)| x >= l && x <= u)
1849            );
1850        }
1851    }
1852
1853    #[test]
1854    fn iir_level_derivative_respects_the_additive_energy_floor() {
1855        let (mut pb, tuning, x, pols) = fixture(-400.0);
1856        for h in &mut pb.lp {
1857            *h *= 1e-15;
1858        }
1859        let ctx = Context::serial();
1860        let mut objective = Objective::new(&pb, &tuning, &ctx, &pols);
1861        let _ = NormalEquations::residual(&mut objective, &x);
1862        objective.linearize(&x).unwrap();
1863        let mut direction = vec![0.0; x.len()];
1864        direction[0] = 1.0;
1865        let mut jv = vec![0.0; objective.rows()];
1866        objective.jvp(&direction, &mut jv).unwrap();
1867        let (mut up, mut down) = (x.clone(), x);
1868        up[0] += 1e-3;
1869        down[0] -= 1e-3;
1870        let up = NormalEquations::residual(&mut objective, &up);
1871        let down = NormalEquations::residual(&mut objective, &down);
1872        let row = 2 * pb.xs.len() * pb.n;
1873        let central = (up[row] - down[row]) / 2e-3;
1874        assert!((jv[row] - central).abs() < 1e-7 * central.abs().max(1.0));
1875    }
1876
1877    #[test]
1878    fn iir_operator_error_preserves_dense_fallback() {
1879        let (pb, tuning, x, pols) = fixture(80.0);
1880        let ctx = Context::serial();
1881        // Public API validation rejects this option before any design work.
1882        // Passing it internally injects an operator error to exercise recovery.
1883        let options = IirSolveOptions {
1884            solver: IirSolver::MatrixFree {
1885                max_cg_iterations: 0,
1886                cg_rtol: 1e-3,
1887            },
1888            dense_fallback: true,
1889            ..IirSolveOptions::default()
1890        };
1891        assert!(options.validate().is_err());
1892        let recovered = solve_joint_with_options(&pb, &tuning, &ctx, &x, &pols, &options).unwrap();
1893        let dense = solve_joint(&pb, &tuning, &ctx, &x, &pols).unwrap();
1894        assert_eq!(recovered.cost.to_bits(), dense.cost.to_bits());
1895        assert_eq!(recovered.nfev, dense.nfev);
1896        assert!(
1897            recovered
1898                .x
1899                .iter()
1900                .zip(dense.x)
1901                .all(|(a, b)| a.to_bits() == b.to_bits())
1902        );
1903        assert!(
1904            solve_joint_with_options(
1905                &pb,
1906                &tuning,
1907                &ctx,
1908                &x,
1909                &pols,
1910                &IirSolveOptions {
1911                    dense_fallback: false,
1912                    ..options
1913                }
1914            )
1915            .is_err()
1916        );
1917    }
1918}
1919
1920#[cfg(test)]
1921mod tuning_tests {
1922    use super::*;
1923
1924    #[test]
1925    fn iir_tuning_ranges_are_checked_at_entry() {
1926        // TD-104: band counts beyond the seed fit's residuals, and bounds too
1927        // narrow for the 1e-6 start margins (f64::clamp panics on min > max).
1928        let req = MimoRequest::default();
1929        let ok = |t: Tuning| validate_request(&req, &t).is_ok();
1930        assert!(ok(Tuning::default()));
1931        // 2 + 3·106 = 320 parameters per support: as many as residuals.
1932        assert!(ok(Tuning {
1933            mimo_k_bands: 106,
1934            mimo_a_bands: 0,
1935            ..Tuning::default()
1936        }));
1937        for (k, a) in [(106, 1), (0, 160), (usize::MAX, 0), (0, usize::MAX)] {
1938            let t = Tuning {
1939                mimo_k_bands: k,
1940                mimo_a_bands: a,
1941                ..Tuning::default()
1942            };
1943            assert!(
1944                matches!(validate_request(&req, &t), Err(EngineError::Input(_))),
1945                "{k} peaking and {a} all-pass bands"
1946            );
1947        }
1948        assert!(ok(Tuning {
1949            mimo_band_db: 2e-6,
1950            ..Tuning::default()
1951        }));
1952        for t in [
1953            Tuning {
1954                mimo_band_db: 1e-6,
1955                ..Tuning::default()
1956            },
1957            Tuning {
1958                mimo_q_max: 0.5 * 1e-6f64.exp(),
1959                ..Tuning::default()
1960            },
1961            Tuning {
1962                mimo_gain_max_db: -80.0 + 1e-6,
1963                ..Tuning::default()
1964            },
1965        ] {
1966            assert!(
1967                matches!(validate_request(&req, &t), Err(EngineError::Input(_))),
1968                "{t:?}"
1969            );
1970        }
1971    }
1972}