use std::sync::{Arc, OnceLock};
use crate::error::{
Error, require_accuracy, require_nonzero_size, require_positive_finite, require_threshold,
};
use crate::kernel::{BasisKernel, KernelProperties, LogisticKernel};
use crate::poly::{PiecewiseLegendrePoly, PiecewiseLegendrePolyVector};
use crate::polyfourier::PiecewiseLegendreFTVector;
use crate::sve::{SVEResult, TworkType, compute_sve};
use crate::traits::{Bosonic, Fermionic, StatisticsType};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Statistics {
Fermionic,
Bosonic,
}
#[derive(Clone)]
pub struct FiniteTempBasis<K, S>
where
K: BasisKernel,
S: StatisticsType,
{
kernel: K,
sve_result: Arc<SVEResult>,
accuracy: f64,
beta: f64,
u: Arc<PiecewiseLegendrePolyVector>,
v: Arc<PiecewiseLegendrePolyVector>,
s: Vec<f64>,
uhat: Arc<PiecewiseLegendreFTVector<S>>,
uhat_full: Arc<PiecewiseLegendreFTVector<S>>,
default_matsubara_points: [OnceLock<Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>>; 2],
_phantom: std::marker::PhantomData<S>,
}
fn check_kernel_domain<K: KernelProperties>(
kernel: &K,
sve_result: &SVEResult,
) -> Result<(), Error> {
let domain =
|funcs: &PiecewiseLegendrePolyVector| funcs.polys().first().map(|p| (p.xmin(), p.xmax()));
let (Some(u), Some(v)) = (domain(sve_result.u()), domain(sve_result.v())) else {
return Err(Error::EmptyInput { name: "sve_result" });
};
let (x, y) = (
(kernel.xmin(), kernel.xmax()),
(kernel.ymin(), kernel.ymax()),
);
if x != (-1.0, 1.0) {
return Err(Error::InvalidParameter {
name: "kernel",
value: format!("x domain [{:?}, {:?}]", x.0, x.1),
reason: "a basis needs the x domain [-1, 1], mapped to tau in [0, beta]".to_string(),
});
}
let matches = |(lo, hi): (f64, f64), (min, max): (f64, f64)| {
(lo - min).abs() <= 1e-12 && (hi - max).abs() <= 1e-12
};
if matches(u, x) && matches(v, y) {
Ok(())
} else {
Err(Error::InvalidParameter {
name: "sve_result",
value: format!("an SVE on [{:?}, {:?}] × [{:?}, {:?}]", u.0, u.1, v.0, v.1),
reason: format!(
"must be an SVE on the kernel's domain [{:?}, {:?}] × [{:?}, {:?}]",
x.0, x.1, y.0, y.1
),
})
}
}
fn snapped_knots_and_widths(
poly: &PiecewiseLegendrePoly,
min: f64,
max: f64,
) -> (Vec<f64>, Vec<f64>) {
let mut knots = poly.knots().to_vec();
let mut widths = poly.delta_x().to_vec();
let last = knots.len() - 1;
if knots[0] != min {
knots[0] = min;
widths[0] = knots[1] - knots[0];
}
if knots[last] != max {
knots[last] = max;
widths[last - 1] = knots[last] - knots[last - 1];
}
(knots, widths)
}
impl<K, S> FiniteTempBasis<K, S>
where
K: BasisKernel,
S: StatisticsType,
{
pub fn kernel(&self) -> &K {
&self.kernel
}
pub fn sve_result(&self) -> &Arc<SVEResult> {
&self.sve_result
}
pub fn accuracy(&self) -> f64 {
self.accuracy
}
pub fn beta(&self) -> f64 {
self.beta
}
pub fn u(&self) -> &Arc<PiecewiseLegendrePolyVector> {
&self.u
}
pub fn v(&self) -> &Arc<PiecewiseLegendrePolyVector> {
&self.v
}
pub fn s(&self) -> &[f64] {
&self.s
}
pub fn uhat(&self) -> &Arc<PiecewiseLegendreFTVector<S>> {
&self.uhat
}
pub fn uhat_full(&self) -> &Arc<PiecewiseLegendreFTVector<S>> {
&self.uhat_full
}
pub fn wmax(&self) -> f64 {
self.kernel.kernel_lambda() / self.beta
}
pub fn default_matsubara_sampling_points_i64(
&self,
positive_only: bool,
) -> Result<Vec<i64>, Error>
where
S: 'static,
{
Ok(self
.default_matsubara_sampling_points(positive_only)?
.into_iter()
.map(|f| f.n())
.collect())
}
pub fn default_matsubara_sampling_points_i64_with_mitigate(
&self,
positive_only: bool,
mitigate: bool,
n_points: usize,
) -> Result<Vec<i64>, Error>
where
S: 'static,
{
let freqs = if !mitigate && n_points == self.size() {
self.default_matsubara_sampling_points(positive_only)?
} else {
default_matsubara_sampling_points_from_uhat(
&self.uhat_full,
n_points,
mitigate,
positive_only,
)?
};
Ok(freqs.into_iter().map(|f| f.n()).collect())
}
pub fn matsubara_sampling_points(
&self,
positive_only: bool,
mitigate: bool,
method: MatsubaraPointMethod,
) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
where
S: 'static,
{
matsubara_sampling_points_from_uhat(
&self.uhat_full,
self.size(),
mitigate,
positive_only,
method,
)
}
pub fn new(
kernel: K,
beta: f64,
epsilon: Option<f64>,
max_size: Option<usize>,
) -> Result<Self, Error> {
require_positive_finite("beta", beta)?;
require_accuracy("epsilon", epsilon)?;
require_nonzero_size("max_size", max_size)?;
let sve_result = compute_sve(
kernel.clone(),
epsilon,
None, None, TworkType::Auto,
)?;
Self::from_sve_result(kernel, beta, sve_result, epsilon, max_size)
}
pub fn from_sve_result(
kernel: K,
beta: f64,
sve_result: SVEResult,
epsilon: Option<f64>,
max_size: Option<usize>,
) -> Result<Self, Error> {
require_positive_finite("beta", beta)?;
require_threshold("epsilon", epsilon)?;
require_nonzero_size("max_size", max_size)?;
check_kernel_domain(&kernel, &sve_result)?;
let part = sve_result.truncate(epsilon, max_size)?;
let (u_sve, s_sve, v_sve) = (part.u().clone(), part.s(), part.v().clone());
let accuracy = if sve_result.s().len() > s_sve.len() {
sve_result.s()[s_sve.len()] / sve_result.s()[0]
} else {
sve_result.s()[sve_result.s().len() - 1] / sve_result.s()[0]
};
let wmax = kernel.kernel_lambda() / beta;
let (x_knots, x_widths) =
snapped_knots_and_widths(&u_sve.polys()[0], kernel.xmin(), kernel.xmax());
let u_knots: Vec<f64> = x_knots.iter().map(|&x| beta / 2.0 * (x + 1.0)).collect();
let u_delta_x: Vec<f64> = x_widths.iter().map(|&dx| beta / 2.0 * dx).collect();
let u_symm: Vec<i32> = u_sve.polys().iter().map(|p| p.symm()).collect();
let u = u_sve.rescale_domain(u_knots, Some(u_delta_x), Some(u_symm))?;
let (y_knots, y_widths) =
snapped_knots_and_widths(&v_sve.polys()[0], kernel.ymin(), kernel.ymax());
let v_knots: Vec<f64> = y_knots.iter().map(|&y| wmax * y).collect();
let v_delta_x: Vec<f64> = y_widths.iter().map(|&dy| wmax * dy).collect();
let v_symm: Vec<i32> = v_sve.polys().iter().map(|p| p.symm()).collect();
let v = v_sve.rescale_domain(v_knots, Some(v_delta_x), Some(v_symm))?;
let ypower = kernel.ypower();
let scale_factor = (beta / 2.0 * wmax).sqrt() * wmax.powi(ypower);
let s: Vec<f64> = s_sve.iter().map(|&x| scale_factor * x).collect();
let uhat_base_full = sve_result.u().scale_data(beta.sqrt());
let conv_rad = kernel.conv_radius();
let stat_marker = S::default();
let uhat_full = PiecewiseLegendreFTVector::<S>::from_poly_vector(
&uhat_base_full,
stat_marker,
Some(conv_rad),
)?;
let uhat_polyvec: Vec<_> = uhat_full.polyvec.iter().take(s.len()).cloned().collect();
let uhat = PiecewiseLegendreFTVector::from_vector(uhat_polyvec);
Ok(Self {
kernel,
sve_result: Arc::new(sve_result),
accuracy,
beta,
u: Arc::new(u),
v: Arc::new(v),
s,
uhat: Arc::new(uhat),
uhat_full: Arc::new(uhat_full),
default_matsubara_points: [OnceLock::new(), OnceLock::new()],
_phantom: std::marker::PhantomData,
})
}
pub fn size(&self) -> usize {
self.s.len()
}
pub fn lambda(&self) -> f64 {
self.kernel.kernel_lambda()
}
pub fn omega_max(&self) -> f64 {
self.kernel.ymax() * self.wmax()
}
pub fn omega_min(&self) -> f64 {
self.kernel.ymin() * self.wmax()
}
pub fn significance(&self) -> Vec<f64> {
let s0 = self.s[0];
self.s.iter().map(|&s| s / s0).collect()
}
pub fn default_tau_sampling_points(&self) -> Result<Vec<f64>, Error> {
let points = self.default_tau_sampling_points_size_requested(self.size())?;
let basis_size = self.size();
if points.len() < basis_size {
debug_warn!(
"Number of tau sampling points ({}) is less than basis size ({}). \
Basis parameters: beta={}, wmax={}, epsilon={:.2e}",
points.len(),
basis_size,
self.beta,
self.wmax(),
self.accuracy()
);
}
Ok(points)
}
pub fn default_tau_sampling_points_size_requested(
&self,
size_requested: usize,
) -> Result<Vec<f64>, Error> {
let x_domain = (self.kernel.xmin(), self.kernel.xmax());
let x = default_sampling_points(self.sve_result.u(), "u", x_domain, size_requested)?;
let half_beta = self.beta / 2.0;
let mut smpl_taus: Vec<f64> = x
.iter()
.map(|&xi| {
let tau = half_beta * (xi + 1.0);
if tau <= half_beta {
tau
} else {
tau - self.beta
}
})
.collect();
smpl_taus.sort_by(|a, b| a.partial_cmp(b).unwrap());
Ok(smpl_taus)
}
pub fn default_matsubara_sampling_points(
&self,
positive_only: bool,
) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
where
S: 'static,
{
let points = self.default_matsubara_points[usize::from(positive_only)]
.get_or_init(|| {
default_matsubara_sampling_points_from_uhat(
&self.uhat_full,
self.size(),
false,
positive_only,
)
})
.clone()?;
let basis_size = self.size();
let effective_points = if positive_only {
2 * points.len()
} else {
points.len()
};
if effective_points < basis_size {
debug_warn!(
"Number of Matsubara sampling points ({}{}) is less than basis size ({}). \
Basis parameters: beta={}, wmax={}, epsilon={:.2e}",
points.len(),
if positive_only { " × 2" } else { "" },
basis_size,
self.beta,
self.wmax(),
self.accuracy()
);
}
Ok(points)
}
pub fn default_omega_sampling_points(&self) -> Result<Vec<f64>, Error> {
let sz = self.size();
let y_domain = (self.kernel.ymin(), self.kernel.ymax());
let y = default_sampling_points(self.sve_result.v(), "v", y_domain, sz)?;
let wmax = self.wmax();
let omega_points: Vec<f64> = y.into_iter().map(|yi| wmax * yi).collect();
Ok(omega_points)
}
}
impl<K, S> crate::basis_trait::Basis<S> for FiniteTempBasis<K, S>
where
K: BasisKernel,
S: StatisticsType + 'static,
{
fn beta(&self) -> f64 {
self.beta
}
fn wmax(&self) -> f64 {
self.kernel.kernel_lambda() / self.beta
}
fn lambda(&self) -> f64 {
self.kernel.kernel_lambda()
}
fn size(&self) -> usize {
self.size()
}
fn accuracy(&self) -> f64 {
self.accuracy
}
fn significance(&self) -> Vec<f64> {
if let Some(&first_s) = self.s.first() {
self.s.iter().map(|&s| s / first_s).collect()
} else {
vec![]
}
}
fn svals(&self) -> Vec<f64> {
self.s.clone()
}
fn default_tau_sampling_points(&self) -> Result<Vec<f64>, Error> {
self.default_tau_sampling_points()
}
fn default_matsubara_sampling_points(
&self,
positive_only: bool,
) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error> {
self.default_matsubara_sampling_points(positive_only)
}
fn evaluate_tau(&self, tau: &[f64]) -> Result<crate::Matrix<f64>, Error> {
use crate::matrix::{Mat, MatTyped};
use crate::taufuncs::normalize_tau;
let basis_size = self.size();
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, basis_size], 0.0).into_typed());
}
Ok(Mat::<f64>::from_fn([normalized.len(), basis_size], |idx| {
let (tau_norm, sign) = normalized[idx[0]];
sign * self.u[idx[1]].evaluate(tau_norm)
})
.into_typed())
}
fn evaluate_matsubara(
&self,
freqs: &[crate::freq::MatsubaraFreq<S>],
) -> Result<crate::Matrix<num_complex::Complex<f64>>, Error> {
use crate::matrix::{Mat, MatTyped};
use num_complex::Complex;
let n_points = freqs.len();
let basis_size = self.size();
if n_points == 0 {
return Ok(
Mat::<Complex<f64>>::from_elem([0, basis_size], Complex::new(0.0, 0.0))
.into_typed(),
);
}
let rows = self.uhat.evaluate_at_many(freqs);
Ok(
Mat::<Complex<f64>>::from_fn([n_points, basis_size], |idx| rows[idx[0]][idx[1]])
.into_typed(),
)
}
fn evaluate_omega(&self, omega: &[f64]) -> Result<crate::Matrix<f64>, Error> {
use crate::matrix::{Mat, MatTyped};
let basis_size = self.size();
let domain = (self.v.xmin(), self.v.xmax());
if let Some(&w) = omega.iter().find(|&&w| !(w >= domain.0 && w <= domain.1)) {
return Err(Error::OutOfDomain {
name: "omega",
value: w,
domain,
});
}
if omega.is_empty() {
return Ok(Mat::<f64>::from_elem([0, basis_size], 0.0).into_typed());
}
Ok(Mat::<f64>::from_fn([omega.len(), basis_size], |idx| {
self.v[idx[1]].evaluate(omega[idx[0]])
})
.into_typed())
}
fn default_omega_sampling_points(&self) -> Result<Vec<f64>, Error> {
self.default_omega_sampling_points()
}
}
pub type FermionicBasis = FiniteTempBasis<LogisticKernel, Fermionic>;
pub type BosonicBasis = FiniteTempBasis<LogisticKernel, Bosonic>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MatsubaraPointMethod {
SignChanges,
PairSelection,
}
pub fn default_matsubara_sampling_points_from_uhat<S>(
uhat_full: &PiecewiseLegendreFTVector<S>,
l: usize,
mitigate: bool,
positive_only: bool,
) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
where
S: StatisticsType + 'static,
{
let method = if uhat_full.get_polys().iter().any(|u| u.poly.symm() == 0) {
MatsubaraPointMethod::PairSelection
} else {
MatsubaraPointMethod::SignChanges
};
matsubara_sampling_points_from_uhat(uhat_full, l, mitigate, positive_only, method)
}
pub fn matsubara_sampling_points_from_uhat<S>(
uhat_full: &PiecewiseLegendreFTVector<S>,
l: usize,
mitigate: bool,
positive_only: bool,
method: MatsubaraPointMethod,
) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
where
S: StatisticsType + 'static,
{
if uhat_full.is_empty() {
return Err(Error::EmptyInput { name: "uhat_full" });
}
match method {
MatsubaraPointMethod::SignChanges => {
sign_change_sampling_points(uhat_full, l, mitigate, positive_only)
}
MatsubaraPointMethod::PairSelection => {
crate::polyfourier::pair_sampling_points(uhat_full, l, positive_only, mitigate)
}
}
}
fn sign_change_sampling_points<S>(
uhat_full: &PiecewiseLegendreFTVector<S>,
l: usize,
mitigate: bool,
positive_only: bool,
) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error>
where
S: StatisticsType + 'static,
{
use crate::freq::MatsubaraFreq;
use crate::polyfourier::{find_extrema, sign_changes};
use std::collections::BTreeSet;
let mut l_requested = l;
if S::STATISTICS == crate::traits::Statistics::Fermionic && l_requested % 2 != 0 {
l_requested += 1;
} else if S::STATISTICS == crate::traits::Statistics::Bosonic && l_requested % 2 == 0 {
l_requested += 1;
}
let mut omega_n = if l_requested < uhat_full.len() {
sign_changes(&uhat_full[l_requested], positive_only)?
} else {
find_extrema(&uhat_full[uhat_full.len() - 1], positive_only)?
};
if S::STATISTICS == crate::traits::Statistics::Bosonic {
omega_n.push(MatsubaraFreq::<S>::new(0).unwrap());
}
let omega_n_set: BTreeSet<MatsubaraFreq<S>> = omega_n.into_iter().collect();
let mut omega_n: Vec<MatsubaraFreq<S>> = omega_n_set.into_iter().collect();
let expected_size = if positive_only {
l_requested.div_ceil(2)
} else {
l_requested
};
if omega_n.len() != expected_size {
debug_warn!(
"Requested {} sampling frequencies for basis size L = {}, but got {}.",
expected_size,
l,
omega_n.len()
);
}
if mitigate {
fence_matsubara_sampling(&mut omega_n, positive_only);
}
Ok(omega_n)
}
fn fence_matsubara_sampling<S: StatisticsType + 'static>(
omega_n: &mut Vec<crate::freq::MatsubaraFreq<S>>,
positive_only: bool,
) {
use crate::freq::{BosonicFreq, MatsubaraFreq};
if omega_n.is_empty() {
return;
}
let mut outer_frequencies = Vec::new();
if positive_only {
outer_frequencies.push(omega_n[omega_n.len() - 1]);
} else {
outer_frequencies.push(omega_n[0]);
outer_frequencies.push(omega_n[omega_n.len() - 1]);
}
for wn_outer in outer_frequencies {
let outer_val = wn_outer.n();
let mut diff_val = 2 * (0.025 * outer_val as f64).round() as i64;
if diff_val == 0 {
diff_val = 2;
}
let wn_diff = BosonicFreq::new(diff_val).unwrap().n();
let sign_val = if outer_val > 0 {
1
} else if outer_val < 0 {
-1
} else {
0
};
let original_size = omega_n.len();
if original_size >= 20 {
let new_n = outer_val - sign_val * wn_diff;
if let Ok(new_freq) = MatsubaraFreq::<S>::new(new_n) {
omega_n.push(new_freq);
}
}
if original_size >= 42 {
let new_n = outer_val + sign_val * wn_diff;
if let Ok(new_freq) = MatsubaraFreq::<S>::new(new_n) {
omega_n.push(new_freq);
}
}
}
let omega_n_set: std::collections::BTreeSet<MatsubaraFreq<S>> = omega_n.drain(..).collect();
*omega_n = omega_n_set.into_iter().collect();
}
pub(crate) fn default_sampling_points(
u: &PiecewiseLegendrePolyVector,
name: &'static str,
domain: (f64, f64),
l: usize,
) -> Result<Vec<f64>, Error> {
if (u.xmin() - domain.0).abs() > 1e-10 || (u.xmax() - domain.1).abs() > 1e-10 {
return Err(Error::InvalidParameter {
name,
value: format!("functions on [{:?}, {:?}]", u.xmin(), u.xmax()),
reason: format!(
"must be the unscaled functions of an SVE, on [{:?}, {:?}]",
domain.0, domain.1
),
});
}
let x0 = if l < u.len() {
u[l].roots()
} else {
let poly = u.last();
let poly_deriv = poly.deriv(1);
let maxima = poly_deriv.roots();
let (Some(&first), Some(&last)) = (maxima.first(), maxima.last()) else {
return Err(Error::NotSupported {
what: format!(
"default sampling points for {l} basis functions: the last singular \
function (l = {}) has no extrema to stand in for the roots of the \
missing function l = {l} (an SVE truncated to too few functions)",
poly.l()
),
});
};
let left = (first + poly.xmin()) / 2.0;
let right = (last + poly.xmax()) / 2.0;
let mut x0_vec = Vec::with_capacity(maxima.len() + 2);
x0_vec.push(left);
x0_vec.extend_from_slice(&maxima);
x0_vec.push(right);
x0_vec
};
if x0.len() != l {
debug_warn!(
"Expecting to get {} sampling points for corresponding basis function, \
instead got {}. This may happen if not enough precision is left in the polynomial.",
l,
x0.len()
);
}
Ok(x0)
}
#[cfg(test)]
#[path = "basis_tests.rs"]
mod basis_tests;