sparse-ir-core 0.13.0

Core of sparse-ir: statistics, errors, GEMM, fitters, the Basis trait and sparse sampling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! Shared machinery for fitters.
//!
//! Every fitter operation is a contraction of a stored matrix with one axis of
//! a column-major tensor. The tensor is addressed as `[pre, n, post]`, where
//! `pre` is the product of the extents before the target axis and `post` the
//! product of those after it, so no data movement is needed to bring the
//! target axis to the front.
//!
//! This module provides the `InplaceFitter` trait, layout validation for
//! tenferro tensors and views, and the SVD-based least-squares factors.

use crate::error::{ArrayRole, Error, Result};
use crate::fpu_check::FpuGuard;
use crate::gemm::{GemmBackendHandle, GemmScalar, apply_along_axis};
use num_complex::Complex;
use tenferro_tensor::{TypedTensor, TypedTensorView, TypedTensorViewMut};

// ============================================================================
// InplaceFitter trait
// ============================================================================

/// Evaluation and fitting along one axis of an N-dimensional tensor, writing
/// into a caller-provided output view.
///
/// Method suffixes follow BLAS naming (`d` = `f64`, `z` = `Complex<f64>`):
/// `evaluate_nd_dz_to` maps real coefficients to complex values.
///
/// Inputs may have any strided host layout (non-contiguous inputs are copied
/// once). Outputs must be host-resident compact column-major views whose
/// shape equals the input shape with axis `dim` replaced by the output
/// extent.
///
/// Each method returns `Ok(())` after writing the result to `out`. On an
/// error nothing is written to `out`:
/// - [`Error::NotSupported`] if the fitter does not support this pair of
///   types (the default implementations), or if `out` is not a compact
///   column-major view;
/// - [`Error::AxisOutOfRange`] if `dim` is not an axis of the input;
/// - [`Error::ShapeMismatch`] of the input if it does not have `basis_size`
///   (evaluate) or `n_points` (fit) along `dim`, and of the output if `out`
///   does not have the shape of the input with `n_points` (evaluate) or
///   `basis_size` (fit) along `dim`;
/// - [`Error::DecompositionFailed`] if a fit needs the singular value
///   decomposition of the matrix and it fails.
///
/// An empty input of the right shape (a batch axis of extent 0) gives
/// `Ok(())` without computing anything.
pub trait InplaceFitter {
    /// Number of sampling points.
    fn n_points(&self) -> usize;

    /// Number of basis functions.
    fn basis_size(&self) -> usize;

    /// Evaluate: `f64` coefficients to `f64` values.
    fn evaluate_nd_dd_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        coeffs: &TypedTensorView<'_, f64>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, f64>,
    ) -> Result<()> {
        let _ = (backend, coeffs, dim, out);
        Err(not_supported(
            "evaluate_nd_dd_to (real coefficients to real values)",
        ))
    }

    /// Evaluate: `f64` coefficients to `Complex<f64>` values.
    fn evaluate_nd_dz_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        coeffs: &TypedTensorView<'_, f64>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, Complex<f64>>,
    ) -> Result<()> {
        let _ = (backend, coeffs, dim, out);
        Err(not_supported(
            "evaluate_nd_dz_to (real coefficients to complex values)",
        ))
    }

    /// Evaluate: `Complex<f64>` coefficients to `f64` values.
    fn evaluate_nd_zd_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        coeffs: &TypedTensorView<'_, Complex<f64>>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, f64>,
    ) -> Result<()> {
        let _ = (backend, coeffs, dim, out);
        Err(not_supported(
            "evaluate_nd_zd_to (complex coefficients to real values)",
        ))
    }

    /// Evaluate: `Complex<f64>` coefficients to `Complex<f64>` values.
    fn evaluate_nd_zz_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        coeffs: &TypedTensorView<'_, Complex<f64>>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, Complex<f64>>,
    ) -> Result<()> {
        let _ = (backend, coeffs, dim, out);
        Err(not_supported(
            "evaluate_nd_zz_to (complex coefficients to complex values)",
        ))
    }

    /// Fit: `f64` values to `f64` coefficients.
    fn fit_nd_dd_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        values: &TypedTensorView<'_, f64>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, f64>,
    ) -> Result<()> {
        let _ = (backend, values, dim, out);
        Err(not_supported(
            "fit_nd_dd_to (real values to real coefficients)",
        ))
    }

    /// Fit: `f64` values to `Complex<f64>` coefficients.
    fn fit_nd_dz_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        values: &TypedTensorView<'_, f64>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, Complex<f64>>,
    ) -> Result<()> {
        let _ = (backend, values, dim, out);
        Err(not_supported(
            "fit_nd_dz_to (real values to complex coefficients)",
        ))
    }

    /// Fit: `Complex<f64>` values to `f64` coefficients.
    fn fit_nd_zd_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        values: &TypedTensorView<'_, Complex<f64>>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, f64>,
    ) -> Result<()> {
        let _ = (backend, values, dim, out);
        Err(not_supported(
            "fit_nd_zd_to (complex values to real coefficients)",
        ))
    }

    /// Fit: `Complex<f64>` values to `Complex<f64>` coefficients.
    fn fit_nd_zz_to(
        &self,
        backend: Option<&GemmBackendHandle>,
        values: &TypedTensorView<'_, Complex<f64>>,
        dim: usize,
        out: &mut TypedTensorViewMut<'_, Complex<f64>>,
    ) -> Result<()> {
        let _ = (backend, values, dim, out);
        Err(not_supported(
            "fit_nd_zz_to (complex values to complex coefficients)",
        ))
    }
}

