Skip to main content

sparse_ir_basis/
ir_dlr.rs

1//! Discrete Lehmann representations built from an IR basis
2//!
3//! The DLR itself needs no IR basis (see
4//! [`DiscreteLehmannRepresentation::new`]). This module connects the two:
5//! [`IrBasis`] is a [`Basis`] with a kernel (the IR basis
6//! [`FiniteTempBasis`]), [`DlrFromIr`] builds a DLR whose poles come from such
7//! a basis, and [`IrBasis::dlr_transform`] the linear map between the
8//! coefficients of the basis and of any DLR on the same domain.
9
10use crate::basis::FiniteTempBasis;
11use crate::basis_trait::Basis;
12use crate::dlr::{DiscreteLehmannRepresentation, IrDlrTransform};
13use crate::error::Error;
14use crate::kernel::{BasisKernel, KernelProperties, SVEKernel};
15use crate::matrix::Mat;
16use crate::traits::{Statistics, StatisticsType};
17
18/// A basis with a kernel: the IR basis [`FiniteTempBasis`]
19///
20/// The kernel supplies the pole weights `w(β, ω)` of a DLR built from the
21/// basis. A DLR is not an `IrBasis`, so no DLR can be built from a DLR.
22pub trait IrBasis<S: StatisticsType>: Basis<S> {
23    /// Kernel type
24    type Kernel: KernelProperties;
25
26    /// The kernel the basis was built from
27    fn kernel(&self) -> &Self::Kernel;
28
29    /// The linear map between the coefficients of this basis and of `dlr`.
30    ///
31    /// # Errors
32    /// * [`Error::KernelStatisticsMismatch`] if the kernel of this basis does not
33    ///   support the statistics
34    /// * [`Error::InvalidParameter`] named `basis` if the β of this basis differs from that
35    ///   of `dlr`, or its kernel weight vanishes at a pole where the DLR
36    ///   weight does not
37    /// * [`Error::OutOfDomain`] named `poles` for a pole of `dlr` outside
38    ///   the frequency window [ωmin, ωmax] of this basis
39    fn dlr_transform(&self, dlr: &DiscreteLehmannRepresentation<S>) -> Result<IrDlrTransform, Error>
40    where
41        S: 'static,
42    {
43        if S::STATISTICS == Statistics::Fermionic && self.kernel().ypower() == 1 {
44            return Err(Error::KernelStatisticsMismatch);
45        }
46        let (beta, wmax) = (Basis::beta(self), Basis::wmax(self));
47        let rel = |a: f64, b: f64| (a - b).abs() <= 1e-12 * a.abs().max(b.abs());
48        if !rel(beta, dlr.beta()) {
49            return Err(Error::InvalidParameter {
50                name: "basis",
51                value: format!("beta = {beta:?}"),
52                reason: format!("must equal beta = {:?} of the DLR", dlr.beta()),
53            });
54        }
55        // The frequency window [ωmin, ωmax] = wmax [ymin, ymax] of this basis
56        let domain = (self.kernel().ymin() * wmax, self.kernel().ymax() * wmax);
57        if let Some(&pole) = dlr
58            .poles()
59            .iter()
60            .find(|p| !(domain.0..=domain.1).contains(*p))
61        {
62            return Err(Error::OutOfDomain {
63                name: "poles",
64                value: pole,
65                domain,
66            });
67        }
68        let mut ratio = Vec::with_capacity(dlr.poles().len());
69        for (&pole, &w) in dlr.poles().iter().zip(dlr.pole_weights()) {
70            let wir = self.kernel().regularizer::<S>(beta, pole);
71            if w == wir {
72                ratio.push(1.0);
73            } else if wir == 0.0 {
74                return Err(Error::InvalidParameter {
75                    name: "basis",
76                    value: format!("kernel weight 0 at pole {pole:?}"),
77                    reason: "must not vanish where the DLR weight does not".to_string(),
78                });
79            } else {
80                ratio.push(w / wir);
81            }
82        }
83        let v_at_poles =
84            crate::sampling::mat_from_matrix(&Basis::evaluate_omega(self, dlr.poles())?)?;
85        let s = Basis::svals(self);
86        let fitmat = Mat::<f64>::from_fn([Basis::size(self), dlr.poles().len()], |idx| {
87            let (l, i) = (idx[0], idx[1]);
88            -s[l] * v_at_poles[[i, l]] * ratio[i]
89        });
90        Ok(IrDlrTransform::from_matrix(fitmat))
91    }
92}
93
94impl<K, S> IrBasis<S> for FiniteTempBasis<K, S>
95where
96    K: BasisKernel,
97    S: StatisticsType + 'static,
98{
99    type Kernel = K;
100
101    fn kernel(&self) -> &K {
102        FiniteTempBasis::kernel(self)
103    }
104}
105
106/// Constructors of a [`DiscreteLehmannRepresentation`] from an IR basis
107///
108/// The returned DLR carries the [`IrDlrTransform`] of its source basis, so
109/// [`DiscreteLehmannRepresentation::from_ir_nd`] and
110/// [`DiscreteLehmannRepresentation::to_ir_nd`] work on it.
111pub trait DlrFromIr<S: StatisticsType>: Sized {
112    /// Create a DLR from an IR basis with custom poles
113    ///
114    /// The tau-domain pole basis is built from the logistic representation, while
115    /// kernel-specific regularizers are preserved for compatible kernels.
116    ///
117    /// # Arguments
118    /// * `basis` - The IR basis to construct DLR from
119    /// * `poles` - Pole positions on the real-frequency axis, in the
120    ///   frequency window [ωmin, ωmax] of `basis` ([-ωmax, ωmax] for a
121    ///   symmetric kernel)
122    ///
123    /// # Errors
124    /// * [`Error::KernelStatisticsMismatch`] if the kernel does not support
125    ///   the requested statistics (e.g. `RegularizedBoseKernel` with fermionic
126    ///   statistics)
127    /// * [`Error::EmptyInput`] if `poles` is empty
128    /// * [`Error::NonFiniteInput`] if a pole is NaN or infinite, and
129    ///   [`Error::OutOfDomain`] if a pole is outside [ωmin, ωmax] of `basis`,
130    ///   both named `poles`, for the first such pole
131    /// * [`Error::NotSupported`] for a bosonic pole at 0 if the kernel has a
132    ///   `ypower` other than 0 or 1 (the DLR knows the limit at 0 for those
133    ///   only)
134    ///
135    /// Duplicate poles are accepted. They make [`DiscreteLehmannRepresentation::from_ir_nd`]
136    /// ill-conditioned: the coefficients of equal poles are not unique,
137    /// although the round trip through [`DiscreteLehmannRepresentation::to_ir_nd`] still recovers the
138    /// IR coefficients.
139    fn from_ir_with_poles<B: IrBasis<S>>(basis: &B, poles: Vec<f64>) -> Result<Self, Error>;
140
141    /// Create a DLR from an IR basis with its default pole locations
142    ///
143    /// Uses the default omega sampling points from the basis.
144    ///
145    /// # Arguments
146    /// * `basis` - The IR basis to construct DLR from
147    ///
148    /// # Errors
149    /// * [`Error::InsufficientDefaultPoles`] if the basis has fewer default
150    ///   poles than functions. This can happen with certain kernel types
151    ///   (e.g. `RegularizedBoseKernel`) due to numerical precision limitations
152    ///   in root finding.
153    /// * [`Error::KernelStatisticsMismatch`] as in [`Self::from_ir_with_poles`]
154    /// * [`Error::NotSupported`] as in [`Self::from_ir_with_poles`]: for a default
155    ///   pole at 0 of a bosonic basis whose kernel has a `ypower` other than
156    ///   0 or 1
157    /// * The errors of
158    ///   [`Basis::default_omega_sampling_points`]
159    ///   (NotSupported for an SVE with too few singular functions)
160    fn from_ir<B: IrBasis<S>>(basis: &B) -> Result<Self, Error>;
161}
162
163impl<S: StatisticsType + 'static> DlrFromIr<S> for DiscreteLehmannRepresentation<S> {
164    fn from_ir_with_poles<B: IrBasis<S>>(basis: &B, poles: Vec<f64>) -> Result<Self, Error> {
165        // RegularizedBoseKernel (ypower == 1) is meaningful only for bosonic
166        // statistics; its regularizer panics for fermionic input. Reject the
167        // combination before computing anything.
168        if S::STATISTICS == Statistics::Fermionic && basis.kernel().ypower() == 1 {
169            return Err(Error::KernelStatisticsMismatch);
170        }
171        // Without poles the fitting matrix has no columns and the DLR has no
172        // functions.
173        if poles.is_empty() {
174            return Err(Error::EmptyInput { name: "poles" });
175        }
176
177        let beta = Basis::beta(basis);
178        let wmax = Basis::wmax(basis);
179        let accuracy = Basis::accuracy(basis);
180        let kernel_ypower = basis.kernel().ypower();
181
182        // Each pole must be finite and in [ωmin, ωmax] = wmax [ymin, ymax],
183        // the domain of V_l. evaluate_omega below checks the domain of the
184        // basis again.
185        let domain = (basis.kernel().ymin() * wmax, basis.kernel().ymax() * wmax);
186        for (i, &pole) in poles.iter().enumerate() {
187            if !pole.is_finite() {
188                return Err(Error::NonFiniteInput {
189                    name: "poles",
190                    index: vec![i],
191                    value: pole,
192                });
193            }
194            if !(domain.0..=domain.1).contains(&pole) {
195                return Err(Error::OutOfDomain {
196                    name: "poles",
197                    value: pole,
198                    domain,
199                });
200            }
201        }
202        // A bosonic pole at 0 is evaluated through its finite limit, which is
203        // known for ypower 0 (regularizer tanh(βω/2)) and 1 (regularizer ω)
204        // only; see zero_pole_tau_limit.
205        if S::STATISTICS == Statistics::Bosonic
206            && !(0..=1).contains(&kernel_ypower)
207            && poles.contains(&0.0)
208        {
209            return Err(Error::NotSupported {
210                what: format!(
211                    "a bosonic DLR pole at 0 for a kernel with ypower = {kernel_ypower}: \
212                     its limit is known for ypower 0 and 1 only"
213                ),
214            });
215        }
216
217        // Compute fitting matrix: fitmat = -s · V(poles)
218        // This transforms DLR coefficients to IR coefficients
219        let v_at_poles = crate::sampling::mat_from_matrix(&Basis::evaluate_omega(basis, &poles)?)?; // shape: [n_poles, basis_size]
220        let s = Basis::svals(basis); // Non-normalized singular values (same as C++)
221
222        let basis_size = Basis::size(basis);
223        let n_poles = poles.len();
224
225        // fitmat[l, i] = -s[l] * V_l(pole[i])
226        // C++: fitmat = (-A_array * s_array.replicate(1, A.cols())).matrix()
227        let fitmat = Mat::<f64>::from_fn([basis_size, n_poles], |idx| {
228            let l = idx[0];
229            let i = idx[1];
230            -s[l] * v_at_poles[[i, l]]
231        });
232
233        let ir = IrDlrTransform::from_matrix(fitmat);
234
235        let regularizers: Vec<f64> = poles
236            .iter()
237            .map(|&pole| basis.kernel().regularizer::<S>(beta, pole))
238            .collect();
239
240        Ok(DiscreteLehmannRepresentation::from_parts(
241            beta,
242            wmax,
243            accuracy,
244            poles,
245            regularizers,
246            kernel_ypower,
247            Some(ir),
248        ))
249    }
250
251    fn from_ir<B: IrBasis<S>>(basis: &B) -> Result<Self, Error> {
252        let poles = Basis::default_omega_sampling_points(basis)?;
253        let basis_size = Basis::size(basis);
254        if basis_size > poles.len() {
255            return Err(Error::InsufficientDefaultPoles {
256                basis_size,
257                n_poles: poles.len(),
258            });
259        }
260        Self::from_ir_with_poles(basis, poles)
261    }
262}