Skip to main content

sparse_ir/fitters/
common.rs

1//! Common utilities for fitters
2//!
3//! This module contains shared helper functions and SVD structures
4//! used by all fitter implementations.
5
6use crate::error::{ArrayRole, Error};
7use crate::fpu_check::FpuGuard;
8use crate::gemm::GemmBackendHandle;
9use mdarray::{DTensor, DynRank, Shape, Slice, ViewMut};
10use num_complex::Complex;
11
12// ============================================================================
13// InplaceFitter trait
14// ============================================================================
15
16/// Trait for inplace evaluation and fitting operations on N-dimensional arrays.
17///
18/// Uses BLAS-style naming convention for type suffixes:
19/// - `d` = double (f64)
20/// - `z` = double complex (Complex<f64>)
21///
22/// For example:
23/// - `evaluate_nd_dd_to`: f64 input → f64 output
24/// - `evaluate_nd_zz_to`: Complex<f64> input → Complex<f64> output
25/// - `evaluate_nd_dz_to`: f64 input → Complex<f64> output
26/// - `evaluate_nd_zd_to`: Complex<f64> input → f64 output
27///
28/// Each method returns `Ok(())` after writing the result to `out`. On an
29/// error nothing is written to `out`:
30/// - [`Error::NotSupported`] if the fitter does not support this pair of
31///   types (the default implementations);
32/// - [`Error::AxisOutOfRange`] if `dim` is not an axis of the input;
33/// - [`Error::ShapeMismatch`] of the input if it does not have `basis_size`
34///   (evaluate) or `n_points` (fit) along `dim`, and of the output if `out`
35///   does not have the shape of the input with `n_points` (evaluate) or
36///   `basis_size` (fit) along `dim`;
37/// - [`Error::DecompositionFailed`] if a fit needs the singular value
38///   decomposition of the matrix and it fails.
39///
40/// An empty input of the right shape (a batch axis of extent 0) gives
41/// `Ok(())` without computing anything.
42pub trait InplaceFitter {
43    /// Number of sampling points
44    fn n_points(&self) -> usize;
45
46    /// Number of basis functions
47    fn basis_size(&self) -> usize;
48
49    /// Evaluate ND: f64 coeffs → f64 values
50    fn evaluate_nd_dd_to(
51        &self,
52        backend: Option<&GemmBackendHandle>,
53        coeffs: &Slice<f64, DynRank>,
54        dim: usize,
55        out: &mut ViewMut<'_, f64, DynRank>,
56    ) -> Result<(), Error> {
57        let _ = (backend, coeffs, dim, out);
58        Err(not_supported(
59            "evaluate_nd_dd_to (real coefficients to real values)",
60        ))
61    }
62
63    /// Evaluate ND: f64 coeffs → Complex<f64> values
64    fn evaluate_nd_dz_to(
65        &self,
66        backend: Option<&GemmBackendHandle>,
67        coeffs: &Slice<f64, DynRank>,
68        dim: usize,
69        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
70    ) -> Result<(), Error> {
71        let _ = (backend, coeffs, dim, out);
72        Err(not_supported(
73            "evaluate_nd_dz_to (real coefficients to complex values)",
74        ))
75    }
76
77    /// Evaluate ND: Complex<f64> coeffs → f64 values
78    fn evaluate_nd_zd_to(
79        &self,
80        backend: Option<&GemmBackendHandle>,
81        coeffs: &Slice<Complex<f64>, DynRank>,
82        dim: usize,
83        out: &mut ViewMut<'_, f64, DynRank>,
84    ) -> Result<(), Error> {
85        let _ = (backend, coeffs, dim, out);
86        Err(not_supported(
87            "evaluate_nd_zd_to (complex coefficients to real values)",
88        ))
89    }
90
91    /// Evaluate ND: Complex<f64> coeffs → Complex<f64> values
92    fn evaluate_nd_zz_to(
93        &self,
94        backend: Option<&GemmBackendHandle>,
95        coeffs: &Slice<Complex<f64>, DynRank>,
96        dim: usize,
97        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
98    ) -> Result<(), Error> {
99        let _ = (backend, coeffs, dim, out);
100        Err(not_supported(
101            "evaluate_nd_zz_to (complex coefficients to complex values)",
102        ))
103    }
104
105    /// Fit ND: f64 values → f64 coeffs
106    fn fit_nd_dd_to(
107        &self,
108        backend: Option<&GemmBackendHandle>,
109        values: &Slice<f64, DynRank>,
110        dim: usize,
111        out: &mut ViewMut<'_, f64, DynRank>,
112    ) -> Result<(), Error> {
113        let _ = (backend, values, dim, out);
114        Err(not_supported(
115            "fit_nd_dd_to (real values to real coefficients)",
116        ))
117    }
118
119    /// Fit ND: f64 values → Complex<f64> coeffs
120    fn fit_nd_dz_to(
121        &self,
122        backend: Option<&GemmBackendHandle>,
123        values: &Slice<f64, DynRank>,
124        dim: usize,
125        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
126    ) -> Result<(), Error> {
127        let _ = (backend, values, dim, out);
128        Err(not_supported(
129            "fit_nd_dz_to (real values to complex coefficients)",
130        ))
131    }
132
133    /// Fit ND: Complex<f64> values → f64 coeffs
134    fn fit_nd_zd_to(
135        &self,
136        backend: Option<&GemmBackendHandle>,
137        values: &Slice<Complex<f64>, DynRank>,
138        dim: usize,
139        out: &mut ViewMut<'_, f64, DynRank>,
140    ) -> Result<(), Error> {
141        let _ = (backend, values, dim, out);
142        Err(not_supported(
143            "fit_nd_zd_to (complex values to real coefficients)",
144        ))
145    }
146
147    /// Fit ND: Complex<f64> values → Complex<f64> coeffs
148    fn fit_nd_zz_to(
149        &self,
150        backend: Option<&GemmBackendHandle>,
151        values: &Slice<Complex<f64>, DynRank>,
152        dim: usize,
153        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
154    ) -> Result<(), Error> {
155        let _ = (backend, values, dim, out);
156        Err(not_supported(
157            "fit_nd_zz_to (complex values to complex coefficients)",
158        ))
159    }
160}
161
162/// The error of an [`InplaceFitter`] method that a fitter does not support
163fn not_supported(operation: &str) -> Error {
164    Error::NotSupported {
165        what: format!("{operation} for this sampling"),
166    }
167}
168
169// ============================================================================
170// Permutation helpers
171// ============================================================================
172
173/// Generate permutation to move dimension `dim` to position 0
174///
175/// For example, with rank=4 and dim=2:
176/// - Result: [2, 0, 1, 3]
177pub(crate) fn make_perm_to_front(rank: usize, dim: usize) -> Vec<usize> {
178    let mut perm = Vec::with_capacity(rank);
179    perm.push(dim);
180    for i in 0..rank {
181        if i != dim {
182            perm.push(i);
183        }
184    }
185    perm
186}
187
188// ============================================================================
189// Shape validation
190// ============================================================================
191
192/// Check the input of an N-D evaluate or fit along axis `dim`
193///
194/// `Ok` if `dim` is an axis of the input and the input has extent `n_in`
195/// along it. Call this before reading `input_dims[dim]` anywhere else, and
196/// before allocating an output from the input shape.
197///
198/// # Errors
199///
200/// * [`Error::AxisOutOfRange`] if `dim` is not an axis of the input
201/// * [`Error::ShapeMismatch`] of the input, with the shape it should have,
202///   if its extent along `dim` is not `n_in`
203pub(crate) fn check_input_shape(
204    input_dims: &[usize],
205    dim: usize,
206    n_in: usize,
207) -> Result<(), Error> {
208    let rank = input_dims.len();
209    if dim >= rank {
210        return Err(Error::AxisOutOfRange { axis: dim, rank });
211    }
212    if input_dims[dim] != n_in {
213        let mut expected = input_dims.to_vec();
214        expected[dim] = n_in;
215        return Err(Error::ShapeMismatch {
216            which: ArrayRole::Input,
217            expected,
218            actual: input_dims.to_vec(),
219        });
220    }
221    Ok(())
222}
223
224/// Check the shapes of an N-D evaluate or fit along axis `dim` that writes
225/// to `out`
226///
227/// The N-D methods of the fitters address the input and `out` as contiguous
228/// matrices through unchecked views and pointer offsets computed from the
229/// shape of the input. So the input must pass [`check_input_shape`], and
230/// `out` must have the shape of the input with `n_out` along `dim` (in
231/// particular its rank). Call this before any unchecked access or write.
232///
233/// # Errors
234///
235/// The errors of [`check_input_shape`], then [`Error::ShapeMismatch`] of the
236/// output, with the shape it should have, if `out` has another shape
237pub(crate) fn check_nd_shapes(
238    input_dims: &[usize],
239    dim: usize,
240    n_in: usize,
241    out_dims: &[usize],
242    n_out: usize,
243) -> Result<(), Error> {
244    check_input_shape(input_dims, dim, n_in)?;
245    let mut expected = input_dims.to_vec();
246    expected[dim] = n_out;
247    if out_dims != expected.as_slice() {
248        return Err(Error::ShapeMismatch {
249            which: ArrayRole::Output,
250            expected,
251            actual: out_dims.to_vec(),
252        });
253    }
254    Ok(())
255}
256
257// ============================================================================
258// Strided copy helpers
259// ============================================================================
260
261/// Copy data from a contiguous slice to a strided view
262///
263/// This is useful for copying GEMM results back to a permuted output view.
264///
265/// # Arguments
266/// * `src` - Source slice (contiguous)
267/// * `dst` - Destination slice (may be strided)
268pub(crate) fn copy_from_contiguous<T: Copy>(
269    src: &[T],
270    dst: &mut mdarray::Slice<T, mdarray::DynRank, mdarray::Strided>,
271) {
272    assert_eq!(src.len(), dst.len(), "Source size mismatch");
273
274    // mdarray's iter_mut() returns elements in row-major order
275    for (d, s) in dst.iter_mut().zip(src.iter()) {
276        *d = *s;
277    }
278}
279
280// ============================================================================
281// Complex-Real reinterpretation helpers
282// ============================================================================
283
284/// Reinterpret a mutable Complex<f64> slice as a mutable f64 view with an extra dimension of size 2
285///
286/// Complex<f64> array `[d0, d1, ..., dN]` becomes f64 array `[d0, d1, ..., dN, 2]`
287/// where the last dimension contains [re, im] pairs.
288#[allow(dead_code)]
289pub(crate) fn complex_slice_mut_as_real<'a>(
290    out: &'a mut Slice<Complex<f64>, DynRank>,
291) -> mdarray::ViewMut<'a, f64, DynRank, mdarray::Dense> {
292    // Build new shape: [..., 2]
293    let mut new_shape: Vec<usize> = Vec::with_capacity(out.rank() + 1);
294    out.shape().with_dims(|dims| {
295        for d in dims {
296            new_shape.push(*d);
297        }
298    });
299    new_shape.push(2);
300
301    unsafe {
302        let shape: DynRank = Shape::from_dims(&new_shape[..]);
303        let mapping = mdarray::DenseMapping::new(shape);
304        mdarray::ViewMut::new_unchecked(out.as_mut_ptr() as *mut f64, mapping)
305    }
306}
307
308// ============================================================================
309// SVD structures
310// ============================================================================
311
312/// Transpose of a matrix, as a new dense tensor
313///
314/// Zero-extent guard: mdarray 0.7.2 copies the transposed (strided) view of a
315/// `[n, 0]` matrix out of bounds (https://github.com/fre-hu/mdarray/issues/21),
316/// which the SVD of a matrix with a zero dimension produces. An empty matrix
317/// has nothing to copy.
318fn transposed<T: Clone + Default>(m: &DTensor<T, 2>) -> DTensor<T, 2> {
319    let (rows, cols) = *m.shape();
320    if m.is_empty() {
321        return DTensor::<T, 2>::zeros([cols, rows]);
322    }
323    m.transpose().to_tensor()
324}
325
326/// SVD decomposition for real matrices
327pub(crate) struct RealSVD {
328    pub ut: DTensor<f64, 2>, // (min_dim, n_rows) - U^T
329    pub s: Vec<f64>,         // (min_dim,)
330    pub v: DTensor<f64, 2>,  // (n_cols, min_dim) - V (transpose of V^T)
331}
332
333impl RealSVD {
334    pub fn new(u: DTensor<f64, 2>, s: Vec<f64>, vt: DTensor<f64, 2>) -> Self {
335        // Check dimensions
336        let (_, u_cols) = *u.shape();
337        let (vt_rows, _) = *vt.shape();
338        let min_dim = s.len();
339
340        assert_eq!(
341            u_cols, min_dim,
342            "u.cols()={} must equal s.len()={}",
343            u_cols, min_dim
344        );
345        assert_eq!(
346            vt_rows, min_dim,
347            "vt.rows()={} must equal s.len()={}",
348            vt_rows, min_dim
349        );
350
351        // Create ut and v from u and vt
352        let ut = transposed(&u); // (min_dim, n_rows)
353        let v = transposed(&vt); // (n_cols, min_dim)
354
355        // Verify v.cols() == s.len() (v.shape().1 is the second dimension, which is min_dim)
356        assert_eq!(
357            v.shape().1,
358            min_dim,
359            "v.cols()={} must equal s.len()={}",
360            v.shape().1,
361            min_dim
362        );
363
364        Self { ut, s, v }
365    }
366}
367
368/// SVD decomposition for complex matrices
369pub(crate) struct ComplexSVD {
370    pub ut: DTensor<Complex<f64>, 2>, // (min_dim, n_rows) - U^H
371    pub s: Vec<f64>,                  // (min_dim,) - singular values are real
372    pub v: DTensor<Complex<f64>, 2>,  // (n_cols, min_dim) - V (transpose of V^T)
373}
374
375impl ComplexSVD {
376    pub fn new(u: DTensor<Complex<f64>, 2>, s: Vec<f64>, vt: DTensor<Complex<f64>, 2>) -> Self {
377        // Check dimensions
378        let (_, u_cols) = *u.shape();
379        let (vt_rows, _) = *vt.shape();
380        let min_dim = s.len();
381
382        assert_eq!(
383            u_cols, min_dim,
384            "u.cols()={} must equal s.len()={}",
385            u_cols, min_dim
386        );
387        assert_eq!(
388            vt_rows, min_dim,
389            "vt.rows()={} must equal s.len()={}",
390            vt_rows, min_dim
391        );
392
393        // Create ut (U^H, conjugate transpose) and v from u and vt
394        let ut = transposed(&u).map(|x| x.conj()); // conjugate transpose: U^H
395        let v = transposed(&vt); // (n_cols, min_dim)
396
397        // Verify v.cols() == s.len() (v.shape().1 is the second dimension, which is min_dim)
398        assert_eq!(
399            v.shape().1,
400            min_dim,
401            "v.cols()={} must equal s.len()={}",
402            v.shape().1,
403            min_dim
404        );
405
406        Self { ut, s, v }
407    }
408}
409
410/// Condition number `σ_max / σ_min` from the singular values of a fitting matrix
411///
412/// Conventions shared by the `condition_number` methods of all samplings and
413/// by `spir_sampling_get_cond_num`:
414/// - `f64::INFINITY` if `σ_min < 1e-15` (numerically singular matrix);
415/// - `1.0` if there are no singular values (a matrix with a zero dimension);
416/// - `NaN` if any singular value is NaN, so a failed decomposition never
417///   yields a plausible finite value.
418pub(crate) fn condition_number_from_singular_values(s: &[f64]) -> f64 {
419    if s.is_empty() {
420        return 1.0;
421    }
422    if s.iter().any(|x| x.is_nan()) {
423        return f64::NAN;
424    }
425    let s_max = s.iter().copied().fold(f64::NEG_INFINITY, f64::max);
426    let s_min = s.iter().copied().fold(f64::INFINITY, f64::min);
427    if s_min.abs() < 1e-15 {
428        return f64::INFINITY;
429    }
430    s_max / s_min
431}
432
433// ============================================================================
434// SVD computation functions
435// ============================================================================
436
437/// `Ok` if a slice of `len` elements has the `expected` length
438///
439/// # Errors
440///
441/// [`Error::ShapeMismatch`] of `which`, with the lengths as one-entry shapes
442pub(crate) fn check_len(which: ArrayRole, len: usize, expected: usize) -> Result<(), Error> {
443    if len == expected {
444        Ok(())
445    } else {
446        Err(Error::ShapeMismatch {
447            which,
448            expected: vec![expected],
449            actual: vec![len],
450        })
451    }
452}
453
454/// Name of a `rows × cols` sampling matrix in an error
455fn sampling_matrix((rows, cols): (usize, usize)) -> String {
456    format!("{rows} x {cols} sampling matrix")
457}
458
459/// The error of an SVD that failed; `matrix` names the matrix, e.g.
460/// "5 x 3 sampling matrix"
461fn svd_failed(matrix: String, err: impl std::fmt::Display) -> Error {
462    Error::DecompositionFailed {
463        reason: format!("the SVD of the {matrix} failed: {err}"),
464    }
465}
466
467/// Compute SVD of a real matrix using mdarray-linalg
468///
469/// # Errors
470///
471/// [`Error::DecompositionFailed`] if the SVD does not converge, e.g. for a
472/// matrix with a NaN or an infinite entry (which the public constructors
473/// of the samplings reject)
474pub(crate) fn compute_real_svd(matrix: &DTensor<f64, 2>) -> Result<RealSVD, Error> {
475    compute_real_svd_of(matrix, || sampling_matrix(*matrix.shape()))
476}
477
478/// [`compute_real_svd`] of a matrix that `name` names in the error
479pub(crate) fn compute_real_svd_of(
480    matrix: &DTensor<f64, 2>,
481    name: impl FnOnce() -> String,
482) -> Result<RealSVD, Error> {
483    use mdarray_linalg::prelude::SVD;
484    use mdarray_linalg::svd::SVDDecomp;
485    use mdarray_linalg_faer::Faer;
486
487    // Protect FPU state during SVD computation (required for Intel Fortran compatibility)
488    let _guard = FpuGuard::new_protect_computation();
489
490    let mut a = matrix.clone();
491    let SVDDecomp { u, s, vt } = Faer.svd(&mut *a).map_err(|e| svd_failed(name(), e))?;
492
493    // Extract singular values from first row
494    let min_dim = s.shape().0.min(s.shape().1);
495    let s_vec: Vec<f64> = (0..min_dim).map(|i| s[[0, i]]).collect();
496
497    // Trim u and vt to min_dim
498    // u: (n_rows, n_cols) -> (n_rows, min_dim) - take first min_dim columns
499    // vt: (n_rows, n_cols) -> (min_dim, n_cols) - take first min_dim rows
500    let u_trimmed = u.view(.., ..min_dim).to_tensor();
501    let vt_trimmed = vt.view(..min_dim, ..).to_tensor();
502
503    Ok(RealSVD::new(u_trimmed, s_vec, vt_trimmed))
504}
505
506/// Compute SVD of a complex matrix directly
507///
508/// # Errors
509///
510/// [`Error::DecompositionFailed`] if the SVD does not converge, e.g. for a
511/// matrix with a NaN or an infinite entry (which the public constructors
512/// of the samplings reject)
513pub(crate) fn compute_complex_svd(matrix: &DTensor<Complex<f64>, 2>) -> Result<ComplexSVD, Error> {
514    use mdarray_linalg::prelude::SVD;
515    use mdarray_linalg::svd::SVDDecomp;
516    use mdarray_linalg_faer::Faer;
517
518    // Protect FPU state during SVD computation (required for Intel Fortran compatibility)
519    let _guard = FpuGuard::new_protect_computation();
520
521    // Use matrix directly (Complex<f64> is compatible with faer's c64)
522    let mut matrix_c64 = matrix.clone();
523
524    // Compute complex SVD directly
525    let SVDDecomp { u, s, vt } = Faer
526        .svd(&mut *matrix_c64)
527        .map_err(|e| svd_failed(sampling_matrix(*matrix.shape()), e))?;
528
529    // Extract singular values from first row (they are real even though stored as Complex)
530    let min_dim = s.shape().0.min(s.shape().1);
531    let s_vec: Vec<f64> = (0..min_dim).map(|i| s[[0, i]].re).collect();
532
533    // Trim u and vt to min_dim
534    // u: (n_rows, n_cols) -> (n_rows, min_dim) - take first min_dim columns
535    // vt: (n_rows, n_cols) -> (min_dim, n_cols) - take first min_dim rows
536    let u_trimmed = u.view(.., ..min_dim).to_tensor();
537    let vt_trimmed = vt.view(..min_dim, ..).to_tensor();
538
539    Ok(ComplexSVD::new(u_trimmed, s_vec, vt_trimmed))
540}
541
542// ============================================================================
543// Complex-Real conversion helpers
544// ============================================================================
545
546/// Combine real and imaginary parts into complex tensor
547pub(crate) fn combine_complex(
548    re: &DTensor<f64, 2>,
549    im: &DTensor<f64, 2>,
550) -> DTensor<Complex<f64>, 2> {
551    let (n_points, extra_size) = *re.shape();
552    DTensor::<Complex<f64>, 2>::from_fn([n_points, extra_size], |idx| {
553        Complex::new(re[idx], im[idx])
554    })
555}
556
557/// Extract real parts from complex tensor (for coefficients)
558pub(crate) fn extract_real_parts_coeffs(coeffs_2d: &DTensor<Complex<f64>, 2>) -> DTensor<f64, 2> {
559    let (basis_size, extra_size) = *coeffs_2d.shape();
560    DTensor::<f64, 2>::from_fn([basis_size, extra_size], |idx| coeffs_2d[idx].re)
561}