use crate::error::{Error, require_finite, require_positive_finite};
use crate::fitters::FitScalar;
use crate::fitters::RealMatrixFitter;
use crate::freq::MatsubaraFreq;
use crate::gemm::GemmBackendHandle;
use crate::matrix::{Mat, MatTyped};
use crate::taufuncs::normalize_tau;
use crate::traits::{Statistics, StatisticsType};
use num_complex::Complex;
use std::marker::PhantomData;
use std::sync::OnceLock;
use tenferro_tensor::TypedTensor;
pub fn gtau_single_pole<S: StatisticsType>(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
match S::STATISTICS {
Statistics::Fermionic => fermionic_single_pole(tau, omega, beta),
Statistics::Bosonic => bosonic_single_pole(tau, omega, beta),
}
}
pub fn fermionic_single_pole(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
use crate::traits::Fermionic;
let (tau_normalized, sign) = normalize_tau::<Fermionic>(tau, beta)?;
require_finite("omega", omega)?;
Ok(sign * fermionic_single_pole_unchecked(tau_normalized, omega, beta))
}
pub(crate) fn fermionic_single_pole_unchecked(tau_normalized: f64, omega: f64, beta: f64) -> f64 {
if omega >= 0.0 {
-(-omega * tau_normalized).exp() / (1.0 + (-beta * omega).exp())
} else {
-(omega * (beta - tau_normalized)).exp() / (1.0 + (beta * omega).exp())
}
}
pub fn bosonic_single_pole(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
use crate::traits::Bosonic;
let tau_normalized = normalize_tau::<Bosonic>(tau, beta)?.0;
require_finite("omega", omega)?;
if omega >= 0.0 {
let denominator = -(-beta * omega).exp_m1();
Ok(-(-omega * tau_normalized).exp() / denominator)
} else {
let denominator = -(beta * omega).exp_m1();
Ok((omega * (beta - tau_normalized)).exp() / denominator)
}
}
pub fn giwn_single_pole<S: StatisticsType>(
matsubara_freq: &MatsubaraFreq<S>,
omega: f64,
beta: f64,
) -> Result<Complex<f64>, Error> {
require_positive_finite("beta", beta)?;
require_finite("omega", omega)?;
let wn = matsubara_freq.value(beta);
let denominator = Complex::new(0.0, 1.0) * wn - Complex::new(omega, 0.0);
Ok(Complex::new(1.0, 0.0) / denominator)
}
pub struct DiscreteLehmannRepresentation<S>
where
S: StatisticsType,
{
poles: Vec<f64>,
beta: f64,
wmax: f64,
kernel_ypower: i32,
accuracy: f64,
regularizers: Vec<f64>,
pole_weights: Vec<f64>,
ir: Option<IrDlrTransform>,
tau_nodes: OnceLock<Vec<f64>>,
matsubara_nodes: OnceLock<Vec<i64>>,
matsubara_nodes_positive: OnceLock<Vec<i64>>,
_phantom: PhantomData<S>,
}
fn logistic_regularizer<S: StatisticsType>(beta: f64, omega: f64) -> f64 {
match S::STATISTICS {
Statistics::Fermionic => 1.0,
Statistics::Bosonic => (0.5 * beta * omega).tanh(),
}
}
#[derive(Debug, Clone)]
pub struct DlrBuilder<S: StatisticsType> {
beta: f64,
wmax: f64,
accuracy: f64,
max_size: Option<usize>,
_phantom: PhantomData<S>,
}
impl<S: StatisticsType + 'static> DlrBuilder<S> {
pub const DEFAULT_ACCURACY: f64 = 1e-14;
pub fn new(beta: f64, wmax: f64) -> Self {
Self {
beta,
wmax,
accuracy: Self::DEFAULT_ACCURACY,
max_size: None,
_phantom: PhantomData,
}
}
pub fn accuracy(mut self, accuracy: f64) -> Self {
self.accuracy = accuracy;
self
}
pub fn max_size(mut self, max_size: usize) -> Self {
self.max_size = Some(max_size);
self
}
pub fn build(self) -> Result<DiscreteLehmannRepresentation<S>, Error> {
require_positive_finite("beta", self.beta)?;
require_positive_finite("wmax", self.wmax)?;
crate::error::require_accuracy("accuracy", Some(self.accuracy))?;
crate::error::require_nonzero_size("max_size", self.max_size)?;
let lambda = self.beta * self.wmax;
let poles: Vec<f64> = crate::dlr_id::select_poles(lambda, self.accuracy, self.max_size)
.into_iter()
.map(|w| w / self.beta)
.collect();
let regularizers = poles
.iter()
.map(|&pole| logistic_regularizer::<S>(self.beta, pole))
.collect();
Ok(DiscreteLehmannRepresentation::from_parts(
self.beta,
self.wmax,
self.accuracy,
poles,
regularizers,
0,
None,
))
}
}
impl<S> DiscreteLehmannRepresentation<S>
where
S: StatisticsType,
{
pub fn kernel_ypower(&self) -> i32 {
self.kernel_ypower
}
pub fn pole_weights(&self) -> &[f64] {
&self.pole_weights
}
pub fn poles(&self) -> &[f64] {
&self.poles
}
pub fn regularizers(&self) -> &[f64] {
&self.regularizers
}
pub fn ir_basis_size(&self) -> Option<usize> {
self.ir.as_ref().map(IrDlrTransform::ir_size)
}
pub fn ir_transform(&self) -> Option<&IrDlrTransform> {
self.ir.as_ref()
}
pub fn new(beta: f64, wmax: f64, accuracy: f64) -> Result<Self, Error>
where
S: 'static,
{
DlrBuilder::new(beta, wmax).accuracy(accuracy).build()
}
#[doc(hidden)]
pub fn from_parts(
beta: f64,
wmax: f64,
accuracy: f64,
poles: Vec<f64>,
regularizers: Vec<f64>,
kernel_ypower: i32,
ir: Option<IrDlrTransform>,
) -> Self {
let pole_weights = regularizers.clone();
Self {
poles,
beta,
wmax,
kernel_ypower,
accuracy,
regularizers,
pole_weights,
ir,
tau_nodes: OnceLock::new(),
matsubara_nodes: OnceLock::new(),
matsubara_nodes_positive: OnceLock::new(),
_phantom: PhantomData,
}
}
fn zero_pole_tau_limit(&self) -> f64 {
match self.kernel_ypower {
0 => -0.5,
1 => -1.0 / self.beta,
_ => panic!(
"DLR tau evaluation does not support kernel ypower = {}",
self.kernel_ypower
),
}
}
fn zero_pole_matsubara_limit(&self) -> f64 {
match self.kernel_ypower {
0 => -0.5 * self.beta,
1 => -1.0,
_ => panic!(
"DLR Matsubara evaluation does not support kernel ypower = {}",
self.kernel_ypower
),
}
}
pub fn from_ir_nd<T: FitScalar>(
&self,
backend: Option<&GemmBackendHandle>,
gl: &TypedTensor<T>,
dim: usize,
) -> Result<TypedTensor<T>, Error> {
self.require_ir()?.ir_to_dlr_nd(backend, gl, dim)
}
pub fn to_ir_nd<T: FitScalar>(
&self,
backend: Option<&GemmBackendHandle>,
g_dlr: &TypedTensor<T>,
dim: usize,
) -> Result<TypedTensor<T>, Error> {
self.require_ir()?.dlr_to_ir_nd(backend, g_dlr, dim)
}
fn require_ir(&self) -> Result<&IrDlrTransform, Error> {
self.ir.as_ref().ok_or_else(|| Error::NotSupported {
what: "IR <-> DLR conversion of a DLR that was not built from an IR basis; \
build an IrDlrTransform for the IR basis instead"
.to_string(),
})
}
}
impl<S> DiscreteLehmannRepresentation<S>
where
S: StatisticsType + 'static,
{
pub fn tau_nodes(&self) -> &[f64] {
use crate::basis_trait::Basis;
self.tau_nodes.get_or_init(|| {
let taus: Vec<f64> = crate::dlr_id::tau_candidates(self.beta * self.wmax)
.iter()
.map(|t| self.beta * t.value())
.collect();
let mat = self
.evaluate_tau(&taus)
.expect("the candidate times lie in [0, beta]");
let rows = crate::dlr_id::select_rows(
mat.host_data().expect("an owned matrix is host-resident"),
taus.len(),
self.poles.len(),
self.poles.len(),
);
rows.into_iter().map(|i| taus[i]).collect()
})
}
pub fn matsubara_nodes(&self, positive_only: bool) -> &[i64] {
let cell = if positive_only {
&self.matsubara_nodes_positive
} else {
&self.matsubara_nodes
};
cell.get_or_init(|| self.select_matsubara_nodes(positive_only))
}
fn select_matsubara_nodes(&self, positive_only: bool) -> Vec<i64> {
use crate::basis_trait::Basis;
let zeta = match S::STATISTICS {
Statistics::Fermionic => 1,
Statistics::Bosonic => 0,
};
let ns = crate::dlr_id::matsubara_candidates(self.beta * self.wmax, zeta, positive_only);
let freqs: Vec<MatsubaraFreq<S>> = ns
.iter()
.map(|&n| MatsubaraFreq::new(n).expect("candidate parity matches statistics"))
.collect();
let mat = self
.evaluate_matsubara(&freqs)
.expect("evaluating the DLR functions at Matsubara frequencies cannot fail");
let data = mat.host_data().expect("an owned matrix is host-resident");
let (nf, r) = (freqs.len(), self.poles.len());
if !positive_only {
let rows = crate::dlr_id::select_rows(data, nf, r, r);
return rows.into_iter().map(|i| ns[i]).collect();
}
let mut stacked = vec![0.0; 2 * nf * r];
for j in 0..r {
for i in 0..nf {
let z = data[i + nf * j];
stacked[i + 2 * nf * j] = z.re;
stacked[nf + i + 2 * nf * j] = z.im;
}
}
let mut out: Vec<i64> = crate::dlr_id::select_rows(&stacked, 2 * nf, r, r)
.into_iter()
.map(|i| ns[i % nf])
.collect();
out.sort_unstable();
out.dedup();
out
}
}
pub struct IrDlrTransform {
fitter: RealMatrixFitter,
}
impl IrDlrTransform {
#[doc(hidden)]
pub fn from_matrix(matrix: Mat<f64>) -> Self {
Self {
fitter: RealMatrixFitter::new(matrix),
}
}
pub fn ir_size(&self) -> usize {
self.fitter.n_points()
}
pub fn dlr_size(&self) -> usize {
self.fitter.basis_size()
}
pub fn matrix(&self) -> &crate::Matrix<f64> {
self.fitter.matrix()
}
pub fn ir_to_dlr_nd<T: FitScalar>(
&self,
backend: Option<&GemmBackendHandle>,
gl: &TypedTensor<T>,
dim: usize,
) -> Result<TypedTensor<T>, Error> {
self.fitter.fit_nd(backend, gl, dim)
}
pub fn dlr_to_ir_nd<T: FitScalar>(
&self,
backend: Option<&GemmBackendHandle>,
g_dlr: &TypedTensor<T>,
dim: usize,
) -> Result<TypedTensor<T>, Error> {
self.fitter.evaluate_nd(backend, g_dlr, dim)
}
}
impl<S> crate::basis_trait::Basis<S> for DiscreteLehmannRepresentation<S>
where
S: StatisticsType + 'static,
{
fn beta(&self) -> f64 {
self.beta
}
fn wmax(&self) -> f64 {
self.wmax
}
fn lambda(&self) -> f64 {
self.beta * self.wmax
}
fn size(&self) -> usize {
self.poles.len()
}
fn accuracy(&self) -> f64 {
self.accuracy
}
fn significance(&self) -> Vec<f64> {
vec![1.0; self.poles.len()]
}
fn svals(&self) -> Vec<f64> {
vec![1.0; self.poles.len()]
}
fn default_tau_sampling_points(&self) -> Result<Vec<f64>, Error> {
Ok(self.tau_nodes().to_vec())
}
fn default_matsubara_sampling_points(
&self,
positive_only: bool,
) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error> {
self.matsubara_nodes(positive_only)
.iter()
.map(|&n| crate::freq::MatsubaraFreq::new(n))
.collect()
}
fn evaluate_tau(&self, tau: &[f64]) -> Result<crate::Matrix<f64>, Error> {
let n_poles = self.poles.len();
let normalized = tau
.iter()
.map(|&t| normalize_tau::<S>(t, self.beta))
.collect::<Result<Vec<(f64, f64)>, Error>>()?;
if normalized.is_empty() {
return Ok(Mat::<f64>::from_elem([0, n_poles], 0.0).into_typed());
}
Ok(Mat::<f64>::from_fn([normalized.len(), n_poles], |idx| {
let (tau_norm, sign) = normalized[idx[0]];
let pole = self.poles[idx[1]];
let pole_weight = self.pole_weights[idx[1]];
match S::STATISTICS {
Statistics::Fermionic => {
sign * fermionic_single_pole_unchecked(tau_norm, pole, self.beta) * pole_weight
}
Statistics::Bosonic => {
if pole == 0.0 {
self.zero_pole_tau_limit()
} else if pole > 0.0 {
let denominator = -(-self.beta * pole).exp_m1();
-(-tau_norm * pole).exp() * pole_weight / denominator
} else {
let denominator = -(self.beta * pole).exp_m1();
(pole * (self.beta - tau_norm)).exp() * pole_weight / denominator
}
}
}
})
.into_typed())
}
fn evaluate_matsubara(
&self,
freqs: &[crate::freq::MatsubaraFreq<S>],
) -> Result<crate::Matrix<num_complex::Complex<f64>>, Error> {
use num_complex::Complex;
let n_points = freqs.len();
let n_poles = self.poles.len();
if n_points == 0 {
return Ok(
Mat::<Complex<f64>>::from_elem([0, n_poles], Complex::new(0.0, 0.0)).into_typed(),
);
}
Ok(Mat::<Complex<f64>>::from_fn([n_points, n_poles], |idx| {
let freq = &freqs[idx[0]];
let pole = self.poles[idx[1]];
let pole_weight = self.pole_weights[idx[1]];
let iv = freq.value_imaginary(self.beta);
if S::STATISTICS == Statistics::Bosonic && pole == 0.0 {
if crate::freq::is_zero(freq) {
Complex::new(self.zero_pole_matsubara_limit(), 0.0)
} else {
Complex::new(0.0, 0.0)
}
} else {
Complex::new(pole_weight, 0.0) / (iv - Complex::new(pole, 0.0))
}
})
.into_typed())
}
fn evaluate_omega(&self, _omega: &[f64]) -> Result<crate::Matrix<f64>, Error> {
Err(Error::NotSupported {
what: "evaluate_omega of a DLR: its pole functions have no real-frequency \
representation (#205); use the IR basis"
.to_string(),
})
}
fn default_omega_sampling_points(&self) -> Result<Vec<f64>, Error> {
Ok(self.poles.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::{Bosonic, Fermionic};
fn test_periodicity_generic<S: StatisticsType>(expected_sign: f64, stat_name: &str) {
let beta = 1.0;
let omega = 5.0;
for tau in [0.1, 0.3, 0.7] {
let g_tau = gtau_single_pole::<S>(tau, omega, beta).unwrap();
let g_tau_minus_beta = gtau_single_pole::<S>(tau - beta, omega, beta).unwrap();
let expected = expected_sign * g_tau;
assert!(
(expected - g_tau_minus_beta).abs() < 1e-14,
"{} periodicity violated at τ={}: G(τ)={}, G(τ-β)={}, expected={}",
stat_name,
tau,
g_tau,
g_tau_minus_beta,
expected
);
}
}
#[test]
fn test_fermionic_antiperiodicity() {
test_periodicity_generic::<Fermionic>(-1.0, "Fermionic");
}
#[test]
fn test_bosonic_periodicity() {
test_periodicity_generic::<Bosonic>(1.0, "Bosonic");
}
#[test]
fn test_generic_function_matches_specific() {
let beta = 1.0;
let omega = 5.0;
let tau = 0.5;
let g_f_specific = fermionic_single_pole(tau, omega, beta).unwrap();
let g_f_generic = gtau_single_pole::<Fermionic>(tau, omega, beta).unwrap();
let g_b_specific = bosonic_single_pole(tau, omega, beta).unwrap();
let g_b_generic = gtau_single_pole::<Bosonic>(tau, omega, beta).unwrap();
assert!(
(g_f_specific - g_f_generic).abs() < 1e-14,
"Fermionic: specific={}, generic={}",
g_f_specific,
g_f_generic
);
assert!(
(g_b_specific - g_b_generic).abs() < 1e-14,
"Bosonic: specific={}, generic={}",
g_b_specific,
g_b_generic
);
}
}