Skip to main content

secs_engine/mimo/
design.rs

1//! Port of SECS 2 `src/secs/mimo.py` (GPL-3.0), support ranges and guards.
2//! Normal equations exploit the Toeplitz blocks without allocating A.
3
4use secs_dsp::{
5    fft,
6    fir::firwin,
7    iir::{BType, Sos, butter, sosfilt},
8    interp, pairwise_sum,
9    response::hp2,
10    smooth::{Fraction, smooth_power},
11};
12
13use crate::{
14    C, Design, EngineError, Note, Spectra,
15    decay::{self, onset},
16    grid::design_freqs,
17    measurement::delay_response,
18};
19
20const FS_LOW: f64 = 600.0;
21const EARLY: usize = 36;
22
23use super::solve::solve;
24use crate::{EngineConfig, MeasurementSet};
25#[cfg(test)]
26use secs_compute::MapError;
27use secs_compute::{Context, MemoryError};
28
29#[derive(Debug, Clone, PartialEq)]
30pub struct MimoRequest {
31    pub fsiso: f64,
32    pub level_db: f64,
33    pub f_low: Option<f64>,
34    pub max_supports: Option<usize>,
35    pub exclude: Vec<String>,
36    pub groups: Option<Vec<String>>,
37    pub taps_low: usize,
38}
39
40impl Default for MimoRequest {
41    fn default() -> Self {
42        Self {
43            fsiso: 150.0,
44            level_db: -12.0,
45            f_low: None,
46            max_supports: None,
47            exclude: Vec::new(),
48            groups: None,
49            taps_low: 180,
50        }
51    }
52}
53
54pub type SupportRanges = Vec<(String, Option<(f64, f64)>)>;
55pub type InputSupports = Vec<(String, Vec<(String, Vec<f64>)>)>;
56
57#[derive(Debug, Clone, PartialEq)]
58pub struct MimoDesign {
59    pub fs_low: f64,
60    pub ranges: SupportRanges,
61    pub supports: InputSupports,
62    pub level_db: Vec<(String, f64)>,
63    pub notes: Vec<Note>,
64}
65
66impl Default for MimoDesign {
67    fn default() -> Self {
68        Self {
69            fs_low: FS_LOW,
70            ranges: Vec::new(),
71            supports: Vec::new(),
72            level_db: Vec::new(),
73            notes: Vec::new(),
74        }
75    }
76}
77
78pub fn lowpass_fir(fc: f64, taps: usize) -> Result<Vec<f64>, EngineError> {
79    Ok(firwin(taps, fc, FS_LOW)?)
80}
81
82fn geomspace(start: f64, end: f64) -> Vec<f64> {
83    let step = (end.log10() - start.log10()) / 199.0;
84    let mut values: Vec<_> = (0..200)
85        .map(|k| 10f64.powf(start.log10() + k as f64 * step))
86        .collect();
87    values[0] = start;
88    values[199] = end;
89    values
90}
91
92/// Position-mean one-third-octave support ranges, in main then sub order.
93/// Long spectra must already include the sub's fixed and bundle filters.
94pub fn support_ranges(
95    design: &Design,
96    spectra: &Spectra,
97    fsiso: f64,
98    positions: &[u32],
99) -> Result<SupportRanges, EngineError> {
100    if positions.is_empty() || !fsiso.is_finite() || fsiso <= 0.0 {
101        return Err(EngineError::Input("invalid MIMO range inputs".into()));
102    }
103    let f = design_freqs();
104    let mut out = Vec::new();
105    for (role, sub) in design
106        .mains
107        .iter()
108        .map(|m| (m.role.as_str(), None))
109        .chain(design.chain.subs.iter().map(|s| (s.role.as_str(), Some(s))))
110    {
111        let Some(paths): Option<Vec<_>> = positions.iter().map(|&p| spectra.get(p, role)).collect()
112        else {
113            continue;
114        };
115        let mut power = vec![0.0; f.len()];
116        for h in paths {
117            if h.len() != f.len() {
118                return Err(EngineError::Input("invalid MIMO spectrum length".into()));
119            }
120            for (sum, h) in power.iter_mut().zip(h.iter()) {
121                let a = h.re.hypot(h.im);
122                *sum += a * a;
123            }
124        }
125        for p in &mut power {
126            *p /= positions.len() as f64;
127        }
128        let db: Vec<_> = smooth_power(f, &power, Fraction::Scalar(3.0))?
129            .iter()
130            .map(|p| 10.0 * (p + 1e-30).log10())
131            .collect();
132        let (lo_ref, hi_ref) = if sub.is_some() {
133            (30.0, 80.0)
134        } else {
135            (200.0, 1000.0)
136        };
137        let mut reference = decay::median(
138            &f.iter()
139                .zip(&db)
140                .filter(|(f, _)| (lo_ref..=hi_ref).contains(*f))
141                .map(|(_, &v)| v)
142                .collect::<Vec<_>>(),
143        );
144        let mut start = if sub.is_some() {
145            50.0
146        } else {
147            fsiso.min(200.0)
148        };
149        if let Some(s) = sub.filter(|s| s.hp_hz != 0.0 || s.lp_hz != 0.0) {
150            let lo = s.hp_hz.max(15.0);
151            let hi = (if s.lp_hz != 0.0 {
152                s.lp_hz.min(80.0)
153            } else {
154                80.0
155            })
156            .max(lo * 1.5);
157            let indices: Vec<_> = f
158                .iter()
159                .enumerate()
160                .filter(|(_, f)| (lo..=hi).contains(f))
161                .map(|(k, _)| k)
162                .collect();
163            let values: Vec<_> = indices.iter().map(|&k| db[k]).collect();
164            let k = indices[decay::first_max(&values)];
165            reference = db[k];
166            start = f[k];
167        }
168        let low = geomspace(start, 15.0)
169            .into_iter()
170            .find(|&v| interp(v, f, &db) < reference - 10.0)
171            .unwrap_or(15.0)
172            .max(if sub.is_some() { 20.0 } else { 50.0 });
173        let high = geomspace(start, fsiso)
174            .into_iter()
175            .find(|&v| interp(v, f, &db) < reference - 10.0)
176            .unwrap_or(fsiso);
177        out.push((
178            role.to_owned(),
179            (low < high.min(fsiso) * 0.8).then(|| {
180                (
181                    (low * 10.0).round_ties_even() / 10.0,
182                    (high * 10.0).round_ties_even() / 10.0,
183                )
184            }),
185        ));
186    }
187    Ok(out)
188}
189
190/// Arrival-aligned acoustic path with the fourth-order lower-edge protection.
191pub fn support_path(
192    mimo: &MimoDesign,
193    role: &str,
194    spectra: &Spectra,
195    position: u32,
196    align_delay_ms: &[(String, f64)],
197) -> Result<Vec<C>, EngineError> {
198    let h = spectra
199        .get(position, role)
200        .ok_or_else(|| EngineError::Input(format!("missing MIMO path {position}/{role}")))?;
201    let delay = align_delay_ms
202        .iter()
203        .find(|(r, _)| r == role)
204        .map_or(0.0, |(_, ms)| *ms);
205    let low = mimo
206        .ranges
207        .iter()
208        .find(|(r, _)| r == role)
209        .and_then(|(_, r)| *r)
210        .map_or(50.0, |r| r.0);
211    Ok(h.iter()
212        .zip(delay_response(delay))
213        .zip(hp2(design_freqs(), low))
214        .map(|((&h, d), hp)| h * d * (hp * hp))
215        .collect())
216}
217
218pub(crate) fn convolve(a: &[f64], b: &[f64]) -> Vec<f64> {
219    if a.is_empty() || b.is_empty() {
220        return Vec::new();
221    }
222    // NumPy's convolve swaps the operands when the second is longer, then
223    // accumulates the first operand in increasing index order for each output.
224    let (a, b) = if a.len() < b.len() { (b, a) } else { (a, b) };
225    (0..a.len() + b.len() - 1)
226        .map(|t| {
227            let mut sum = 0.0;
228            for k in t.saturating_sub(b.len() - 1)..=(t.min(a.len() - 1)) {
229                sum += a[k] * b[t - k];
230            }
231            sum
232        })
233        .collect()
234}
235
236/// One block pair `(j, jj)` of the weighted normal equations, summed over
237/// positions in order, and the right-hand side of `j` when `j == jj`.
238/// The first row/column are direct time sums; the diagonal recurrence handles
239/// the truncated last sample and the weight step at `onset + 36`.
240fn block_pair(
241    xs: &[Vec<f64>],
242    paths: &[Vec<Vec<f64>>],
243    (j, jj): (usize, usize),
244    taps: usize,
245    early_weight: f64,
246) -> (Vec<f64>, Vec<f64>) {
247    let mut total = vec![0.0; taps * taps];
248    let mut rhs = vec![0.0; if j == jj { taps } else { 0 }];
249    for (x, gs) in xs.iter().zip(paths) {
250        let n = x.len();
251        let e = (onset(x) + EARLY).min(n);
252        let c = |t: usize| if t < e { early_weight } else { 1.0 };
253        let (g, h) = (&gs[j], &gs[jj]);
254        for (k, b) in rhs.iter_mut().enumerate() {
255            for t in e.max(k)..n {
256                *b -= x[t] * g[t - k];
257            }
258        }
259        let mut block = vec![0.0; taps * taps];
260        for k in 0..taps {
261            for t in k..n {
262                block[k * taps] += c(t) * g[t - k] * h[t];
263            }
264        }
265        for l in 1..taps {
266            for t in l..n {
267                block[l] += c(t) * g[t] * h[t - l];
268            }
269        }
270        for k in 0..taps - 1 {
271            for l in 0..taps - 1 {
272                let mut v = block[k * taps + l] - c(n - 1) * g[n - 1 - k] * h[n - 1 - l];
273                if e < n && e > k.max(l) {
274                    v += (1.0 - early_weight) * g[e - 1 - k] * h[e - 1 - l];
275                }
276                block[(k + 1) * taps + l + 1] = v;
277            }
278        }
279        for (sum, v) in total.iter_mut().zip(block) {
280            *sum += v;
281        }
282    }
283    (total, rhs)
284}
285
286/// A block pair's index and its `(block, rhs)`.
287type PairBlock = ((usize, usize), (Vec<f64>, Vec<f64>));
288
289fn block_pairs(candidates: usize) -> Vec<(usize, usize)> {
290    (0..candidates)
291        .flat_map(|j| (j..candidates).map(move |jj| (j, jj)))
292        .collect()
293}
294
295/// Place the upper-triangle blocks; AᵀA is symmetric, and the opposite
296/// triangle reuses the same value instead of a second accumulation.
297fn place(blocks: Vec<PairBlock>, ata: &mut [f64], atb: &mut [f64], taps: usize) {
298    let dim = atb.len();
299    for ((j, jj), (block, rhs)) in blocks {
300        if j == jj {
301            atb[j * taps..(j + 1) * taps].copy_from_slice(&rhs);
302        }
303        for k in 0..taps {
304            for l in 0..taps {
305                if j != jj || k <= l {
306                    let (row, col) = (j * taps + k, jj * taps + l);
307                    ata[row * dim + col] = block[k * taps + l];
308                    ata[col * dim + row] = block[k * taps + l];
309                }
310            }
311        }
312    }
313}
314
315/// Weighted normal equations, position-major paths, row-major output.
316/// `early_weight=10` is the design system, `0` is candidate ranking.
317pub(crate) fn normal_equations(
318    xs: &[Vec<f64>],
319    paths: &[Vec<Vec<f64>>],
320    taps: usize,
321    early_weight: f64,
322) -> (Vec<f64>, Vec<f64>) {
323    let candidates = paths[0].len();
324    let dim = candidates * taps;
325    let (mut ata, mut atb) = (vec![0.0; dim * dim], vec![0.0; dim]);
326    for pair in block_pairs(candidates) {
327        let block = block_pair(xs, paths, pair, taps, early_weight);
328        place(vec![(pair, block)], &mut ata, &mut atb, taps);
329    }
330    (ata, atb)
331}
332
333/// [`normal_equations`] with the block pairs as a map over `ctx`. Each block
334/// keeps the position order of its sums, and placement adds nothing, so the
335/// result has the same bits for any thread count.
336pub(crate) fn normal_equations_mapped(
337    xs: &[Vec<f64>],
338    paths: &[Vec<Vec<f64>>],
339    taps: usize,
340    early_weight: f64,
341    ctx: &Context,
342) -> Result<(Vec<f64>, Vec<f64>), EngineError> {
343    check(ctx)?;
344    let candidates = paths[0].len();
345    let dim = candidates * taps;
346    let (mut ata, mut atb) = (vec![0.0; dim * dim], vec![0.0; dim]);
347    // Retain at most eight completed blocks alongside AᵀA. Each block keeps
348    // its original position/time sums; placement only copies disjoint entries.
349    for pairs in block_pairs(candidates).chunks(8) {
350        let blocks = ctx
351            .map(pairs.to_vec(), |pair| {
352                (pair, block_pair(xs, paths, pair, taps, early_weight))
353            })
354            .map_err(|_| EngineError::Cancelled)?;
355        place(blocks, &mut ata, &mut atb, taps);
356    }
357    Ok((ata, atb))
358}
359
360// Retain the direct form as an independent guard oracle and diagnostic entry.
361#[cfg(any(test, feature = "test-support"))]
362pub(crate) fn worst_band_db(
363    xs: &[Vec<f64>],
364    paths: &[Vec<Vec<f64>>],
365    supports: &[Vec<f64>],
366    fsiso: f64,
367) -> f64 {
368    let n = xs[0].len();
369    let nf = 2 * n;
370    let bins = secs_dsp::grid::freqs(nf, FS_LOW).expect("MIMO grid");
371    let mut bands = third_octave_bands(fsiso);
372    let refs: Vec<_> = xs.iter().map(Vec::as_slice).collect();
373    bands.extend(
374        decay::late_peaks(&refs, 6)
375            .iter()
376            .map(|&f| (f - 1.5, f + 1.5)),
377    );
378    let mut before = vec![0.0; bands.len()];
379    let mut after = before.clone();
380    for (x, gs) in xs.iter().zip(paths) {
381        let mut add = vec![0.0; n];
382        for (g, s) in gs.iter().zip(supports) {
383            for (a, v) in add.iter_mut().zip(convolve(g, s)) {
384                *a += v;
385            }
386        }
387        let e = (onset(x) + EARLY).min(n);
388        for (acc, addition) in [(&mut before, false), (&mut after, true)] {
389            let mut y = vec![0.0; nf];
390            for t in e..n {
391                y[t] = x[t] + if addition { add[t] } else { 0.0 };
392            }
393            let spectrum: Vec<_> = fft::rfft(&y)
394                .iter()
395                .map(|h| {
396                    let a = h.re.hypot(h.im);
397                    a * a
398                })
399                .collect();
400            for (total, &(lo, hi)) in acc.iter_mut().zip(&bands) {
401                let begin = bins.partition_point(|&f| f < lo);
402                let end = bins.partition_point(|&f| f < hi);
403                *total += pairwise_sum(&spectrum[begin..end]);
404            }
405        }
406    }
407    before
408        .iter()
409        .zip(after)
410        .filter(|(a, _)| **a > 0.0)
411        .map(|(a, b)| 10.0 * ((b + 1e-30) / a).log10())
412        .reduce(f64::max)
413        .unwrap_or(-99.0)
414}
415
416/// The guards' third-octave bands from 20 Hz while the upper edge stays below
417/// `fsiso`, as `(lo, hi)` in Hz (TD-75: the CPU guard, its direct-form oracle
418/// and the IIR guard share them).
419pub(crate) fn third_octave_bands(fsiso: f64) -> Vec<(f64, f64)> {
420    let stop = (fsiso / 20.0).log2() + 1e-9;
421    let edges: Vec<_> = (0..)
422        .map(|k| k as f64 / 3.0)
423        .take_while(|&v| v < stop)
424        .map(|v| 20.0 * 2f64.powf(v))
425        .collect();
426    edges.windows(2).map(|v| (v[0], v[1])).collect()
427}
428
429#[derive(Debug)]
430pub(crate) struct BandGuard {
431    n: usize,
432    starts: Vec<usize>,
433    bands: Vec<(usize, usize)>,
434    before: Vec<f64>,
435}
436
437impl BandGuard {
438    pub(crate) fn new(xs: &[Vec<f64>], fsiso: f64) -> Self {
439        let n = xs[0].len();
440        let bins = secs_dsp::grid::freqs(2 * n, FS_LOW).expect("MIMO grid");
441        let refs: Vec<_> = xs.iter().map(Vec::as_slice).collect();
442        let bands = third_octave_bands(fsiso)
443            .into_iter()
444            .chain(
445                decay::late_peaks(&refs, 6)
446                    .into_iter()
447                    .map(|f| (f - 1.5, f + 1.5)),
448            )
449            .map(|(lo, hi)| {
450                (
451                    bins.partition_point(|&f| f < lo),
452                    bins.partition_point(|&f| f < hi),
453                )
454            })
455            .collect();
456        let mut guard = Self {
457            n,
458            starts: xs.iter().map(|x| (onset(x) + EARLY).min(n)).collect(),
459            bands,
460            before: Vec::new(),
461        };
462        guard.before = guard.energies(xs, true);
463        guard
464    }
465
466    fn energies(&self, responses: &[Vec<f64>], baseline: bool) -> Vec<f64> {
467        let mut totals = vec![0.0; self.bands.len()];
468        for (response, &start) in responses.iter().zip(&self.starts) {
469            let mut window = vec![0.0; 2 * self.n];
470            for t in start..self.n {
471                // Preserve the original baseline's x + 0.0, including -0.0.
472                window[t] = if baseline {
473                    response[t] + 0.0
474                } else {
475                    response[t]
476                };
477            }
478            let spectrum: Vec<_> = fft::rfft(&window)
479                .iter()
480                .map(|h| {
481                    let a = h.re.hypot(h.im);
482                    a * a
483                })
484                .collect();
485            for (total, &(begin, end)) in totals.iter_mut().zip(&self.bands) {
486                *total += pairwise_sum(&spectrum[begin..end]);
487            }
488        }
489        totals
490    }
491
492    pub(crate) fn evaluate(&self, ys: &[Vec<f64>]) -> f64 {
493        self.before
494            .iter()
495            .zip(self.energies(ys, false))
496            .filter(|(a, _)| **a > 0.0)
497            .map(|(a, b)| 10.0 * ((b + 1e-30) / a).log10())
498            .reduce(f64::max)
499            .unwrap_or(-99.0)
500    }
501}
502
503/// Absolute modal-tail change, in the upstream 0.15 seconds-per-dB scale.
504/// Despite its name this guard does not compare fitted T60 slopes.
505pub fn worst_t60_change(
506    xs: &[Vec<f64>],
507    ys: &[Vec<f64>],
508    count: usize,
509) -> Result<f64, EngineError> {
510    T60Guard::new(xs, count).evaluate(ys)
511}
512
513#[derive(Debug)]
514struct TailBaseline {
515    frequency: f64,
516    positions: usize,
517    sos: Sos,
518    energy: f64,
519}
520
521/// Fixed original modal peaks and mode-specific tails, shared across guard
522/// trials. Each trial still discovers its own new peaks before taking the
523/// union, so reducing the support cannot hide a newly exposed mode.
524#[derive(Debug)]
525pub(crate) struct T60Guard<'a> {
526    xs: &'a [Vec<f64>],
527    count: usize,
528    original_modes: Vec<f64>,
529    starts: Vec<usize>,
530    baselines: Vec<TailBaseline>,
531}
532
533impl<'a> T60Guard<'a> {
534    pub(crate) fn new(xs: &'a [Vec<f64>], count: usize) -> Self {
535        Self {
536            xs,
537            count,
538            original_modes: decay::late_peaks(
539                &xs.iter().map(Vec::as_slice).collect::<Vec<_>>(),
540                count,
541            ),
542            starts: xs.iter().map(|x| onset(x) + 180).collect(),
543            baselines: Vec::new(),
544        }
545    }
546
547    pub(crate) fn evaluate(&mut self, ys: &[Vec<f64>]) -> Result<f64, EngineError> {
548        let mut modes: Vec<_> = self
549            .original_modes
550            .iter()
551            .copied()
552            .chain(decay::late_peaks(
553                &ys.iter().map(Vec::as_slice).collect::<Vec<_>>(),
554                self.count,
555            ))
556            .map(|f| (f * 10.0).round_ties_even() / 10.0)
557            .collect();
558        modes.sort_by(f64::total_cmp);
559        modes.dedup();
560        let positions = self.xs.len().min(ys.len());
561        let mut tails = Vec::new();
562        for fm in modes {
563            let index = self
564                .baselines
565                .iter()
566                .position(|entry| entry.frequency == fm && entry.positions == positions);
567            let index = if let Some(index) = index {
568                index
569            } else {
570                let sos = butter(2, &[(fm - 1.5).max(1.0), fm + 1.5], BType::Bandpass, FS_LOW)?;
571                let mut energy = 0.0;
572                for (x, &t) in self.xs.iter().zip(&self.starts).take(positions) {
573                    let xf = sosfilt(&sos, x)?;
574                    energy += decay::energy(&xf[t.min(xf.len())..]);
575                }
576                self.baselines.push(TailBaseline {
577                    frequency: fm,
578                    positions,
579                    sos,
580                    energy,
581                });
582                self.baselines.len() - 1
583            };
584            let baseline = &self.baselines[index];
585            let mut after = 0.0;
586            for (y, &t) in ys.iter().zip(&self.starts).take(positions) {
587                let yf = sosfilt(&baseline.sos, y)?;
588                after += decay::energy(&yf[t.min(yf.len())..]);
589            }
590            tails.push((baseline.energy, after));
591        }
592        let top = tails.iter().map(|&(a, _)| a).fold(0.0, f64::max);
593        let mut worst: f64 = -99.0;
594        for (a, b) in tails {
595            if a > 0.0 && a >= top * 10f64.powf(-20.0 / 10.0) {
596                worst = worst.max(10.0 * ((b + 1e-30) / a).log10());
597            }
598        }
599        Ok(worst * 0.15)
600    }
601}
602
603#[cfg(test)]
604pub(crate) fn worst_t60_change_before(
605    xs: &[Vec<f64>],
606    ys: &[Vec<f64>],
607    count: usize,
608) -> Result<f64, EngineError> {
609    let refs =
610        |v: &[Vec<f64>]| decay::late_peaks(&v.iter().map(Vec::as_slice).collect::<Vec<_>>(), count);
611    let mut modes: Vec<_> = refs(xs)
612        .into_iter()
613        .chain(refs(ys))
614        .map(|f| (f * 10.0).round_ties_even() / 10.0)
615        .collect();
616    modes.sort_by(f64::total_cmp);
617    modes.dedup();
618    let mut tails = Vec::new();
619    for fm in modes {
620        let sos = butter(2, &[(fm - 1.5).max(1.0), fm + 1.5], BType::Bandpass, FS_LOW)?;
621        let (mut a, mut b) = (0.0, 0.0);
622        for (x, y) in xs.iter().zip(ys) {
623            let t = onset(x) + 180;
624            let xf = sosfilt(&sos, x)?;
625            let yf = sosfilt(&sos, y)?;
626            a += decay::energy(&xf[t.min(xf.len())..]);
627            b += decay::energy(&yf[t.min(yf.len())..]);
628        }
629        tails.push((a, b));
630    }
631    let top = tails.iter().map(|&(a, _)| a).fold(0.0, f64::max);
632    let mut worst: f64 = -99.0;
633    for (a, b) in tails {
634        if a > 0.0 && a >= top * 10f64.powf(-20.0 / 10.0) {
635            worst = worst.max(10.0 * ((b + 1e-30) / a).log10());
636        }
637    }
638    Ok(worst * 0.15)
639}
640
641#[derive(Debug, Clone, PartialEq)]
642pub(crate) struct LambdaStep {
643    pub mid: f64,
644    pub ratio: f64,
645    pub accepted: bool,
646}
647#[derive(Debug, Clone, PartialEq)]
648pub(crate) struct GuardStep {
649    pub scale: f64,
650    pub band_db: f64,
651    pub t60_change: f64,
652}
653#[derive(Debug, Clone, PartialEq)]
654pub(crate) struct InputTrace {
655    pub candidates: Vec<String>,
656    pub ranking: Vec<(String, f64)>,
657    pub trajectory: Vec<LambdaStep>,
658    pub log_lambda: f64,
659    pub ratio: f64,
660    pub guards: Vec<GuardStep>,
661    pub guard_scale: f64,
662}
663#[derive(Debug)]
664pub(crate) struct InputResult {
665    pub supports: Vec<(String, Vec<f64>)>,
666    pub level_db: f64,
667    pub trace: InputTrace,
668}
669
670fn check(ctx: &Context) -> Result<(), EngineError> {
671    ctx.cancel().check().map_err(|_| EngineError::Cancelled)
672}
673
674pub(crate) fn rank_supports(
675    candidates: &[String],
676    xs: &[Vec<f64>],
677    paths: &[Vec<Vec<f64>>],
678    taps: usize,
679    ctx: &Context,
680) -> Result<Vec<(String, f64)>, EngineError> {
681    let late_input: Vec<_> = xs
682        .iter()
683        .flat_map(|x| {
684            let e = onset(x) + EARLY;
685            x.iter()
686                .enumerate()
687                .map(move |(t, &x)| if t >= e { x } else { 0.0 })
688        })
689        .collect();
690    let input_energy = decay::energy(&late_input);
691    let work = xs.iter().map(Vec::len).sum::<usize>() + 3 * taps;
692    let mut scored = Vec::new();
693    for (j, role) in candidates.iter().enumerate() {
694        check(ctx)?;
695        let candidate_paths: Vec<_> = paths.iter().map(|g| vec![g[j].clone()]).collect();
696        let (ata, atb) = normal_equations(xs, &candidate_paths, taps, 0.0);
697        let diagonal: Vec<_> = (0..taps).map(|k| ata[k * taps + k]).collect();
698        let lambda = 1e-2 * pairwise_sum(&diagonal) / taps as f64;
699        let u = solve(&ata, &atb, lambda, false)?;
700        let path_energy = candidate_paths.iter().map(|gs| decay::energy(&gs[0])).sum();
701        let (score, uncertainty) =
702            rank_score(input_energy, path_energy, &ata, &atb, &u, lambda, work);
703        // Cancellation and nonfinite arithmetic must not make a poor path
704        // look perfect. Keep the original residual evaluation in that case.
705        let direct = !score.is_finite() || !uncertainty.is_finite() || score <= 8.0 * uncertainty;
706        scored.push((
707            role.clone(),
708            if direct {
709                rank_score_direct(xs, paths, j, &u)
710            } else {
711                score
712            },
713            if direct { 0.0 } else { uncertainty },
714            u,
715        ));
716    }
717    // A tiny scalar roundoff must not change the discrete support ordering.
718    // Recompute both members of every overlapping score interval, before
719    // the stable sort, in the original time-domain accumulation order.
720    let mut direct = vec![false; scored.len()];
721    for i in 0..scored.len() {
722        for j in i + 1..scored.len() {
723            if (scored[i].1 - scored[j].1).abs() <= scored[i].2 + scored[j].2 {
724                direct[i] = true;
725                direct[j] = true;
726            }
727        }
728    }
729    let mut scores = Vec::with_capacity(scored.len());
730    for (j, ((role, score, _, u), direct)) in scored.into_iter().zip(direct).enumerate() {
731        check(ctx)?;
732        scores.push((
733            role,
734            if direct {
735                rank_score_direct(xs, paths, j, &u)
736            } else {
737                score
738            },
739        ));
740    }
741    scores.sort_by(|a, b| a.1.total_cmp(&b.1));
742    Ok(scores)
743}
744
745fn rank_score(
746    input_energy: f64,
747    path_energy: f64,
748    ata: &[f64],
749    atb: &[f64],
750    u: &[f64],
751    lambda: f64,
752    work: usize,
753) -> (f64, f64) {
754    let products: Vec<_> = u.iter().zip(atb).map(|(u, b)| u * b).collect();
755    let ub = pairwise_sum(&products);
756    let regularization = lambda * decay::energy(u);
757    let u_l1 = u.iter().map(|v| v.abs()).sum::<f64>();
758    // Full path energy also bounds cancellation in the Gram's sliding
759    // recurrence when the retained late-window block itself is tiny.
760    let mut magnitude = input_energy
761        + 2.0 * products.iter().map(|v| v.abs()).sum::<f64>()
762        + regularization.abs()
763        + path_energy * u_l1 * u_l1;
764    let mut row_products = vec![0.0; u.len()];
765    let mut corrections = Vec::with_capacity(u.len());
766    for (i, row) in ata.chunks_exact(u.len()).enumerate() {
767        for ((v, a), u) in row_products.iter_mut().zip(row).zip(u) {
768            *v = a * u;
769        }
770        let residual = (pairwise_sum(&row_products) + lambda * u[i]) - atb[i];
771        corrections.push(u[i] * residual);
772        magnitude += u[i].abs() * row_products.iter().map(|v| v.abs()).sum::<f64>();
773    }
774    // b = -Aᵀx, M = AᵀA. For a finite-precision solve the exact identity is
775    // ||Au+x||² = xᵀx - uᵀb - λuᵀu + uᵀ((M+λI)u-b).
776    // The O(taps²) residual correction is cheaper than the old O(P*N*taps)
777    // convolutions and does not assume the solver residual is exactly zero.
778    let score = ((input_energy - ub) - regularization) + pairwise_sum(&corrections);
779    // This deliberately conservative reevaluation trigger scales with Gram
780    // recurrences and dot products. It is not a certified error bound or a
781    // relaxation of any result-validation tolerance.
782    let uncertainty = 64.0 * f64::EPSILON * work.max(1) as f64 * magnitude;
783    (score, uncertainty)
784}
785
786pub(crate) fn rank_score_direct(
787    xs: &[Vec<f64>],
788    paths: &[Vec<Vec<f64>>],
789    candidate: usize,
790    u: &[f64],
791) -> f64 {
792    let mut residual = Vec::new();
793    for (x, gs) in xs.iter().zip(paths) {
794        let y = convolve(&gs[candidate], u);
795        let e = onset(x) + EARLY;
796        residual.extend(
797            x.iter()
798                .enumerate()
799                .map(|(t, &x)| if t >= e { y[t] + x } else { 0.0 }),
800        );
801    }
802    decay::energy(&residual)
803}
804
805/// The low-rate stage boundary used by the oracle: paths have lower-edge
806/// protection and arrival alignment, but not the common low-pass FIR yet.
807pub(crate) fn design_input(
808    xs: &[Vec<f64>],
809    raw_paths: &[Vec<Vec<f64>>],
810    direct: &[f64],
811    candidates: &[String],
812    req: &MimoRequest,
813    ctx: &Context,
814) -> Result<InputResult, EngineError> {
815    design_input_observed(xs, raw_paths, direct, candidates, req, ctx, &|_, _| {})
816}
817
818pub(crate) fn design_input_observed(
819    xs: &[Vec<f64>],
820    raw_paths: &[Vec<Vec<f64>>],
821    direct: &[f64],
822    candidates: &[String],
823    req: &MimoRequest,
824    ctx: &Context,
825    observe: &dyn Fn(&str, std::time::Duration),
826) -> Result<InputResult, EngineError> {
827    design_input_accelerated(xs, raw_paths, direct, candidates, req, ctx, observe, None)
828}
829
830#[allow(clippy::too_many_arguments)]
831fn design_input_accelerated(
832    xs: &[Vec<f64>],
833    raw_paths: &[Vec<Vec<f64>>],
834    direct: &[f64],
835    candidates: &[String],
836    req: &MimoRequest,
837    ctx: &Context,
838    observe: &dyn Fn(&str, std::time::Duration),
839    acceleration: Option<&super::acceleration::RunAcceleration<'_>>,
840) -> Result<InputResult, EngineError> {
841    let started = std::time::Instant::now();
842    let taps = req.taps_low;
843    let lp = lowpass_fir(req.fsiso, 31)?;
844    let n = xs[0].len();
845    let all_paths: Vec<Vec<Vec<f64>>> = raw_paths
846        .iter()
847        .map(|gs| {
848            gs.iter()
849                .map(|g| {
850                    let mut h = convolve(g, &lp);
851                    h.truncate(n);
852                    h
853                })
854                .collect()
855        })
856        .collect();
857    observe("path_building", started.elapsed());
858    let started = std::time::Instant::now();
859    let ranking = if req
860        .max_supports
861        .is_some_and(|cap| cap > 0 && candidates.len() > cap)
862    {
863        rank_supports(candidates, xs, &all_paths, taps, ctx)?
864    } else {
865        Vec::new()
866    };
867    observe("ranking", started.elapsed());
868    let selected: Vec<_> = if ranking.is_empty() {
869        candidates.to_vec()
870    } else {
871        ranking
872            .iter()
873            .take(req.max_supports.unwrap())
874            .map(|(r, _)| r.clone())
875            .collect()
876    };
877    let indices: Vec<_> = selected
878        .iter()
879        .map(|r| candidates.iter().position(|v| v == r).unwrap())
880        .collect();
881    let select = |paths: &[Vec<Vec<f64>>]| {
882        paths
883            .iter()
884            .map(|gs| indices.iter().map(|&j| gs[j].clone()).collect())
885            .collect::<Vec<_>>()
886    };
887    design_selected(
888        xs,
889        &select(raw_paths),
890        direct,
891        &select(&all_paths),
892        &selected,
893        &ranking,
894        req,
895        ctx,
896        observe,
897        acceleration,
898    )
899}
900
901#[allow(clippy::too_many_arguments)]
902fn design_selected(
903    xs: &[Vec<f64>],
904    raw_paths: &[Vec<Vec<f64>>],
905    direct: &[f64],
906    paths: &[Vec<Vec<f64>>],
907    candidates: &[String],
908    ranking: &[(String, f64)],
909    req: &MimoRequest,
910    ctx: &Context,
911    observe: &dyn Fn(&str, std::time::Duration),
912    acceleration: Option<&super::acceleration::RunAcceleration<'_>>,
913) -> Result<InputResult, EngineError> {
914    let taps = req.taps_low;
915    let lp = lowpass_fir(req.fsiso, 31)?;
916    let n = xs[0].len();
917    let started = std::time::Instant::now();
918    let (ata, atb) = normal_equations_mapped(xs, paths, taps, 10.0, ctx)?;
919    observe("normal_equations", started.elapsed());
920    let started = std::time::Instant::now();
921    let dim = atb.len();
922    if dim == 0 {
923        return Err(EngineError::Input("no MIMO support candidates".into()));
924    }
925    let diagonal: Vec<_> = (0..dim).map(|k| ata[k * dim + k]).collect();
926    let normalization = pairwise_sum(&diagonal) / dim as f64;
927    let target = 10f64.powf(req.level_db / 10.0);
928    let direct_energy = decay::energy(direct).max(1e-30);
929    let result = super::acceleration::run_sweep(
930        super::acceleration::RidgeProblem {
931            ata: &ata,
932            atb: &atb,
933            lp: &lp,
934            taps,
935            normalization,
936            target,
937            direct_energy,
938        },
939        ctx.cancel(),
940        acceleration,
941    )?;
942    let (u, ratio, hi, trajectory) = (result.u, result.ratio, result.log_lambda, result.trajectory);
943    observe("sweep", started.elapsed());
944    let started = std::time::Instant::now();
945    let supports: Vec<_> = (0..candidates.len())
946        .map(|k| convolve(&lp, &u[k * taps..(k + 1) * taps]))
947        .collect();
948    let mut scale = 1.0;
949    let mut guards = Vec::new();
950    let band_guard = BandGuard::new(xs, req.fsiso);
951    let mut tail_guard = T60Guard::new(xs, 6);
952    for step in 0..5 {
953        check(ctx)?;
954        let trial: Vec<Vec<_>> = supports
955            .iter()
956            .map(|s| s.iter().map(|v| v * scale).collect())
957            .collect();
958        let ys: Vec<_> = xs
959            .iter()
960            .zip(raw_paths)
961            .map(|(x, gs)| {
962                let mut add = vec![0.0; n];
963                for (g, s) in gs.iter().zip(&trial) {
964                    for (v, h) in add.iter_mut().zip(convolve(g, s)) {
965                        *v += h;
966                    }
967                }
968                x.iter().zip(add).map(|(x, a)| x + a).collect()
969            })
970            .collect();
971        let band_db = band_guard.evaluate(&ys);
972        let t60_change = tail_guard.evaluate(&ys)?;
973        guards.push(GuardStep {
974            scale,
975            band_db,
976            t60_change,
977        });
978        if band_db <= 1.0 && t60_change <= 0.15 {
979            break;
980        }
981        scale = if step == 4 {
982            0.0
983        } else {
984            scale * 10f64.powf(-3.0 / 20.0)
985        };
986    }
987    observe("guard_steps", started.elapsed());
988    Ok(InputResult {
989        supports: if scale > 0.0 {
990            candidates
991                .iter()
992                .cloned()
993                .zip(
994                    supports
995                        .into_iter()
996                        .map(|s| s.into_iter().map(|v| v * scale).collect()),
997                )
998                .collect()
999        } else {
1000            Vec::new()
1001        },
1002        level_db: 10.0 * (ratio * scale * scale).max(1e-30).log10(),
1003        trace: InputTrace {
1004            candidates: candidates.to_vec(),
1005            ranking: ranking.to_vec(),
1006            trajectory,
1007            log_lambda: hi,
1008            ratio,
1009            guards,
1010            guard_scale: scale,
1011        },
1012    })
1013}
1014
1015pub fn design_mimo(
1016    design: &Design,
1017    measurements: &MeasurementSet,
1018    config: &EngineConfig,
1019    req: &MimoRequest,
1020    ctx: &Context,
1021) -> Result<MimoDesign, EngineError> {
1022    design_mimo_traced(design, measurements, config, req, ctx).map(|(out, _)| out)
1023}
1024
1025pub(crate) fn design_mimo_traced(
1026    design: &Design,
1027    measurements: &MeasurementSet,
1028    config: &EngineConfig,
1029    req: &MimoRequest,
1030    ctx: &Context,
1031) -> Result<(MimoDesign, Vec<(String, InputTrace)>), EngineError> {
1032    design_mimo_inputs(design, measurements, config, req, ctx, None)
1033}
1034
1035pub(crate) fn design_mimo_inputs(
1036    design: &Design,
1037    measurements: &MeasurementSet,
1038    config: &EngineConfig,
1039    req: &MimoRequest,
1040    ctx: &Context,
1041    input: Option<&str>,
1042) -> Result<(MimoDesign, Vec<(String, InputTrace)>), EngineError> {
1043    design_mimo_inputs_observed(design, measurements, config, req, ctx, input, &|_, _| {})
1044}
1045
1046#[allow(clippy::too_many_arguments)]
1047pub(crate) fn design_mimo_inputs_observed(
1048    design: &Design,
1049    measurements: &MeasurementSet,
1050    config: &EngineConfig,
1051    req: &MimoRequest,
1052    ctx: &Context,
1053    input: Option<&str>,
1054    observe: &(dyn Fn(&str, std::time::Duration) + Sync),
1055) -> Result<(MimoDesign, Vec<(String, InputTrace)>), EngineError> {
1056    check(ctx)?;
1057    let mut out = MimoDesign::default();
1058    let positions = &design.spectra.positions;
1059    if positions.len() < 3 {
1060        out.notes
1061            .push(Note::Mimo(crate::notes::MimoNote::InsufficientPositions {
1062                measured: positions.len(),
1063            }));
1064        return Ok((out, Vec::new()));
1065    }
1066    validate_request(req)?;
1067    let started = std::time::Instant::now();
1068    let prepared = super::prepared::Prepared::new(design, measurements, config, ctx)?;
1069    observe("preparation", started.elapsed());
1070    design_mimo_prepared(design, &prepared, req, ctx, input, observe)
1071}
1072
1073#[allow(clippy::too_many_arguments)]
1074pub(crate) fn design_mimo_prepared(
1075    design: &Design,
1076    prepared: &super::prepared::Prepared<'_>,
1077    req: &MimoRequest,
1078    ctx: &Context,
1079    input: Option<&str>,
1080    observe: &(dyn Fn(&str, std::time::Duration) + Sync),
1081) -> Result<(MimoDesign, Vec<(String, InputTrace)>), EngineError> {
1082    design_mimo_prepared_accelerated(design, prepared, req, ctx, input, observe, None)
1083}
1084
1085#[allow(clippy::too_many_arguments)]
1086pub(crate) fn design_mimo_prepared_accelerated(
1087    design: &Design,
1088    prepared: &super::prepared::Prepared<'_>,
1089    req: &MimoRequest,
1090    ctx: &Context,
1091    input: Option<&str>,
1092    observe: &(dyn Fn(&str, std::time::Duration) + Sync),
1093    acceleration: Option<&super::acceleration::RunAcceleration<'_>>,
1094) -> Result<(MimoDesign, Vec<(String, InputTrace)>), EngineError> {
1095    check(ctx)?;
1096    let mut out = MimoDesign::default();
1097    let positions = &design.spectra.positions;
1098    if positions.len() < 3 {
1099        out.notes
1100            .push(Note::Mimo(crate::notes::MimoNote::InsufficientPositions {
1101                measured: positions.len(),
1102            }));
1103        return Ok((out, Vec::new()));
1104    }
1105    validate_request(req)?;
1106    let spectra = &prepared.spectra;
1107    let started = std::time::Instant::now();
1108    out.ranges = support_ranges(design, spectra, req.fsiso, positions)?;
1109    if let Some(low) = req.f_low.filter(|v| *v != 0.0) {
1110        for (_, range) in &mut out.ranges {
1111            *range =
1112                range.and_then(|(lo, hi)| (lo.max(low) < hi * 0.8).then_some((lo.max(low), hi)));
1113        }
1114    }
1115    let usable: Vec<_> = out
1116        .ranges
1117        .iter()
1118        .filter(|(r, range)| {
1119            range.is_some()
1120                && !req.exclude.contains(r)
1121                && req.groups.as_ref().is_none_or(|groups| {
1122                    design
1123                        .groups
1124                        .iter()
1125                        .any(|(g, roles)| groups.contains(g) && roles.contains(r))
1126                })
1127        })
1128        .map(|(r, _)| r.clone())
1129        .collect();
1130    if !req.exclude.is_empty() {
1131        let mut excluded = req.exclude.clone();
1132        excluded.sort();
1133        out.notes
1134            .push(Note::Mimo(crate::notes::MimoNote::ExcludedSupports(
1135                excluded,
1136            )));
1137    }
1138    out.notes
1139        .push(Note::Mimo(crate::notes::MimoNote::SupportRanges(
1140            out.ranges.clone(),
1141        )));
1142    observe("ranges", started.elapsed());
1143    let started = std::time::Instant::now();
1144    let mains: Vec<_> = design
1145        .mains
1146        .iter()
1147        .filter(|m| input.is_none_or(|r| r == m.role))
1148        .collect();
1149    let roles: Vec<_> = usable
1150        .iter()
1151        .filter(|r| mains.iter().any(|m| m.role != **r))
1152        .collect();
1153    let pairs: Vec<_> = positions
1154        .iter()
1155        .flat_map(|&p| roles.iter().map(move |r| (p, *r)))
1156        .collect();
1157    let shared_bytes = (pairs.len()
1158        * (720 * 8 + std::mem::size_of::<Vec<f64>>() + 2 * std::mem::size_of::<(u32, &String)>()))
1159        as u64;
1160    let scratch_bytes = (32 * design_freqs().len() * 8) as u64;
1161    let largest_input = mains
1162        .iter()
1163        .map(|m| {
1164            input_bytes(
1165                positions.len(),
1166                usable.iter().filter(|r| **r != m.role).count(),
1167                req.taps_low,
1168            ) as u64
1169        })
1170        .max()
1171        .unwrap_or(0);
1172    // A retained reservation must not leave a worker waiting for bytes that
1173    // this same invocation cannot release until the worker has finished. The
1174    // preparation's spectra stay reserved underneath (TD-24).
1175    let retained = prepared.reserved.saturating_add(shared_bytes);
1176    let needed = retained.saturating_add(largest_input.max(scratch_bytes));
1177    if needed > ctx.budget().total() {
1178        return Err(EngineError::Input(
1179            MemoryError::TooLarge {
1180                requested: needed,
1181                total: ctx.budget().total(),
1182            }
1183            .to_string(),
1184        ));
1185    }
1186    let _shared_permit = ctx
1187        .budget()
1188        .acquire(shared_bytes, ctx.cancel())
1189        .map_err(memory_error)?;
1190    let low_paths = crate::memory::try_map(
1191        ctx,
1192        pairs.clone(),
1193        retained,
1194        |_| scratch_bytes,
1195        |(p, r)| {
1196            let h = support_path(&out, r, spectra, p, &prepared.align_delay_ms)?;
1197            Ok::<_, EngineError>(secs_dsp::lowrate::to_low(&h, design_freqs(), 720)?)
1198        },
1199    )?;
1200    observe("shared_paths", started.elapsed());
1201    let started = std::time::Instant::now();
1202    let results = crate::memory::try_map(
1203        ctx,
1204        mains,
1205        retained,
1206        |main| {
1207            input_bytes(
1208                positions.len(),
1209                usable.iter().filter(|r| **r != main.role).count(),
1210                req.taps_low,
1211            ) as u64
1212        },
1213        |main| {
1214            let candidates: Vec<_> = usable
1215                .iter()
1216                .filter(|r| **r != main.role)
1217                .cloned()
1218                .collect();
1219            let started = std::time::Instant::now();
1220            let mut xs = Vec::new();
1221            let mut paths = Vec::new();
1222            for &p in positions {
1223                check(ctx)?;
1224                let response =
1225                    crate::input_response(design, &main.role, spectra, p).ok_or_else(|| {
1226                        EngineError::Input(format!("missing MIMO input {p}/{}", main.role))
1227                    })?;
1228                xs.push(secs_dsp::lowrate::to_low(&response, design_freqs(), 720)?);
1229                paths.push(
1230                    candidates
1231                        .iter()
1232                        .map(|r| {
1233                            let index = pairs
1234                                .iter()
1235                                .position(|(pos, role)| *pos == p && *role == r)
1236                                .unwrap();
1237                            low_paths[index].clone()
1238                        })
1239                        .collect(),
1240                );
1241            }
1242            let direct = secs_dsp::lowrate::to_low(&main.response, design_freqs(), 720)?;
1243            observe("input_preparation", started.elapsed());
1244            let result = design_input_accelerated(
1245                &xs,
1246                &paths,
1247                &direct,
1248                &candidates,
1249                req,
1250                ctx,
1251                observe,
1252                acceleration,
1253            )?;
1254            Ok((main.role.clone(), result))
1255        },
1256    )?;
1257    observe("inputs_wall", started.elapsed());
1258    let mut traces = Vec::new();
1259    for (role, result) in results {
1260        let scale = result.trace.guard_scale;
1261        if scale < 1.0 {
1262            out.notes.push(Note::Mimo(if scale > 0.0 {
1263                crate::notes::MimoNote::GuardReduced {
1264                    role: role.clone(),
1265                    gain_db: 20.0 * scale.max(1e-9).log10(),
1266                }
1267            } else {
1268                crate::notes::MimoNote::GuardDisabled { role: role.clone() }
1269            }));
1270        }
1271        out.supports.push((role.clone(), result.supports));
1272        out.level_db.push((role.clone(), result.level_db));
1273        traces.push((role, result.trace));
1274    }
1275    Ok((out, traces))
1276}
1277
1278fn validate_request(req: &MimoRequest) -> Result<(), EngineError> {
1279    if !(0.0..300.0).contains(&req.fsiso)
1280        || req.fsiso == 0.0
1281        || !req.level_db.is_finite()
1282        || req.taps_low == 0
1283        || req.taps_low > 720
1284        || req.f_low.is_some_and(|f| !f.is_finite())
1285    {
1286        return Err(EngineError::Input("invalid MIMO request".into()));
1287    }
1288    Ok(())
1289}
1290
1291fn memory_error(error: MemoryError) -> EngineError {
1292    match error {
1293        MemoryError::Cancelled => EngineError::Cancelled,
1294        other => EngineError::Input(other.to_string()),
1295    }
1296}
1297
1298fn input_bytes(positions: usize, candidates: usize, taps: usize) -> usize {
1299    let dim = candidates * taps;
1300    8 * (4 * dim * dim
1301        + taps * taps
1302        + positions * 720 * (4 * candidates + 8)
1303        + 32 * design_freqs().len()
1304        + 16 * dim
1305        + 16384)
1306}
1307
1308// Pre-P18c per-input preparation, retained only as an independent bitwise oracle.
1309#[cfg(test)]
1310pub(crate) fn design_mimo_before(
1311    design: &Design,
1312    measurements: &MeasurementSet,
1313    config: &EngineConfig,
1314    req: &MimoRequest,
1315    ctx: &Context,
1316    input: Option<&str>,
1317) -> Result<(MimoDesign, Vec<(String, InputTrace)>), EngineError> {
1318    check(ctx)?;
1319    let mut out = MimoDesign::default();
1320    let positions = &design.spectra.positions;
1321    if positions.len() < 3 {
1322        out.notes
1323            .push(Note::Mimo(crate::notes::MimoNote::InsufficientPositions {
1324                measured: positions.len(),
1325            }));
1326        return Ok((out, Vec::new()));
1327    }
1328    if !(0.0..300.0).contains(&req.fsiso)
1329        || req.fsiso == 0.0
1330        || !req.level_db.is_finite()
1331        || req.taps_low == 0
1332        || req.taps_low > 720
1333        || req.f_low.is_some_and(|f| !f.is_finite())
1334    {
1335        return Err(EngineError::Input("invalid MIMO request".into()));
1336    }
1337    let prepared =
1338        crate::measurement::prepare(measurements, config, &crate::setup::Setup::new(config))?;
1339    let spectra =
1340        crate::export_view::export_view_prepared(design, measurements, &prepared, &|| false)?
1341            .spectra;
1342    out.ranges = support_ranges(design, &spectra, req.fsiso, positions)?;
1343    if let Some(low) = req.f_low.filter(|v| *v != 0.0) {
1344        for (_, range) in &mut out.ranges {
1345            *range =
1346                range.and_then(|(lo, hi)| (lo.max(low) < hi * 0.8).then_some((lo.max(low), hi)));
1347        }
1348    }
1349    let usable: Vec<_> = out
1350        .ranges
1351        .iter()
1352        .filter(|(r, range)| {
1353            range.is_some()
1354                && !req.exclude.contains(r)
1355                && req.groups.as_ref().is_none_or(|groups| {
1356                    design
1357                        .groups
1358                        .iter()
1359                        .any(|(g, roles)| groups.contains(g) && roles.contains(r))
1360                })
1361        })
1362        .map(|(r, _)| r.clone())
1363        .collect();
1364    if !req.exclude.is_empty() {
1365        let mut excluded = req.exclude.clone();
1366        excluded.sort();
1367        out.notes
1368            .push(Note::Mimo(crate::notes::MimoNote::ExcludedSupports(
1369                excluded,
1370            )));
1371    }
1372    out.notes
1373        .push(Note::Mimo(crate::notes::MimoNote::SupportRanges(
1374            out.ranges.clone(),
1375        )));
1376    let results = ctx
1377        .try_map(
1378            design
1379                .mains
1380                .iter()
1381                .filter(|m| input.is_none_or(|r| r == m.role))
1382                .collect(),
1383            |main| {
1384                let candidates: Vec<_> = usable
1385                    .iter()
1386                    .filter(|r| **r != main.role)
1387                    .cloned()
1388                    .collect();
1389                let dim = candidates.len() * req.taps_low;
1390                // Normal equations, Householder reduction, possible fallback factor,
1391                // and scratch (also covers the mapped blocks during construction),
1392                // plus path/guard/design-grid buffers. Reserve before allocating.
1393                let bytes = 8
1394                    * (4 * dim * dim
1395                        + req.taps_low * req.taps_low
1396                        + positions.len() * 720 * (4 * candidates.len() + 8)
1397                        + 32 * design_freqs().len()
1398                        + 16 * dim
1399                        + 16384);
1400                let _permit =
1401                    ctx.budget()
1402                        .acquire(bytes as u64, ctx.cancel())
1403                        .map_err(|e| match e {
1404                            MemoryError::Cancelled => EngineError::Cancelled,
1405                            other => EngineError::Input(other.to_string()),
1406                        })?;
1407                let mut xs = Vec::new();
1408                let mut paths = Vec::new();
1409                for &p in positions {
1410                    check(ctx)?;
1411                    let response = crate::input_response(design, &main.role, &spectra, p)
1412                        .ok_or_else(|| {
1413                            EngineError::Input(format!("missing MIMO input {p}/{}", main.role))
1414                        })?;
1415                    xs.push(secs_dsp::lowrate::to_low(&response, design_freqs(), 720)?);
1416                    let gs: Result<Vec<_>, EngineError> = candidates
1417                        .iter()
1418                        .map(|r| {
1419                            let h = support_path(&out, r, &spectra, p, &prepared.align_delay_ms)?;
1420                            Ok(secs_dsp::lowrate::to_low(&h, design_freqs(), 720)?)
1421                        })
1422                        .collect();
1423                    paths.push(gs?);
1424                }
1425                let direct = secs_dsp::lowrate::to_low(&main.response, design_freqs(), 720)?;
1426                let result = design_input(&xs, &paths, &direct, &candidates, req, ctx)?;
1427                Ok((main.role.clone(), result))
1428            },
1429        )
1430        .map_err(|e| match e {
1431            MapError::Cancelled => EngineError::Cancelled,
1432            MapError::Item { error, .. } => error,
1433        })?;
1434    let mut traces = Vec::new();
1435    for (role, result) in results {
1436        let scale = result.trace.guard_scale;
1437        if scale < 1.0 {
1438            out.notes.push(Note::Mimo(if scale > 0.0 {
1439                crate::notes::MimoNote::GuardReduced {
1440                    role: role.clone(),
1441                    gain_db: 20.0 * scale.max(1e-9).log10(),
1442                }
1443            } else {
1444                crate::notes::MimoNote::GuardDisabled { role: role.clone() }
1445            }));
1446        }
1447        out.supports.push((role.clone(), result.supports));
1448        out.level_db.push((role.clone(), result.level_db));
1449        traces.push((role, result.trace));
1450    }
1451    Ok((out, traces))
1452}