Skip to main content

sparse_ir_core/
matsubara_sampling.rs

1//! Sparse sampling in Matsubara frequencies
2//!
3//! This module provides Matsubara frequency sampling for transforming between
4//! IR basis coefficients and values at sparse Matsubara frequencies.
5
6use crate::Matrix;
7use crate::error::{Error, Result};
8use crate::fitters::{ComplexMatrixFitter, ComplexToRealFitter, InplaceFitter};
9use crate::freq::MatsubaraFreq;
10use crate::gemm::GemmBackendHandle;
11use crate::sampling::{check_finite_matrix, check_sampling_matrix_shape, mat_from_matrix};
12use crate::traits::StatisticsType;
13use num_complex::Complex;
14use std::marker::PhantomData;
15use tenferro_tensor::{TypedTensor, TypedTensorView, TypedTensorViewMut};
16
17type C64 = Complex<f64>;
18
19mod sealed {
20    pub trait Sealed {}
21    impl Sealed for f64 {}
22    impl Sealed for num_complex::Complex<f64> {}
23}
24
25/// Coefficient types that Matsubara sampling can evaluate (`f64` or
26/// `Complex<f64>`).
27///
28/// This provides compile-time dispatch between the real-coefficient and
29/// complex-coefficient kernels.
30pub trait MatsubaraCoeffs: tenferro_tensor::TensorScalar + Copy + sealed::Sealed {
31    /// Evaluate coefficients using the given sampler
32    ///
33    /// # Errors
34    ///
35    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
36    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
37    ///   `basis_size` along `dim`
38    fn evaluate_nd_with<S: StatisticsType>(
39        sampler: &MatsubaraSampling<S>,
40        backend: Option<&GemmBackendHandle>,
41        coeffs: &TypedTensor<Self>,
42        dim: usize,
43    ) -> Result<TypedTensor<C64>>;
44
45    /// Evaluate along axis `dim` into an output view.
46    fn evaluate_nd_to_with<S: StatisticsType>(
47        sampler: &MatsubaraSampling<S>,
48        backend: Option<&GemmBackendHandle>,
49        coeffs: &TypedTensorView<'_, Self>,
50        dim: usize,
51        out: &mut TypedTensorViewMut<'_, C64>,
52    ) -> Result<()>;
53}
54
55impl MatsubaraCoeffs for f64 {
56    fn evaluate_nd_with<S: StatisticsType>(
57        sampler: &MatsubaraSampling<S>,
58        backend: Option<&GemmBackendHandle>,
59        coeffs: &TypedTensor<Self>,
60        dim: usize,
61    ) -> Result<TypedTensor<C64>> {
62        sampler.fitter.evaluate_nd_dz(backend, coeffs, dim)
63    }
64
65    fn evaluate_nd_to_with<S: StatisticsType>(
66        sampler: &MatsubaraSampling<S>,
67        backend: Option<&GemmBackendHandle>,
68        coeffs: &TypedTensorView<'_, Self>,
69        dim: usize,
70        out: &mut TypedTensorViewMut<'_, C64>,
71    ) -> Result<()> {
72        sampler.fitter.evaluate_nd_dz_to(backend, coeffs, dim, out)
73    }
74}
75
76impl MatsubaraCoeffs for C64 {
77    fn evaluate_nd_with<S: StatisticsType>(
78        sampler: &MatsubaraSampling<S>,
79        backend: Option<&GemmBackendHandle>,
80        coeffs: &TypedTensor<Self>,
81        dim: usize,
82    ) -> Result<TypedTensor<C64>> {
83        sampler.fitter.evaluate_nd_zz(backend, coeffs, dim)
84    }
85
86    fn evaluate_nd_to_with<S: StatisticsType>(
87        sampler: &MatsubaraSampling<S>,
88        backend: Option<&GemmBackendHandle>,
89        coeffs: &TypedTensorView<'_, Self>,
90        dim: usize,
91        out: &mut TypedTensorViewMut<'_, C64>,
92    ) -> Result<()> {
93        sampler.fitter.evaluate_nd_zz_to(backend, coeffs, dim, out)
94    }
95}
96
97/// `Ok` if no point is negative, as positive-only samplings require (#247)
98///
99/// # Errors
100///
101/// [`Error::InvalidMatsubaraIndex`] for the first negative point
102fn check_non_negative<S: StatisticsType>(points: &[MatsubaraFreq<S>]) -> Result<(), Error> {
103    match points.iter().find(|f| f.n() < 0) {
104        Some(freq) => Err(Error::InvalidMatsubaraIndex {
105            n: freq.n(),
106            statistics: S::STATISTICS,
107        }),
108        None => Ok(()),
109    }
110}
111
112/// Some part of `z` that is not finite: the real part if it is not, else
113/// the imaginary part
114fn non_finite_part(z: Complex<f64>) -> Option<f64> {
115    if !z.re.is_finite() {
116        Some(z.re)
117    } else if !z.im.is_finite() {
118        Some(z.im)
119    } else {
120        None
121    }
122}
123
124/// Matsubara sampling for full frequency range (positive and negative)
125///
126/// General complex problem without symmetry assumptions.
127/// Supports both real and complex coefficients.
128pub struct MatsubaraSampling<S: StatisticsType> {
129    sampling_points: Vec<MatsubaraFreq<S>>,
130    fitter: ComplexMatrixFitter,
131    _phantom: PhantomData<S>,
132}
133
134impl<S: StatisticsType> MatsubaraSampling<S> {
135    /// Create Matsubara sampling with default sampling points
136    ///
137    /// Uses the default sampling points of the basis (symmetric: positive and
138    /// negative frequencies).
139    ///
140    /// # Errors
141    ///
142    /// The errors of [`Basis::default_matsubara_sampling_points`](crate::basis_trait::Basis::default_matsubara_sampling_points)
143    /// (NotSupported for a DLR)
144    pub fn new(basis: &impl crate::basis_trait::Basis<S>) -> Result<Self>
145    where
146        S: 'static,
147    {
148        let sampling_points = basis.default_matsubara_sampling_points(false)?;
149        Self::with_sampling_points(basis, sampling_points)
150    }
151
152    /// Create Matsubara sampling with custom sampling points
153    ///
154    /// The points may be in any order, and are kept in the given order:
155    /// [`Self::sampling_points`] returns them unchanged, and index i along the
156    /// sampling-point axis of `evaluate` and `fit` refers to
157    /// `sampling_points[i]`.
158    ///
159    /// Duplicate points are accepted; they only raise the condition number.
160    ///
161    /// # Errors
162    ///
163    /// * [`Error::EmptyInput`] if `sampling_points` is empty
164    /// * The errors of [`Basis::evaluate_matsubara`](crate::basis_trait::Basis::evaluate_matsubara)
165    pub fn with_sampling_points(
166        basis: &impl crate::basis_trait::Basis<S>,
167        sampling_points: Vec<MatsubaraFreq<S>>,
168    ) -> Result<Self>
169    where
170        S: 'static,
171    {
172        if sampling_points.is_empty() {
173            return Err(Error::EmptyInput {
174                name: "sampling_points",
175            });
176        }
177        let matrix = mat_from_matrix(&basis.evaluate_matsubara(&sampling_points)?)?;
178        Ok(Self {
179            sampling_points,
180            fitter: ComplexMatrixFitter::new(matrix),
181            _phantom: PhantomData,
182        })
183    }
184
185    /// Create Matsubara sampling with custom sampling points and pre-computed matrix
186    ///
187    /// This constructor is useful when the sampling matrix is already computed
188    /// (e.g., from external sources or for testing).
189    ///
190    /// # Arguments
191    /// * `sampling_points` - Matsubara frequency sampling points, in any order
192    /// * `matrix` - Pre-computed sampling matrix (n_points × basis_size); row i
193    ///   belongs to `sampling_points[i]`
194    ///
195    /// The points are kept in the given order: [`Self::sampling_points`]
196    /// returns them unchanged, and index i along the sampling-point axis of
197    /// `evaluate` and `fit` refers to `sampling_points[i]`.
198    ///
199    /// Duplicate points are accepted; they only raise the condition number.
200    ///
201    /// # Errors
202    ///
203    /// * [`Error::EmptyInput`] if `sampling_points` is empty, or `matrix`
204    ///   has no columns
205    /// * [`Error::ShapeMismatch`] of the input if `matrix` does not have one
206    ///   row per point
207    /// * [`Error::NonFiniteInput`] for the first entry of `matrix` with a NaN
208    ///   or infinite part
209    pub fn from_matrix(
210        sampling_points: Vec<MatsubaraFreq<S>>,
211        matrix: &Matrix<C64>,
212    ) -> Result<Self> {
213        let matrix = mat_from_matrix(matrix)?;
214        check_sampling_matrix_shape(sampling_points.len(), *matrix.shape())?;
215        check_finite_matrix(&matrix, non_finite_part)?;
216        Ok(Self {
217            sampling_points,
218            fitter: ComplexMatrixFitter::new(matrix),
219            _phantom: PhantomData,
220        })
221    }
222
223    /// Get sampling points
224    pub fn sampling_points(&self) -> &[MatsubaraFreq<S>] {
225        &self.sampling_points
226    }
227
228    /// Number of sampling points
229    pub fn n_sampling_points(&self) -> usize {
230        self.sampling_points.len()
231    }
232
233    /// Basis size
234    pub fn basis_size(&self) -> usize {
235        self.fitter.basis_size()
236    }
237
238    /// Get the sampling matrix
239    pub fn matrix(&self) -> &Matrix<C64> {
240        self.fitter.matrix()
241    }
242
243    /// Condition number of the sampling matrix, which fitting solves with
244    ///
245    /// Returns `σ_max / σ_min`, the ratio of the largest to the smallest of the
246    /// `min(n_sampling_points, basis_size)` singular values of the complex
247    /// `n_sampling_points × basis_size` matrix [`Self::matrix`]. It bounds how
248    /// much [`Self::fit`] can amplify relative errors in the values.
249    ///
250    /// Returns `f64::INFINITY` if the smallest singular value is below `1e-15`
251    /// (numerically singular matrix). The singular value decomposition is the
252    /// one fitting uses: it is computed by the first call to this method or to
253    /// a fit, then cached.
254    ///
255    /// # Errors
256    ///
257    /// [`Error::DecompositionFailed`] if the singular value decomposition
258    /// fails, which a matrix of finite entries does not cause in practice
259    /// (the constructors reject non-finite entries)
260    pub fn condition_number(&self) -> Result<f64> {
261        self.fitter.condition_number()
262    }
263
264    /// Evaluate complex basis coefficients at sampling points
265    ///
266    /// # Arguments
267    /// * `coeffs` - Complex basis coefficients (length = basis_size)
268    ///
269    /// # Returns
270    /// Complex values at Matsubara frequencies (length = n_sampling_points)
271    ///
272    /// # Errors
273    ///
274    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have length
275    ///   `basis_size`
276    pub fn evaluate(&self, coeffs: &[C64]) -> Result<Vec<C64>> {
277        self.fitter.evaluate(None, coeffs)
278    }
279
280    /// Evaluate real basis coefficients at sampling points
281    pub fn evaluate_real(&self, coeffs: &[f64]) -> Result<Vec<C64>> {
282        self.fitter.evaluate_real(None, coeffs)
283    }
284
285    /// Fit complex basis coefficients from values at sampling points
286    ///
287    /// # Arguments
288    /// * `values` - Complex values at Matsubara frequencies (length = n_sampling_points)
289    ///
290    /// # Returns
291    /// Fitted complex basis coefficients (length = basis_size)
292    ///
293    /// # Errors
294    ///
295    /// * [`Error::ShapeMismatch`] of the input if `values` does not have length
296    ///   `n_sampling_points`
297    /// * [`Error::DecompositionFailed`] if the singular value decomposition
298    ///   fails
299    pub fn fit(&self, values: &[C64]) -> Result<Vec<C64>> {
300        self.fitter.fit(None, values)
301    }
302
303    /// Fit real basis coefficients: the least-squares solution over real
304    /// coefficients (see [`Self::fit_nd_real`])
305    pub fn fit_real(&self, values: &[C64]) -> Result<Vec<f64>> {
306        self.fitter.fit_real(None, values)
307    }
308
309    /// Evaluate N-dimensional coefficients at Matsubara sampling points
310    ///
311    /// Supports both real (`f64`) and complex (`Complex<f64>`) coefficients and
312    /// always returns complex values at the Matsubara frequencies. The
313    /// implementation is selected at compile time through the `MatsubaraCoeffs`
314    /// trait.
315    ///
316    /// # Type Parameter
317    /// * `T` - Must implement `MatsubaraCoeffs` (currently `f64` or `Complex<f64>`)
318    ///
319    /// # Arguments
320    /// * `backend` - Optional GEMM backend handle (`None` uses the global dispatcher)
321    /// * `coeffs` - N-dimensional tensor of basis coefficients
322    /// * `dim` - Dimension along which to evaluate (must have size = basis_size)
323    ///
324    /// # Returns
325    /// N-dimensional tensor of complex values at Matsubara frequencies, with
326    /// dimension `dim` of size n_sampling_points
327    ///
328    /// # Errors
329    ///
330    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
331    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
332    ///   `basis_size` along `dim`
333    ///
334    /// # Example
335    /// ```
336    /// use num_complex::Complex;
337    /// use sparse_ir::{FermionicBasis, LogisticKernel, MatsubaraSampling, TypedTensor};
338    ///
339    /// let beta = 10.0;
340    /// let wmax = 1.0;
341    /// let basis = FermionicBasis::new(LogisticKernel::new(beta * wmax).unwrap(), beta, Some(1e-6), None).unwrap();
342    /// let sampling = MatsubaraSampling::new(&basis).unwrap();
343    /// let (size, n_points) = (sampling.basis_size(), sampling.n_sampling_points());
344    ///
345    /// // Real coefficients: two sets stacked along axis 1 (column-major), evaluated along axis 0
346    /// let real_data: Vec<f64> = (0..2 * size)
347    ///     .map(|k| 1.0 / (1.0 + (k % size + k / size) as f64))
348    ///     .collect();
349    /// let coeffs_real = TypedTensor::from_vec_col_major(vec![size, 2], real_data.clone()).unwrap();
350    /// let values = sampling.evaluate_nd::<f64>(None, &coeffs_real, 0).unwrap();
351    /// assert_eq!(values.shape(), &[n_points, 2]);
352    ///
353    /// // Complex coefficients
354    /// let complex_data: Vec<Complex<f64>> =
355    ///     real_data.iter().map(|&x| Complex::new(x, -0.5 * x)).collect();
356    /// let coeffs_complex = TypedTensor::from_vec_col_major(vec![size, 2], complex_data.clone()).unwrap();
357    /// let values_z = sampling.evaluate_nd::<Complex<f64>>(None, &coeffs_complex, 0).unwrap();
358    ///
359    /// // Each column matches the 1-D `evaluate` of the corresponding coefficient set
360    /// let (values, values_z) = (values.host_data().unwrap(), values_z.host_data().unwrap());
361    /// for j in 0..2 {
362    ///     let real: Vec<Complex<f64>> = real_data[j * size..(j + 1) * size].iter().map(|&x| x.into()).collect();
363    ///     let complex = &complex_data[j * size..(j + 1) * size];
364    ///     let (expected, expected_z) = (sampling.evaluate(&real).unwrap(), sampling.evaluate(complex).unwrap());
365    ///     for i in 0..n_points {
366    ///         assert!((values[i + n_points * j] - expected[i]).norm() < 1e-12);
367    ///         assert!((values_z[i + n_points * j] - expected_z[i]).norm() < 1e-12);
368    ///     }
369    /// }
370    /// ```
371    pub fn evaluate_nd<T: MatsubaraCoeffs>(
372        &self,
373        backend: Option<&GemmBackendHandle>,
374        coeffs: &TypedTensor<T>,
375        dim: usize,
376    ) -> Result<TypedTensor<C64>> {
377        T::evaluate_nd_with(self, backend, coeffs, dim)
378    }
379
380    /// Evaluate real basis coefficients at Matsubara sampling points (N-dimensional)
381    ///
382    /// This method takes real coefficients and produces complex values, useful when
383    /// working with symmetry-exploiting representations or real-valued IR coefficients.
384    ///
385    /// # Arguments
386    /// * `backend` - Optional GEMM backend handle (None uses default)
387    /// * `coeffs` - N-dimensional tensor of real basis coefficients
388    /// * `dim` - Dimension along which to evaluate (must have size = basis_size)
389    ///
390    /// # Returns
391    /// N-dimensional tensor of complex values at Matsubara frequencies
392    ///
393    /// # Errors
394    ///
395    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
396    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
397    ///   `basis_size` along `dim`
398    pub fn evaluate_nd_real(
399        &self,
400        backend: Option<&GemmBackendHandle>,
401        coeffs: &TypedTensor<f64>,
402        dim: usize,
403    ) -> Result<TypedTensor<C64>> {
404        self.fitter.evaluate_nd_dz(backend, coeffs, dim)
405    }
406
407    /// Fit N-dimensional array of complex values to complex basis coefficients
408    ///
409    /// # Arguments
410    /// * `backend` - Optional GEMM backend handle (None uses default)
411    /// * `values` - N-dimensional tensor of complex values at Matsubara frequencies
412    /// * `dim` - Dimension along which to fit (must have size = n_sampling_points)
413    ///
414    /// # Returns
415    /// N-dimensional tensor of complex basis coefficients
416    ///
417    /// # Errors
418    ///
419    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
420    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
421    ///   `n_sampling_points` along `dim`
422    /// * [`Error::DecompositionFailed`] if the singular value decomposition
423    ///   fails
424    pub fn fit_nd(
425        &self,
426        backend: Option<&GemmBackendHandle>,
427        values: &TypedTensor<C64>,
428        dim: usize,
429    ) -> Result<TypedTensor<C64>> {
430        self.fitter.fit_nd_zz(backend, values, dim)
431    }
432
433    /// Fit N-dimensional array of complex values to real basis coefficients
434    ///
435    /// This method fits complex Matsubara values to real IR coefficients.
436    /// The least-squares solution over real coefficients,
437    /// `[Re A; Im A]⁺ [Re y; Im y]`. For points symmetric in ±n, such as
438    /// the default ones, this is the real part of the complex solution `A⁺y`
439    /// for any data. For other points it is not, and where `A` lacks full
440    /// column rank (fewer points than functions, say) the real part of `A⁺y`
441    /// need not fit even data that real coefficients reproduce exactly.
442    ///
443    /// # Arguments
444    /// * `backend` - Optional GEMM backend handle (None uses default)
445    /// * `values` - N-dimensional tensor of complex values at Matsubara frequencies
446    /// * `dim` - Dimension along which to fit (must have size = n_sampling_points)
447    ///
448    /// # Returns
449    /// N-dimensional tensor of real basis coefficients
450    ///
451    /// # Errors
452    ///
453    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
454    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
455    ///   `n_sampling_points` along `dim`
456    /// * [`Error::DecompositionFailed`] if the singular value decomposition
457    ///   fails
458    pub fn fit_nd_real(
459        &self,
460        backend: Option<&GemmBackendHandle>,
461        values: &TypedTensor<C64>,
462        dim: usize,
463    ) -> Result<TypedTensor<f64>> {
464        self.fitter.fit_nd_zd(backend, values, dim)
465    }
466
467    /// Evaluate basis coefficients at Matsubara sampling points (N-dimensional) with in-place output
468    ///
469    /// # Type Parameters
470    /// * `T` - Coefficient type (f64 or Complex<f64>)
471    ///
472    /// # Arguments
473    /// * `coeffs` - N-dimensional tensor with `coeffs.shape().dim(dim) == basis_size`
474    /// * `dim` - Dimension along which to evaluate (0-indexed)
475    /// * `out` - Output tensor with `out.shape().dim(dim) == n_sampling_points` (Complex<f64>)
476    ///
477    /// # Errors
478    ///
479    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
480    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
481    ///   `basis_size` along `dim`, and of the output if `out` does not have
482    ///   the shape of `coeffs` with `n_sampling_points` along `dim`
483    ///
484    /// Nothing is written to `out` then.
485    pub fn evaluate_nd_to<T: MatsubaraCoeffs>(
486        &self,
487        backend: Option<&GemmBackendHandle>,
488        coeffs: &TypedTensorView<'_, T>,
489        dim: usize,
490        out: &mut TypedTensorViewMut<'_, C64>,
491    ) -> Result<()> {
492        T::evaluate_nd_to_with(self, backend, coeffs, dim, out)
493    }
494
495    /// Fit N-dimensional complex values to complex coefficients with in-place output
496    ///
497    /// # Arguments
498    /// * `values` - N-dimensional tensor with `values.shape().dim(dim) == n_sampling_points`
499    /// * `dim` - Dimension along which to fit (0-indexed)
500    /// * `out` - Output tensor with `out.shape().dim(dim) == basis_size` (Complex<f64>)
501    ///
502    /// # Errors
503    ///
504    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
505    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
506    ///   `n_sampling_points` along `dim`, and of the output if `out` does not have
507    ///   the shape of `values` with `basis_size` along `dim`
508    /// * [`Error::DecompositionFailed`] if the singular value decomposition
509    ///   fails
510    ///
511    /// Nothing is written to `out` then.
512    pub fn fit_nd_to(
513        &self,
514        backend: Option<&GemmBackendHandle>,
515        values: &TypedTensorView<'_, C64>,
516        dim: usize,
517        out: &mut TypedTensorViewMut<'_, C64>,
518    ) -> Result<()> {
519        self.fitter.fit_nd_zz_to(backend, values, dim, out)
520    }
521}
522
523impl<S: StatisticsType> InplaceFitter for MatsubaraSampling<S> {
524    fn n_points(&self) -> usize {
525        self.n_sampling_points()
526    }
527
528    fn basis_size(&self) -> usize {
529        self.basis_size()
530    }
531
532    fn evaluate_nd_dz_to(
533        &self,
534        backend: Option<&GemmBackendHandle>,
535        coeffs: &TypedTensorView<'_, f64>,
536        dim: usize,
537        out: &mut TypedTensorViewMut<'_, C64>,
538    ) -> Result<()> {
539        self.fitter.evaluate_nd_dz_to(backend, coeffs, dim, out)
540    }
541
542    fn evaluate_nd_zz_to(
543        &self,
544        backend: Option<&GemmBackendHandle>,
545        coeffs: &TypedTensorView<'_, C64>,
546        dim: usize,
547        out: &mut TypedTensorViewMut<'_, C64>,
548    ) -> Result<()> {
549        self.fitter.evaluate_nd_zz_to(backend, coeffs, dim, out)
550    }
551
552    fn fit_nd_zd_to(
553        &self,
554        backend: Option<&GemmBackendHandle>,
555        values: &TypedTensorView<'_, C64>,
556        dim: usize,
557        out: &mut TypedTensorViewMut<'_, f64>,
558    ) -> Result<()> {
559        self.fitter.fit_nd_zd_to(backend, values, dim, out)
560    }
561
562    fn fit_nd_zz_to(
563        &self,
564        backend: Option<&GemmBackendHandle>,
565        values: &TypedTensorView<'_, C64>,
566        dim: usize,
567        out: &mut TypedTensorViewMut<'_, C64>,
568    ) -> Result<()> {
569        self.fitter.fit_nd_zz_to(backend, values, dim, out)
570    }
571}
572
573/// Matsubara sampling for positive frequencies only
574///
575/// Exploits the symmetry `G(-iωn) = conj(G(iωn))` of physical Green's
576/// functions to fit real coefficients from values at non-negative
577/// frequencies. Supports: {0, 1, 2, 3, ...} (no negative frequencies)
578pub struct MatsubaraSamplingPositiveOnly<S: StatisticsType> {
579    sampling_points: Vec<MatsubaraFreq<S>>,
580    fitter: ComplexToRealFitter,
581    _phantom: PhantomData<S>,
582}
583
584impl<S: StatisticsType> MatsubaraSamplingPositiveOnly<S> {
585    /// Create Matsubara sampling with default positive-only sampling points
586    ///
587    /// Uses the default sampling points of the basis (non-negative frequencies only).
588    /// Exploits symmetry to reconstruct real coefficients.
589    ///
590    /// # Errors
591    ///
592    /// The errors of [`Basis::default_matsubara_sampling_points`](crate::basis_trait::Basis::default_matsubara_sampling_points)
593    /// (NotSupported for a DLR)
594    pub fn new(basis: &impl crate::basis_trait::Basis<S>) -> Result<Self>
595    where
596        S: 'static,
597    {
598        let sampling_points = basis.default_matsubara_sampling_points(true)?;
599        Self::with_sampling_points(basis, sampling_points)
600    }
601
602    /// Create Matsubara sampling with custom positive-only sampling points
603    ///
604    /// The points may be in any order, and are kept in the given order:
605    /// [`Self::sampling_points`] returns them unchanged, and index i along the
606    /// sampling-point axis of `evaluate` and `fit` refers to
607    /// `sampling_points[i]`.
608    ///
609    /// Duplicate points are accepted; they only raise the condition number.
610    ///
611    /// # Errors
612    ///
613    /// * [`Error::EmptyInput`] if `sampling_points` is empty
614    /// * [`Error::InvalidMatsubaraIndex`] if a point is negative
615    /// * The errors of [`Basis::evaluate_matsubara`](crate::basis_trait::Basis::evaluate_matsubara)
616    pub fn with_sampling_points(
617        basis: &impl crate::basis_trait::Basis<S>,
618        sampling_points: Vec<MatsubaraFreq<S>>,
619    ) -> Result<Self>
620    where
621        S: 'static,
622    {
623        if sampling_points.is_empty() {
624            return Err(Error::EmptyInput {
625                name: "sampling_points",
626            });
627        }
628        // Positive-only sampling uses non-negative frequencies only (#247).
629        check_non_negative(&sampling_points)?;
630        let matrix = mat_from_matrix(&basis.evaluate_matsubara(&sampling_points)?)?;
631        Ok(Self {
632            sampling_points,
633            fitter: ComplexToRealFitter::new(matrix),
634            _phantom: PhantomData,
635        })
636    }
637
638    /// Create Matsubara sampling (positive-only) with custom sampling points and pre-computed matrix
639    ///
640    /// This constructor is useful when the sampling matrix is already computed.
641    /// Uses symmetry to fit real coefficients from complex values at non-negative frequencies.
642    ///
643    /// # Arguments
644    /// * `sampling_points` - Matsubara frequency sampling points (must be
645    ///   non-negative), in any order
646    /// * `matrix` - Pre-computed sampling matrix (n_points × basis_size); row i
647    ///   belongs to `sampling_points[i]`
648    ///
649    /// The points are kept in the given order: [`Self::sampling_points`]
650    /// returns them unchanged, and index i along the sampling-point axis of
651    /// `evaluate` and `fit` refers to `sampling_points[i]`.
652    ///
653    /// Duplicate points are accepted; they only raise the condition number.
654    ///
655    /// # Errors
656    ///
657    /// * [`Error::EmptyInput`] if `sampling_points` is empty, or `matrix`
658    ///   has no columns
659    /// * [`Error::ShapeMismatch`] of the input if `matrix` does not have one
660    ///   row per point
661    /// * [`Error::InvalidMatsubaraIndex`] for the first negative point
662    /// * [`Error::NonFiniteInput`] for the first entry of `matrix` with a NaN
663    ///   or infinite part
664    pub fn from_matrix(
665        sampling_points: Vec<MatsubaraFreq<S>>,
666        matrix: &Matrix<C64>,
667    ) -> Result<Self> {
668        let matrix = mat_from_matrix(matrix)?;
669        check_sampling_matrix_shape(sampling_points.len(), *matrix.shape())?;
670        check_non_negative(&sampling_points)?;
671        check_finite_matrix(&matrix, non_finite_part)?;
672        Ok(Self {
673            sampling_points,
674            fitter: ComplexToRealFitter::new(matrix),
675            _phantom: PhantomData,
676        })
677    }
678
679    /// Get sampling points
680    pub fn sampling_points(&self) -> &[MatsubaraFreq<S>] {
681        &self.sampling_points
682    }
683
684    /// Number of sampling points
685    pub fn n_sampling_points(&self) -> usize {
686        self.sampling_points.len()
687    }
688
689    /// Basis size
690    pub fn basis_size(&self) -> usize {
691        self.fitter.basis_size()
692    }
693
694    /// Get the original complex sampling matrix
695    pub fn matrix(&self) -> &Matrix<C64> {
696        self.fitter.matrix()
697    }
698
699    /// Condition number of the real least-squares problem that fitting solves
700    ///
701    /// Fitting real coefficients `x` to complex values `g` at non-negative
702    /// frequencies solves `[Re A; Im A] x = [Re g; Im g]`, where `A` is the
703    /// complex `n_sampling_points × basis_size` matrix [`Self::matrix`]. This
704    /// returns `σ_max / σ_min`, the ratio of the largest to the smallest of the
705    /// `min(2 n_sampling_points, basis_size)` singular values of that real
706    /// `2 n_sampling_points × basis_size` matrix; it bounds how much
707    /// [`Self::fit`] can amplify relative errors in the values. It is not the
708    /// condition number of `A`: with `n_sampling_points ≈ basis_size / 2`, `A`
709    /// is wide, and its condition number can understate that amplification by
710    /// orders of magnitude.
711    ///
712    /// Returns `f64::INFINITY` if the smallest singular value is below `1e-15`
713    /// (numerically singular matrix). The singular value decomposition is the
714    /// one fitting uses: it is computed by the first call to this method or to
715    /// a fit, then cached.
716    ///
717    /// # Errors
718    ///
719    /// [`Error::DecompositionFailed`] if the singular value decomposition
720    /// fails, which a matrix of finite entries does not cause in practice
721    /// (the constructors reject non-finite entries)
722    pub fn condition_number(&self) -> Result<f64> {
723        self.fitter.condition_number()
724    }
725
726    /// Evaluate basis coefficients at sampling points
727    ///
728    /// # Errors
729    ///
730    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have length
731    ///   `basis_size`
732    pub fn evaluate(&self, coeffs: &[f64]) -> Result<Vec<C64>> {
733        self.fitter.evaluate(None, coeffs)
734    }
735
736    /// Fit basis coefficients from values at sampling points
737    ///
738    /// # Errors
739    ///
740    /// * [`Error::ShapeMismatch`] of the input if `values` does not have length
741    ///   `n_sampling_points`
742    /// * [`Error::DecompositionFailed`] if the singular value decomposition
743    ///   fails
744    pub fn fit(&self, values: &[C64]) -> Result<Vec<f64>> {
745        self.fitter.fit(None, values)
746    }
747
748    /// Evaluate N-dimensional array of real basis coefficients at sampling points
749    ///
750    /// # Arguments
751    /// * `coeffs` - N-dimensional tensor of real basis coefficients
752    /// * `dim` - Dimension along which to evaluate (must have size = basis_size)
753    ///
754    /// # Returns
755    /// N-dimensional tensor of complex values at Matsubara frequencies
756    ///
757    /// # Errors
758    ///
759    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
760    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
761    ///   `basis_size` along `dim`
762    pub fn evaluate_nd(
763        &self,
764        backend: Option<&GemmBackendHandle>,
765        coeffs: &TypedTensor<f64>,
766        dim: usize,
767    ) -> Result<TypedTensor<C64>> {
768        self.fitter.evaluate_nd_dz(backend, coeffs, dim)
769    }
770
771    /// Fit N-dimensional array of complex values to real basis coefficients
772    ///
773    /// # Arguments
774    /// * `backend` - Optional GEMM backend handle (None uses default)
775    /// * `values` - N-dimensional tensor of complex values at Matsubara frequencies
776    /// * `dim` - Dimension along which to fit (must have size = n_sampling_points)
777    ///
778    /// # Returns
779    /// N-dimensional tensor of real basis coefficients
780    ///
781    /// # Errors
782    ///
783    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
784    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
785    ///   `n_sampling_points` along `dim`
786    /// * [`Error::DecompositionFailed`] if the singular value decomposition
787    ///   fails
788    pub fn fit_nd(
789        &self,
790        backend: Option<&GemmBackendHandle>,
791        values: &TypedTensor<C64>,
792        dim: usize,
793    ) -> Result<TypedTensor<f64>> {
794        self.fitter.fit_nd_zd(backend, values, dim)
795    }
796
797    /// Evaluate real basis coefficients at Matsubara sampling points (N-dimensional) with in-place output
798    ///
799    /// # Arguments
800    /// * `coeffs` - N-dimensional tensor of real coefficients with `coeffs.shape().dim(dim) == basis_size`
801    /// * `dim` - Dimension along which to evaluate (0-indexed)
802    /// * `out` - Output tensor with `out.shape().dim(dim) == n_sampling_points` (Complex<f64>)
803    ///
804    /// # Errors
805    ///
806    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `coeffs`
807    /// * [`Error::ShapeMismatch`] of the input if `coeffs` does not have
808    ///   `basis_size` along `dim`, and of the output if `out` does not have
809    ///   the shape of `coeffs` with `n_sampling_points` along `dim`
810    ///
811    /// Nothing is written to `out` then.
812    pub fn evaluate_nd_to(
813        &self,
814        backend: Option<&GemmBackendHandle>,
815        coeffs: &TypedTensorView<'_, f64>,
816        dim: usize,
817        out: &mut TypedTensorViewMut<'_, C64>,
818    ) -> Result<()> {
819        self.fitter.evaluate_nd_dz_to(backend, coeffs, dim, out)
820    }
821
822    /// Fit N-dimensional complex values to real coefficients with in-place output
823    ///
824    /// # Arguments
825    /// * `values` - N-dimensional tensor with `values.shape().dim(dim) == n_sampling_points`
826    /// * `dim` - Dimension along which to fit (0-indexed)
827    /// * `out` - Output tensor with `out.shape().dim(dim) == basis_size` (f64)
828    ///
829    /// # Errors
830    ///
831    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `values`
832    /// * [`Error::ShapeMismatch`] of the input if `values` does not have
833    ///   `n_sampling_points` along `dim`, and of the output if `out` does not have
834    ///   the shape of `values` with `basis_size` along `dim`
835    /// * [`Error::DecompositionFailed`] if the singular value decomposition
836    ///   fails
837    ///
838    /// Nothing is written to `out` then.
839    pub fn fit_nd_to(
840        &self,
841        backend: Option<&GemmBackendHandle>,
842        values: &TypedTensorView<'_, C64>,
843        dim: usize,
844        out: &mut TypedTensorViewMut<'_, f64>,
845    ) -> Result<()> {
846        self.fitter.fit_nd_zd_to(backend, values, dim, out)
847    }
848}
849
850impl<S: StatisticsType> InplaceFitter for MatsubaraSamplingPositiveOnly<S> {
851    fn n_points(&self) -> usize {
852        self.n_sampling_points()
853    }
854
855    fn basis_size(&self) -> usize {
856        self.basis_size()
857    }
858
859    fn evaluate_nd_dz_to(
860        &self,
861        backend: Option<&GemmBackendHandle>,
862        coeffs: &TypedTensorView<'_, f64>,
863        dim: usize,
864        out: &mut TypedTensorViewMut<'_, C64>,
865    ) -> Result<()> {
866        self.fitter.evaluate_nd_dz_to(backend, coeffs, dim, out)
867    }
868
869    fn evaluate_nd_zz_to(
870        &self,
871        backend: Option<&GemmBackendHandle>,
872        coeffs: &TypedTensorView<'_, C64>,
873        dim: usize,
874        out: &mut TypedTensorViewMut<'_, C64>,
875    ) -> Result<()> {
876        self.fitter.evaluate_nd_zz_to(backend, coeffs, dim, out)
877    }
878
879    fn fit_nd_zd_to(
880        &self,
881        backend: Option<&GemmBackendHandle>,
882        values: &TypedTensorView<'_, C64>,
883        dim: usize,
884        out: &mut TypedTensorViewMut<'_, f64>,
885    ) -> Result<()> {
886        self.fitter.fit_nd_zd_to(backend, values, dim, out)
887    }
888
889    fn fit_nd_zz_to(
890        &self,
891        backend: Option<&GemmBackendHandle>,
892        values: &TypedTensorView<'_, C64>,
893        dim: usize,
894        out: &mut TypedTensorViewMut<'_, C64>,
895    ) -> Result<()> {
896        self.fitter.fit_nd_zz_to(backend, values, dim, out)
897    }
898}