/// The error of an [`InplaceFitter`] method that a fitter does not support
fn not_supported(operation: &str) -> Error {
    Error::NotSupported {
        what: format!("{operation} for this sampling"),
    }
}

/// The error of a tensor view that the fitters cannot address as compact
/// column-major storage
fn layout_error(what: impl Into<String>) -> Error {
    Error::NotSupported { what: what.into() }
}

// ============================================================================
// Scalar reinterpretation
// ============================================================================

/// `f64` or `Complex<f64>`, viewable as interleaved `f64` storage.
///
/// A column-major complex tensor of shape `[pre, n, post]` is a real tensor
/// of shape `[2 * pre, n, post]`, so real-matrix contractions apply to it
/// with `pre` doubled.
pub trait FitScalar: GemmScalar {
    /// Number of `f64` values per element (1 or 2).
    const REAL_WIDTH: usize;
    /// Reinterpret as `f64` storage.
    fn as_f64(s: &[Self]) -> &[f64];
    /// Reinterpret mutably as `f64` storage.
    fn as_f64_mut(s: &mut [Self]) -> &mut [f64];
}

impl FitScalar for f64 {
    const REAL_WIDTH: usize = 1;
    fn as_f64(s: &[f64]) -> &[f64] {
        s
    }
    fn as_f64_mut(s: &mut [f64]) -> &mut [f64] {
        s
    }
}

impl FitScalar for Complex<f64> {
    const REAL_WIDTH: usize = 2;
    fn as_f64(s: &[Self]) -> &[f64] {
        // SAFETY: `Complex<f64>` is `#[repr(C)] { re: f64, im: f64 }`, so a
        // slice of N complex values is a valid slice of 2N f64 values with
        // the same lifetime and alignment.
        unsafe { std::slice::from_raw_parts(s.as_ptr().cast::<f64>(), 2 * s.len()) }
    }
    fn as_f64_mut(s: &mut [Self]) -> &mut [f64] {
        // SAFETY: as above; the unique borrow is transferred.
        unsafe { std::slice::from_raw_parts_mut(s.as_mut_ptr().cast::<f64>(), 2 * s.len()) }
    }
}

// ============================================================================
// Axis geometry and layout validation
// ============================================================================

/// Extents of a tensor split around the target axis.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AxisSplit {
    pub pre: usize,
    pub post: usize,
}

/// Check the input of an N-D evaluate or fit along axis `dim`
///
/// `Ok` if `dim` is an axis of the input and the input has extent `n_in`
/// along it. Call this before reading `input_dims[dim]` anywhere else, and
/// before allocating an output from the input shape.
///
/// # Errors
///
/// * [`Error::AxisOutOfRange`] if `dim` is not an axis of the input
/// * [`Error::ShapeMismatch`] of the input, with the shape it should have,
///   if its extent along `dim` is not `n_in`
pub(crate) fn check_input_shape(input_dims: &[usize], dim: usize, n_in: usize) -> Result<()> {
    let rank = input_dims.len();
    if dim >= rank {
        return Err(Error::AxisOutOfRange { axis: dim, rank });
    }
    if input_dims[dim] != n_in {
        let mut expected = input_dims.to_vec();
        expected[dim] = n_in;
        return Err(Error::ShapeMismatch {
            which: ArrayRole::Input,
            expected,
            actual: input_dims.to_vec(),
        });
    }
    Ok(())
}

