1use 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
31pub trait CentrosymmKernel: ReducedKernel {
37 fn lambda(&self) -> f64;
39}
40
41pub trait BasisKernel: ExpandableKernel + KernelProperties {
53 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#[derive(Debug, Clone, Copy)]
75pub struct LogisticKernel {
76 lambda: f64,
77}
78
79impl LogisticKernel {
80 pub fn new(lambda: f64) -> Result<Self, Error> {
89 require_positive_finite("lambda", lambda)?;
90 Ok(Self { lambda })
91 }
92
93 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 let v_half: T = T::from_f64_unchecked(lambda * 0.5) * y;
143 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#[derive(Debug, Clone, Copy)]
190pub struct LogisticKernelWindowed {
191 logistic: LogisticKernel,
193 ymin: f64,
194 ymax: f64,
195}
196
197impl LogisticKernelWindowed {
198 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 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#[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 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 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#[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 pub(crate) fn half_segments_x(&self) -> Vec<T> {
359 let nzeros = std::cmp::max((15.0 * self.kernel.lambda().log10()).round() as usize, 1);
362
363 let mut temp = vec![0.0; nzeros];
365 for i in 0..nzeros {
366 temp[i] = 0.143 * i as f64;
367 }
368
369 let mut diffs = vec![0.0; nzeros];
371 for i in 0..nzeros {
372 diffs[i] = 1.0 / temp[i].cosh();
373 }
374
375 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 let last_zero = zeros[nzeros - 1];
384 for i in 0..nzeros {
385 zeros[i] /= last_zero;
386 }
387
388 let mut segments = Vec::with_capacity(nzeros + 1);
390
391 segments.push(<T as CustomNumeric>::from_f64_unchecked(0.0));
393
394 for i in 0..nzeros {
396 segments.push(<T as CustomNumeric>::from_f64_unchecked(zeros[i]));
397 }
398
399 segments.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
401
402 segments
403 }
404
405 pub(crate) fn half_segments_y(&self) -> Vec<T> {
408 let nzeros = std::cmp::max((20.0 * self.kernel.lambda().log10()).round() as usize, 2);
411
412 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 if nzeros < diffs.len() {
421 diffs.truncate(nzeros);
422 }
423
424 for i in 20..nzeros {
426 let x = 0.141 * i as f64;
427 diffs.push(0.25 * (-x).exp());
428 }
429
430 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 let last_zero = zeros[nzeros - 1];
439 for i in 0..nzeros {
440 zeros[i] /= last_zero;
441 }
442 zeros.pop(); let nzeros = zeros.len();
446
447 for i in 0..nzeros {
449 zeros[i] -= 1.0;
450 }
451
452 let mut segments: Vec<T> = Vec::new();
454
455 segments.push(<T as CustomNumeric>::from_f64_unchecked(1.0));
456
457 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 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#[derive(Debug, Clone, Copy, PartialEq)]
533pub struct RegularizedBoseKernel {
534 pub(crate) lambda: f64,
536}
537
538impl RegularizedBoseKernel {
539 #[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 pub fn lambda(&self) -> f64 {
558 self.lambda
559 }
560
561 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 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 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 if absv.to_f64() < 2e-14 {
598 let term0 = inv_lambda;
599 let term1 = half * x * y;
600 return term0 - term1;
601 }
602
603 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 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 -T::from_f64_unchecked(1.0)
619 };
620
621 -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 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 -y * xv_half.sinh() / v_half.sinh()
678 } else {
679 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#[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 pub(crate) fn half_segments_x(&self) -> Vec<T> {
721 let nzeros = ((15.0 * self.kernel.lambda.log10()).round() as usize).max(15);
724
725 let mut temp = vec![0.0; nzeros];
727 for i in 0..nzeros {
728 temp[i] = 0.18 * i as f64;
729 }
730
731 let mut diffs = vec![0.0; nzeros];
733 for i in 0..nzeros {
734 diffs[i] = 1.0 / temp[i].cosh();
735 }
736
737 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 let last_zero = zeros[nzeros - 1];
746 for i in 0..nzeros {
747 zeros[i] /= last_zero;
748 }
749
750 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 segments.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
759
760 segments
761 }
762
763 pub(crate) fn half_segments_y(&self) -> Vec<T> {
766 let nzeros = ((20.0 * self.kernel.lambda.log10()).round() as usize).max(20);
769
770 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 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 let last_zero = zeros[nzeros - 1];
787 for i in 0..nzeros {
788 zeros[i] /= last_zero;
789 }
790 zeros.pop(); 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 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 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
831pub trait KernelProperties: SVEKernel {
833 fn ypower(&self) -> i32;
838
839 fn conv_radius(&self) -> f64;
844
845 fn regularizer<S: StatisticsType + 'static>(&self, beta: f64, omega: f64) -> f64;
864}
865
866fn logistic_regularizer<S: StatisticsType + 'static>(beta: f64, omega: f64) -> f64 {
868 match S::STATISTICS {
869 Statistics::Fermionic => {
870 1.0
872 }
873 Statistics::Bosonic => {
874 (0.5 * beta * omega).tanh()
877 }
878 }
879}
880
881impl KernelProperties for LogisticKernel {
882 fn ypower(&self) -> i32 {
883 0 }
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 fn conv_radius(&self) -> f64 {
902 40.0 * self.lambda()
903 }
904
905 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 }
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 omega
928 }
929 }
930 }
931}
932
933#[cfg(test)]
934#[path = "kernel_tests.rs"]
935mod tests;