Skip to main content

sparse_ir_basis/
basis.rs

1//! Finite temperature basis for SparseIR
2//!
3//! This module provides the `FiniteTempBasis` type which represents the
4//! intermediate representation (IR) basis for a given temperature.
5
6use std::sync::{Arc, OnceLock};
7
8use crate::error::{
9    Error, require_accuracy, require_nonzero_size, require_positive_finite, require_threshold,
10};
11use crate::kernel::{BasisKernel, KernelProperties, LogisticKernel};
12use crate::poly::{PiecewiseLegendrePoly, PiecewiseLegendrePolyVector};
13use crate::polyfourier::PiecewiseLegendreFTVector;
14use crate::sve::{SVEResult, TworkType, compute_sve};
15use crate::traits::{Bosonic, Fermionic, StatisticsType};
16
17// Re-export Statistics enum for C-API
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Statistics {
20    Fermionic,
21    Bosonic,
22}
23
24/// Finite temperature basis for imaginary time/frequency Green's functions
25///
26/// For a continuation kernel `K` from real frequencies `ω ∈ [ωmin, ωmax]`
27/// (`[-ωmax, ωmax]` for centrosymmetric kernels) to imaginary time
28/// `τ ∈ [0, β]`, this type stores the truncated singular value expansion or
29/// IR basis:
30///
31/// ```text
32/// K(τ, ω) ≈ sum(u[l](τ) * s[l] * v[l](ω) for l in 0..L)
33/// ```
34///
35/// This basis is inferred from a reduced form by appropriate scaling of
36/// the variables.
37///
38/// # Type Parameters
39///
40/// * `K` - Kernel type implementing `KernelProperties + AbstractKernel`
41/// * `S` - Statistics type (`Fermionic` or `Bosonic`)
42#[derive(Clone)]
43pub struct FiniteTempBasis<K, S>
44where
45    K: BasisKernel,
46    S: StatisticsType,
47{
48    /// The kernel used to construct this basis
49    kernel: K,
50
51    /// The SVE result (in scaled variables)
52    sve_result: Arc<SVEResult>,
53
54    /// Accuracy of the basis (relative error)
55    accuracy: f64,
56
57    /// Inverse temperature β
58    beta: f64,
59
60    /// Left singular functions on imaginary time axis τ ∈ [0, β]
61    /// Arc for efficient sharing (large immutable data)
62    u: Arc<PiecewiseLegendrePolyVector>,
63
64    /// Right singular functions on real frequency axis ω ∈ [ωmin, ωmax]
65    /// Arc for efficient sharing (large immutable data)
66    v: Arc<PiecewiseLegendrePolyVector>,
67
68    /// Singular values
69    s: Vec<f64>,
70
71    /// Left singular functions on Matsubara frequency axis (Fourier transform of u)
72    /// Arc for efficient sharing (large immutable data)
73    uhat: Arc<PiecewiseLegendreFTVector<S>>,
74
75    /// Full uhat (before truncation to basis size)
76    /// Arc for efficient sharing (large immutable data, used for Matsubara sampling)
77    uhat_full: Arc<PiecewiseLegendreFTVector<S>>,
78
79    /// Default Matsubara sampling points for `positive_only` = false and
80    /// true, found on first use: each sampling object and C-API query asks
81    /// for them again
82    default_matsubara_points: [OnceLock<Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>>; 2],
83
84    _phantom: std::marker::PhantomData<S>,
85}
86
87/// Check that `sve_result` is an SVE on the domain `[xmin, xmax] × [ymin, ymax]`
88/// of `kernel` (up to 1e-12, as from `spir_sve_result_from_matrix`)
89fn check_kernel_domain<K: KernelProperties>(
90    kernel: &K,
91    sve_result: &SVEResult,
92) -> Result<(), Error> {
93    let domain =
94        |funcs: &PiecewiseLegendrePolyVector| funcs.polys().first().map(|p| (p.xmin(), p.xmax()));
95    let (Some(u), Some(v)) = (domain(sve_result.u()), domain(sve_result.v())) else {
96        return Err(Error::EmptyInput { name: "sve_result" });
97    };
98    let (x, y) = (
99        (kernel.xmin(), kernel.xmax()),
100        (kernel.ymin(), kernel.ymax()),
101    );
102    // The basis maps x ∈ [-1, 1] to τ = β (x + 1) / 2 ∈ [0, β]
103    if x != (-1.0, 1.0) {
104        return Err(Error::InvalidParameter {
105            name: "kernel",
106            value: format!("x domain [{:?}, {:?}]", x.0, x.1),
107            reason: "a basis needs the x domain [-1, 1], mapped to tau in [0, beta]".to_string(),
108        });
109    }
110    let matches = |(lo, hi): (f64, f64), (min, max): (f64, f64)| {
111        (lo - min).abs() <= 1e-12 && (hi - max).abs() <= 1e-12
112    };
113    if matches(u, x) && matches(v, y) {
114        Ok(())
115    } else {
116        Err(Error::InvalidParameter {
117            name: "sve_result",
118            value: format!("an SVE on [{:?}, {:?}] × [{:?}, {:?}]", u.0, u.1, v.0, v.1),
119            reason: format!(
120                "must be an SVE on the kernel's domain [{:?}, {:?}] × [{:?}, {:?}]",
121                x.0, x.1, y.0, y.1
122            ),
123        })
124    }
125}
126
127/// Knots and widths of `poly` with the first and last knot set exactly to
128/// `min` and `max`
129///
130/// `check_kernel_domain` accepts an SVE whose domain differs from the
131/// kernel's by up to 1e-12 (e.g. from `spir_sve_result_from_matrix`). Scaled
132/// to τ and ω, such knots end inside [0, β] and [ωmin, ωmax], where evaluating
133/// at the ends panics. The width of an end segment is recomputed only if its
134/// knot moved, so an SVE with exact ends keeps its knots and widths bit for
135/// bit.
136fn snapped_knots_and_widths(
137    poly: &PiecewiseLegendrePoly,
138    min: f64,
139    max: f64,
140) -> (Vec<f64>, Vec<f64>) {
141    let mut knots = poly.knots().to_vec();
142    let mut widths = poly.delta_x().to_vec();
143    let last = knots.len() - 1;
144    if knots[0] != min {
145        knots[0] = min;
146        widths[0] = knots[1] - knots[0];
147    }
148    if knots[last] != max {
149        knots[last] = max;
150        widths[last - 1] = knots[last] - knots[last - 1];
151    }
152    (knots, widths)
153}
154
155impl<K, S> FiniteTempBasis<K, S>
156where
157    K: BasisKernel,
158    S: StatisticsType,
159{
160    // ========== Getters ==========
161
162    /// Get a reference to the kernel
163    pub fn kernel(&self) -> &K {
164        &self.kernel
165    }
166
167    /// Get the SVE result the basis was built from
168    ///
169    /// It is not truncated to the basis size: a basis limited by `max_size`
170    /// or `epsilon` keeps all singular functions of the SVE.
171    pub fn sve_result(&self) -> &Arc<SVEResult> {
172        &self.sve_result
173    }
174
175    /// Get the accuracy of the basis
176    pub fn accuracy(&self) -> f64 {
177        self.accuracy
178    }
179
180    /// Get the inverse temperature β
181    pub fn beta(&self) -> f64 {
182        self.beta
183    }
184
185    /// Get the left singular functions (u) on imaginary time axis
186    pub fn u(&self) -> &Arc<PiecewiseLegendrePolyVector> {
187        &self.u
188    }
189
190    /// Get the right singular functions (v) on real frequency axis
191    pub fn v(&self) -> &Arc<PiecewiseLegendrePolyVector> {
192        &self.v
193    }
194
195    /// Get the singular values
196    pub fn s(&self) -> &[f64] {
197        &self.s
198    }
199
200    /// Get the left singular functions on Matsubara frequency axis (uhat)
201    pub fn uhat(&self) -> &Arc<PiecewiseLegendreFTVector<S>> {
202        &self.uhat
203    }
204
205    /// Get the full uhat (before truncation)
206    ///
207    /// Holds the Matsubara transforms of all singular functions of
208    /// [`sve_result`](Self::sve_result), not only of the `size()` basis
209    /// functions; the default Matsubara sampling points use them.
210    pub fn uhat_full(&self) -> &Arc<PiecewiseLegendreFTVector<S>> {
211        &self.uhat_full
212    }
213
214    // ========== Other methods ==========
215
216    /// Get the frequency scale wmax = Λ/β, with ω = wmax·y: the frequency
217    /// cutoff ωmax of a symmetric kernel, and the larger of |ωmin| and ωmax of
218    /// an asymmetric window
219    pub fn wmax(&self) -> f64 {
220        self.kernel.kernel_lambda() / self.beta
221    }
222
223    /// Get default Matsubara sampling points as i64 indices (for C-API)
224    ///
225    /// # Errors
226    ///
227    /// The errors of [`Self::default_matsubara_sampling_points`]
228    pub fn default_matsubara_sampling_points_i64(
229        &self,
230        positive_only: bool,
231    ) -> Result<Vec<i64>, Error>
232    where
233        S: 'static,
234    {
235        Ok(self
236            .default_matsubara_sampling_points(positive_only)?
237            .into_iter()
238            .map(|f| f.n())
239            .collect())
240    }
241
242    /// Get default Matsubara sampling points as i64 indices with mitigate parameter (for C-API)
243    ///
244    /// # Errors
245    ///
246    /// The errors of [`Self::default_matsubara_sampling_points`]
247    pub fn default_matsubara_sampling_points_i64_with_mitigate(
248        &self,
249        positive_only: bool,
250        mitigate: bool,
251        n_points: usize,
252    ) -> Result<Vec<i64>, Error>
253    where
254        S: 'static,
255    {
256        // The points of the basis itself are cached (computed once per basis)
257        let freqs = if !mitigate && n_points == self.size() {
258            self.default_matsubara_sampling_points(positive_only)?
259        } else {
260            default_matsubara_sampling_points_from_uhat(
261                &self.uhat_full,
262                n_points,
263                mitigate,
264                positive_only,
265            )?
266        };
267        Ok(freqs.into_iter().map(|f| f.n()).collect())
268    }
269
270    /// Matsubara sampling points chosen by `method`
271    ///
272    /// [`Self::default_matsubara_sampling_points`] uses
273    /// [`MatsubaraPointMethod::SignChanges`] for basis functions with a
274    /// definite parity and [`MatsubaraPointMethod::PairSelection`] for the
275    /// others; this chooses the method explicitly, e.g. the pair selection
276    /// for a basis of a centrosymmetric kernel. See
277    /// [`matsubara_sampling_points_from_uhat`] for `mitigate`.
278    ///
279    /// # Errors
280    ///
281    /// The errors of [`matsubara_sampling_points_from_uhat`]: for
282    /// [`MatsubaraPointMethod::SignChanges`], [`Error::NotSupported`] if the
283    /// basis functions have no definite parity
284    pub fn matsubara_sampling_points(
285        &self,
286        positive_only: bool,
287        mitigate: bool,
288        method: MatsubaraPointMethod,
289    ) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
290    where
291        S: 'static,
292    {
293        matsubara_sampling_points_from_uhat(
294            &self.uhat_full,
295            self.size(),
296            mitigate,
297            positive_only,
298            method,
299        )
300    }
301
302    /// Create a new FiniteTempBasis
303    ///
304    /// # Arguments
305    ///
306    /// * `kernel` - Kernel implementing [`BasisKernel`]
307    /// * `beta` - Inverse temperature (β > 0)
308    /// * `epsilon` - Accuracy of the basis, in (0, 1). `None` selects the best
309    ///   accuracy of the working precision (about 1.6e-16).
310    /// * `max_size` - Maximum number of basis functions (optional). It limits
311    ///   the basis, not the SVE: the SVE is computed and kept in full, as in
312    ///   [`from_sve_result`](Self::from_sve_result) with an untruncated SVE.
313    ///   The default sampling points and [`accuracy`](Self::accuracy) of the
314    ///   basis use the singular functions beyond it.
315    ///
316    /// # Returns
317    ///
318    /// A new FiniteTempBasis
319    ///
320    /// # Errors
321    ///
322    /// * [`Error::InvalidParameter`] if `beta` is not positive and finite,
323    ///   `epsilon` is not in (0, 1), or `max_size` is `Some(0)`. These are
324    ///   checked before the SVE is computed.
325    /// * The errors of [`compute_sve`]: [`Error::NonFiniteInput`] if the
326    ///   discretized kernel has a non-finite entry, [`Error::DecompositionFailed`]
327    ///   if an SVD of the SVE fails
328    /// * The errors of [`from_sve_result`](Self::from_sve_result)
329    pub fn new(
330        kernel: K,
331        beta: f64,
332        epsilon: Option<f64>,
333        max_size: Option<usize>,
334    ) -> Result<Self, Error> {
335        // Validate before the (expensive) SVE
336        require_positive_finite("beta", beta)?;
337        require_accuracy("epsilon", epsilon)?;
338        require_nonzero_size("max_size", max_size)?;
339
340        // Compute the SVE without a size limit; `from_sve_result` truncates
341        // only the basis to `max_size`. The default sampling points of a basis
342        // of size L are the roots of u_L (tau) and v_L (omega) and the sign
343        // changes of uhat_L or uhat_{L+1} (Matsubara), and its accuracy is
344        // s_L / s_0. An SVE truncated to `max_size` functions lacks them, and
345        // the point selection would fall back to the extrema of the last
346        // function (issue #285).
347        //
348        // Convention-matched with SparseIR.jl 1.1.4 (src/basis.jl,
349        // `FiniteTempBasis(statistics, β, ωmax, ε; max_size, kernel,
350        // sve_result=SVEResult(kernel; ε))`): its default SVE takes no `lmax`,
351        // and `part(sve_result; ε, max_size)` truncates the basis only. No
352        // code was ported.
353        let sve_result = compute_sve(
354            kernel.clone(),
355            epsilon,
356            None, // cutoff
357            None, // no limit on the number of singular values
358            TworkType::Auto,
359        )?;
360
361        Self::from_sve_result(kernel, beta, sve_result, epsilon, max_size)
362    }
363
364    /// Create basis from existing SVE result
365    ///
366    /// This is useful when you want to reuse the same SVE computation
367    /// for both fermionic and bosonic bases.
368    ///
369    /// `max_size` (and `epsilon`) truncate the basis functions and singular
370    /// values only. `sve_result` is kept as given: the default sampling points
371    /// and [`accuracy`](Self::accuracy) use its singular functions beyond the
372    /// basis, so pass an untruncated SVE to get the points of SparseIR.jl.
373    ///
374    /// # Errors
375    ///
376    /// * [`Error::InvalidParameter`] if `beta` is not positive and finite,
377    ///   `epsilon` is not in [0, 1) (0 keeps every singular value), `max_size`
378    ///   is `Some(0)`, or `sve_result` is not an SVE on the kernel's domain
379    ///   `[xmin, xmax] × [ymin, ymax]`
380    /// * [`Error::EmptyInput`] if `sve_result` has no singular functions
381    /// * The errors of [`SVEResult::truncate`] (for an `SVEResult` whose public
382    ///   fields break its invariants)
383    pub fn from_sve_result(
384        kernel: K,
385        beta: f64,
386        sve_result: SVEResult,
387        epsilon: Option<f64>,
388        max_size: Option<usize>,
389    ) -> Result<Self, Error> {
390        require_positive_finite("beta", beta)?;
391        require_threshold("epsilon", epsilon)?;
392        require_nonzero_size("max_size", max_size)?;
393        check_kernel_domain(&kernel, &sve_result)?;
394
395        // Get truncated u, s, v from SVE result
396        let part = sve_result.truncate(epsilon, max_size)?;
397        let (u_sve, s_sve, v_sve) = (part.u().clone(), part.s(), part.v().clone());
398
399        // Calculate accuracy
400        let accuracy = if sve_result.s().len() > s_sve.len() {
401            sve_result.s()[s_sve.len()] / sve_result.s()[0]
402        } else {
403            sve_result.s()[sve_result.s().len() - 1] / sve_result.s()[0]
404        };
405
406        // Get kernel parameters: ω = wmax * y with wmax = Λ/β, so that
407        // y ∈ [ymin, ymax] maps to ω ∈ [ωmin, ωmax] (wmax = ωmax for
408        // symmetric kernels)
409        let wmax = kernel.kernel_lambda() / beta;
410
411        // Scale polynomials to new variables
412        // tau = β/2 * (x + 1), w = wmax * y
413
414        // Transform u: x ∈ [-1, 1] → τ ∈ [0, β]
415        let (x_knots, x_widths) =
416            snapped_knots_and_widths(&u_sve.polys()[0], kernel.xmin(), kernel.xmax());
417        let u_knots: Vec<f64> = x_knots.iter().map(|&x| beta / 2.0 * (x + 1.0)).collect();
418        let u_delta_x: Vec<f64> = x_widths.iter().map(|&dx| beta / 2.0 * dx).collect();
419        let u_symm: Vec<i32> = u_sve.polys().iter().map(|p| p.symm()).collect();
420
421        let u = u_sve.rescale_domain(u_knots, Some(u_delta_x), Some(u_symm))?;
422
423        // Transform v: y ∈ [ymin, ymax] → ω ∈ [ωmin, ωmax]
424        let (y_knots, y_widths) =
425            snapped_knots_and_widths(&v_sve.polys()[0], kernel.ymin(), kernel.ymax());
426        let v_knots: Vec<f64> = y_knots.iter().map(|&y| wmax * y).collect();
427        let v_delta_x: Vec<f64> = y_widths.iter().map(|&dy| wmax * dy).collect();
428        let v_symm: Vec<i32> = v_sve.polys().iter().map(|p| p.symm()).collect();
429
430        let v = v_sve.rescale_domain(v_knots, Some(v_delta_x), Some(v_symm))?;
431
432        // Scale singular values to τ = β(x + 1)/2 and ω = wmax y. A kernel with
433        // `ypower` carries that power of y = ω/wmax, so its physical form is
434        // K(τ, ω) = wmax^ypower K(x, y) and
435        // s_scaled = sqrt(β/2 * wmax) * wmax^ypower * s_sve,
436        // e.g. S_l = sqrt(β ωmax³/2) s_l for RegularizedBoseKernel (irbasis
437        // paper, Chikano et al., CPC 240, 181 (2019), arXiv:1807.05237, Eq. (25)).
438        let ypower = kernel.ypower();
439        let scale_factor = (beta / 2.0 * wmax).sqrt() * wmax.powi(ypower);
440        let s: Vec<f64> = s_sve.iter().map(|&x| scale_factor * x).collect();
441
442        // Construct uhat (Fourier transform of u)
443        // HACK: Fourier transforms only work on unit interval, so we scale the data
444        let uhat_base_full = sve_result.u().scale_data(beta.sqrt());
445        let conv_rad = kernel.conv_radius();
446
447        // Create statistics marker instance using Default trait
448        // S is a zero-sized type (ZST) like Fermionic or Bosonic
449        let stat_marker = S::default();
450
451        let uhat_full = PiecewiseLegendreFTVector::<S>::from_poly_vector(
452            &uhat_base_full,
453            stat_marker,
454            Some(conv_rad),
455        )?;
456
457        // Truncate uhat to basis size
458        let uhat_polyvec: Vec<_> = uhat_full.polyvec.iter().take(s.len()).cloned().collect();
459        let uhat = PiecewiseLegendreFTVector::from_vector(uhat_polyvec);
460
461        Ok(Self {
462            kernel,
463            sve_result: Arc::new(sve_result),
464            accuracy,
465            beta,
466            u: Arc::new(u),
467            v: Arc::new(v),
468            s,
469            uhat: Arc::new(uhat),
470            uhat_full: Arc::new(uhat_full),
471            default_matsubara_points: [OnceLock::new(), OnceLock::new()],
472            _phantom: std::marker::PhantomData,
473        })
474    }
475
476    /// Get the size of the basis (number of basis functions)
477    pub fn size(&self) -> usize {
478        self.s.len()
479    }
480
481    /// Get the cutoff parameter Λ = β * ωmax
482    pub fn lambda(&self) -> f64 {
483        self.kernel.kernel_lambda()
484    }
485
486    /// Upper edge ωmax of the frequency window (= [`wmax`](Self::wmax) for
487    /// symmetric kernels)
488    pub fn omega_max(&self) -> f64 {
489        self.kernel.ymax() * self.wmax()
490    }
491
492    /// Lower edge ωmin of the frequency window (= -[`wmax`](Self::wmax) for
493    /// symmetric kernels)
494    pub fn omega_min(&self) -> f64 {
495        self.kernel.ymin() * self.wmax()
496    }
497
498    /// Get significance of each singular value (s[i] / s[0])
499    pub fn significance(&self) -> Vec<f64> {
500        let s0 = self.s[0];
501        self.s.iter().map(|&s| s / s0).collect()
502    }
503
504    /// Get default tau sampling points
505    ///
506    /// Returns sampling points in imaginary time τ ∈ [-β/2, β/2].
507    ///
508    /// Roots are found with symmetry exploitation (matching Python 1.x / Julia v1),
509    /// then mapped to [-β/2, β/2] by folding τ_physical ∈ [0, β] around β/2.
510    ///
511    /// # Errors
512    ///
513    /// * [`Error::NotSupported`] if the default points are not defined for
514    ///   this basis: its SVE has so few singular functions that the last one
515    ///   has no extrema (e.g. `compute_sve` with `max_num_svals = Some(2)`)
516    pub fn default_tau_sampling_points(&self) -> Result<Vec<f64>, Error> {
517        let points = self.default_tau_sampling_points_size_requested(self.size())?;
518        let basis_size = self.size();
519        if points.len() < basis_size {
520            debug_warn!(
521                "Number of tau sampling points ({}) is less than basis size ({}). \
522                 Basis parameters: beta={}, wmax={}, epsilon={:.2e}",
523                points.len(),
524                basis_size,
525                self.beta,
526                self.wmax(),
527                self.accuracy()
528            );
529        }
530        Ok(points)
531    }
532
533    /// Get default tau sampling points with a requested size
534    ///
535    /// Returns sampling points in τ ∈ [-β/2, β/2].
536    ///
537    /// # Errors
538    ///
539    /// * [`Error::NotSupported`] if the default points are not defined for
540    ///   this basis: its SVE has so few singular functions that the last one
541    ///   has no extrema (e.g. `compute_sve` with `max_num_svals = Some(2)`)
542    pub fn default_tau_sampling_points_size_requested(
543        &self,
544        size_requested: usize,
545    ) -> Result<Vec<f64>, Error> {
546        let x_domain = (self.kernel.xmin(), self.kernel.xmax());
547        let x = default_sampling_points(self.sve_result.u(), "u", x_domain, size_requested)?;
548        let half_beta = self.beta / 2.0;
549        // Map roots to physical tau ∈ [0, β], then fold to [-β/2, β/2]
550        let mut smpl_taus: Vec<f64> = x
551            .iter()
552            .map(|&xi| {
553                let tau = half_beta * (xi + 1.0);
554                if tau <= half_beta {
555                    tau
556                } else {
557                    tau - self.beta
558                }
559            })
560            .collect();
561        smpl_taus.sort_by(|a, b| a.partial_cmp(b).unwrap());
562        Ok(smpl_taus)
563    }
564
565    /// Get default Matsubara frequency sampling points
566    ///
567    /// Returns sampling points as MatsubaraFreq objects: the sign changes of the
568    /// first discarded Matsubara basis function (its extrema when that function
569    /// is not available), as in SparseIR.jl; bosonic sets always include n = 0.
570    /// Basis functions without a definite parity (an SVE that is not
571    /// centrosymmetric, e.g. of [`LogisticKernelWindowed`] or from
572    /// the full-domain SVE (`SVEOptions::full_domain`)) have no such sign changes; their points are
573    /// selected as a set symmetric in ±n instead (see
574    /// [`default_matsubara_sampling_points_from_uhat`]).
575    ///
576    /// # Arguments
577    /// * `positive_only` - If true, returns only non-negative frequencies
578    ///
579    /// # Returns
580    /// Vector of Matsubara frequency sampling points
581    ///
582    /// # Errors
583    ///
584    /// [`Error::EmptyInput`] if the basis has no Matsubara functions, which a
585    /// basis from [`Self::new`] or [`Self::from_sve_result`] always has
586    ///
587    /// [`LogisticKernelWindowed`]: crate::kernel::LogisticKernelWindowed
588    pub fn default_matsubara_sampling_points(
589        &self,
590        positive_only: bool,
591    ) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
592    where
593        S: 'static,
594    {
595        let points = self.default_matsubara_points[usize::from(positive_only)]
596            .get_or_init(|| {
597                default_matsubara_sampling_points_from_uhat(
598                    &self.uhat_full,
599                    self.size(),
600                    false,
601                    positive_only,
602                )
603            })
604            .clone()?;
605        let basis_size = self.size();
606        // For positive_only=true, we need 2*n_sampling_points >= basis_size
607        // For positive_only=false, we need n_sampling_points >= basis_size
608        let effective_points = if positive_only {
609            2 * points.len()
610        } else {
611            points.len()
612        };
613        if effective_points < basis_size {
614            debug_warn!(
615                "Number of Matsubara sampling points ({}{}) is less than basis size ({}). \
616                 Basis parameters: beta={}, wmax={}, epsilon={:.2e}",
617                points.len(),
618                if positive_only { " × 2" } else { "" },
619                basis_size,
620                self.beta,
621                self.wmax(),
622                self.accuracy()
623            );
624        }
625        Ok(points)
626    }
627
628    /// Get default omega (real frequency) sampling points
629    ///
630    /// Returns sampling points on the real-frequency axis ω ∈ [ωmin, ωmax].
631    /// These are used as pole locations for the Discrete Lehmann Representation (DLR).
632    ///
633    /// The sampling points are chosen as the roots of the L-th basis function
634    /// in the spectral domain (v), which provides near-optimal conditioning.
635    ///
636    /// # Returns
637    /// Vector of real-frequency sampling points in [ωmin, ωmax]
638    ///
639    /// # Errors
640    ///
641    /// * [`Error::NotSupported`] if the default points are not defined for
642    ///   this basis: its SVE has so few singular functions that the last one
643    ///   has no extrema (e.g. `compute_sve` with `max_num_svals = Some(2)`)
644    pub fn default_omega_sampling_points(&self) -> Result<Vec<f64>, Error> {
645        let sz = self.size();
646
647        // Use UNTRUNCATED sve_result.v (same as C++)
648        // C++: default_sampling_points(*(sve_result->v), sz)
649        let y_domain = (self.kernel.ymin(), self.kernel.ymax());
650        let y = default_sampling_points(self.sve_result.v(), "v", y_domain, sz)?;
651
652        // Scale y ∈ [ymin, ymax] to ω ∈ [ωmin, ωmax]
653        let wmax = self.wmax();
654        let omega_points: Vec<f64> = y.into_iter().map(|yi| wmax * yi).collect();
655
656        Ok(omega_points)
657    }
658}
659
660// ============================================================================
661// Trait implementations
662// ============================================================================
663
664impl<K, S> crate::basis_trait::Basis<S> for FiniteTempBasis<K, S>
665where
666    K: BasisKernel,
667    S: StatisticsType + 'static,
668{
669    fn beta(&self) -> f64 {
670        self.beta
671    }
672
673    fn wmax(&self) -> f64 {
674        self.kernel.kernel_lambda() / self.beta
675    }
676
677    fn lambda(&self) -> f64 {
678        self.kernel.kernel_lambda()
679    }
680
681    fn size(&self) -> usize {
682        self.size()
683    }
684
685    fn accuracy(&self) -> f64 {
686        self.accuracy
687    }
688
689    fn significance(&self) -> Vec<f64> {
690        if let Some(&first_s) = self.s.first() {
691            self.s.iter().map(|&s| s / first_s).collect()
692        } else {
693            vec![]
694        }
695    }
696
697    fn svals(&self) -> Vec<f64> {
698        self.s.clone()
699    }
700
701    fn default_tau_sampling_points(&self) -> Result<Vec<f64>, Error> {
702        self.default_tau_sampling_points()
703    }
704
705    fn default_matsubara_sampling_points(
706        &self,
707        positive_only: bool,
708    ) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error> {
709        self.default_matsubara_sampling_points(positive_only)
710    }
711
712    fn evaluate_tau(&self, tau: &[f64]) -> Result<crate::Matrix<f64>, Error> {
713        use crate::matrix::{Mat, MatTyped};
714        use crate::taufuncs::normalize_tau;
715
716        let basis_size = self.size();
717
718        // Normalize every τ ∈ [-β, β] to [0, β] with the statistics sign
719        // first; this rejects a τ outside [-β, β] and NaN. The u polynomials
720        // are on [0, β] exactly (from_sve_result sets their ends), so
721        // evaluating them cannot fail.
722        let normalized = tau
723            .iter()
724            .map(|&t| normalize_tau::<S>(t, self.beta))
725            .collect::<Result<Vec<(f64, f64)>, Error>>()?;
726        if normalized.is_empty() {
727            // An empty set of points gives an empty matrix.
728            return Ok(Mat::<f64>::from_elem([0, basis_size], 0.0).into_typed());
729        }
730
731        // Result: matrix[i, l] = u_l(tau[i])
732        Ok(Mat::<f64>::from_fn([normalized.len(), basis_size], |idx| {
733            let (tau_norm, sign) = normalized[idx[0]];
734            sign * self.u[idx[1]].evaluate(tau_norm)
735        })
736        .into_typed())
737    }
738
739    fn evaluate_matsubara(
740        &self,
741        freqs: &[crate::freq::MatsubaraFreq<S>],
742    ) -> Result<crate::Matrix<num_complex::Complex<f64>>, Error> {
743        use crate::matrix::{Mat, MatTyped};
744        use num_complex::Complex;
745
746        let n_points = freqs.len();
747        let basis_size = self.size();
748        if n_points == 0 {
749            // See evaluate_tau.
750            return Ok(
751                Mat::<Complex<f64>>::from_elem([0, basis_size], Complex::new(0.0, 0.0))
752                    .into_typed(),
753            );
754        }
755
756        // Evaluate all basis functions frequency by frequency, so that the
757        // segment-wise factors of the transform are shared among them.
758        // Result: matrix[i, l] = uhat_l(iν[i])
759        let rows = self.uhat.evaluate_at_many(freqs);
760        Ok(
761            Mat::<Complex<f64>>::from_fn([n_points, basis_size], |idx| rows[idx[0]][idx[1]])
762                .into_typed(),
763        )
764    }
765
766    fn evaluate_omega(&self, omega: &[f64]) -> Result<crate::Matrix<f64>, Error> {
767        use crate::matrix::{Mat, MatTyped};
768
769        let basis_size = self.size();
770        // The v polynomials are on [ωmin, ωmax] exactly (from_sve_result
771        // sets their ends).
772        let domain = (self.v.xmin(), self.v.xmax());
773        if let Some(&w) = omega.iter().find(|&&w| !(w >= domain.0 && w <= domain.1)) {
774            return Err(Error::OutOfDomain {
775                name: "omega",
776                value: w,
777                domain,
778            });
779        }
780        if omega.is_empty() {
781            // See evaluate_tau.
782            return Ok(Mat::<f64>::from_elem([0, basis_size], 0.0).into_typed());
783        }
784
785        // Result: matrix[i, l] = V_l(omega[i])
786        Ok(Mat::<f64>::from_fn([omega.len(), basis_size], |idx| {
787            self.v[idx[1]].evaluate(omega[idx[0]])
788        })
789        .into_typed())
790    }
791
792    fn default_omega_sampling_points(&self) -> Result<Vec<f64>, Error> {
793        self.default_omega_sampling_points()
794    }
795}
796
797// ============================================================================
798// Type aliases
799// ============================================================================
800
801/// Type alias for fermionic basis with LogisticKernel
802pub type FermionicBasis = FiniteTempBasis<LogisticKernel, Fermionic>;
803
804/// Type alias for bosonic basis with LogisticKernel
805pub type BosonicBasis = FiniteTempBasis<LogisticKernel, Bosonic>;
806
807/// How the Matsubara sampling points of a basis are chosen
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809#[non_exhaustive]
810pub enum MatsubaraPointMethod {
811    /// The sign changes of the first function beyond the basis, as in
812    /// SparseIR.jl and libsparseir: the default for functions with a definite
813    /// parity (centrosymmetric kernels), which only they have.
814    SignChanges,
815    /// A set symmetric in ±n, selected in pairs by an interpolative
816    /// decomposition (pivoted QR of the rows `Re û(n)`, `Im û(n)`, as Kaye,
817    /// Chen and Parcollet do for the DLR, Phys. Rev. B 105, 235115 (2022)):
818    /// the only method, and so the default, for functions without a parity
819    /// (e.g. [`LogisticKernelWindowed`]); available for the others on
820    /// request.
821    ///
822    /// [`LogisticKernelWindowed`]: crate::kernel::LogisticKernelWindowed
823    PairSelection,
824}
825
826/// Default Matsubara sampling points for a basis of size `l`, from the
827/// Matsubara basis functions `uhat_full` alone
828///
829/// For functions with a definite parity, the points are those of
830/// [`MatsubaraPointMethod::SignChanges`], as in SparseIR.jl; for functions
831/// without one (symm = 0, as from an SVE that is not centrosymmetric), those
832/// of [`MatsubaraPointMethod::PairSelection`]. This is what
833/// [`FiniteTempBasis::default_matsubara_sampling_points`] computes, for a
834/// caller that holds the functions but not the basis.
835///
836/// # Errors
837///
838/// [`Error::EmptyInput`] if `uhat_full` is empty
839pub fn default_matsubara_sampling_points_from_uhat<S>(
840    uhat_full: &PiecewiseLegendreFTVector<S>,
841    l: usize,
842    mitigate: bool,
843    positive_only: bool,
844) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
845where
846    S: StatisticsType + 'static,
847{
848    let method = if uhat_full.get_polys().iter().any(|u| u.poly.symm() == 0) {
849        MatsubaraPointMethod::PairSelection
850    } else {
851        MatsubaraPointMethod::SignChanges
852    };
853    matsubara_sampling_points_from_uhat(uhat_full, l, mitigate, positive_only, method)
854}
855
856/// Matsubara sampling points for a basis of size `l` by `method`, from the
857/// Matsubara basis functions `uhat_full` alone
858///
859/// [`MatsubaraPointMethod::SignChanges`]: the sign changes of `uhat_full[l]`
860/// (after the parity adjustment of `l`), or the extrema of the last function
861/// when `uhat_full` has no function `l`, as in SparseIR.jl; bosonic sets
862/// always include n = 0. `mitigate` adds points near the outer frequencies
863/// (fencing).
864///
865/// [`MatsubaraPointMethod::PairSelection`]: as many frequencies as
866/// functions, rounded up to an even number for fermions and an odd one
867/// including n = 0 for bosons, chosen among the frequencies of the grid of
868/// the sign-change search (spacing about 2% at high frequency); `mitigate`
869/// adds about 10% more frequencies (oversampling that minimizes the noise
870/// variance of the fit).
871///
872/// # Errors
873///
874/// * [`Error::EmptyInput`] if `uhat_full` is empty
875/// * For [`MatsubaraPointMethod::PairSelection`], [`Error::InvalidParameter`]
876///   if `l` exceeds the number of functions of `uhat_full`, and
877///   [`Error::DecompositionFailed`] if they have rank below `l` on the
878///   candidate frequencies
879/// * [`Error::NotSupported`] for [`MatsubaraPointMethod::SignChanges`] if the
880///   functions have no definite parity (symm = 0, #183)
881pub fn matsubara_sampling_points_from_uhat<S>(
882    uhat_full: &PiecewiseLegendreFTVector<S>,
883    l: usize,
884    mitigate: bool,
885    positive_only: bool,
886    method: MatsubaraPointMethod,
887) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
888where
889    S: StatisticsType + 'static,
890{
891    if uhat_full.is_empty() {
892        return Err(Error::EmptyInput { name: "uhat_full" });
893    }
894    match method {
895        MatsubaraPointMethod::SignChanges => {
896            sign_change_sampling_points(uhat_full, l, mitigate, positive_only)
897        }
898        MatsubaraPointMethod::PairSelection => {
899            crate::polyfourier::pair_sampling_points(uhat_full, l, positive_only, mitigate)
900        }
901    }
902}
903
904/// [`MatsubaraPointMethod::SignChanges`], as in main and SparseIR.jl
905fn sign_change_sampling_points<S>(
906    uhat_full: &PiecewiseLegendreFTVector<S>,
907    l: usize,
908    mitigate: bool,
909    positive_only: bool,
910) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
911where
912    S: StatisticsType + 'static,
913{
914    use crate::freq::MatsubaraFreq;
915    use crate::polyfourier::{find_extrema, sign_changes};
916    use std::collections::BTreeSet;
917
918    let mut l_requested = l;
919
920    // Adjust l_requested based on statistics (same as C++)
921    if S::STATISTICS == crate::traits::Statistics::Fermionic && l_requested % 2 != 0 {
922        l_requested += 1;
923    } else if S::STATISTICS == crate::traits::Statistics::Bosonic && l_requested % 2 == 0 {
924        l_requested += 1;
925    }
926
927    // Choose sign_changes or find_extrema based on l_requested
928    let mut omega_n = if l_requested < uhat_full.len() {
929        sign_changes(&uhat_full[l_requested], positive_only)?
930    } else {
931        find_extrema(&uhat_full[uhat_full.len() - 1], positive_only)?
932    };
933
934    // For bosons, include zero frequency explicitly to prevent conditioning issues
935    if S::STATISTICS == crate::traits::Statistics::Bosonic {
936        omega_n.push(MatsubaraFreq::<S>::new(0).unwrap());
937    }
938
939    // Sort and remove duplicates using BTreeSet
940    let omega_n_set: BTreeSet<MatsubaraFreq<S>> = omega_n.into_iter().collect();
941    let mut omega_n: Vec<MatsubaraFreq<S>> = omega_n_set.into_iter().collect();
942
943    // Check expected size
944    let expected_size = if positive_only {
945        l_requested.div_ceil(2)
946    } else {
947        l_requested
948    };
949
950    if omega_n.len() != expected_size {
951        debug_warn!(
952            "Requested {} sampling frequencies for basis size L = {}, but got {}.",
953            expected_size,
954            l,
955            omega_n.len()
956        );
957    }
958
959    // Apply fencing if requested (same as C++ implementation)
960    if mitigate {
961        fence_matsubara_sampling(&mut omega_n, positive_only);
962    }
963
964    Ok(omega_n)
965}
966
967/// Fence Matsubara sampling points to improve conditioning
968///
969/// This function adds additional sampling points near the outer frequencies
970/// to improve the conditioning of the sampling matrix. This is particularly
971/// important for Matsubara sampling where we cannot freely choose sampling points.
972///
973/// Implementation matches C++ version in `basis.hpp` (lines 407-452).
974fn fence_matsubara_sampling<S: StatisticsType + 'static>(
975    omega_n: &mut Vec<crate::freq::MatsubaraFreq<S>>,
976    positive_only: bool,
977) {
978    use crate::freq::{BosonicFreq, MatsubaraFreq};
979
980    if omega_n.is_empty() {
981        return;
982    }
983
984    // Collect outer frequencies
985    let mut outer_frequencies = Vec::new();
986    if positive_only {
987        outer_frequencies.push(omega_n[omega_n.len() - 1]);
988    } else {
989        outer_frequencies.push(omega_n[0]);
990        outer_frequencies.push(omega_n[omega_n.len() - 1]);
991    }
992
993    for wn_outer in outer_frequencies {
994        let outer_val = wn_outer.n();
995        // In SparseIR.jl-v1, ωn_diff is always created as BosonicFreq
996        // This ensures diff_val is always even (valid for Bosonic)
997        let mut diff_val = 2 * (0.025 * outer_val as f64).round() as i64;
998
999        // Handle edge case: if diff_val is 0, set it to 2 (minimum even value for Bosonic)
1000        if diff_val == 0 {
1001            diff_val = 2;
1002        }
1003
1004        // Get the n value from BosonicFreq (same as diff_val since it's even)
1005        let wn_diff = BosonicFreq::new(diff_val).unwrap().n();
1006
1007        // Sign function: returns +1 if n > 0, -1 if n < 0, 0 if n == 0
1008        // Matches C++ implementation: (a.get_n() > 0) - (a.get_n() < 0)
1009        let sign_val = if outer_val > 0 {
1010            1
1011        } else if outer_val < 0 {
1012            -1
1013        } else {
1014            0
1015        };
1016
1017        // Check original size before adding (C++ checks wn.size() before each push)
1018        let original_size = omega_n.len();
1019        if original_size >= 20 {
1020            // For Fermionic: wn_outer.n is odd, wn_diff is even, so wn_outer.n ± wn_diff is odd (valid)
1021            // For Bosonic: wn_outer.n is even, wn_diff is even, so wn_outer.n ± wn_diff is even (valid)
1022            let new_n = outer_val - sign_val * wn_diff;
1023            if let Ok(new_freq) = MatsubaraFreq::<S>::new(new_n) {
1024                omega_n.push(new_freq);
1025            }
1026        }
1027        if original_size >= 42 {
1028            let new_n = outer_val + sign_val * wn_diff;
1029            if let Ok(new_freq) = MatsubaraFreq::<S>::new(new_n) {
1030                omega_n.push(new_freq);
1031            }
1032        }
1033    }
1034
1035    // Sort and remove duplicates using BTreeSet
1036    let omega_n_set: std::collections::BTreeSet<MatsubaraFreq<S>> = omega_n.drain(..).collect();
1037    *omega_n = omega_n_set.into_iter().collect();
1038}
1039
1040/// Get default sampling points in [-1, 1]
1041///
1042/// C++ implementation: libsparseir/include/sparseir/basis.hpp:287-310
1043///
1044/// For orthogonal polynomials (the high-T limit of IR), we know that the
1045/// ideal sampling points for a basis of size L are the roots of the L-th
1046/// polynomial. We empirically find that these stay good sampling points
1047/// for our kernels (probably because the kernels are totally positive).
1048///
1049/// If we do not have enough polynomials in the basis, we approximate the
1050/// roots of the L'th polynomial by the extrema of the last basis function,
1051/// which is sensible due to the strong interleaving property of these
1052/// functions' roots.
1053///
1054/// `name` names `u` in the errors (`"u"` or `"v"`), and `domain` is the
1055/// domain of the kernel the SVE expanded (`[xmin, xmax]` for `u`,
1056/// `[ymin, ymax]` for `v`; [-1, 1] for a symmetric kernel).
1057///
1058/// # Errors
1059///
1060/// * [`Error::InvalidParameter`] named `name` if `u` is not on `domain`
1061///   (1e-10), i.e. not the unscaled functions of an SVE
1062/// * [`Error::NotSupported`] if the extrema are needed and the last function
1063///   has none (e.g. an SVE truncated to 2 functions, whose u_1 is monotonic)
1064pub(crate) fn default_sampling_points(
1065    u: &PiecewiseLegendrePolyVector,
1066    name: &'static str,
1067    domain: (f64, f64),
1068    l: usize,
1069) -> Result<Vec<f64>, Error> {
1070    // C++: if (u.xmin() != -1.0 || u.xmax() != 1.0)
1071    //          throw std::runtime_error("Expecting unscaled functions here.");
1072    // (here generalized to the domain of an asymmetric kernel)
1073    if (u.xmin() - domain.0).abs() > 1e-10 || (u.xmax() - domain.1).abs() > 1e-10 {
1074        return Err(Error::InvalidParameter {
1075            name,
1076            value: format!("functions on [{:?}, {:?}]", u.xmin(), u.xmax()),
1077            reason: format!(
1078                "must be the unscaled functions of an SVE, on [{:?}, {:?}]",
1079                domain.0, domain.1
1080            ),
1081        });
1082    }
1083
1084    let x0 = if l < u.len() {
1085        // C++: return u.polyvec[L].roots();
1086        u[l].roots()
1087    } else {
1088        // C++: PiecewiseLegendrePoly poly = u.polyvec.back();
1089        //      Eigen::VectorXd maxima = poly.deriv().roots();
1090        let poly = u.last();
1091        let poly_deriv = poly.deriv(1);
1092        let maxima = poly_deriv.roots();
1093
1094        // C++ reads maxima[0] without a check; SparseIR.jl's first(maxima)
1095        // fails the same way.
1096        let (Some(&first), Some(&last)) = (maxima.first(), maxima.last()) else {
1097            return Err(Error::NotSupported {
1098                what: format!(
1099                    "default sampling points for {l} basis functions: the last singular \
1100                     function (l = {}) has no extrema to stand in for the roots of the \
1101                     missing function l = {l} (an SVE truncated to too few functions)",
1102                    poly.l()
1103                ),
1104            });
1105        };
1106
1107        // C++: double left = (maxima[0] + poly.xmin) / 2.0;
1108        let left = (first + poly.xmin()) / 2.0;
1109
1110        // C++: double right = (maxima[maxima.size() - 1] + poly.xmax) / 2.0;
1111        let right = (last + poly.xmax()) / 2.0;
1112
1113        // C++: Eigen::VectorXd x0(maxima.size() + 2);
1114        //      x0[0] = left;
1115        //      x0.segment(1, maxima.size()) = maxima;
1116        //      x0[x0.size() - 1] = right;
1117        let mut x0_vec = Vec::with_capacity(maxima.len() + 2);
1118        x0_vec.push(left);
1119        x0_vec.extend_from_slice(&maxima);
1120        x0_vec.push(right);
1121        x0_vec
1122    };
1123
1124    // C++: if (x0.size() != L) { warning }
1125    if x0.len() != l {
1126        debug_warn!(
1127            "Expecting to get {} sampling points for corresponding basis function, \
1128             instead got {}. This may happen if not enough precision is left in the polynomial.",
1129            l,
1130            x0.len()
1131        );
1132    }
1133
1134    Ok(x0)
1135}
1136
1137#[cfg(test)]
1138#[path = "basis_tests.rs"]
1139mod basis_tests;