sparse_ir_sve/kernel.rs
1//! Kernels K(x, y) and the traits the singular value expansion needs
2//!
3//! The SVE expands a kernel in the Fredholm integral equation of the first
4//! kind
5//!
6//! u(x) = integral of K(x, y) v(y) dy
7//!
8//! where x ∈ [xmin, xmax] and y ∈ [ymin, ymax]. A kernel implements
9//! [`AbstractKernel`] (its values) and [`SVEKernel`] (its domain and the
10//! discretization hints of its SVE). A centrosymmetric kernel implements
11//! [`ReducedKernel`] as well, whose SVE is block-diagonalized into the even
12//! and odd reduced kernels; any other kernel implements [`ExpandableKernel`]
13//! (no methods), whose SVE is taken over the full domain. Either is what
14//! [`compute_sve`](crate::sve::compute_sve) accepts.
15
16use crate::error::Error;
17use crate::numeric::CustomNumeric;
18use crate::sve::strategy::{CentrosymmSVE, NonCentrosymmSVE, SVEStrategy};
19use std::fmt::Debug;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum SymmetryType {
23 Even,
24 Odd,
25}
26
27impl SymmetryType {
28 pub fn sign(self) -> i32 {
29 match self {
30 SymmetryType::Even => 1,
31 SymmetryType::Odd => -1,
32 }
33 }
34}
35
36/// Trait for SVE (Singular Value Expansion) hints
37///
38/// Provides discretization hints for singular value expansion of a given kernel.
39/// This includes segment information and numerical parameters for efficient computation.
40pub trait SVEHints<T>: Debug + Send + Sync
41where
42 T: Copy + Debug + Send + Sync,
43{
44 /// Segment boundaries on x: strictly increasing from `xmin` to `xmax`
45 ///
46 /// The SVE of a centrosymmetric kernel ([`ReducedKernel`]) discretizes
47 /// the half `[0, xmax]`: the boundaries in `(0, xmax]` with 0 added. The
48 /// mirror images of these are its boundaries on `[-xmax, 0]`.
49 fn segments_x(&self) -> Vec<T>;
50
51 /// Segment boundaries on y: strictly increasing from `ymin` to `ymax`
52 ///
53 /// The SVE of a centrosymmetric kernel ([`ReducedKernel`]) discretizes
54 /// the half `[0, ymax]`, as for [`Self::segments_x`].
55 fn segments_y(&self) -> Vec<T>;
56
57 /// Get the number of singular values hint
58 fn nsvals(&self) -> usize;
59
60 /// Get the number of Gauss points for quadrature
61 fn ngauss(&self) -> usize;
62}
63
64/// The domain of a kernel and the discretization hints of its SVE
65///
66/// This is what [`crate::sve::compute_sve`] needs of a kernel besides its
67/// values ([`AbstractKernel`]) and its strategy ([`ExpandableKernel`]).
68pub trait SVEKernel: AbstractKernel {
69 /// Associated type for SVE hints
70 type SVEHintsType<T>: SVEHints<T> + Clone
71 where
72 T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
73
74 /// Get the upper bound of the x domain
75 fn xmax(&self) -> f64;
76
77 /// Get the upper bound of the y domain
78 fn ymax(&self) -> f64;
79
80 /// Lower bound of the x domain. Defaults to the symmetric case `-xmax`.
81 fn xmin(&self) -> f64 {
82 -self.xmax()
83 }
84
85 /// Lower bound of the y domain. Defaults to the symmetric case `-ymax`.
86 fn ymin(&self) -> f64 {
87 -self.ymax()
88 }
89
90 /// Create SVE hints for this kernel type.
91 ///
92 /// Provides discretization hints for singular value expansion computation.
93 /// The hints include segment information and numerical parameters optimized
94 /// for the specific kernel type.
95 ///
96 /// @param epsilon Target accuracy for the SVE computation
97 /// @return SVE hints specific to this kernel type
98 fn sve_hints<T>(&self, epsilon: f64) -> Self::SVEHintsType<T>
99 where
100 T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
101}
102
103/// Trait for general kernels (both centrosymmetric and non-centrosymmetric)
104///
105/// This trait provides the basic interface for computing kernel values.
106/// Centrosymmetric kernels implement [`ReducedKernel`] as well, which
107/// provides additional optimizations.
108pub trait AbstractKernel: Send + Sync {
109 /// Compute the kernel value K(x, y) with high precision
110 ///
111 /// # Arguments
112 ///
113 /// * `x` - The x coordinate (typically in [xmin, xmax])
114 /// * `y` - The y coordinate (typically in [ymin, ymax])
115 ///
116 /// # Returns
117 ///
118 /// The kernel value K(x, y)
119 fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T;
120}
121
122/// Trait for centrosymmetric kernels, through their reduced kernels
123///
124/// Centrosymmetric kernels satisfy K(x, y) = K(-x, -y) on a symmetric domain
125/// and can be decomposed into even and odd components for efficient
126/// computation.
127pub trait ReducedKernel: AbstractKernel {
128 /// Compute the reduced kernel value
129 ///
130 /// K_red(x, y) = K(x, y) + sign * K(x, -y)
131 /// where sign = 1 for even symmetry and sign = -1 for odd symmetry
132 fn compute_reduced<T: CustomNumeric + Copy + Debug>(
133 &self,
134 x: T,
135 y: T,
136 symmetry: SymmetryType,
137 ) -> T;
138}
139
140/// The kernels whose SVE [`compute_sve`](crate::sve::compute_sve) computes
141///
142/// Implemented for every [`ReducedKernel`], whose SVE is block-diagonalized
143/// into the even and odd reduced kernels. Other kernels implement it with
144/// no methods (`impl ExpandableKernel for MyKernel {}`; Rust cannot provide
145/// it for every kernel that is not a [`ReducedKernel`]); their SVE is taken
146/// over the full domain
147/// `[xmin, xmax] × [ymin, ymax]` and their singular functions have no
148/// definite parity.
149pub trait ExpandableKernel: SVEKernel + Clone + 'static {
150 /// The SVE strategy of the kernel: the even/odd blocks for a
151 /// [`ReducedKernel`], otherwise the full domain
152 ///
153 /// # Errors
154 ///
155 /// The errors of [`NonCentrosymmSVE::new`] or [`CentrosymmSVE::new`]
156 #[doc(hidden)]
157 fn sve_strategy<T>(&self, epsilon: f64) -> Result<Box<dyn SVEStrategy<T>>, Error>
158 where
159 T: CustomNumeric + Send + Sync + Clone + 'static,
160 {
161 Ok(Box::new(NonCentrosymmSVE::new(self.clone(), epsilon)?))
162 }
163
164 /// Whether the kernel implements [`ReducedKernel`], i.e. is
165 /// centrosymmetric
166 #[doc(hidden)]
167 fn implements_reduced_kernel(&self) -> bool {
168 false
169 }
170}
171
172impl<K> ExpandableKernel for K
173where
174 K: ReducedKernel + SVEKernel + Clone + 'static,
175{
176 fn sve_strategy<T>(&self, epsilon: f64) -> Result<Box<dyn SVEStrategy<T>>, Error>
177 where
178 T: CustomNumeric + Send + Sync + Clone + 'static,
179 {
180 Ok(Box::new(CentrosymmSVE::new(self.clone(), epsilon)?))
181 }
182
183 fn implements_reduced_kernel(&self) -> bool {
184 true
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 // Simple non-centrosymmetric kernel for testing AbstractKernel trait
193 // K(x, y) = x + y (clearly non-centrosymmetric: K(-x, -y) = -x - y = -(x + y) != x + y = K(x, y))
194 #[derive(Debug, Clone, Copy)]
195 struct SimpleNonCentrosymmKernel {
196 lambda: f64,
197 }
198
199 impl SimpleNonCentrosymmKernel {
200 fn new(lambda: f64) -> Self {
201 Self { lambda }
202 }
203 }
204
205 impl AbstractKernel for SimpleNonCentrosymmKernel {
206 fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
207 x + y
208 }
209 }
210
211 #[test]
212 fn test_noncentrosymm_kernel_compute() {
213 let kernel = SimpleNonCentrosymmKernel::new(10.0);
214
215 // Test basic computation: K(x, y) = x + y
216 let result1: f64 = kernel.compute(0.5, 0.5);
217 assert!((result1 - 1.0).abs() < 1e-10);
218
219 let result2: f64 = kernel.compute(-0.5, 0.5);
220 assert!((result2 - 0.0).abs() < 1e-10);
221
222 // Verify non-centrosymmetry: K(-x, -y) != K(x, y)
223 // K(0.5, 0.5) = 1.0, K(-0.5, -0.5) = -1.0
224 let result3: f64 = kernel.compute(0.5, 0.5);
225 let result4: f64 = kernel.compute(-0.5, -0.5);
226 assert!((result3 - result4).abs() > 1e-10); // Should be different (1.0 vs -1.0)
227 }
228}