/// Check the shapes of an N-D evaluate or fit along axis `dim` that writes
/// to `out`: the input must pass [`check_input_shape`], and `out` must have
/// the shape of the input with `n_out` along `dim` (in particular its rank).
///
/// # Errors
///
/// The errors of [`check_input_shape`], then [`Error::ShapeMismatch`] of the
/// output, with the shape it should have, if `out` has another shape
pub(crate) fn check_nd_shapes(
    input_dims: &[usize],
    dim: usize,
    n_in: usize,
    out_dims: &[usize],
    n_out: usize,
) -> Result<()> {
    check_input_shape(input_dims, dim, n_in)?;
    let expected = replace_axis(input_dims, dim, n_out);
    if out_dims != expected.as_slice() {
        return Err(Error::ShapeMismatch {
            which: ArrayRole::Output,
            expected,
            actual: out_dims.to_vec(),
        });
    }
    Ok(())
}

/// `Ok` if a slice of `len` elements has the `expected` length
///
/// # Errors
///
/// [`Error::ShapeMismatch`] of `which`, with the lengths as one-entry shapes
pub(crate) fn check_len(which: ArrayRole, len: usize, expected: usize) -> Result<()> {
    if len == expected {
        Ok(())
    } else {
        Err(Error::ShapeMismatch {
            which,
            expected: vec![expected],
            actual: vec![len],
        })
    }
}

/// Split `shape` around `dim` after [`check_input_shape`].
pub(crate) fn split_axis(shape: &[usize], dim: usize, expected: usize) -> Result<AxisSplit> {
    check_input_shape(shape, dim, expected)?;
    Ok(AxisSplit {
        pre: shape[..dim].iter().product(),
        post: shape[dim + 1..].iter().product(),
    })
}

/// `shape` with axis `dim` replaced by `extent`.
pub(crate) fn replace_axis(shape: &[usize], dim: usize, extent: usize) -> Vec<usize> {
    let mut out = shape.to_vec();
    out[dim] = extent;
    out
}

/// Compact column-major host slice of a view, copying a strided view once.
pub(crate) enum InputSlice<'a, T: tenferro_tensor::TensorScalar> {
    Borrowed(&'a [T]),
    Owned(Vec<T>),
}

impl<T: tenferro_tensor::TensorScalar> InputSlice<'_, T> {
    pub(crate) fn get(&self) -> Result<&[T]> {
        match self {
            InputSlice::Borrowed(s) => Ok(s),
            InputSlice::Owned(v) => Ok(v),
        }
    }
}

pub(crate) fn input_slice<'a, T: tenferro_tensor::TensorScalar>(
    view: &TypedTensorView<'a, T>,
) -> Result<InputSlice<'a, T>> {
    if view.is_col_major_contiguous()? {
        Ok(InputSlice::Borrowed(view.as_slice()?))
    } else {
        Ok(InputSlice::Owned(gather_col_major(view)?))
    }
}

/// Copy a strided host view into a compact column-major buffer.
fn gather_col_major<T: tenferro_tensor::TensorScalar>(
    view: &TypedTensorView<'_, T>,
) -> Result<Vec<T>> {
    let shape = view.shape();
    let strides = view.strides();
    let storage = view.host_storage()?;
    let len = view.n_elements();
    if len == 0 {
        return Ok(Vec::new());
    }
    // Validate the reachable offset range once, before allocating.
    let (mut lo, mut hi) = (view.offset(), view.offset());
    for (&n, &st) in shape.iter().zip(strides) {
        let span = isize::try_from(n - 1)
            .ok()
            .and_then(|m| m.checked_mul(st))
            .ok_or_else(|| layout_error("input view stride overflow"))?;
        if span < 0 {
            lo += span;
        } else {
            hi += span;
        }
    }
    if lo < 0 || usize::try_from(hi).map_or(true, |h| h >= storage.len()) {
        return Err(layout_error("input view exceeds its storage"));
    }
    let mut out = Vec::with_capacity(len);
    let mut idx = vec![0usize; shape.len()];
    let mut pos = view.offset();
    for _ in 0..len {
        // pos is within [lo, hi] by the range check above.
        out.push(storage[pos as usize].clone());
        for (k, i) in idx.iter_mut().enumerate() {
            *i += 1;
            pos += strides[k];
            if *i < shape[k] {
                break;
            }
            pos -= strides[k] * shape[k] as isize;
            *i = 0;
        }
    }
    Ok(out)
}

