Skip to main content

sparse_ir_dlr/
dlr.rs

1//! Discrete Lehmann Representation (DLR)
2//!
3//! This module provides the Discrete Lehmann Representation (DLR) basis,
4//! which represents Green's functions as a linear combination of poles on the
5//! real-frequency axis.
6
7use crate::error::{Error, require_finite, require_positive_finite};
8use crate::fitters::FitScalar;
9use crate::fitters::RealMatrixFitter;
10use crate::freq::MatsubaraFreq;
11use crate::gemm::GemmBackendHandle;
12use crate::matrix::Mat;
13use crate::taufuncs::normalize_tau;
14use crate::traits::{Statistics, StatisticsType};
15use num_complex::Complex;
16use std::marker::PhantomData;
17use std::sync::OnceLock;
18use tenferro_tensor::TypedTensor;
19
20/// Generic single-pole Green's function at imaginary time τ
21///
22/// Computes G(τ) for either fermionic or bosonic statistics based on the type parameter S.
23/// Both use G(τ) = -exp(-ω×τ) / (1 ± exp(-β×ω)) (+ for fermions, - for bosons),
24/// the imaginary-time counterpart of [`giwn_single_pole`]'s G(iν) = 1/(iν - ω).
25///
26/// # Type Parameters
27/// * `S` - Statistics type (Fermionic or Bosonic)
28///
29/// # Arguments
30/// * `tau` - Imaginary time τ ∈ [-β, β]; τ < 0 is mapped to [0, β] by
31///   (anti-)periodicity (see [`fermionic_single_pole`] and [`bosonic_single_pole`])
32/// * `omega` - Pole position (real frequency)
33/// * `beta` - Inverse temperature
34///
35/// # Returns
36/// Real-valued Green's function G(τ)
37///
38/// # Errors
39///
40/// * [`Error::InvalidParameter`] if `beta` is not positive and finite, or
41///   `omega` is not finite
42/// * [`Error::OutOfDomain`] if `tau` is outside [-β, β] or NaN
43///
44/// # Example
45/// ```
46/// use sparse_ir::traits::{Bosonic, Fermionic};
47/// use sparse_ir::{bosonic_single_pole, fermionic_single_pole, gtau_single_pole};
48///
49/// let g_f = gtau_single_pole::<Fermionic>(0.5, 5.0, 1.0).unwrap();
50/// assert_eq!(g_f, fermionic_single_pole(0.5, 5.0, 1.0).unwrap());
51///
52/// let g_b = gtau_single_pole::<Bosonic>(0.5, 5.0, 1.0).unwrap();
53/// assert_eq!(g_b, bosonic_single_pole(0.5, 5.0, 1.0).unwrap());
54/// ```
55pub fn gtau_single_pole<S: StatisticsType>(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
56    match S::STATISTICS {
57        Statistics::Fermionic => fermionic_single_pole(tau, omega, beta),
58        Statistics::Bosonic => bosonic_single_pole(tau, omega, beta),
59    }
60}
61
62/// Compute fermionic single-pole Green's function at imaginary time τ
63///
64/// Evaluates G(τ) = -exp(-ω×τ) / (1 + exp(-β×ω)) for a single pole at frequency ω.
65///
66/// Supports negative τ with anti-periodic boundary conditions:
67/// - G(τ + β) = -G(τ) (fermionic anti-periodicity)
68/// - Valid for τ ∈ [-β, β]; τ is normalized with
69///   [`normalize_tau`]
70///
71/// # Arguments
72/// * `tau` - Imaginary time τ ∈ [-β, β]
73/// * `omega` - Pole position (real frequency)
74/// * `beta` - Inverse temperature
75///
76/// # Returns
77/// Real-valued Green's function G(τ)
78///
79/// # Errors
80///
81/// * [`Error::InvalidParameter`] if `beta` is not positive and finite, or
82///   `omega` is not finite
83/// * [`Error::OutOfDomain`] if `tau` is outside [-β, β] or NaN
84///
85/// # Example
86/// ```
87/// use sparse_ir::fermionic_single_pole;
88///
89/// let beta = 1.0;
90/// let omega = 5.0;
91/// let tau = 0.5 * beta;
92/// let g = fermionic_single_pole(tau, omega, beta).unwrap();
93///
94/// let expected = -(-omega * tau).exp() / (1.0 + (-beta * omega).exp());
95/// assert!((g - expected).abs() < 1e-15);
96///
97/// // Anti-periodicity: G(τ - β) = -G(τ)
98/// assert!((fermionic_single_pole(tau - beta, omega, beta).unwrap() + g).abs() < 1e-15);
99/// ```
100pub fn fermionic_single_pole(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
101    use crate::traits::Fermionic;
102
103    // Normalize τ to [0, β] and track sign from anti-periodicity
104    // G(τ + β) = -G(τ) for fermions
105    let (tau_normalized, sign) = normalize_tau::<Fermionic>(tau, beta)?;
106    require_finite("omega", omega)?;
107    Ok(sign * fermionic_single_pole_unchecked(tau_normalized, omega, beta))
108}
109
110/// Fermionic single-pole G(τ) for τ already in [0, β], without the sign of
111/// the antiperiodic continuation
112///
113/// Checked callers only: β positive and finite, ω finite. The DLR checks its
114/// poles in `from_ir_with_poles` and they cannot be changed afterwards.
115pub(crate) fn fermionic_single_pole_unchecked(tau_normalized: f64, omega: f64, beta: f64) -> f64 {
116    // Avoid overflow for large negative ω by factoring out exp(βω).
117    // Both branches keep the exponent non-positive.
118    if omega >= 0.0 {
119        -(-omega * tau_normalized).exp() / (1.0 + (-beta * omega).exp())
120    } else {
121        -(omega * (beta - tau_normalized)).exp() / (1.0 + (beta * omega).exp())
122    }
123}
124
125/// Compute bosonic single-pole Green's function at imaginary time τ
126///
127/// Evaluates G(τ) = -exp(-ω×τ) / (1 - exp(-β×ω)) for a single pole at frequency ω.
128///
129/// This is the imaginary-time counterpart of [`giwn_single_pole`]:
130/// G(iνn) = ∫₀^β dτ exp(iνn×τ) G(τ) = 1/(iνn - ω). G(τ) is negative for ω > 0
131/// and positive for ω < 0, the same sign convention as [`fermionic_single_pole`]
132/// and the bosonic τ functions of [`DiscreteLehmannRepresentation`].
133///
134/// Supports negative τ with periodic boundary conditions:
135/// - G(τ + β) = G(τ) (bosonic periodicity)
136/// - Valid for τ ∈ [-β, β]; τ is normalized with
137///   [`normalize_tau`]
138///
139/// ω = 0 is a genuine pole of the Bose factor, so the result is infinite there:
140/// `-inf` for `omega = +0.0` (the ω → 0⁺ limit) and `+inf` for `omega = -0.0`.
141/// [`DiscreteLehmannRepresentation`] evaluates a zero pole through its finite,
142/// regularized limit instead.
143///
144/// # Arguments
145/// * `tau` - Imaginary time τ ∈ [-β, β]
146/// * `omega` - Pole position (real frequency)
147/// * `beta` - Inverse temperature
148///
149/// # Returns
150/// Real-valued Green's function G(τ)
151///
152/// # Errors
153///
154/// * [`Error::InvalidParameter`] if `beta` is not positive and finite, or
155///   `omega` is not finite
156/// * [`Error::OutOfDomain`] if `tau` is outside [-β, β] or NaN
157///
158/// # Example
159/// ```
160/// use sparse_ir::bosonic_single_pole;
161///
162/// let beta = 1.0;
163/// let omega = 5.0;
164/// let tau = 0.5 * beta;
165/// let g = bosonic_single_pole(tau, omega, beta).unwrap();
166///
167/// let expected = -(-omega * tau).exp() / (1.0 - (-beta * omega).exp());
168/// assert!((g - expected).abs() <= 1e-14 * expected.abs());
169/// assert!(g < 0.0);
170///
171/// // Periodicity: G(τ - β) = G(τ)
172/// assert!((bosonic_single_pole(tau - beta, omega, beta).unwrap() - g).abs() < 1e-15);
173/// ```
174pub fn bosonic_single_pole(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
175    use crate::traits::Bosonic;
176
177    // Normalize τ to [0, β] using periodicity
178    // G(τ + β) = G(τ) for bosons
179    let tau_normalized = normalize_tau::<Bosonic>(tau, beta)?.0;
180    require_finite("omega", omega)?;
181
182    // Avoid overflow for large negative ω by factoring out exp(βω): both
183    // branches keep the exponents non-positive. expm1 keeps the Bose
184    // denominator 1 - exp(-β|ω|) accurate for small β|ω|. This is the same
185    // form as the bosonic arm of `DiscreteLehmannRepresentation::evaluate_tau`.
186    // At ω = ±0 the denominator is a signed zero and the result is ∓inf.
187    if omega >= 0.0 {
188        // 1 - exp(-βω) = -expm1(-βω)
189        let denominator = -(-beta * omega).exp_m1();
190        Ok(-(-omega * tau_normalized).exp() / denominator)
191    } else {
192        // -exp(-ωτ) / (1 - exp(-βω)) = exp(ω(β - τ)) / (1 - exp(βω))
193        let denominator = -(beta * omega).exp_m1();
194        Ok((omega * (beta - tau_normalized)).exp() / denominator)
195    }
196}
197
198/// Generic single-pole Green's function at Matsubara frequency
199///
200/// Computes G(iν) = 1/(iν - ω) for a single pole at frequency ω.
201///
202/// # Type Parameters
203/// * `S` - Statistics type (Fermionic or Bosonic)
204///
205/// # Arguments
206/// * `matsubara_freq` - Matsubara frequency
207/// * `omega` - Pole position (real frequency)
208/// * `beta` - Inverse temperature
209///
210/// # Returns
211/// Complex-valued Green's function G(iν)
212///
213/// # Errors
214///
215/// [`Error::InvalidParameter`] if `beta` is not positive and finite, or
216/// `omega` is not finite
217pub fn giwn_single_pole<S: StatisticsType>(
218    matsubara_freq: &MatsubaraFreq<S>,
219    omega: f64,
220    beta: f64,
221) -> Result<Complex<f64>, Error> {
222    require_positive_finite("beta", beta)?;
223    require_finite("omega", omega)?;
224    // G(iν) = 1/(iν - ω)
225    let wn = matsubara_freq.value(beta);
226    let denominator = Complex::new(0.0, 1.0) * wn - Complex::new(omega, 0.0);
227    Ok(Complex::new(1.0, 0.0) / denominator)
228}
229
230// ============================================================================
231// Discrete Lehmann Representation
232// ============================================================================
233
234/// Discrete Lehmann Representation (DLR)
235///
236/// The DLR is a variant of the IR basis based on a "sketching" of the analytic
237/// continuation kernel K. Instead of using singular value expansion, it represents
238/// Green's functions as a linear combination of poles on the real-frequency axis:
239///
240/// ```text
241/// G(iν) = Σ_i a[i] * reg[i] / (iν - ω[i])
242/// ```
243///
244/// where:
245/// - `ω[i]` are pole positions on the real axis
246/// - `a[i]` are expansion coefficients
247/// - `reg[i]` are the kernel regularizers `w(β, ω_i)`
248///
249/// The public `regularizers` field stores `w(β, ω_i)`: 1 for fermions and
250/// `tanh(βω_i/2)` for bosons with `LogisticKernel`, and `ω_i` for
251/// `RegularizedBoseKernel`. The DLR functions are `-K(τ, ω_i)` and its Fourier
252/// transform for the physical kernel `K(τ, ω) = Σ_l U_l(τ) S_l V_l(ω)` of the
253/// source basis.
254///
255/// Two constructions are available:
256/// - **independent (default)**: [`DiscreteLehmannRepresentation::new`] /
257///   [`DlrBuilder`] select the poles by an interpolative decomposition of the
258///   discretized logistic kernel (Kaye, Chen, Parcollet, PRB 105, 235115),
259///   without building an IR basis;
260/// - **IR-derived**: `DiscreteLehmannRepresentation::from_ir` (trait
261///   `DlrFromIr` of the IR crate) uses the default real-frequency sampling
262///   points of an IR basis as poles, and `from_ir_with_poles` takes the poles.
263///
264/// Conversions to and from an IR basis are provided by [`IrDlrTransform`];
265/// an IR-derived DLR carries one for its source basis.
266///
267/// Imaginary-time and Matsubara nodes for square interpolation are selected
268/// by a row interpolative decomposition and are exposed through
269/// [`Basis::default_tau_sampling_points`](crate::basis_trait::Basis::default_tau_sampling_points)
270/// and
271/// [`Basis::default_matsubara_sampling_points`](crate::basis_trait::Basis::default_matsubara_sampling_points),
272/// so [`TauSampling::new`](crate::TauSampling::new) and
273/// [`MatsubaraSampling::new`](crate::MatsubaraSampling::new) work on a DLR.
274///
275/// # Type Parameters
276/// * `S` - Statistics type (Fermionic or Bosonic)
277pub struct DiscreteLehmannRepresentation<S>
278where
279    S: StatisticsType,
280{
281    /// Pole positions on the real-frequency axis ω ∈ [-ωmax, ωmax]
282    poles: Vec<f64>,
283
284    /// Inverse temperature β
285    beta: f64,
286
287    /// Maximum frequency ωmax
288    wmax: f64,
289
290    /// Power with which the source kernel scales the spectral variable.
291    kernel_ypower: i32,
292
293    /// Accuracy of the representation
294    accuracy: f64,
295
296    /// Regularizers for each pole: regularizer[i] = w(β, ω_i) of the logistic
297    /// kernel, or of the kernel of the source IR basis for an IR-derived DLR
298    regularizers: Vec<f64>,
299
300    /// Pole weights used in tau and Matsubara evaluations.
301    ///
302    /// They equal `regularizers`: the τ functions are
303    /// `-w_i e^{-τω_i} / (1 ± e^{-βω_i})` and the Matsubara functions
304    /// `w_i / (iν - ω_i)`, which is `-K(τ, ω_i)` and its Fourier transform for
305    /// the physical kernel of the source basis.
306    pole_weights: Vec<f64>,
307
308    /// IR <-> DLR transform for the source basis of an IR-derived DLR.
309    ir: Option<IrDlrTransform>,
310
311    /// Lazily selected interpolation nodes.
312    tau_nodes: OnceLock<Vec<f64>>,
313    matsubara_nodes: OnceLock<Vec<i64>>,
314    matsubara_nodes_positive: OnceLock<Vec<i64>>,
315
316    /// Marker for statistics type
317    _phantom: PhantomData<S>,
318}
319
320/// Regularizer `w(β, ω)` of the logistic kernel: 1 for fermions and
321/// `tanh(βω/2)` for bosons
322fn logistic_regularizer<S: StatisticsType>(beta: f64, omega: f64) -> f64 {
323    match S::STATISTICS {
324        Statistics::Fermionic => 1.0,
325        Statistics::Bosonic => (0.5 * beta * omega).tanh(),
326    }
327}
328
329/// Builder for the independent (interpolative-decomposition) DLR.
330///
331/// ```
332/// use sparse_ir::{DlrBuilder, Fermionic};
333/// let dlr = DlrBuilder::<Fermionic>::new(10.0, 10.0)
334///     .accuracy(1e-10)
335///     .build()
336///     .unwrap();
337/// assert!(!dlr.poles().is_empty());
338/// ```
339#[derive(Debug, Clone)]
340pub struct DlrBuilder<S: StatisticsType> {
341    beta: f64,
342    wmax: f64,
343    accuracy: f64,
344    max_size: Option<usize>,
345    _phantom: PhantomData<S>,
346}
347
348impl<S: StatisticsType + 'static> DlrBuilder<S> {
349    /// Default target accuracy.
350    pub const DEFAULT_ACCURACY: f64 = 1e-15;
351
352    /// Start a DLR for inverse temperature `beta` and frequency cutoff `wmax`.
353    pub fn new(beta: f64, wmax: f64) -> Self {
354        Self {
355            beta,
356            wmax,
357            accuracy: Self::DEFAULT_ACCURACY,
358            max_size: None,
359            _phantom: PhantomData,
360        }
361    }
362
363    /// Target relative accuracy of the kernel interpolation.
364    pub fn accuracy(mut self, accuracy: f64) -> Self {
365        self.accuracy = accuracy;
366        self
367    }
368
369    /// Upper bound on the number of poles.
370    pub fn max_size(mut self, max_size: usize) -> Self {
371        self.max_size = Some(max_size);
372        self
373    }
374
375    /// Select the poles and build the representation.
376    ///
377    /// # Errors
378    /// [`Error::InvalidParameter`] if `beta` or `wmax` is not positive and
379    /// finite, the accuracy is not in (0, 1), or `max_size` is 0.
380    pub fn build(self) -> Result<DiscreteLehmannRepresentation<S>, Error> {
381        require_positive_finite("beta", self.beta)?;
382        require_positive_finite("wmax", self.wmax)?;
383        crate::error::require_accuracy("accuracy", Some(self.accuracy))?;
384        crate::error::require_nonzero_size("max_size", self.max_size)?;
385        let lambda = self.beta * self.wmax;
386        let poles: Vec<f64> = crate::dlr_id::select_poles(lambda, self.accuracy, self.max_size)
387            .into_iter()
388            .map(|w| w / self.beta)
389            .collect();
390        let regularizers = poles
391            .iter()
392            .map(|&pole| logistic_regularizer::<S>(self.beta, pole))
393            .collect();
394        Ok(DiscreteLehmannRepresentation::from_parts(
395            self.beta,
396            self.wmax,
397            self.accuracy,
398            poles,
399            regularizers,
400            0,
401            None,
402        ))
403    }
404}
405
406impl<S> DiscreteLehmannRepresentation<S>
407where
408    S: StatisticsType,
409{
410    pub fn kernel_ypower(&self) -> i32 {
411        self.kernel_ypower
412    }
413
414    pub fn pole_weights(&self) -> &[f64] {
415        &self.pole_weights
416    }
417
418    /// Pole positions on the real-frequency axis, in the order they were
419    /// given to `from_ir_with_poles` (sorted ascending when chosen by
420    /// [`Self::new`] or `from_ir`)
421    pub fn poles(&self) -> &[f64] {
422        &self.poles
423    }
424
425    /// Regularizers of the poles: `regularizers[i] = w(β, poles[i])` of the
426    /// kernel of the IR basis this DLR was built from (of the logistic
427    /// kernel for an independent DLR)
428    pub fn regularizers(&self) -> &[f64] {
429        &self.regularizers
430    }
431
432    /// Number of functions of the IR basis this DLR was built from: the
433    /// extent of the IR axis of [`Self::from_ir_nd`] and [`Self::to_ir_nd`].
434    /// `None` for a DLR built independently of an IR basis.
435    pub fn ir_basis_size(&self) -> Option<usize> {
436        self.ir.as_ref().map(IrDlrTransform::ir_size)
437    }
438
439    /// IR <-> DLR transform of the source basis (IR-derived DLR only).
440    pub fn ir_transform(&self) -> Option<&IrDlrTransform> {
441        self.ir.as_ref()
442    }
443
444    /// Build a DLR independently of any IR basis (default construction).
445    ///
446    /// Equivalent to `DlrBuilder::new(beta, wmax).accuracy(accuracy).build()`.
447    ///
448    /// # Errors
449    /// See [`DlrBuilder::build`].
450    pub fn new(beta: f64, wmax: f64, accuracy: f64) -> Result<Self, Error>
451    where
452        S: 'static,
453    {
454        DlrBuilder::new(beta, wmax).accuracy(accuracy).build()
455    }
456
457    /// Assemble a DLR from checked parts: the constructors of the IR crate
458    /// build on this after validating the poles against their basis.
459    ///
460    /// `regularizers[i]` is the kernel regularizer `w(β, poles[i])`, which is
461    /// also the weight of the pole functions; `kernel_ypower` is 0 or 1 when a
462    /// bosonic pole lies at 0. `ir` is the transform to the source IR basis,
463    /// if any.
464    #[doc(hidden)]
465    pub fn from_parts(
466        beta: f64,
467        wmax: f64,
468        accuracy: f64,
469        poles: Vec<f64>,
470        regularizers: Vec<f64>,
471        kernel_ypower: i32,
472        ir: Option<IrDlrTransform>,
473    ) -> Self {
474        let pole_weights = regularizers.clone();
475        Self {
476            poles,
477            beta,
478            wmax,
479            kernel_ypower,
480            accuracy,
481            regularizers,
482            pole_weights,
483            ir,
484            tau_nodes: OnceLock::new(),
485            matsubara_nodes: OnceLock::new(),
486            matsubara_nodes_positive: OnceLock::new(),
487            _phantom: PhantomData,
488        }
489    }
490
491    fn zero_pole_tau_limit(&self) -> f64 {
492        match self.kernel_ypower {
493            // -lim_{ω→0} w(β, ω) e^{-τω} / (1 - e^{-βω}) with w = tanh(βω/2) or ω
494            0 => -0.5,
495            1 => -1.0 / self.beta,
496            // Unreachable: from_ir_with_poles rejects a bosonic pole at 0 for any
497            // other ypower, and neither the poles nor the kernel can be
498            // changed afterwards.
499            _ => panic!(
500                "DLR tau evaluation does not support kernel ypower = {}",
501                self.kernel_ypower
502            ),
503        }
504    }
505
506    fn zero_pole_matsubara_limit(&self) -> f64 {
507        match self.kernel_ypower {
508            // lim_{ω→0} w(β, ω) / (0 - ω) at n = 0 with w = tanh(βω/2) or ω
509            0 => -0.5 * self.beta,
510            1 => -1.0,
511            // Unreachable: from_ir_with_poles rejects a bosonic pole at 0 for any
512            // other ypower, and neither the poles nor the kernel can be
513            // changed afterwards.
514            _ => panic!(
515                "DLR Matsubara evaluation does not support kernel ypower = {}",
516                self.kernel_ypower
517            ),
518        }
519    }
520
521    // ========================================================================
522    // Public API (generic, user-friendly)
523    // ========================================================================
524
525    /// Convert IR coefficients to DLR (N-dimensional, generic over real/complex)
526    ///
527    /// # Type Parameters
528    /// * `T` - Element type (f64 or Complex<f64>)
529    ///
530    /// # Arguments
531    /// * `gl` - IR coefficients as N-D tensor
532    /// * `dim` - Dimension along which to transform
533    ///
534    /// # Returns
535    /// DLR coefficients as N-D tensor, with [`Basis::size`](crate::basis_trait::Basis::size)
536    /// (the number of poles) entries along `dim`. An empty batch (a zero
537    /// extent on another axis) gives an empty result.
538    ///
539    /// # Errors
540    ///
541    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `gl`
542    /// * [`Error::ShapeMismatch`] of the input if `gl` does not have
543    ///   [`Self::ir_basis_size`] entries along `dim`
544    /// * [`Error::DecompositionFailed`] if the SVD of the fitting matrix fails
545    ///   (its entries are finite, since the poles are)
546    pub fn from_ir_nd<T: FitScalar>(
547        &self,
548        backend: Option<&GemmBackendHandle>,
549        gl: &TypedTensor<T>,
550        dim: usize,
551    ) -> Result<TypedTensor<T>, Error> {
552        // An empty batch gives an empty result; the fit fails only if the
553        // SVD of the fitting matrix does.
554        self.require_ir()?.ir_to_dlr_nd(backend, gl, dim)
555    }
556
557    /// Convert DLR coefficients to IR (N-dimensional, generic over real/complex)
558    ///
559    /// # Type Parameters
560    /// * `T` - Element type (f64 or Complex<f64>)
561    ///
562    /// # Arguments
563    /// * `g_dlr` - DLR coefficients as N-D tensor
564    /// * `dim` - Dimension along which to transform
565    ///
566    /// # Returns
567    /// IR coefficients as N-D tensor, with [`Self::ir_basis_size`] entries
568    /// along `dim`. An empty batch gives an empty result.
569    ///
570    /// # Errors
571    ///
572    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `g_dlr`
573    /// * [`Error::ShapeMismatch`] of the input if `g_dlr` does not have
574    ///   [`Basis::size`](crate::basis_trait::Basis::size) (the number of
575    ///   poles) entries along `dim`
576    pub fn to_ir_nd<T: FitScalar>(
577        &self,
578        backend: Option<&GemmBackendHandle>,
579        g_dlr: &TypedTensor<T>,
580        dim: usize,
581    ) -> Result<TypedTensor<T>, Error> {
582        self.require_ir()?.dlr_to_ir_nd(backend, g_dlr, dim)
583    }
584
585    fn require_ir(&self) -> Result<&IrDlrTransform, Error> {
586        self.ir.as_ref().ok_or_else(|| Error::NotSupported {
587            what: "IR <-> DLR conversion of a DLR that was not built from an IR basis; \
588                   build an IrDlrTransform for the IR basis instead"
589                .to_string(),
590        })
591    }
592}
593
594impl<S> DiscreteLehmannRepresentation<S>
595where
596    S: StatisticsType + 'static,
597{
598    /// Imaginary-time interpolation nodes (sorted), one per pole.
599    pub fn tau_nodes(&self) -> &[f64] {
600        use crate::basis_trait::Basis;
601        self.tau_nodes.get_or_init(|| {
602            let taus: Vec<f64> = crate::dlr_id::tau_candidates(self.beta * self.wmax)
603                .iter()
604                .map(|t| self.beta * t.value())
605                .collect();
606            let mat = self
607                .evaluate_tau(&taus)
608                .expect("the candidate times lie in [0, beta]");
609            let rows = crate::dlr_id::select_rows(
610                mat.host_data().expect("an owned matrix is host-resident"),
611                taus.len(),
612                self.poles.len(),
613                self.poles.len(),
614            );
615            rows.into_iter().map(|i| taus[i]).collect()
616        })
617    }
618
619    /// Matsubara interpolation nodes as indices `n` (`ν = nπ/β`, sorted).
620    ///
621    /// With `positive_only`, nodes are chosen among `n >= 0` so that the
622    /// stacked real and imaginary parts determine the coefficients of a
623    /// Green's function with `G(-iν) = conj(G(iν))`.
624    pub fn matsubara_nodes(&self, positive_only: bool) -> &[i64] {
625        let cell = if positive_only {
626            &self.matsubara_nodes_positive
627        } else {
628            &self.matsubara_nodes
629        };
630        cell.get_or_init(|| self.select_matsubara_nodes(positive_only))
631    }
632
633    fn select_matsubara_nodes(&self, positive_only: bool) -> Vec<i64> {
634        use crate::basis_trait::Basis;
635        let zeta = match S::STATISTICS {
636            Statistics::Fermionic => 1,
637            Statistics::Bosonic => 0,
638        };
639        let ns = crate::dlr_id::matsubara_candidates(self.beta * self.wmax, zeta, positive_only);
640        let freqs: Vec<MatsubaraFreq<S>> = ns
641            .iter()
642            .map(|&n| MatsubaraFreq::new(n).expect("candidate parity matches statistics"))
643            .collect();
644        let mat = self
645            .evaluate_matsubara(&freqs)
646            .expect("evaluating the DLR functions at Matsubara frequencies cannot fail");
647        let data = mat.host_data().expect("an owned matrix is host-resident");
648        let (nf, r) = (freqs.len(), self.poles.len());
649        if !positive_only {
650            let rows = crate::dlr_id::select_rows(data, nf, r, r);
651            return rows.into_iter().map(|i| ns[i]).collect();
652        }
653        // Stack [Re; Im] so each frequency contributes two real rows.
654        let mut stacked = vec![0.0; 2 * nf * r];
655        for j in 0..r {
656            for i in 0..nf {
657                let z = data[i + nf * j];
658                stacked[i + 2 * nf * j] = z.re;
659                stacked[nf + i + 2 * nf * j] = z.im;
660            }
661        }
662        let mut out: Vec<i64> = crate::dlr_id::select_rows(&stacked, 2 * nf, r, r)
663            .into_iter()
664            .map(|i| ns[i % nf])
665            .collect();
666        out.sort_unstable();
667        out.dedup();
668        out
669    }
670}
671
672// ============================================================================
673// IR <-> DLR transform
674// ============================================================================
675
676/// Linear map between the coefficients of an IR basis and of a DLR on the
677/// same domain.
678///
679/// The DLR basis function of pole `ω_i` is expanded in the IR basis as
680/// `u_i = Σ_l T[l, i] U_l` with `T[l, i] = -s_l V_l(ω_i) (w_i / w^{IR}_i)`,
681/// where `w_i` and `w^{IR}_i` are the pole weights of the DLR and of the IR
682/// kernel. DLR -> IR applies `T`; IR -> DLR is its least-squares inverse.
683pub struct IrDlrTransform {
684    fitter: RealMatrixFitter,
685}
686
687impl IrDlrTransform {
688    /// The transform with the `ir_size x dlr_size` matrix `T` mapping DLR to
689    /// IR coefficients (see the type documentation). The IR crate builds it
690    /// from its basis.
691    #[doc(hidden)]
692    pub fn from_matrix(matrix: Mat<f64>) -> Self {
693        Self {
694            fitter: RealMatrixFitter::new(matrix),
695        }
696    }
697
698    /// IR basis size.
699    pub fn ir_size(&self) -> usize {
700        self.fitter.n_points()
701    }
702
703    /// Number of DLR poles.
704    pub fn dlr_size(&self) -> usize {
705        self.fitter.basis_size()
706    }
707
708    /// The `ir_size x dlr_size` matrix `T` mapping DLR to IR coefficients.
709    pub fn matrix(&self) -> &crate::Matrix<f64> {
710        self.fitter.matrix()
711    }
712
713    /// IR -> DLR along axis `dim` (least squares).
714    ///
715    /// # Errors
716    /// The errors of [`DiscreteLehmannRepresentation::from_ir_nd`].
717    pub fn ir_to_dlr_nd<T: FitScalar>(
718        &self,
719        backend: Option<&GemmBackendHandle>,
720        gl: &TypedTensor<T>,
721        dim: usize,
722    ) -> Result<TypedTensor<T>, Error> {
723        self.fitter.fit_nd(backend, gl, dim)
724    }
725
726    /// DLR -> IR along axis `dim`.
727    ///
728    /// # Errors
729    /// The errors of [`DiscreteLehmannRepresentation::to_ir_nd`].
730    pub fn dlr_to_ir_nd<T: FitScalar>(
731        &self,
732        backend: Option<&GemmBackendHandle>,
733        g_dlr: &TypedTensor<T>,
734        dim: usize,
735    ) -> Result<TypedTensor<T>, Error> {
736        self.fitter.evaluate_nd(backend, g_dlr, dim)
737    }
738}
739
740// ============================================================================
741// Basis trait implementation for DLR
742// ============================================================================
743
744impl<S> crate::basis_trait::Basis<S> for DiscreteLehmannRepresentation<S>
745where
746    S: StatisticsType + 'static,
747{
748    fn beta(&self) -> f64 {
749        self.beta
750    }
751
752    fn wmax(&self) -> f64 {
753        self.wmax
754    }
755
756    fn lambda(&self) -> f64 {
757        self.beta * self.wmax
758    }
759
760    fn size(&self) -> usize {
761        self.poles.len()
762    }
763
764    fn accuracy(&self) -> f64 {
765        self.accuracy
766    }
767
768    fn significance(&self) -> Vec<f64> {
769        // All poles are equally significant in DLR
770        vec![1.0; self.poles.len()]
771    }
772
773    fn svals(&self) -> Vec<f64> {
774        // All poles are equally significant in DLR (no singular value concept)
775        vec![1.0; self.poles.len()]
776    }
777
778    fn default_tau_sampling_points(&self) -> Result<Vec<f64>, Error> {
779        Ok(self.tau_nodes().to_vec())
780    }
781
782    fn default_matsubara_sampling_points(
783        &self,
784        positive_only: bool,
785    ) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error> {
786        self.matsubara_nodes(positive_only)
787            .iter()
788            .map(|&n| crate::freq::MatsubaraFreq::new(n))
789            .collect()
790    }
791
792    fn evaluate_tau(&self, tau: &[f64]) -> Result<crate::Matrix<f64>, Error> {
793        let n_poles = self.poles.len();
794        // Normalize every τ first: this rejects a τ outside [-β, β] and NaN
795        // for every pole, including the bosonic pole at 0, whose limit does
796        // not depend on τ.
797        let normalized = tau
798            .iter()
799            .map(|&t| normalize_tau::<S>(t, self.beta))
800            .collect::<Result<Vec<(f64, f64)>, Error>>()?;
801        if normalized.is_empty() {
802            // An empty set of points gives an empty matrix.
803            return Ok(Mat::<f64>::from_elem([0, n_poles], 0.0).into_typed());
804        }
805        Ok(Mat::<f64>::from_fn([normalized.len(), n_poles], |idx| {
806            let (tau_norm, sign) = normalized[idx[0]];
807            let pole = self.poles[idx[1]];
808            let pole_weight = self.pole_weights[idx[1]];
809            match S::STATISTICS {
810                Statistics::Fermionic => {
811                    sign * fermionic_single_pole_unchecked(tau_norm, pole, self.beta) * pole_weight
812                }
813                Statistics::Bosonic => {
814                    // The bosonic sign of normalize_tau is always 1.
815                    if pole == 0.0 {
816                        self.zero_pole_tau_limit()
817                    } else if pole > 0.0 {
818                        let denominator = -(-self.beta * pole).exp_m1();
819                        -(-tau_norm * pole).exp() * pole_weight / denominator
820                    } else {
821                        let denominator = -(self.beta * pole).exp_m1();
822                        (pole * (self.beta - tau_norm)).exp() * pole_weight / denominator
823                    }
824                }
825            }
826        })
827        .into_typed())
828    }
829
830    fn evaluate_matsubara(
831        &self,
832        freqs: &[crate::freq::MatsubaraFreq<S>],
833    ) -> Result<crate::Matrix<num_complex::Complex<f64>>, Error> {
834        use num_complex::Complex;
835
836        let n_points = freqs.len();
837        let n_poles = self.poles.len();
838        if n_points == 0 {
839            // See evaluate_tau.
840            return Ok(
841                Mat::<Complex<f64>>::from_elem([0, n_poles], Complex::new(0.0, 0.0)).into_typed(),
842            );
843        }
844
845        // Evaluate MatsubaraPoles basis functions
846        Ok(Mat::<Complex<f64>>::from_fn([n_points, n_poles], |idx| {
847            let freq = &freqs[idx[0]];
848            let pole = self.poles[idx[1]];
849            let pole_weight = self.pole_weights[idx[1]];
850
851            // iν = iπn/β, with n = freq.n() (odd for fermions, even for bosons)
852            let iv = freq.value_imaginary(self.beta);
853
854            // u_i(iν) = pole_weight / (iν - pole_i), where `pole_weight` is the
855            // regularizer w(β, ω_i) of the source kernel.
856            if S::STATISTICS == Statistics::Bosonic && pole == 0.0 {
857                if crate::freq::is_zero(freq) {
858                    Complex::new(self.zero_pole_matsubara_limit(), 0.0)
859                } else {
860                    Complex::new(0.0, 0.0)
861                }
862            } else {
863                Complex::new(pole_weight, 0.0) / (iv - Complex::new(pole, 0.0))
864            }
865        })
866        .into_typed())
867    }
868
869    fn evaluate_omega(&self, _omega: &[f64]) -> Result<crate::Matrix<f64>, Error> {
870        // TODO(#205): For the IR basis, evaluate_omega returns V_l(omega).
871        // For DLR, the "basis functions" in omega-space are single-pole
872        // functions (conceptually delta functions at the pole positions),
873        // which do not have a well-defined continuous representation on the
874        // real-frequency axis analogous to V_l(omega).  A proper
875        // implementation would require either:
876        //   (a) returning the IR basis's V_l(omega) (but DLR does not store
877        //       the IR basis), or
878        //   (b) defining an appropriate discretized representation for the
879        //       pole basis in omega-space.
880        // Until the semantics are clarified, this is NotSupported.
881        Err(Error::NotSupported {
882            what: "evaluate_omega of a DLR: its pole functions have no real-frequency \
883                   representation (#205); use the IR basis"
884                .to_string(),
885        })
886    }
887
888    fn default_omega_sampling_points(&self) -> Result<Vec<f64>, Error> {
889        // DLR poles ARE the omega sampling points
890        Ok(self.poles.clone())
891    }
892}
893
894#[cfg(test)]
895mod tests {
896    use super::*;
897    use crate::traits::{Bosonic, Fermionic};
898
899    /// Generic test for periodicity/anti-periodicity
900    fn test_periodicity_generic<S: StatisticsType>(expected_sign: f64, stat_name: &str) {
901        let beta = 1.0;
902        let omega = 5.0;
903
904        // Test periodicity by comparing G(τ) with G(τ-β)
905        // Since normalize_tau is restricted to [-β, β], we test:
906        // For τ ∈ (0, β]: compare G(τ) with G(τ-β)
907        // For fermions: G(τ) should equal -G(τ-β)
908        // For bosons: G(τ) should equal G(τ-β)
909        for tau in [0.1, 0.3, 0.7] {
910            let g_tau = gtau_single_pole::<S>(tau, omega, beta).unwrap();
911            let g_tau_minus_beta = gtau_single_pole::<S>(tau - beta, omega, beta).unwrap();
912
913            // For fermions: G(τ) = -G(τ-β) → G(τ-β) = -G(τ)
914            // For bosons: G(τ) = G(τ-β)
915            let expected = expected_sign * g_tau;
916
917            assert!(
918                (expected - g_tau_minus_beta).abs() < 1e-14,
919                "{} periodicity violated at τ={}: G(τ)={}, G(τ-β)={}, expected={}",
920                stat_name,
921                tau,
922                g_tau,
923                g_tau_minus_beta,
924                expected
925            );
926        }
927    }
928
929    #[test]
930    fn test_fermionic_antiperiodicity() {
931        // Fermions: G(τ+β) = -G(τ)
932        test_periodicity_generic::<Fermionic>(-1.0, "Fermionic");
933    }
934
935    #[test]
936    fn test_bosonic_periodicity() {
937        // Bosons: G(τ+β) = G(τ)
938        test_periodicity_generic::<Bosonic>(1.0, "Bosonic");
939    }
940
941    #[test]
942    fn test_generic_function_matches_specific() {
943        let beta = 1.0;
944        let omega = 5.0;
945        let tau = 0.5;
946
947        // Test that generic function matches specific functions
948        let g_f_specific = fermionic_single_pole(tau, omega, beta).unwrap();
949        let g_f_generic = gtau_single_pole::<Fermionic>(tau, omega, beta).unwrap();
950
951        let g_b_specific = bosonic_single_pole(tau, omega, beta).unwrap();
952        let g_b_generic = gtau_single_pole::<Bosonic>(tau, omega, beta).unwrap();
953
954        assert!(
955            (g_f_specific - g_f_generic).abs() < 1e-14,
956            "Fermionic: specific={}, generic={}",
957            g_f_specific,
958            g_f_generic
959        );
960        assert!(
961            (g_b_specific - g_b_generic).abs() < 1e-14,
962            "Bosonic: specific={}, generic={}",
963            g_b_specific,
964            g_b_generic
965        );
966    }
967}