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