/// Compact column-major host slice of an output view.
pub(crate) fn output_slice<'a, T: tenferro_tensor::TensorScalar>(
    view: &'a mut TypedTensorViewMut<'_, T>,
) -> Result<&'a mut [T]> {
    if !view.is_col_major_contiguous()? {
        return Err(layout_error(format!(
            "output view must be compact column-major, got {}",
            view.layout_summary()
        )));
    }
    let offset = usize::try_from(view.offset())
        .map_err(|_| layout_error("output view has a negative offset"))?;
    let len = view.n_elements();
    let storage = view
        .host_storage_mut()
        .map_err(|e| layout_error(e.to_string()))?;
    storage
        .get_mut(offset..offset + len)
        .ok_or_else(|| layout_error("output view exceeds its storage"))
}

/// Run an axis operation `n_in -> n_out` from `input` into `out`.
///
/// `op` receives compact column-major `[pre, n_in, post]` and
/// `[pre, n_out, post]` slices.
pub(crate) fn run_to<Tin, Tout, F>(
    input: &TypedTensorView<'_, Tin>,
    dim: usize,
    n_in: usize,
    n_out: usize,
    out: &mut TypedTensorViewMut<'_, Tout>,
    op: F,
) -> Result<()>
where
    Tin: tenferro_tensor::TensorScalar,
    Tout: tenferro_tensor::TensorScalar,
    F: FnOnce(&[Tin], AxisSplit, &mut [Tout]) -> Result<()>,
{
    check_nd_shapes(input.shape(), dim, n_in, out.shape(), n_out)?;
    let split = split_axis(input.shape(), dim, n_in)?;
    let x = input_slice(input)?;
    let y = output_slice(out)?;
    op(x.get()?, split, y)
}

/// Run an axis operation `n_in -> n_out` into a newly allocated tensor.
pub(crate) fn run_alloc<Tin, Tout, F>(
    input: &TypedTensor<Tin>,
    dim: usize,
    n_in: usize,
    n_out: usize,
    op: F,
) -> Result<TypedTensor<Tout>>
where
    Tin: tenferro_tensor::TensorScalar,
    Tout: tenferro_tensor::TensorScalar + num_traits::Zero,
    F: FnOnce(&[Tin], AxisSplit, &mut [Tout]) -> Result<()>,
{
    let split = split_axis(input.shape(), dim, n_in)?;
    let out_shape = replace_axis(input.shape(), dim, n_out);
    // Owned tensors are compact column-major by tenferro's invariant, so the
    // host buffer is the tensor in order (and avoids building a view).
    let x = input.host_data()?;
    debug_assert_eq!(x.len(), input.n_elements());
    let mut y = vec![Tout::zero(); split.pre * n_out * split.post];
    op(x, split, &mut y)?;
    Ok(TypedTensor::from_vec_col_major(out_shape, y)?)
}

// ============================================================================
// Complex <-> stacked-real layout helpers
// ============================================================================

/// Convert real `[pre, 2n, post]` (rows `0..n` real parts, `n..2n` imaginary
/// parts) into complex `[pre, n, post]`.
pub(crate) fn stacked_to_complex(
    t: &[f64],
    pre: usize,
    n: usize,
    post: usize,
    y: &mut [Complex<f64>],
) {
    for q in 0..post {
        for i in 0..n {
            let re = &t[pre * (i + 2 * n * q)..][..pre];
            let im = &t[pre * (n + i + 2 * n * q)..][..pre];
            let dst = &mut y[pre * (i + n * q)..][..pre];
            for p in 0..pre {
                dst[p] = Complex::new(re[p], im[p]);
            }
        }
    }
}

/// Convert complex `[pre, n, post]` into real `[pre, 2n, post]` with real
/// parts in rows `0..n` and imaginary parts in rows `n..2n`.
pub(crate) fn complex_to_stacked(
    x: &[Complex<f64>],
    pre: usize,
    n: usize,
    post: usize,
) -> Vec<f64> {
    let mut t = vec![0.0; 2 * pre * n * post];
    for q in 0..post {
        for i in 0..n {
            let src = &x[pre * (i + n * q)..][..pre];
            let base_re = pre * (i + 2 * n * q);
            let base_im = pre * (n + i + 2 * n * q);
            for p in 0..pre {
                t[base_re + p] = src[p].re;
                t[base_im + p] = src[p].im;
            }
        }
    }
    t
}

