Skip to main content

sparse_ir/
sampling.rs

1//! Sparse sampling in imaginary time
2//!
3//! This module provides `TauSampling` for transforming between IR basis coefficients
4//! and values at sparse sampling points in imaginary time.
5
6use crate::error::Error;
7use crate::fitters::InplaceFitter;
8use crate::fitters::common::check_input_shape;
9use crate::gemm::GemmBackendHandle;
10use crate::traits::StatisticsType;
11use mdarray::{DTensor, DynRank, Shape, Slice, Tensor, ViewMut};
12use num_complex::Complex;
13
14/// Build output shape by replacing dimension `dim` with `new_size`
15pub(crate) fn build_output_shape<S: Shape>(
16    input_shape: &S,
17    dim: usize,
18    new_size: usize,
19) -> Vec<usize> {
20    let mut out_shape: Vec<usize> = Vec::with_capacity(input_shape.rank());
21    input_shape.with_dims(|dims| {
22        for (i, d) in dims.iter().enumerate() {
23            if i == dim {
24                out_shape.push(new_size);
25            } else {
26                out_shape.push(*d);
27            }
28        }
29    });
30    out_shape
31}
32
33/// Move axis from position `src` to position `dst`
34///
35/// This is equivalent to numpy.moveaxis or libsparseir's movedim.
36/// It creates a permutation array that moves the specified axis.
37///
38/// # Arguments
39/// * `arr` - Input array slice (Tensor or View)
40/// * `src` - Source axis position
41/// * `dst` - Destination axis position
42///
43/// # Returns
44/// Tensor with axes permuted
45///
46/// # Panics
47///
48/// Panics if `src` or `dst` is not an axis of `arr`, also when they are equal.
49///
50/// # Example
51/// ```
52/// use sparse_ir::sampling::movedim;
53/// use sparse_ir::{DynRank, Tensor};
54///
55/// // For a 4D tensor with shape (2, 3, 4, 5)
56/// let arr = Tensor::<usize, DynRank>::from_fn(&[2, 3, 4, 5][..], |idx| {
57///     1000 * idx[0] + 100 * idx[1] + 10 * idx[2] + idx[3]
58/// });
59///
60/// // movedim(arr, 0, 2) moves axis 0 to position 2
61/// let moved = movedim(&arr, 0, 2);
62///
63/// // Result shape: (3, 4, 2, 5) with axes permuted as [1, 2, 0, 3]
64/// assert_eq!(moved.shape().dims(), &[3, 4, 2, 5]);
65/// assert_eq!(moved[&[2, 3, 1, 4][..]], arr[&[1, 2, 3, 4][..]]);
66/// ```
67pub fn movedim<T: Clone>(arr: &Slice<T, DynRank>, src: usize, dst: usize) -> Tensor<T, DynRank> {
68    let rank = arr.rank();
69    assert!(
70        src < rank,
71        "src axis {} out of bounds for rank {}",
72        src,
73        rank
74    );
75    assert!(
76        dst < rank,
77        "dst axis {} out of bounds for rank {}",
78        dst,
79        rank
80    );
81    if src == dst {
82        return arr.to_tensor();
83    }
84
85    // Generate permutation: move src to dst position
86    let mut perm = Vec::with_capacity(rank);
87    let mut pos = 0;
88    for i in 0..rank {
89        if i == dst {
90            perm.push(src);
91        } else {
92            // Skip src position
93            if pos == src {
94                pos += 1;
95            }
96            perm.push(pos);
97            pos += 1;
98        }
99    }
100
101    if arr.is_empty() {
102        // Zero-extent guard: mdarray 0.7.2 (and 0.8.0) copies a permuted,
103        // strided view out of bounds when an extent other than the last is
104        // zero (https://github.com/fre-hu/mdarray/issues/21). An empty array
105        // has no elements to move, so reshape it (a dense view) instead.
106        let dims: Vec<usize> = perm.iter().map(|&axis| arr.shape().dim(axis)).collect();
107        return arr.reshape(&dims[..]).to_tensor();
108    }
109
110    arr.permute(&perm[..]).to_tensor()
111}
112
113/// Check the shape of a given sampling matrix against its points: some
114/// points, one row per point and at least one column
115///
116/// # Errors
117///
118/// * [`Error::EmptyInput`] named `sampling_points` if there are no points
119/// * [`Error::ShapeMismatch`] of the input if the matrix does not have one
120///   row per point
121/// * [`Error::EmptyInput`] named `matrix` if it has no columns: it describes
122///   no basis function, and the fitter would transpose `[n, 0]` arrays,
123///   which mdarray 0.7.2 does out of bounds
124///   (<https://github.com/fre-hu/mdarray/issues/21>)
125pub(crate) fn check_sampling_matrix_shape(
126    n_points: usize,
127    (rows, cols): (usize, usize),
128) -> Result<(), Error> {
129    if n_points == 0 {
130        return Err(Error::EmptyInput {
131            name: "sampling_points",
132        });
133    }
134    if rows != n_points {
135        return Err(Error::ShapeMismatch {
136            which: crate::error::ArrayRole::Input,
137            expected: vec![n_points, cols],
138            actual: vec![rows, cols],
139        });
140    }
141    if cols == 0 {
142        return Err(Error::EmptyInput { name: "matrix" });
143    }
144    Ok(())
145}
146
147/// `Ok` if every entry of a given sampling matrix is finite (the fitter
148/// factorizes it)
149///
150/// # Errors
151///
152/// [`Error::NonFiniteInput`] named `matrix` at the first NaN or infinite
153/// entry in row-major order; for a complex entry, `value` is its real part
154/// if that is not finite, and its imaginary part otherwise
155pub(crate) fn check_finite_matrix<T: Copy>(
156    matrix: &DTensor<T, 2>,
157    non_finite_part: impl Fn(T) -> Option<f64>,
158) -> Result<(), Error> {
159    let (rows, cols) = *matrix.shape();
160    for i in 0..rows {
161        for j in 0..cols {
162            if let Some(value) = non_finite_part(matrix[[i, j]]) {
163                return Err(Error::NonFiniteInput {
164                    name: "matrix",
165                    index: vec![i, j],
166                    value,
167                });
168            }
169        }
170    }
171    Ok(())
172}
173
174/// Sparse sampling in imaginary time
175///
176/// Allows transformation between the IR basis and a set of sampling points
177/// in imaginary time (τ).
178pub struct TauSampling<S>
179where
180    S: StatisticsType,
181{
182    /// Sampling points in imaginary time, in the order given (τ ∈ [-β, β]
183    /// unless given with a matrix)
184    sampling_points: Vec<f64>,
185
186    /// Real matrix fitter for least-squares fitting
187    fitter: crate::fitters::RealMatrixFitter,
188
189    /// Marker for statistics type
190    _phantom: std::marker::PhantomData<S>,
191}
192
193impl<S> TauSampling<S>
194where
195    S: StatisticsType,
196{
197    /// Create a new TauSampling with default sampling points
198    ///
199    /// The default sampling points are the roots of the first discarded basis
200    /// function u_L (the extrema of u_{L-1} when u_L is not available), which
201    /// gives near-optimal conditioning.
202    /// SVD is computed lazily on first call to `fit` or `fit_nd`.
203    ///
204    /// # Arguments
205    /// * `basis` - Any basis implementing the `Basis` trait
206    ///
207    /// # Returns
208    /// A new TauSampling object
209    ///
210    /// # Errors
211    ///
212    /// The errors of [`Basis::default_tau_sampling_points`](crate::basis_trait::Basis::default_tau_sampling_points)
213    /// (e.g. NotSupported for a DLR, whose IR basis has the default points)
214    pub fn new(basis: &impl crate::basis_trait::Basis<S>) -> Result<Self, Error>
215    where
216        S: 'static,
217    {
218        let sampling_points = basis.default_tau_sampling_points()?;
219        Self::with_sampling_points(basis, sampling_points)
220    }
221
222    /// Create a new TauSampling with custom sampling points
223    ///
224    /// SVD is computed lazily on first call to `fit` or `fit_nd`.
225    ///
226    /// # Arguments
227    /// * `basis` - Any basis implementing the `Basis` trait
228    /// * `sampling_points` - Custom sampling points in τ ∈ [-β, β]
229    ///
230    /// # Returns
231    /// A new TauSampling object
232    ///
233    /// The points are kept in the given order, and duplicates are accepted;
234    /// they only raise the condition number.
235    ///
236    /// # Errors
237    ///
238    /// * [`Error::EmptyInput`] if `sampling_points` is empty
239    /// * [`Error::OutOfDomain`] if a point is outside [-β, β] or NaN (from
240    ///   [`Basis::evaluate_tau`](crate::basis_trait::Basis::evaluate_tau))
241    pub fn with_sampling_points(
242        basis: &impl crate::basis_trait::Basis<S>,
243        sampling_points: Vec<f64>,
244    ) -> Result<Self, Error>
245    where
246        S: 'static,
247    {
248        // With no points the sampling matrix would have no rows, and the
249        // fitter's transposes would go through the zero-extent paths of
250        // mdarray 0.7.2 (https://github.com/fre-hu/mdarray/issues/21).
251        if sampling_points.is_empty() {
252            return Err(Error::EmptyInput {
253                name: "sampling_points",
254            });
255        }
256
257        // Compute sampling matrix: A[i, l] = u_l(τ_i); evaluate_tau checks
258        // that every τ is in [-β, β].
259        let matrix = basis.evaluate_tau(&sampling_points)?;
260        let fitter = crate::fitters::RealMatrixFitter::new(matrix);
261
262        Ok(Self {
263            sampling_points,
264            fitter,
265            _phantom: std::marker::PhantomData,
266        })
267    }
268
269    /// Create a new TauSampling with custom sampling points and pre-computed matrix
270    ///
271    /// This constructor is useful when the sampling matrix is already computed
272    /// (e.g., from external sources or for testing).
273    ///
274    /// # Arguments
275    /// * `sampling_points` - Imaginary times τ that label the rows of
276    ///   `matrix`, in any order. There is no β to check them against, so
277    ///   any finite value is accepted and kept as given.
278    /// * `matrix` - Pre-computed sampling matrix (n_points × basis_size); row i
279    ///   belongs to `sampling_points[i]`
280    ///
281    /// Duplicate points are accepted; they only raise the condition number.
282    ///
283    /// # Errors
284    ///
285    /// * [`Error::EmptyInput`] if `sampling_points` is empty, or `matrix`
286    ///   has no columns
287    /// * [`Error::ShapeMismatch`] of the input if `matrix` does not have one
288    ///   row per point
289    /// * [`Error::NonFiniteInput`] for the first NaN or infinite point, then
290    ///   for the first NaN or infinite entry of `matrix`
291    pub fn from_matrix(sampling_points: Vec<f64>, matrix: DTensor<f64, 2>) -> Result<Self, Error> {
292        check_sampling_matrix_shape(sampling_points.len(), *matrix.shape())?;
293        if let Some((i, &tau)) = sampling_points
294            .iter()
295            .enumerate()
296            .find(|(_, tau)| !tau.is_finite())
297        {
298            return Err(Error::NonFiniteInput {
299                name: "sampling_points",
300                index: vec![i],
301                value: tau,
302            });
303        }
304        check_finite_matrix(&matrix, |x: f64| (!x.is_finite()).then_some(x))?;
305
306        let fitter = crate::fitters::RealMatrixFitter::new(matrix);
307
308        Ok(Self {
309            sampling_points,
310            fitter,
311            _phantom: std::marker::PhantomData,
312        })
313    }
314
315    /// Get the sampling points
316    pub fn sampling_points(&self) -> &[f64] {
317        &self.sampling_points
318    }
319
320    /// Get the number of sampling points
321    pub fn n_sampling_points(&self) -> usize {
322        self.fitter.n_points()
323    }
324
325    /// Get the basis size
326    pub fn basis_size(&self) -> usize {
327        self.fitter.basis_size()
328    }
329
330    /// Get the sampling matrix
331    pub fn matrix(&self) -> &DTensor<f64, 2> {
332        &self.fitter.matrix
333    }
334
335    /// Condition number of the sampling matrix, which fitting solves with
336    ///
337    /// Returns `σ_max / σ_min`, the ratio of the largest to the smallest of the
338    /// `min(n_sampling_points, basis_size)` singular values of the real
339    /// `n_sampling_points × basis_size` matrix [`Self::matrix`]. It bounds how
340    /// much [`Self::fit`] can amplify relative errors in the values.
341    ///
342    /// Returns `f64::INFINITY` if the smallest singular value is below `1e-15`
343    /// (numerically singular matrix). The singular value decomposition is the
344    /// one fitting uses: it is computed by the first call to this method or to
345    /// a fit, then cached.
346    ///
347    /// # Errors
348    ///
349    /// [`Error::DecompositionFailed`] if the singular value decomposition
350    /// fails, which a matrix of finite entries does not cause in practice
351    /// (the constructors reject non-finite entries)
352    pub fn condition_number(&self) -> Result<f64, Error> {
353        self.fitter.condition_number()
354    }
355
356    // ========================================================================
357    // 1D functions (real and complex)
358    // ========================================================================
359
360    /// Evaluate basis coefficients at sampling points
361    ///
362    /// Computes g(τ_i) = Σ_l a_l * u_l(τ_i) for all sampling points
363    ///
364    /// # Arguments
365    /// * `coeffs` - Basis coefficients (length = basis_size)
366    ///
367    /// # Returns
368    /// Values at sampling points (length = n_sampling_points)
369    ///
370    /// # Errors
371    ///
372    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have length
373    ///   `basis_size`
374    pub fn evaluate(&self, coeffs: &[f64]) -> Result<Vec<f64>, Error> {
375        self.fitter.evaluate(None, coeffs)
376    }
377
378    /// Evaluate basis coefficients at sampling points, writing to output slice
379    ///
380    /// # Errors
381    ///
382    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have length
383    ///   `basis_size`
384    /// * [`Error::ShapeMismatch`] of the output if `out` does not have length
385    ///   `n_sampling_points`
386    ///
387    /// Nothing is written to `out` on an error.
388    pub fn evaluate_to(&self, coeffs: &[f64], out: &mut [f64]) -> Result<(), Error> {
389        self.fitter.evaluate_to(None, coeffs, out)
390    }
391
392    /// Fit values at sampling points to basis coefficients
393    ///
394    /// # Errors
395    ///
396    /// * [`Error::ShapeMismatch`] of the input if `values` does not have length
397    ///   `n_sampling_points`
398    /// * [`Error::DecompositionFailed`] if the singular value decomposition
399    ///   fails
400    pub fn fit(&self, values: &[f64]) -> Result<Vec<f64>, Error> {
401        self.fitter.fit(None, values)
402    }
403
404    /// Fit values at sampling points to basis coefficients, writing to output slice
405    ///
406    /// # Errors
407    ///
408    /// * [`Error::ShapeMismatch`] of the input if `values` does not have length
409    ///   `n_sampling_points`
410    /// * [`Error::ShapeMismatch`] of the output if `out` does not have length
411    ///   `basis_size`
412    /// * [`Error::DecompositionFailed`] if the singular value decomposition
413    ///   fails
414    ///
415    /// Nothing is written to `out` on an error.
416    pub fn fit_to(&self, values: &[f64], out: &mut [f64]) -> Result<(), Error> {
417        self.fitter.fit_to(None, values, out)
418    }
419
420    /// Evaluate complex basis coefficients at sampling points
421    ///
422    /// # Errors
423    ///
424    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have length
425    ///   `basis_size`
426    pub fn evaluate_zz(&self, coeffs: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, Error> {
427        self.fitter.evaluate_zz(None, coeffs)
428    }
429
430    /// Evaluate complex basis coefficients, writing to output slice
431    ///
432    /// # Errors
433    ///
434    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have length
435    ///   `basis_size`
436    /// * [`Error::ShapeMismatch`] of the output if `out` does not have length
437    ///   `n_sampling_points`
438    ///
439    /// Nothing is written to `out` on an error.
440    pub fn evaluate_zz_to(
441        &self,
442        coeffs: &[Complex<f64>],
443        out: &mut [Complex<f64>],
444    ) -> Result<(), Error> {
445        self.fitter.evaluate_zz_to(None, coeffs, out)
446    }
447
448    /// Fit complex values at sampling points to basis coefficients
449    ///
450    /// # Errors
451    ///
452    /// * [`Error::ShapeMismatch`] of the input if `values` does not have length
453    ///   `n_sampling_points`
454    /// * [`Error::DecompositionFailed`] if the singular value decomposition
455    ///   fails
456    pub fn fit_zz(&self, values: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, Error> {
457        self.fitter.fit_zz(None, values)
458    }
459
460    /// Fit complex values, writing to output slice
461    ///
462    /// # Errors
463    ///
464    /// * [`Error::ShapeMismatch`] of the input if `values` does not have length
465    ///   `n_sampling_points`
466    /// * [`Error::ShapeMismatch`] of the output if `out` does not have length
467    ///   `basis_size`
468    /// * [`Error::DecompositionFailed`] if the singular value decomposition
469    ///   fails
470    ///
471    /// Nothing is written to `out` on an error.
472    pub fn fit_zz_to(
473        &self,
474        values: &[Complex<f64>],
475        out: &mut [Complex<f64>],
476    ) -> Result<(), Error> {
477        self.fitter.fit_zz_to(None, values, out)
478    }
479
480    // ========================================================================
481    // N-D functions (real)
482    // ========================================================================
483
484    /// Evaluate N-D real coefficients at sampling points
485    ///
486    /// # Arguments
487    /// * `coeffs` - N-dimensional array with `coeffs.shape().dim(dim) == basis_size`
488    /// * `dim` - Dimension along which to evaluate (0-indexed)
489    ///
490    /// # Returns
491    /// N-dimensional array with `result.shape().dim(dim) == n_sampling_points`
492    ///
493    /// # Errors
494    ///
495    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
496    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
497    ///   `basis_size` along `dim`
498    pub fn evaluate_nd(
499        &self,
500        backend: Option<&GemmBackendHandle>,
501        coeffs: &Slice<f64, DynRank>,
502        dim: usize,
503    ) -> Result<Tensor<f64, DynRank>, Error> {
504        check_input_shape(coeffs.shape().dims(), dim, self.basis_size())?;
505        let out_shape = build_output_shape(coeffs.shape(), dim, self.n_sampling_points());
506        let mut out = Tensor::<f64, DynRank>::zeros(&out_shape[..]);
507        self.evaluate_nd_to(backend, coeffs, dim, &mut out.expr_mut())?;
508        Ok(out)
509    }
510
511    /// Evaluate N-D real coefficients, writing to a mutable view
512    ///
513    /// `out` must have the shape of `coeffs` with `n_sampling_points` along
514    /// `dim`.
515    ///
516    /// # Errors
517    ///
518    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
519    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
520    ///   `basis_size` along `dim`, and of the output if `out` does not have
521    ///   the shape of `coeffs` with `n_sampling_points` along `dim`
522    ///
523    /// Nothing is written to `out` then.
524    pub fn evaluate_nd_to(
525        &self,
526        backend: Option<&GemmBackendHandle>,
527        coeffs: &Slice<f64, DynRank>,
528        dim: usize,
529        out: &mut ViewMut<'_, f64, DynRank>,
530    ) -> Result<(), Error> {
531        InplaceFitter::evaluate_nd_dd_to(self, backend, coeffs, dim, out)
532    }
533
534    /// Fit N-D real values at sampling points to basis coefficients
535    ///
536    /// # Arguments
537    /// * `values` - N-dimensional array with `values.shape().dim(dim) == n_sampling_points`
538    /// * `dim` - Dimension along which to fit (0-indexed)
539    ///
540    /// # Returns
541    /// N-dimensional array with `result.shape().dim(dim) == basis_size`
542    ///
543    /// # Errors
544    ///
545    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
546    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
547    ///   `n_sampling_points` along `dim`
548    /// * [`Error::DecompositionFailed`] if the singular value decomposition
549    ///   fails
550    pub fn fit_nd(
551        &self,
552        backend: Option<&GemmBackendHandle>,
553        values: &Slice<f64, DynRank>,
554        dim: usize,
555    ) -> Result<Tensor<f64, DynRank>, Error> {
556        check_input_shape(values.shape().dims(), dim, self.n_sampling_points())?;
557        let out_shape = build_output_shape(values.shape(), dim, self.basis_size());
558        let mut out = Tensor::<f64, DynRank>::zeros(&out_shape[..]);
559        self.fit_nd_to(backend, values, dim, &mut out.expr_mut())?;
560        Ok(out)
561    }
562
563    /// Fit N-D real values, writing to a mutable view
564    ///
565    /// `out` must have the shape of `values` with `basis_size` along `dim`.
566    ///
567    /// # Errors
568    ///
569    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
570    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
571    ///   `n_sampling_points` along `dim`, and of the output if `out` does not have
572    ///   the shape of `values` with `basis_size` along `dim`
573    /// * [`Error::DecompositionFailed`] if the singular value decomposition
574    ///   fails
575    ///
576    /// Nothing is written to `out` then.
577    pub fn fit_nd_to(
578        &self,
579        backend: Option<&GemmBackendHandle>,
580        values: &Slice<f64, DynRank>,
581        dim: usize,
582        out: &mut ViewMut<'_, f64, DynRank>,
583    ) -> Result<(), Error> {
584        InplaceFitter::fit_nd_dd_to(self, backend, values, dim, out)
585    }
586
587    // ========================================================================
588    // N-D functions (complex)
589    // ========================================================================
590
591    /// Evaluate N-D complex coefficients at sampling points
592    ///
593    /// # Arguments
594    /// * `coeffs` - N-dimensional complex array with `coeffs.shape().dim(dim) == basis_size`
595    /// * `dim` - Dimension along which to evaluate (0-indexed)
596    ///
597    /// # Returns
598    /// N-dimensional complex array with `result.shape().dim(dim) == n_sampling_points`
599    ///
600    /// # Errors
601    ///
602    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
603    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
604    ///   `basis_size` along `dim`
605    pub fn evaluate_nd_zz(
606        &self,
607        backend: Option<&GemmBackendHandle>,
608        coeffs: &Slice<Complex<f64>, DynRank>,
609        dim: usize,
610    ) -> Result<Tensor<Complex<f64>, DynRank>, Error> {
611        check_input_shape(coeffs.shape().dims(), dim, self.basis_size())?;
612        let out_shape = build_output_shape(coeffs.shape(), dim, self.n_sampling_points());
613        let mut out = Tensor::<Complex<f64>, DynRank>::zeros(&out_shape[..]);
614        self.evaluate_nd_zz_to(backend, coeffs, dim, &mut out.expr_mut())?;
615        Ok(out)
616    }
617
618    /// Evaluate N-D complex coefficients, writing to a mutable view
619    ///
620    /// `out` must have the shape of `coeffs` with `n_sampling_points` along
621    /// `dim`.
622    ///
623    /// # Errors
624    ///
625    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
626    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
627    ///   `basis_size` along `dim`, and of the output if `out` does not have
628    ///   the shape of `coeffs` with `n_sampling_points` along `dim`
629    ///
630    /// Nothing is written to `out` then.
631    pub fn evaluate_nd_zz_to(
632        &self,
633        backend: Option<&GemmBackendHandle>,
634        coeffs: &Slice<Complex<f64>, DynRank>,
635        dim: usize,
636        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
637    ) -> Result<(), Error> {
638        InplaceFitter::evaluate_nd_zz_to(self, backend, coeffs, dim, out)
639    }
640
641    /// Fit N-D complex values at sampling points to basis coefficients
642    ///
643    /// # Arguments
644    /// * `values` - N-dimensional complex array with `values.shape().dim(dim) == n_sampling_points`
645    /// * `dim` - Dimension along which to fit (0-indexed)
646    ///
647    /// # Returns
648    /// N-dimensional complex array with `result.shape().dim(dim) == basis_size`
649    ///
650    /// # Errors
651    ///
652    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
653    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
654    ///   `n_sampling_points` along `dim`
655    /// * [`Error::DecompositionFailed`] if the singular value decomposition
656    ///   fails
657    pub fn fit_nd_zz(
658        &self,
659        backend: Option<&GemmBackendHandle>,
660        values: &Slice<Complex<f64>, DynRank>,
661        dim: usize,
662    ) -> Result<Tensor<Complex<f64>, DynRank>, Error> {
663        check_input_shape(values.shape().dims(), dim, self.n_sampling_points())?;
664        let out_shape = build_output_shape(values.shape(), dim, self.basis_size());
665        let mut out = Tensor::<Complex<f64>, DynRank>::zeros(&out_shape[..]);
666        self.fit_nd_zz_to(backend, values, dim, &mut out.expr_mut())?;
667        Ok(out)
668    }
669
670    /// Fit N-D complex values, writing to a mutable view
671    ///
672    /// `out` must have the shape of `values` with `basis_size` along `dim`.
673    ///
674    /// # Errors
675    ///
676    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
677    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
678    ///   `n_sampling_points` along `dim`, and of the output if `out` does not have
679    ///   the shape of `values` with `basis_size` along `dim`
680    /// * [`Error::DecompositionFailed`] if the singular value decomposition
681    ///   fails
682    ///
683    /// Nothing is written to `out` then.
684    pub fn fit_nd_zz_to(
685        &self,
686        backend: Option<&GemmBackendHandle>,
687        values: &Slice<Complex<f64>, DynRank>,
688        dim: usize,
689        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
690    ) -> Result<(), Error> {
691        InplaceFitter::fit_nd_zz_to(self, backend, values, dim, out)
692    }
693}
694
695/// InplaceFitter implementation for TauSampling
696///
697/// Delegates to RealMatrixFitter which supports dd and zz operations.
698impl<S: StatisticsType> InplaceFitter for TauSampling<S> {
699    fn n_points(&self) -> usize {
700        self.n_sampling_points()
701    }
702
703    fn basis_size(&self) -> usize {
704        self.basis_size()
705    }
706
707    fn evaluate_nd_dd_to(
708        &self,
709        backend: Option<&GemmBackendHandle>,
710        coeffs: &Slice<f64, DynRank>,
711        dim: usize,
712        out: &mut ViewMut<'_, f64, DynRank>,
713    ) -> Result<(), Error> {
714        self.fitter.evaluate_nd_dd_to(backend, coeffs, dim, out)
715    }
716
717    fn evaluate_nd_zz_to(
718        &self,
719        backend: Option<&GemmBackendHandle>,
720        coeffs: &Slice<Complex<f64>, DynRank>,
721        dim: usize,
722        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
723    ) -> Result<(), Error> {
724        self.fitter.evaluate_nd_zz_to(backend, coeffs, dim, out)
725    }
726
727    fn fit_nd_dd_to(
728        &self,
729        backend: Option<&GemmBackendHandle>,
730        values: &Slice<f64, DynRank>,
731        dim: usize,
732        out: &mut ViewMut<'_, f64, DynRank>,
733    ) -> Result<(), Error> {
734        self.fitter.fit_nd_dd_to(backend, values, dim, out)
735    }
736
737    fn fit_nd_zz_to(
738        &self,
739        backend: Option<&GemmBackendHandle>,
740        values: &Slice<Complex<f64>, DynRank>,
741        dim: usize,
742        out: &mut ViewMut<'_, Complex<f64>, DynRank>,
743    ) -> Result<(), Error> {
744        self.fitter.fit_nd_zz_to(backend, values, dim, out)
745    }
746}
747
748#[cfg(test)]
749#[path = "tau_sampling_tests.rs"]
750mod tests;