use crate::error::{Error, require_finite, require_positive_finite};
use crate::numeric::CustomNumeric;
use crate::traits::{Statistics, StatisticsType};
use std::fmt::Debug;
pub use sparse_ir_sve::kernel::{
AbstractKernel, ExpandableKernel, ReducedKernel, SVEHints, SVEKernel, SymmetryType,
};
pub trait CentrosymmKernel: ReducedKernel {
fn lambda(&self) -> f64;
}
pub trait BasisKernel: ExpandableKernel + KernelProperties {
fn kernel_lambda(&self) -> f64;
}
impl<K> BasisKernel for K
where
K: CentrosymmKernel + KernelProperties + Clone + 'static,
{
fn kernel_lambda(&self) -> f64 {
CentrosymmKernel::lambda(self)
}
}
#[derive(Debug, Clone, Copy)]
pub struct LogisticKernel {
lambda: f64,
}
impl LogisticKernel {
pub fn new(lambda: f64) -> Result<Self, Error> {
require_positive_finite("lambda", lambda)?;
Ok(Self { lambda })
}
pub fn lambda(&self) -> f64 {
self.lambda
}
}
impl SVEKernel for LogisticKernel {
type SVEHintsType<T>
= LogisticSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
fn xmax(&self) -> f64 {
1.0
}
fn ymax(&self) -> f64 {
1.0
}
fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
{
LogisticSVEHints::new(*self, epsilon)
}
}
pub fn compute_logistic_kernel<T: CustomNumeric>(lambda: f64, x: T, y: T) -> T {
let x_plus: T = T::from_f64_unchecked(1.0) + x;
let x_minus: T = T::from_f64_unchecked(1.0) - x;
let u_plus: T = T::from_f64_unchecked(0.5) * x_plus;
let u_minus: T = T::from_f64_unchecked(0.5) * x_minus;
let v: T = T::from_f64_unchecked(lambda) * y;
let mabs_v: T = -v.abs();
let numerator: T = if v >= T::from_f64_unchecked(0.0) {
(u_plus * mabs_v).exp()
} else {
(u_minus * mabs_v).exp()
};
let denominator: T = T::from_f64_unchecked(1.0) + mabs_v.exp();
numerator / denominator
}
fn compute_logistic_kernel_reduced_odd<T: CustomNumeric>(lambda: f64, x: T, y: T) -> T {
let v_half: T = T::from_f64_unchecked(lambda * 0.5) * y;
let xy_small: bool = x * v_half < T::from_f64_unchecked(1.0);
let cosh_finite: bool = v_half < T::from_f64_unchecked(85.0);
if xy_small && cosh_finite {
-(v_half * x).sinh() / v_half.cosh()
} else {
let k_plus = compute_logistic_kernel(lambda, x, y);
let k_minus = compute_logistic_kernel(lambda, x, -y);
k_plus - k_minus
}
}
impl AbstractKernel for LogisticKernel {
fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
compute_logistic_kernel(self.lambda, x, y)
}
}
impl ReducedKernel for LogisticKernel {
fn compute_reduced<T: CustomNumeric + Copy + Debug>(
&self,
x: T,
y: T,
symmetry: SymmetryType,
) -> T {
match symmetry {
SymmetryType::Even => self.compute(x, y) + self.compute(x, -y),
SymmetryType::Odd => compute_logistic_kernel_reduced_odd(self.lambda, x, y),
}
}
}
impl CentrosymmKernel for LogisticKernel {
fn lambda(&self) -> f64 {
self.lambda
}
}
#[derive(Debug, Clone, Copy)]
pub struct LogisticKernelWindowed {
logistic: LogisticKernel,
ymin: f64,
ymax: f64,
}
impl LogisticKernelWindowed {
pub fn from_physical(beta: f64, omega_min: f64, omega_max: f64) -> Result<Self, Error> {
require_positive_finite("beta", beta)?;
require_finite("omega_min", omega_min)?;
require_finite("omega_max", omega_max)?;
if omega_min >= omega_max {
return Err(Error::InvalidParameter {
name: "omega_min",
value: format!("{omega_min:?}"),
reason: format!("must be less than omega_max = {omega_max:?}"),
});
}
let wmax = omega_max.abs().max(omega_min.abs());
let lambda = beta * wmax;
require_positive_finite("beta * max(|omega_min|, |omega_max|)", lambda)?;
Ok(Self {
logistic: LogisticKernel { lambda },
ymin: omega_min / wmax,
ymax: omega_max / wmax,
})
}
pub fn lambda(&self) -> f64 {
self.logistic.lambda
}
}
impl SVEKernel for LogisticKernelWindowed {
type SVEHintsType<T>
= LogisticWindowedSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
fn xmax(&self) -> f64 {
1.0
}
fn ymax(&self) -> f64 {
self.ymax
}
fn ymin(&self) -> f64 {
self.ymin
}
fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
{
LogisticWindowedSVEHints {
inner: LogisticSVEHints::new(self.logistic, epsilon),
ymin: self.ymin,
ymax: self.ymax,
}
}
}
impl AbstractKernel for LogisticKernelWindowed {
fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
self.logistic.compute(x, y)
}
}
impl ExpandableKernel for LogisticKernelWindowed {}
impl BasisKernel for LogisticKernelWindowed {
fn kernel_lambda(&self) -> f64 {
self.lambda()
}
}
#[derive(Debug, Clone)]
pub struct LogisticWindowedSVEHints<T> {
inner: LogisticSVEHints<T>,
ymin: f64,
ymax: f64,
}
impl<T> SVEHints<T> for LogisticWindowedSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric,
{
fn segments_x(&self) -> Vec<T> {
self.inner.segments_x()
}
fn segments_y(&self) -> Vec<T> {
let half = self.inner.half_segments_y();
let (ymin, ymax) = (
T::from_f64_unchecked(self.ymin),
T::from_f64_unchecked(self.ymax),
);
if self.ymin < 0.0 && 0.0 < self.ymax {
let negative = half
.iter()
.rev()
.filter(|&&s| s > T::zero())
.map(|&s| s * ymin);
negative.chain(half.iter().map(|&s| s * ymax)).collect()
} else {
let full = crate::sve::mirror_segments_to_full_domain(&half);
let inside = full.into_iter().filter(|&s| ymin < s && s < ymax);
std::iter::once(ymin)
.chain(inside)
.chain(std::iter::once(ymax))
.collect()
}
}
fn nsvals(&self) -> usize {
self.inner.nsvals()
}
fn ngauss(&self) -> usize {
self.inner.ngauss()
}
}
#[derive(Debug, Clone)]
pub struct LogisticSVEHints<T> {
kernel: LogisticKernel,
epsilon: f64,
_phantom: std::marker::PhantomData<T>,
}
impl<T> LogisticSVEHints<T>
where
T: Copy + Debug + Send + Sync,
{
pub fn new(kernel: LogisticKernel, epsilon: f64) -> Self {
Self {
kernel,
epsilon,
_phantom: std::marker::PhantomData,
}
}
}
impl<T> LogisticSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric,
{
pub(crate) fn half_segments_x(&self) -> Vec<T> {
let nzeros = std::cmp::max((15.0 * self.kernel.lambda().log10()).round() as usize, 1);
let mut temp = vec![0.0; nzeros];
for i in 0..nzeros {
temp[i] = 0.143 * i as f64;
}
let mut diffs = vec![0.0; nzeros];
for i in 0..nzeros {
diffs[i] = 1.0 / temp[i].cosh();
}
let mut zeros = vec![0.0; nzeros];
zeros[0] = diffs[0];
for i in 1..nzeros {
zeros[i] = zeros[i - 1] + diffs[i];
}
let last_zero = zeros[nzeros - 1];
for i in 0..nzeros {
zeros[i] /= last_zero;
}
let mut segments = Vec::with_capacity(nzeros + 1);
segments.push(<T as CustomNumeric>::from_f64_unchecked(0.0));
for i in 0..nzeros {
segments.push(<T as CustomNumeric>::from_f64_unchecked(zeros[i]));
}
segments.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
segments
}
pub(crate) fn half_segments_y(&self) -> Vec<T> {
let nzeros = std::cmp::max((20.0 * self.kernel.lambda().log10()).round() as usize, 2);
let mut diffs = vec![
0.01523, 0.03314, 0.04848, 0.05987, 0.06703, 0.07028, 0.07030, 0.06791, 0.06391,
0.05896, 0.05358, 0.04814, 0.04288, 0.03795, 0.03342, 0.02932, 0.02565, 0.02239,
0.01951, 0.01699,
];
if nzeros < diffs.len() {
diffs.truncate(nzeros);
}
for i in 20..nzeros {
let x = 0.141 * i as f64;
diffs.push(0.25 * (-x).exp());
}
let mut zeros = Vec::with_capacity(nzeros);
zeros.push(diffs[0]);
for i in 1..nzeros {
zeros.push(zeros[i - 1] + diffs[i]);
}
let last_zero = zeros[nzeros - 1];
for i in 0..nzeros {
zeros[i] /= last_zero;
}
zeros.pop();
let nzeros = zeros.len();
for i in 0..nzeros {
zeros[i] -= 1.0;
}
let mut segments: Vec<T> = Vec::new();
segments.push(<T as CustomNumeric>::from_f64_unchecked(1.0));
for i in 0..nzeros {
let abs_val = -zeros[i];
segments.push(<T as CustomNumeric>::from_f64_unchecked(abs_val));
}
if segments[segments.len() - 1].abs() > T::epsilon() {
segments.push(<T as CustomNumeric>::from_f64_unchecked(0.0));
}
segments.sort_by(|a, b| a.partial_cmp(b).unwrap());
segments
}
}
impl<T> SVEHints<T> for LogisticSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric,
{
fn segments_x(&self) -> Vec<T> {
crate::sve::mirror_segments_to_full_domain(&self.half_segments_x())
}
fn segments_y(&self) -> Vec<T> {
crate::sve::mirror_segments_to_full_domain(&self.half_segments_y())
}
fn nsvals(&self) -> usize {
let log10_lambda = self.kernel.lambda().log10().max(1.0);
((25.0 + log10_lambda) * log10_lambda).round() as usize
}
fn ngauss(&self) -> usize {
if self.epsilon >= 1e-8 { 10 } else { 16 }
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RegularizedBoseKernel {
pub(crate) lambda: f64,
}
impl RegularizedBoseKernel {
#[deprecated(
note = "use LogisticKernel, the default kernel for both statistics; RegularizedBoseKernel will be removed in a future release (https://github.com/SpM-lab/sparse-ir-rs/issues/273)"
)]
pub fn new(lambda: f64) -> Result<Self, Error> {
require_positive_finite("lambda", lambda)?;
Ok(Self { lambda })
}
pub fn lambda(&self) -> f64 {
self.lambda
}
fn compute_impl<T>(&self, x: T, y: T, x_plus: Option<T>, x_minus: Option<T>) -> T
where
T: CustomNumeric,
{
let lambda_t = T::from_f64_unchecked(self.lambda);
let half = T::from_f64_unchecked(0.5);
let inv_lambda = T::from_f64_unchecked(1.0) / lambda_t;
let u_plus = x_plus
.map(|xp| half * xp)
.unwrap_or_else(|| half * (T::from_f64_unchecked(1.0) + x));
let u_minus = x_minus
.map(|xm| half * xm)
.unwrap_or_else(|| half * (T::from_f64_unchecked(1.0) - x));
let v = lambda_t * y;
let absv = v.abs();
if absv.to_f64() < 2e-14 {
let term0 = inv_lambda;
let term1 = half * x * y;
return term0 - term1;
}
let enum_val = if v >= T::from_f64_unchecked(0.0) {
(-absv * u_plus).exp()
} else {
(-absv * u_minus).exp()
};
let denom = if absv.to_f64() >= 1e-200 {
let expm1_neg_absv = CustomNumeric::exp_m1(-absv);
absv / expm1_neg_absv
} else {
-T::from_f64_unchecked(1.0)
};
-inv_lambda * enum_val * denom
}
}
impl SVEKernel for RegularizedBoseKernel {
type SVEHintsType<T>
= RegularizedBoseSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
fn xmax(&self) -> f64 {
1.0
}
fn ymax(&self) -> f64 {
1.0
}
fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
{
RegularizedBoseSVEHints::new(*self, epsilon)
}
}
impl AbstractKernel for RegularizedBoseKernel {
fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
let x_plus = Some(T::from_f64_unchecked(1.0) + x);
let x_minus = Some(T::from_f64_unchecked(1.0) - x);
self.compute_impl(x, y, x_plus, x_minus)
}
}
impl ReducedKernel for RegularizedBoseKernel {
fn compute_reduced<T: CustomNumeric + Copy + Debug>(
&self,
x: T,
y: T,
symmetry: SymmetryType,
) -> T {
match symmetry {
SymmetryType::Even => self.compute(x, y) + self.compute(x, -y),
SymmetryType::Odd => {
let v_half = T::from_f64_unchecked(self.lambda * 0.5) * y;
let xv_half = x * v_half;
let xy_small = xv_half.to_f64().abs() < 1.0;
let sinh_finite = v_half.to_f64().abs() < 85.0 && v_half.to_f64().abs() > 1e-200;
if xy_small && sinh_finite {
-y * xv_half.sinh() / v_half.sinh()
} else {
self.compute(x, y) - self.compute(x, -y)
}
}
}
}
}
impl CentrosymmKernel for RegularizedBoseKernel {
fn lambda(&self) -> f64 {
self.lambda
}
}
#[derive(Debug, Clone)]
pub struct RegularizedBoseSVEHints<T> {
kernel: RegularizedBoseKernel,
epsilon: f64,
_phantom: std::marker::PhantomData<T>,
}
impl<T> RegularizedBoseSVEHints<T>
where
T: Copy + Debug + Send + Sync,
{
pub fn new(kernel: RegularizedBoseKernel, epsilon: f64) -> Self {
Self {
kernel,
epsilon,
_phantom: std::marker::PhantomData,
}
}
}
impl<T> RegularizedBoseSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
{
pub(crate) fn half_segments_x(&self) -> Vec<T> {
let nzeros = ((15.0 * self.kernel.lambda.log10()).round() as usize).max(15);
let mut temp = vec![0.0; nzeros];
for i in 0..nzeros {
temp[i] = 0.18 * i as f64;
}
let mut diffs = vec![0.0; nzeros];
for i in 0..nzeros {
diffs[i] = 1.0 / temp[i].cosh();
}
let mut zeros = vec![0.0; nzeros];
zeros[0] = diffs[0];
for i in 1..nzeros {
zeros[i] = zeros[i - 1] + diffs[i];
}
let last_zero = zeros[nzeros - 1];
for i in 0..nzeros {
zeros[i] /= last_zero;
}
let mut segments = Vec::with_capacity(nzeros + 1);
segments.push(T::from_f64_unchecked(0.0));
for i in 0..nzeros {
segments.push(T::from_f64_unchecked(zeros[i]));
}
segments.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
segments
}
pub(crate) fn half_segments_y(&self) -> Vec<T> {
let nzeros = ((20.0 * self.kernel.lambda.log10()).round() as usize).max(20);
let mut diffs = vec![0.0; nzeros];
for j in 0..nzeros {
let j_f64 = j as f64;
let exponent = 0.0337 * j_f64 * (j_f64 + 1.0).ln();
diffs[j] = 0.12 / exponent.exp();
}
let mut zeros = vec![0.0; nzeros];
zeros[0] = diffs[0];
for i in 1..nzeros {
zeros[i] = zeros[i - 1] + diffs[i];
}
let last_zero = zeros[nzeros - 1];
for i in 0..nzeros {
zeros[i] /= last_zero;
}
zeros.pop();
let mut segments = Vec::with_capacity(zeros.len() + 2);
segments.push(T::from_f64_unchecked(0.0));
for &z in zeros.iter().rev() {
segments.push(T::from_f64_unchecked(1.0 - z));
}
segments.push(T::from_f64_unchecked(1.0));
segments
}
}
impl<T> SVEHints<T> for RegularizedBoseSVEHints<T>
where
T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
{
fn segments_x(&self) -> Vec<T> {
crate::sve::mirror_segments_to_full_domain(&self.half_segments_x())
}
fn segments_y(&self) -> Vec<T> {
crate::sve::mirror_segments_to_full_domain(&self.half_segments_y())
}
fn nsvals(&self) -> usize {
let log10_lambda = self.kernel.lambda.log10().max(1.0);
(28.0 * log10_lambda).round() as usize
}
fn ngauss(&self) -> usize {
if self.epsilon >= 1e-8 { 10 } else { 16 }
}
}
pub trait KernelProperties: SVEKernel {
fn ypower(&self) -> i32;
fn conv_radius(&self) -> f64;
fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64;
}
fn logistic_regularizer<S: StatisticsType + 'static>(beta: f64, omega: f64) -> f64 {
match S::STATISTICS {
Statistics::Fermionic => {
1.0
}
Statistics::Bosonic => {
(0.5 * beta * omega).tanh()
}
}
}
impl KernelProperties for LogisticKernel {
fn ypower(&self) -> i32 {
0 }
fn conv_radius(&self) -> f64 {
40.0 * self.lambda()
}
fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64 {
logistic_regularizer::<S>(beta, omega)
}
}
impl KernelProperties for LogisticKernelWindowed {
fn ypower(&self) -> i32 {
0
}
fn conv_radius(&self) -> f64 {
40.0 * self.lambda()
}
fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64 {
logistic_regularizer::<S>(beta, omega)
}
}
impl KernelProperties for RegularizedBoseKernel {
fn ypower(&self) -> i32 {
1 }
fn conv_radius(&self) -> f64 {
40.0 * self.lambda()
}
fn regularizer<S: StatisticsType + 'static>(&self, _beta: f64, omega: f64) -> f64 {
match S::STATISTICS {
Statistics::Fermionic => {
panic!("RegularizedBoseKernel does not support fermionic functions");
}
Statistics::Bosonic => {
omega
}
}
}
}
#[cfg(test)]
#[path = "kernel_tests.rs"]
mod tests;