// ============================================================================
// SVD-based least squares
// ============================================================================

/// Factors of the pseudo-inverse `A^+ = V diag(1/s) U^H` of an `n x m`
/// matrix, stored for axis contractions.
///
/// Rank is `r = min(n, m)` without truncation: sampling matrices are well
/// conditioned by construction.
#[doc(hidden)]
pub struct PinvFactors<T> {
    /// `U^H`, contiguous `r x n`.
    pub uh: Vec<T>,
    /// `V diag(1/s)`, contiguous `m x r`.
    pub v_scaled: Vec<T>,
    /// Singular values `s`, descending (`min(n, m)` of them, before any
    /// truncation).
    pub s: Vec<f64>,
    pub n: usize,
    pub m: usize,
    pub rank: usize,
}

impl<T: GemmScalar> PinvFactors<T> {
    /// Least-squares solve along the middle axis of `[pre, n, post]` into
    /// `[pre, m, post]`.
    pub fn solve(
        &self,
        backend: Option<&GemmBackendHandle>,
        values: &[T],
        pre: usize,
        post: usize,
        out: &mut [T],
    ) -> Result<()> {
        let mut tmp = vec![T::zero(); pre * self.rank * post];
        apply_along_axis(
            backend, &self.uh, self.rank, self.n, values, pre, post, &mut tmp,
        )?;
        apply_along_axis(
            backend,
            &self.v_scaled,
            self.m,
            self.rank,
            &tmp,
            pre,
            post,
            out,
        )?;
        Ok(())
    }
}

/// Scalars with an SVD through tenferro-linalg.
pub trait SvdScalar: GemmScalar + tenferro_linalg::LinalgScalar {
    fn conj_(self) -> Self;
    fn scale(self, s: f64) -> Self;
    fn real_part(v: <Self as tenferro_tensor::TensorScalar>::Real) -> f64;
}

impl SvdScalar for f64 {
    fn conj_(self) -> Self {
        self
    }
    fn scale(self, s: f64) -> Self {
        self * s
    }
    fn real_part(v: f64) -> f64 {
        v
    }
}

impl SvdScalar for Complex<f64> {
    fn conj_(self) -> Self {
        self.conj()
    }
    fn scale(self, s: f64) -> Self {
        self * s
    }
    fn real_part(v: f64) -> f64 {
        v
    }
}

/// Thin SVD of a contiguous column-major `n x m` matrix, returned as
/// pseudo-inverse factors.
///
/// # Errors
/// Propagates tenferro errors (for example a non-converging SVD).
#[doc(hidden)]
pub fn compute_pinv<T: SvdScalar>(a: &[T], n: usize, m: usize) -> Result<PinvFactors<T>> {
    compute_pinv_impl(a, n, m, None, || sampling_matrix((n, m)))
}

/// Like [`compute_pinv`], but keeps only singular values `s_l > rtol * s_0`
/// (truncated-SVD regularization).
///
/// # Errors
/// [`Error::DecompositionFailed`] if the SVD fails.
#[doc(hidden)]
pub fn compute_pinv_truncated<T: SvdScalar>(
    a: &[T],
    n: usize,
    m: usize,
    rtol: f64,
) -> Result<PinvFactors<T>> {
    compute_pinv_impl(a, n, m, Some(rtol), || sampling_matrix((n, m)))
}

/// Name of a `rows × cols` sampling matrix in an error
pub(crate) fn sampling_matrix((rows, cols): (usize, usize)) -> String {
    format!("{rows} x {cols} sampling matrix")
}

/// The error of an SVD that failed; `matrix` names the matrix, e.g.
/// "5 x 3 sampling matrix"
fn svd_failed(matrix: String, err: impl std::fmt::Display) -> Error {
    Error::DecompositionFailed {
        reason: format!("the SVD of the {matrix} failed: {err}"),
    }
}

/// [`compute_pinv`] of a matrix that `name` names in the error
///
/// # Errors
/// [`Error::DecompositionFailed`] if the SVD does not converge or returns
/// factors of the wrong shape.
pub(crate) fn compute_pinv_of<T: SvdScalar>(
    a: &[T],
    n: usize,
    m: usize,
    name: impl FnOnce() -> String,
) -> Result<PinvFactors<T>> {
    compute_pinv_impl(a, n, m, None, name)
}

