Skip to main content

sparse_ir_basis/
kernel.rs

1//! Kernel implementations for SparseIR
2//!
3//! This module provides kernel implementations for analytical continuation in quantum many-body physics.
4//! The kernels are used in Fredholm integral equations of the first kind.
5//!
6//! u(x) = integral of K(x, y) v(y) dy
7//!
8//! where x ∈ [xmin, xmax] and y ∈ [ymin, ymax].
9//!
10//! In general, the kernel is applied to a scaled spectral function rho'(y) as:
11//!
12//! integral of K(x, y) rho'(y) dy,
13//!
14//! where ρ'(y) = ρ(y)/w(y) and w is the kernel's regularizer (see
15//! [`KernelProperties::regularizer`]): it transforms the original spectral
16//! function ρ(y) into the scaled version ρ'(y) used in the integral equation.
17//!
18//! The traits of a kernel's values and of its SVE come from `sparse-ir-sve`,
19//! re-exported here; [`KernelProperties`], [`CentrosymmKernel`] and
20//! [`BasisKernel`] add the physical properties.
21
22use crate::error::{Error, require_finite, require_positive_finite};
23use crate::numeric::CustomNumeric;
24use crate::traits::{Statistics, StatisticsType};
25use std::fmt::Debug;
26
27pub use sparse_ir_sve::kernel::{
28    AbstractKernel, ExpandableKernel, ReducedKernel, SVEHints, SVEKernel, SymmetryType,
29};
30
31/// Trait for centrosymmetric kernels
32///
33/// Centrosymmetric kernels satisfy K(x, y) = K(-x, -y) on a symmetric domain
34/// and can be decomposed into even and odd components for efficient
35/// computation ([`ReducedKernel::compute_reduced`]).
36pub trait CentrosymmKernel: ReducedKernel {
37    /// Get the cutoff parameter Λ (lambda)
38    fn lambda(&self) -> f64;
39}
40
41/// Kernel of a finite-temperature basis: the kernels that
42/// [`FiniteTempBasis`] accepts
43///
44/// Implemented for every [`CentrosymmKernel`], whose SVE is
45/// block-diagonalized into the even and odd reduced kernels, and for
46/// [`LogisticKernelWindowed`]. Other kernels implement
47/// [`BasisKernel::kernel_lambda`] and [`ExpandableKernel`] (no methods);
48/// their SVE is taken over the full domain `[xmin, xmax] × [ymin, ymax]` and
49/// their singular functions have no definite parity.
50///
51/// [`FiniteTempBasis`]: crate::basis::FiniteTempBasis
52pub trait BasisKernel: ExpandableKernel + KernelProperties {
53    /// The cutoff parameter Λ = β·wmax ([`CentrosymmKernel::lambda`] for a
54    /// centrosymmetric kernel; named apart from it so that both traits can
55    /// be in scope)
56    fn kernel_lambda(&self) -> f64;
57}
58
59impl<K> BasisKernel for K
60where
61    K: CentrosymmKernel + KernelProperties + Clone + 'static,
62{
63    fn kernel_lambda(&self) -> f64 {
64        CentrosymmKernel::lambda(self)
65    }
66}
67
68/// Logistic kernel for fermionic and bosonic analytical continuation
69///
70/// For bosons the spectral function is divided by the regularizer tanh(βω/2).
71///
72/// This kernel implements K(x, y) = exp(-Λy(x + 1)/2)/(1 + exp(-Λy))
73/// where x ∈ [-1, 1] and y ∈ [-1, 1]
74#[derive(Debug, Clone, Copy)]
75pub struct LogisticKernel {
76    lambda: f64,
77}
78
79impl LogisticKernel {
80    /// Create a new logistic kernel with the given cutoff parameter
81    ///
82    /// # Arguments
83    /// * `lambda` - Kernel cutoff Λ = β ωmax, positive and finite. The SVE
84    ///   grid, and the memory it needs, grows with Λ.
85    ///
86    /// # Errors
87    /// [`Error::InvalidParameter`] if `lambda` is not positive and finite
88    pub fn new(lambda: f64) -> Result<Self, Error> {
89        require_positive_finite("lambda", lambda)?;
90        Ok(Self { lambda })
91    }
92
93    /// Get the cutoff parameter
94    pub fn lambda(&self) -> f64 {
95        self.lambda
96    }
97}
98
99impl SVEKernel for LogisticKernel {
100    type SVEHintsType<T>
101        = LogisticSVEHints<T>
102    where
103        T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
104
105    fn xmax(&self) -> f64 {
106        1.0
107    }
108    fn ymax(&self) -> f64 {
109        1.0
110    }
111
112    fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
113    where
114        T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
115    {
116        LogisticSVEHints::new(*self, epsilon)
117    }
118}
119
120pub fn compute_logistic_kernel<T: CustomNumeric>(lambda: f64, x: T, y: T) -> T {
121    let x_plus: T = T::from_f64_unchecked(1.0) + x;
122    let x_minus: T = T::from_f64_unchecked(1.0) - x;
123
124    let u_plus: T = T::from_f64_unchecked(0.5) * x_plus;
125    let u_minus: T = T::from_f64_unchecked(0.5) * x_minus;
126    let v: T = T::from_f64_unchecked(lambda) * y;
127
128    let mabs_v: T = -v.abs();
129    let numerator: T = if v >= T::from_f64_unchecked(0.0) {
130        (u_plus * mabs_v).exp()
131    } else {
132        (u_minus * mabs_v).exp()
133    };
134    let denominator: T = T::from_f64_unchecked(1.0) + mabs_v.exp();
135    numerator / denominator
136}
137
138fn compute_logistic_kernel_reduced_odd<T: CustomNumeric>(lambda: f64, x: T, y: T) -> T {
139    // For x * y around 0, antisymmetrization introduces cancellation, which
140    // reduces the relative precision. To combat this, we replace the
141    // values with the explicit form
142    let v_half: T = T::from_f64_unchecked(lambda * 0.5) * y;
143    // Use direct comparison to match C++ implementation (avoid precision loss from to_f64())
144    let xy_small: bool = x * v_half < T::from_f64_unchecked(1.0);
145    let cosh_finite: bool = v_half < T::from_f64_unchecked(85.0);
146    if xy_small && cosh_finite {
147        -(v_half * x).sinh() / v_half.cosh()
148    } else {
149        let k_plus = compute_logistic_kernel(lambda, x, y);
150        let k_minus = compute_logistic_kernel(lambda, x, -y);
151        k_plus - k_minus
152    }
153}
154
155impl AbstractKernel for LogisticKernel {
156    fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
157        compute_logistic_kernel(self.lambda, x, y)
158    }
159}
160
161impl ReducedKernel for LogisticKernel {
162    fn compute_reduced<T: CustomNumeric + Copy + Debug>(
163        &self,
164        x: T,
165        y: T,
166        symmetry: SymmetryType,
167    ) -> T {
168        match symmetry {
169            SymmetryType::Even => self.compute(x, y) + self.compute(x, -y),
170            SymmetryType::Odd => compute_logistic_kernel_reduced_odd(self.lambda, x, y),
171        }
172    }
173}
174
175impl CentrosymmKernel for LogisticKernel {
176    fn lambda(&self) -> f64 {
177        self.lambda
178    }
179}
180
181/// Logistic kernel restricted to an asymmetric frequency window
182///
183/// The kernel formula is that of [`LogisticKernel`]; the non-centrosymmetry
184/// comes solely from restricting the y (= ω/wmax) domain to `[ymin, ymax]`
185/// with `ymin < ymax` and `max(|ymin|, |ymax|) == 1`, so that
186/// Λ = β·wmax with wmax = max(|ωmin|, |ωmax|). The window need not contain
187/// 0: a one-sided window such as `[0, ωmax]` is accepted. Its SVE goes through the
188/// full-domain strategy, and its singular functions have no definite parity.
189#[derive(Debug, Clone, Copy)]
190pub struct LogisticKernelWindowed {
191    /// The kernel on the symmetric domain, whose formula this one shares
192    logistic: LogisticKernel,
193    ymin: f64,
194    ymax: f64,
195}
196
197impl LogisticKernelWindowed {
198    /// Create the kernel for inverse temperature `beta` and the frequency
199    /// window `[omega_min, omega_max]`
200    ///
201    /// # Errors
202    ///
203    /// [`Error::InvalidParameter`] if `beta` is not positive and finite, or
204    /// `omega_min` and `omega_max` are not finite with `omega_min < omega_max`
205    pub fn from_physical(beta: f64, omega_min: f64, omega_max: f64) -> Result<Self, Error> {
206        require_positive_finite("beta", beta)?;
207        require_finite("omega_min", omega_min)?;
208        require_finite("omega_max", omega_max)?;
209        if omega_min >= omega_max {
210            return Err(Error::InvalidParameter {
211                name: "omega_min",
212                value: format!("{omega_min:?}"),
213                reason: format!("must be less than omega_max = {omega_max:?}"),
214            });
215        }
216        let wmax = omega_max.abs().max(omega_min.abs());
217        let lambda = beta * wmax;
218        require_positive_finite("beta * max(|omega_min|, |omega_max|)", lambda)?;
219        Ok(Self {
220            logistic: LogisticKernel { lambda },
221            ymin: omega_min / wmax,
222            ymax: omega_max / wmax,
223        })
224    }
225
226    /// Get the cutoff parameter Λ = β·wmax with wmax = max(|ωmin|, |ωmax|)
227    pub fn lambda(&self) -> f64 {
228        self.logistic.lambda
229    }
230}
231
232impl SVEKernel for LogisticKernelWindowed {
233    type SVEHintsType<T>
234        = LogisticWindowedSVEHints<T>
235    where
236        T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
237
238    fn xmax(&self) -> f64 {
239        1.0
240    }
241
242    fn ymax(&self) -> f64 {
243        self.ymax
244    }
245
246    fn ymin(&self) -> f64 {
247        self.ymin
248    }
249
250    fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
251    where
252        T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
253    {
254        LogisticWindowedSVEHints {
255            inner: LogisticSVEHints::new(self.logistic, epsilon),
256            ymin: self.ymin,
257            ymax: self.ymax,
258        }
259    }
260}
261
262impl AbstractKernel for LogisticKernelWindowed {
263    fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
264        self.logistic.compute(x, y)
265    }
266}
267
268impl ExpandableKernel for LogisticKernelWindowed {}
269
270impl BasisKernel for LogisticKernelWindowed {
271    fn kernel_lambda(&self) -> f64 {
272        self.lambda()
273    }
274}
275
276/// SVE hints for [`LogisticKernelWindowed`] on its full domain
277///
278/// The segments of [`LogisticSVEHints`] on [0, 1] (x) and [0, 1] (y), mirrored
279/// onto [-1, 1]. In y, for a window that contains 0 in its interior, the two
280/// halves are scaled onto [ymin, 0] and [0, ymax]; for a one-sided window, the
281/// segments of [-1, 1] that lie inside it are kept, between its ends.
282#[derive(Debug, Clone)]
283pub struct LogisticWindowedSVEHints<T> {
284    inner: LogisticSVEHints<T>,
285    ymin: f64,
286    ymax: f64,
287}
288
289impl<T> SVEHints<T> for LogisticWindowedSVEHints<T>
290where
291    T: Copy + Debug + Send + Sync + CustomNumeric,
292{
293    fn segments_x(&self) -> Vec<T> {
294        self.inner.segments_x()
295    }
296
297    fn segments_y(&self) -> Vec<T> {
298        let half = self.inner.half_segments_y();
299        let (ymin, ymax) = (
300            T::from_f64_unchecked(self.ymin),
301            T::from_f64_unchecked(self.ymax),
302        );
303        if self.ymin < 0.0 && 0.0 < self.ymax {
304            // [0, s1, ..., 1] -> [ymin, ..., ymin s1, 0, ymax s1, ..., ymax]
305            let negative = half
306                .iter()
307                .rev()
308                .filter(|&&s| s > T::zero())
309                .map(|&s| s * ymin);
310            negative.chain(half.iter().map(|&s| s * ymax)).collect()
311        } else {
312            // [-1, ..., 1] -> [ymin, (its points strictly inside), ymax]
313            let full = crate::sve::mirror_segments_to_full_domain(&half);
314            let inside = full.into_iter().filter(|&s| ymin < s && s < ymax);
315            std::iter::once(ymin)
316                .chain(inside)
317                .chain(std::iter::once(ymax))
318                .collect()
319        }
320    }
321
322    fn nsvals(&self) -> usize {
323        self.inner.nsvals()
324    }
325
326    fn ngauss(&self) -> usize {
327        self.inner.ngauss()
328    }
329}
330
331/// SVE hints for LogisticKernel
332#[derive(Debug, Clone)]
333pub struct LogisticSVEHints<T> {
334    kernel: LogisticKernel,
335    epsilon: f64,
336    _phantom: std::marker::PhantomData<T>,
337}
338
339impl<T> LogisticSVEHints<T>
340where
341    T: Copy + Debug + Send + Sync,
342{
343    pub fn new(kernel: LogisticKernel, epsilon: f64) -> Self {
344        Self {
345            kernel,
346            epsilon,
347            _phantom: std::marker::PhantomData,
348        }
349    }
350}
351
352impl<T> LogisticSVEHints<T>
353where
354    T: Copy + Debug + Send + Sync + CustomNumeric,
355{
356    /// The boundaries on [0, 1] of x, the half domain the SVE
357    /// of the centrosymmetric kernel discretizes
358    pub(crate) fn half_segments_x(&self) -> Vec<T> {
359        // Direct implementation that generates only non-negative sample points
360        // This is equivalent to the C++ implementation but without the full symmetric array creation
361        let nzeros = std::cmp::max((15.0 * self.kernel.lambda().log10()).round() as usize, 1);
362
363        // Create a range of values
364        let mut temp = vec![0.0; nzeros];
365        for i in 0..nzeros {
366            temp[i] = 0.143 * i as f64;
367        }
368
369        // Calculate diffs using the inverse hyperbolic cosine
370        let mut diffs = vec![0.0; nzeros];
371        for i in 0..nzeros {
372            diffs[i] = 1.0 / temp[i].cosh();
373        }
374
375        // Calculate cumulative sum of diffs
376        let mut zeros = vec![0.0; nzeros];
377        zeros[0] = diffs[0];
378        for i in 1..nzeros {
379            zeros[i] = zeros[i - 1] + diffs[i];
380        }
381
382        // Normalize zeros
383        let last_zero = zeros[nzeros - 1];
384        for i in 0..nzeros {
385            zeros[i] /= last_zero;
386        }
387
388        // Create segments with only non-negative values (x >= 0) including endpoints [0, xmax]
389        let mut segments = Vec::with_capacity(nzeros + 1);
390
391        // Add 0.0 endpoint
392        segments.push(<T as CustomNumeric>::from_f64_unchecked(0.0));
393
394        // Add positive zeros (already in [0, 1] range)
395        for i in 0..nzeros {
396            segments.push(<T as CustomNumeric>::from_f64_unchecked(zeros[i]));
397        }
398
399        // Ensure segments are sorted in ascending order [0, ..., xmax]
400        segments.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
401
402        segments
403    }
404
405    /// The boundaries on [0, 1] of y, the half domain the SVE
406    /// of the centrosymmetric kernel discretizes
407    pub(crate) fn half_segments_y(&self) -> Vec<T> {
408        // Direct implementation that generates only non-negative sample points
409        // This is equivalent to the C++ implementation but without the full symmetric array creation
410        let nzeros = std::cmp::max((20.0 * self.kernel.lambda().log10()).round() as usize, 2);
411
412        // Initial differences (from C++ implementation)
413        let mut diffs = vec![
414            0.01523, 0.03314, 0.04848, 0.05987, 0.06703, 0.07028, 0.07030, 0.06791, 0.06391,
415            0.05896, 0.05358, 0.04814, 0.04288, 0.03795, 0.03342, 0.02932, 0.02565, 0.02239,
416            0.01951, 0.01699,
417        ];
418
419        // Truncate diffs if necessary
420        if nzeros < diffs.len() {
421            diffs.truncate(nzeros);
422        }
423
424        // Calculate trailing differences
425        for i in 20..nzeros {
426            let x = 0.141 * i as f64;
427            diffs.push(0.25 * (-x).exp());
428        }
429
430        // Calculate cumulative sum of diffs
431        let mut zeros = Vec::with_capacity(nzeros);
432        zeros.push(diffs[0]);
433        for i in 1..nzeros {
434            zeros.push(zeros[i - 1] + diffs[i]);
435        }
436
437        // Normalize zeros
438        let last_zero = zeros[nzeros - 1];
439        for i in 0..nzeros {
440            zeros[i] /= last_zero;
441        }
442        zeros.pop(); // Remove last element
443
444        // Updated nzeros
445        let nzeros = zeros.len();
446
447        // Adjust zeros
448        for i in 0..nzeros {
449            zeros[i] -= 1.0;
450        }
451
452        // Generate segments directly from negative zeros
453        let mut segments: Vec<T> = Vec::new();
454
455        segments.push(<T as CustomNumeric>::from_f64_unchecked(1.0));
456
457        // Add absolute values of negative zeros
458        for i in 0..nzeros {
459            let abs_val = -zeros[i];
460            segments.push(<T as CustomNumeric>::from_f64_unchecked(abs_val));
461        }
462
463        if segments[segments.len() - 1].abs() > T::epsilon() {
464            segments.push(<T as CustomNumeric>::from_f64_unchecked(0.0));
465        }
466
467        // Sort in ascending order
468        segments.sort_by(|a, b| a.partial_cmp(b).unwrap());
469
470        segments
471    }
472}
473
474impl<T> SVEHints<T> for LogisticSVEHints<T>
475where
476    T: Copy + Debug + Send + Sync + CustomNumeric,
477{
478    fn segments_x(&self) -> Vec<T> {
479        crate::sve::mirror_segments_to_full_domain(&self.half_segments_x())
480    }
481
482    fn segments_y(&self) -> Vec<T> {
483        crate::sve::mirror_segments_to_full_domain(&self.half_segments_y())
484    }
485
486    fn nsvals(&self) -> usize {
487        let log10_lambda = self.kernel.lambda().log10().max(1.0);
488        ((25.0 + log10_lambda) * log10_lambda).round() as usize
489    }
490
491    fn ngauss(&self) -> usize {
492        if self.epsilon >= 1e-8 { 10 } else { 16 }
493    }
494}
495
496// ============================================================================
497// RegularizedBoseKernel
498// ============================================================================
499
500/// Regularized bosonic analytical continuation kernel
501///
502/// **Deprecated:** use [`LogisticKernel`], the default kernel for both
503/// statistics. `RegularizedBoseKernel` will be removed in a future release
504/// (<https://github.com/SpM-lab/sparse-ir-rs/issues/273>).
505///
506/// In dimensionless variables x = 2τ/β - 1, y = βω/Λ, the integral kernel is:
507///
508/// ```text
509/// K(x, y) = y * exp(-Λ y (x + 1) / 2) / (1 - exp(-Λ y))
510/// ```
511///
512/// This kernel is used for bosonic Green's functions. The factor y regularizes
513/// the singularity at ω = 0, making the kernel well-behaved for numerical work.
514///
515/// The dimensionalized kernel is related by:
516/// ```text
517/// K(τ, ω) = ωmax * K(2τ/β - 1, ω/ωmax)
518/// ```
519/// where ωmax = Λ/β.
520///
521/// # Properties
522/// - **Centrosymmetric**: K(x, y) = K(-x, -y)
523/// - **ypower = 1**: K(x, y) carries one power of y; in physical units
524///   K(τ, ω) = ω e^{-τω} / (1 - e^{-βω}) acts on ρ(ω)/ω, i.e.
525///   G(τ) = -∫ dω K(τ, ω) ρ(ω)/ω (irbasis paper, Chikano et al., CPC 240, 181
526///   (2019), arXiv:1807.05237, Eqs. (1)-(3))
527/// - **Bosonic only**: Does not support fermionic statistics
528/// - **Regularizer**: w(β, ω) = ω for bosonic statistics (see `regularizer`)
529///
530/// # Numerical Stability
531/// The expression v / (exp(v) - 1) is evaluated using expm1 for small |v|.
532#[derive(Debug, Clone, Copy, PartialEq)]
533pub struct RegularizedBoseKernel {
534    /// Kernel cutoff parameter Λ = β × ωmax
535    pub(crate) lambda: f64,
536}
537
538impl RegularizedBoseKernel {
539    /// Create a new RegularizedBoseKernel
540    ///
541    /// # Arguments
542    /// * `lambda` - Kernel cutoff Λ (must be positive and finite)
543    ///
544    /// # Errors
545    /// [`Error::InvalidParameter`] if `lambda` is not positive and finite. At
546    /// Λ = 0 the kernel is infinite at y = 0 (K = 1/Λ there), so its SVE does
547    /// not exist.
548    #[deprecated(
549        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)"
550    )]
551    pub fn new(lambda: f64) -> Result<Self, Error> {
552        require_positive_finite("lambda", lambda)?;
553        Ok(Self { lambda })
554    }
555
556    /// Get the cutoff parameter
557    pub fn lambda(&self) -> f64 {
558        self.lambda
559    }
560
561    /// Compute kernel value with numerical stability
562    ///
563    /// Evaluates K(x, y) = y * exp(-Λy(x+1)/2) / (1 - exp(-Λy))
564    /// using expm1 for better accuracy near y = 0.
565    ///
566    /// # Arguments
567    /// * `x` - Normalized time coordinate (x ∈ [-1, 1])
568    /// * `y` - Normalized frequency coordinate (y ∈ [-1, 1])
569    /// * `x_plus` - Precomputed x + 1 (optional, for efficiency)
570    /// * `x_minus` - Precomputed 1 - x (optional, for efficiency)
571    fn compute_impl<T>(&self, x: T, y: T, x_plus: Option<T>, x_minus: Option<T>) -> T
572    where
573        T: CustomNumeric,
574    {
575        // Convert lambda and constants to type T at the beginning
576        let lambda_t = T::from_f64_unchecked(self.lambda);
577        let half = T::from_f64_unchecked(0.5);
578        let inv_lambda = T::from_f64_unchecked(1.0) / lambda_t;
579
580        // u_plus = (x + 1) / 2, u_minus = (1 - x) / 2
581        // x_plus and x_minus are (x+1) and (1-x), so we need to multiply by 0.5
582        let u_plus = x_plus
583            .map(|xp| half * xp)
584            .unwrap_or_else(|| half * (T::from_f64_unchecked(1.0) + x));
585        let u_minus = x_minus
586            .map(|xm| half * xm)
587            .unwrap_or_else(|| half * (T::from_f64_unchecked(1.0) - x));
588
589        let v = lambda_t * y;
590        let absv = v.abs();
591
592        // Handle y ≈ 0 using Taylor expansion
593        // K(x,y) = 1/Λ - xy/2 + (1/24)Λ(3x² - 1)y² + O(y³)
594        // The limit as y->0 is 1/Λ (using L'Hopital's rule)
595        // For |Λy| < 2e-14, use first-order approximation
596        // This avoids division by zero when exp(-|Λy|) ≈ 1
597        if absv.to_f64() < 2e-14 {
598            let term0 = inv_lambda;
599            let term1 = half * x * y;
600            return term0 - term1;
601        }
602
603        // enum_val = exp(-|v| * (v >= 0 ? u_plus : u_minus))
604        let enum_val = if v >= T::from_f64_unchecked(0.0) {
605            (-absv * u_plus).exp()
606        } else {
607            (-absv * u_minus).exp()
608        };
609
610        // Handle v / (exp(v) - 1) with numerical stability using expm1
611        // Follows SparseIR.jl implementation: denom = absv / expm1(-absv)
612        // This is more accurate than exp(-absv) - 1 for small arguments
613        let denom = if absv.to_f64() >= 1e-200 {
614            let expm1_neg_absv = CustomNumeric::exp_m1(-absv);
615            absv / expm1_neg_absv
616        } else {
617            // For very small absv, use -1 (matches SparseIR.jl: -one(absv))
618            -T::from_f64_unchecked(1.0)
619        };
620
621        // K(x, y) = -1/Λ * enum_val * denom
622        // Since denom is negative (exp(-absv) < 1), final result is positive
623        -inv_lambda * enum_val * denom
624    }
625}
626
627impl SVEKernel for RegularizedBoseKernel {
628    type SVEHintsType<T>
629        = RegularizedBoseSVEHints<T>
630    where
631        T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
632
633    fn xmax(&self) -> f64 {
634        1.0
635    }
636
637    fn ymax(&self) -> f64 {
638        1.0
639    }
640
641    fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
642    where
643        T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
644    {
645        RegularizedBoseSVEHints::new(*self, epsilon)
646    }
647}
648
649impl AbstractKernel for RegularizedBoseKernel {
650    fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
651        let x_plus = Some(T::from_f64_unchecked(1.0) + x);
652        let x_minus = Some(T::from_f64_unchecked(1.0) - x);
653        self.compute_impl(x, y, x_plus, x_minus)
654    }
655}
656
657impl ReducedKernel for RegularizedBoseKernel {
658    fn compute_reduced<T: CustomNumeric + Copy + Debug>(
659        &self,
660        x: T,
661        y: T,
662        symmetry: SymmetryType,
663    ) -> T {
664        match symmetry {
665            SymmetryType::Even => self.compute(x, y) + self.compute(x, -y),
666            SymmetryType::Odd => {
667                // For RegularizedBoseKernel, use sinh formulation for numerical stability
668                // K(x,y) - K(x,-y) = -y * sinh(Λ y x / 2) / sinh(Λ y / 2)
669                let v_half = T::from_f64_unchecked(self.lambda * 0.5) * y;
670                let xv_half = x * v_half;
671                let xy_small = xv_half.to_f64().abs() < 1.0;
672                let sinh_finite = v_half.to_f64().abs() < 85.0 && v_half.to_f64().abs() > 1e-200;
673
674                if xy_small && sinh_finite {
675                    // Use sinh formulation for numerical stability
676                    // NOTE: Minus sign is critical! (matches Julia/C++ implementation)
677                    -y * xv_half.sinh() / v_half.sinh()
678                } else {
679                    // Fall back to direct computation
680                    self.compute(x, y) - self.compute(x, -y)
681                }
682            }
683        }
684    }
685}
686
687impl CentrosymmKernel for RegularizedBoseKernel {
688    fn lambda(&self) -> f64 {
689        self.lambda
690    }
691}
692
693/// SVE hints for RegularizedBoseKernel
694#[derive(Debug, Clone)]
695pub struct RegularizedBoseSVEHints<T> {
696    kernel: RegularizedBoseKernel,
697    epsilon: f64,
698    _phantom: std::marker::PhantomData<T>,
699}
700
701impl<T> RegularizedBoseSVEHints<T>
702where
703    T: Copy + Debug + Send + Sync,
704{
705    pub fn new(kernel: RegularizedBoseKernel, epsilon: f64) -> Self {
706        Self {
707            kernel,
708            epsilon,
709            _phantom: std::marker::PhantomData,
710        }
711    }
712}
713
714impl<T> RegularizedBoseSVEHints<T>
715where
716    T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
717{
718    /// The boundaries on [0, 1] of x, the half domain the SVE
719    /// of the centrosymmetric kernel discretizes
720    pub(crate) fn half_segments_x(&self) -> Vec<T> {
721        // Returns segments for x >= 0 domain only
722        // C++/Julia: nzeros = max(round(15 * log10(lambda)), 15)
723        let nzeros = ((15.0 * self.kernel.lambda.log10()).round() as usize).max(15);
724
725        // temp[i] = 0.18 * i
726        let mut temp = vec![0.0; nzeros];
727        for i in 0..nzeros {
728            temp[i] = 0.18 * i as f64;
729        }
730
731        // diffs[i] = 1.0 / cosh(temp[i])
732        let mut diffs = vec![0.0; nzeros];
733        for i in 0..nzeros {
734            diffs[i] = 1.0 / temp[i].cosh();
735        }
736
737        // Cumulative sum
738        let mut zeros = vec![0.0; nzeros];
739        zeros[0] = diffs[0];
740        for i in 1..nzeros {
741            zeros[i] = zeros[i - 1] + diffs[i];
742        }
743
744        // Normalize
745        let last_zero = zeros[nzeros - 1];
746        for i in 0..nzeros {
747            zeros[i] /= last_zero;
748        }
749
750        // Create segments with only non-negative values: [0, zeros[0], zeros[1], ...]
751        let mut segments = Vec::with_capacity(nzeros + 1);
752        segments.push(T::from_f64_unchecked(0.0));
753        for i in 0..nzeros {
754            segments.push(T::from_f64_unchecked(zeros[i]));
755        }
756
757        // Ensure sorted (should already be sorted, but verify)
758        segments.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
759
760        segments
761    }
762
763    /// The boundaries on [0, 1] of y, the half domain the SVE
764    /// of the centrosymmetric kernel discretizes
765    pub(crate) fn half_segments_y(&self) -> Vec<T> {
766        // Returns segments for y >= 0 domain only
767        // Python: nzeros = max(round(20 * log10(lambda)), 20)
768        let nzeros = ((20.0 * self.kernel.lambda.log10()).round() as usize).max(20);
769
770        // diffs[j] = 0.12 / exp(0.0337 * j * log(j + 1))
771        let mut diffs = vec![0.0; nzeros];
772        for j in 0..nzeros {
773            let j_f64 = j as f64;
774            let exponent = 0.0337 * j_f64 * (j_f64 + 1.0).ln();
775            diffs[j] = 0.12 / exponent.exp();
776        }
777
778        // Cumulative sum
779        let mut zeros = vec![0.0; nzeros];
780        zeros[0] = diffs[0];
781        for i in 1..nzeros {
782            zeros[i] = zeros[i - 1] + diffs[i];
783        }
784
785        // Normalize by last value, then remove last
786        let last_zero = zeros[nzeros - 1];
787        for i in 0..nzeros {
788            zeros[i] /= last_zero;
789        }
790        zeros.pop(); // now 0 < zeros[i] < 1
791
792        // Python: zeros -= 1  →  zeros in (-1, 0)
793        // Then positive half = -zeros[::-1]  →  reversed and negated → dense near 0
794        // This concentrates segments near y=0, where RegBose has singularity.
795        let mut segments = Vec::with_capacity(zeros.len() + 2);
796        segments.push(T::from_f64_unchecked(0.0));
797        for &z in zeros.iter().rev() {
798            // -zeros[::-1]: iterate in reverse, negate the shifted value
799            // z is in (0, 1), (z - 1) is in (-1, 0), -(z - 1) = 1 - z is in (0, 1)
800            segments.push(T::from_f64_unchecked(1.0 - z));
801        }
802        segments.push(T::from_f64_unchecked(1.0));
803
804        segments
805    }
806}
807
808impl<T> SVEHints<T> for RegularizedBoseSVEHints<T>
809where
810    T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
811{
812    fn segments_x(&self) -> Vec<T> {
813        crate::sve::mirror_segments_to_full_domain(&self.half_segments_x())
814    }
815
816    fn segments_y(&self) -> Vec<T> {
817        crate::sve::mirror_segments_to_full_domain(&self.half_segments_y())
818    }
819
820    fn nsvals(&self) -> usize {
821        // C++: int(round(28 * max(1.0, log10(lambda))))
822        let log10_lambda = self.kernel.lambda.log10().max(1.0);
823        (28.0 * log10_lambda).round() as usize
824    }
825
826    fn ngauss(&self) -> usize {
827        if self.epsilon >= 1e-8 { 10 } else { 16 }
828    }
829}
830
831/// The physical properties of a kernel, on top of its SVE ([`SVEKernel`])
832pub trait KernelProperties: SVEKernel {
833    /// Power with which the y coordinate scales.
834    ///
835    /// For most kernels, this is 0 (no scaling).
836    /// For RegularizedBoseKernel, this is 1 (linear scaling).
837    fn ypower(&self) -> i32;
838
839    /// Convergence radius of the Matsubara basis asymptotic model
840    ///
841    /// For improved numerical accuracy, IR basis functions on Matsubara axis
842    /// can be evaluated from asymptotic expression for |n| > conv_radius.
843    fn conv_radius(&self) -> f64;
844
845    /// A regularizer for a bosonic kernel for avoiding a divergence at omega = 0.
846    ///
847    /// The bosonic kernel diverges at omega = 0.
848    /// This function returns a regularizer w(beta, omega) that avoids this divergence.
849    ///
850    ///    G(τ) = - ∫ K(τ, ω) ρ(ω) dω = - ∫ [K(τ, ω) w(ω)] [ρ(ω)/w(ω)] dω.
851    ///
852    /// The spectral function ρ(ω) and the weight function w(ω) must vanish linearly at omega = 0.
853    /// For a fermionic kernel, this function is expected to return 1.0.
854    ///
855    /// # Arguments
856    ///
857    /// * `beta` - Inverse temperature
858    /// * `omega` - Frequency
859    ///
860    /// # Returns
861    ///
862    /// The regularizer value w(beta, omega)
863    fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64;
864}
865
866/// The regularizer of [`LogisticKernel`]: 1 for fermions, tanh(βω/2) for bosons
867fn logistic_regularizer<S: StatisticsType + 'static>(beta: f64, omega: f64) -> f64 {
868    match S::STATISTICS {
869        Statistics::Fermionic => {
870            // For fermionic statistics: regularizer = 1.0 (safe, no division by zero)
871            1.0
872        }
873        Statistics::Bosonic => {
874            // For bosonic statistics: regularizer = tanh(0.5 * beta * omega) (safe, handles omega=0 case)
875            // This avoids division by zero when tanh(0.5 * beta * omega) approaches zero
876            (0.5 * beta * omega).tanh()
877        }
878    }
879}
880
881impl KernelProperties for LogisticKernel {
882    fn ypower(&self) -> i32 {
883        0 // No y-power scaling for LogisticKernel
884    }
885
886    fn conv_radius(&self) -> f64 {
887        40.0 * self.lambda()
888    }
889
890    fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64 {
891        logistic_regularizer::<S>(beta, omega)
892    }
893}
894
895impl KernelProperties for LogisticKernelWindowed {
896    fn ypower(&self) -> i32 {
897        0
898    }
899
900    /// The convergence radius of the [`LogisticKernel`] with the same Λ
901    fn conv_radius(&self) -> f64 {
902        40.0 * self.lambda()
903    }
904
905    /// The regularizer of [`LogisticKernel`], whose formula this kernel shares
906    fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64 {
907        logistic_regularizer::<S>(beta, omega)
908    }
909}
910
911impl KernelProperties for RegularizedBoseKernel {
912    fn ypower(&self) -> i32 {
913        1 // K(x, y) carries one power of y; the kernel acts on ρ(ω)/ω
914    }
915
916    fn conv_radius(&self) -> f64 {
917        40.0 * self.lambda()
918    }
919
920    fn regularizer<S: StatisticsType + 'static>(&self, _beta: f64, omega: f64) -> f64 {
921        match S::STATISTICS {
922            Statistics::Fermionic => {
923                panic!("RegularizedBoseKernel does not support fermionic functions");
924            }
925            Statistics::Bosonic => {
926                // regularizer = ω (safe, no division)
927                omega
928            }
929        }
930    }
931}
932
933#[cfg(test)]
934#[path = "kernel_tests.rs"]
935mod tests;