fn compute_pinv_impl<T: SvdScalar>(
    a: &[T],
    n: usize,
    m: usize,
    rtol: Option<f64>,
    name: impl FnOnce() -> String,
) -> Result<PinvFactors<T>> {
    use tenferro_cpu::CpuBackend;
    use tenferro_linalg::TypedTensorLinalgExt;
    use tenferro_tensor::BackendSessionHost;

    // Protect FPU state during SVD computation (required for Intel Fortran compatibility)
    let _guard = FpuGuard::new_protect_computation();

    let rank = n.min(m);
    if rank == 0 {
        return Ok(PinvFactors {
            uh: Vec::new(),
            v_scaled: vec![T::zero(); m * rank],
            s: Vec::new(),
            n,
            m,
            rank,
        });
    }
    let tensor = TypedTensor::<T>::from_vec_col_major(vec![n, m], a.to_vec())?;
    let mut host = CpuBackend::new();
    let (u, s, vt) = match host.with_backend_session(|session| tensor.svd(session)) {
        Ok(f) => f,
        Err(e) => return Err(svd_failed(name(), e)),
    };

    let (u_shape, vt_shape) = (u.shape().to_vec(), vt.shape().to_vec());
    let (u, s, vt) = (u.host_data()?, s.host_data()?, vt.host_data()?);
    if u_shape[0] != n || u_shape[1] < rank || vt_shape[1] != m || vt_shape[0] < rank {
        return Err(svd_failed(
            name(),
            format!("factors U {u_shape:?}, Vt {vt_shape:?}"),
        ));
    }
    let (ldu, ldvt) = (u_shape[0], vt_shape[0]);
    let singular_values: Vec<f64> = s[..rank].iter().map(|&v| T::real_part(v)).collect();
    let rank = match rtol {
        Some(rtol) => {
            let s0 = T::real_part(s[0]);
            (0..rank)
                .take_while(|&l| T::real_part(s[l]) > rtol * s0)
                .count()
        }
        None => rank,
    };

    // U^H: uh[l + r*i] = conj(U[i, l])
    let mut uh = vec![T::zero(); rank * n];
    for i in 0..n {
        for l in 0..rank {
            uh[l + rank * i] = u[i + ldu * l].conj_();
        }
    }
    // V diag(1/s): V[j, l] = conj(Vt[l, j])
    let mut v_scaled = vec![T::zero(); m * rank];
    for l in 0..rank {
        let inv_s = 1.0 / T::real_part(s[l]);
        for j in 0..m {
            v_scaled[j + m * l] = vt[l + ldvt * j].conj_().scale(inv_s);
        }
    }
    Ok(PinvFactors {
        uh,
        v_scaled,
        s: singular_values,
        n,
        m,
        rank,
    })
}

/// Singular values of a contiguous column-major `n x m` matrix, descending.
///
/// # Errors
/// Propagates tenferro errors.
pub fn singular_values<T: SvdScalar>(a: &[T], n: usize, m: usize) -> Result<Vec<f64>> {
    use tenferro_cpu::CpuBackend;
    use tenferro_linalg::TypedTensorLinalgExt;
    use tenferro_tensor::BackendSessionHost;

    let _guard = FpuGuard::new_protect_computation();
    if n.min(m) == 0 {
        return Ok(Vec::new());
    }
    let tensor = TypedTensor::<T>::from_vec_col_major(vec![n, m], a.to_vec())?;
    let mut host = CpuBackend::new();
    let s = host
        .with_backend_session(|session| tensor.svdvals(session))
        .map_err(|e| svd_failed(sampling_matrix((n, m)), e))?;
    Ok(s.host_data()?.iter().map(|&v| T::real_part(v)).collect())
}

/// Condition number `σ_max / σ_min` from the singular values of a fitting matrix
///
/// Conventions shared by the `condition_number` methods of all samplings and
/// by `spir_sampling_get_cond_num`:
/// - `f64::INFINITY` if `σ_min < 1e-15` (numerically singular matrix);
/// - `1.0` if there are no singular values (a matrix with a zero dimension);
/// - `NaN` if any singular value is NaN, so a failed decomposition never
///   yields a plausible finite value.
pub(crate) fn condition_number_from_singular_values(s: &[f64]) -> f64 {
    if s.is_empty() {
        return 1.0;
    }
    if s.iter().any(|x| x.is_nan()) {
        return f64::NAN;
    }
    let s_max = s.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let s_min = s.iter().copied().fold(f64::INFINITY, f64::min);
    if s_min.abs() < 1e-15 {
        return f64::INFINITY;
    }
    s_max / s_min
}