Skip to main content

sparse_ir_sve/
kernelmatrix.rs

1//! Kernel matrix discretization
2//!
3//! This module provides functionality to discretize kernels using Gauss quadrature
4//! rules and store them as matrices for numerical computation.
5
6use crate::gauss::Rule;
7use crate::kernel::{AbstractKernel, ReducedKernel, SVEKernel, SymmetryType};
8use crate::matrix::Mat;
9use crate::numeric::CustomNumeric;
10use std::fmt::Debug;
11
12/// This structure stores a discrete kernel matrix along with the corresponding
13/// Gauss quadrature rules for x and y coordinates. This enables easy application
14/// of weights for SVE computation and maintains the relationship between matrix
15/// elements and their corresponding quadrature points.
16#[derive(Debug, Clone)]
17pub struct DiscretizedKernel<T> {
18    /// Discrete kernel matrix
19    pub matrix: Mat<T>,
20    /// Gauss quadrature rule for x coordinates
21    pub gauss_x: Rule<T>,
22    /// Gauss quadrature rule for y coordinates
23    pub gauss_y: Rule<T>,
24    /// X-axis segment boundaries (from SVEHints)
25    pub segments_x: Vec<T>,
26    /// Y-axis segment boundaries (from SVEHints)
27    pub segments_y: Vec<T>,
28}
29
30impl<T: CustomNumeric + Clone> DiscretizedKernel<T> {
31    /// Create a new DiscretizedKernel
32    pub fn new(
33        matrix: Mat<T>,
34        gauss_x: Rule<T>,
35        gauss_y: Rule<T>,
36        segments_x: Vec<T>,
37        segments_y: Vec<T>,
38    ) -> Self {
39        Self {
40            matrix,
41            gauss_x,
42            gauss_y,
43            segments_x,
44            segments_y,
45        }
46    }
47
48    /// Delegate to matrix methods
49    pub fn is_empty(&self) -> bool {
50        self.matrix.is_empty()
51    }
52
53    pub fn nrows(&self) -> usize {
54        self.matrix.shape().0
55    }
56
57    pub fn ncols(&self) -> usize {
58        self.matrix.shape().1
59    }
60
61    pub fn iter(&self) -> impl Iterator<Item = &T> {
62        self.matrix.iter()
63    }
64
65    /// Apply weights for SVE computation
66    ///
67    /// This applies the square root of Gauss weights to the matrix,
68    /// which is required before performing SVD for SVE computation.
69    /// The original matrix remains unchanged.
70    pub fn apply_weights_for_sve(&self) -> Mat<T> {
71        let mut weighted_matrix = self.matrix.clone();
72        let shape = *weighted_matrix.shape();
73
74        // Apply square root of x-direction weights to rows
75        for i in 0..self.gauss_x.x.len() {
76            let weight_sqrt = self.gauss_x.w[i].sqrt();
77            for j in 0..shape.1 {
78                weighted_matrix[[i, j]] = weighted_matrix[[i, j]] * weight_sqrt;
79            }
80        }
81
82        // Apply square root of y-direction weights to columns
83        for j in 0..self.gauss_y.x.len() {
84            let weight_sqrt = self.gauss_y.w[j].sqrt();
85            for i in 0..shape.0 {
86                weighted_matrix[[i, j]] = weighted_matrix[[i, j]] * weight_sqrt;
87            }
88        }
89
90        weighted_matrix
91    }
92
93    /// Get the number of Gauss points in x direction
94    pub fn n_gauss_x(&self) -> usize {
95        self.gauss_x.x.len()
96    }
97
98    /// Get the number of Gauss points in y direction
99    pub fn n_gauss_y(&self) -> usize {
100        self.gauss_y.x.len()
101    }
102}
103
104/// Compute matrix from Gauss quadrature rules with segments from SVEHints
105///
106/// This function evaluates the kernel at all combinations of Gauss points
107/// and returns a DiscretizedKernel containing the matrix, quadrature rules, and segments.
108pub fn matrix_from_gauss_with_segments<
109    T: CustomNumeric + Clone + Send + Sync,
110    K: ReducedKernel + SVEKernel,
111    H: crate::kernel::SVEHints<T>,
112>(
113    kernel: &K,
114    gauss_x: &Rule<T>,
115    gauss_y: &Rule<T>,
116    symmetry: SymmetryType,
117    hints: &H,
118) -> DiscretizedKernel<T> {
119    // The reduced kernel lives on [0, xmax] x [0, ymax]
120    let segments_x = crate::sve::utils::half_domain_segments(&hints.segments_x());
121    let segments_y = crate::sve::utils::half_domain_segments(&hints.segments_y());
122
123    // TODO: Fix range checking for composite Gauss rules
124    // For now, skip range checking to allow testing
125    /*
126    // Check that Gauss points are within [0, xmax] and [0, ymax]
127    let kernel_xmax = kernel.xmax();
128    let kernel_ymax = kernel.ymax();
129    let tolerance = 1e-12;
130
131    // Check x points are in [0, xmax]
132    for &x in &gauss_x.x {
133        let x_f64 = x.to_f64();
134        assert!(
135            x_f64 >= -tolerance && x_f64 <= kernel_xmax + tolerance,
136            "Gauss x point {} is outside [0, {}]", x_f64, kernel_xmax
137        );
138    }
139
140    // Check y points are in [0, ymax]
141    for &y in &gauss_y.x {
142        let y_f64 = y.to_f64();
143        assert!(
144            y_f64 >= -tolerance && y_f64 <= kernel_ymax + tolerance,
145            "Gauss y point {} is outside [0, {}]", y_f64, kernel_ymax
146        );
147    }
148    */
149
150    let n = gauss_x.x.len();
151    let m = gauss_y.x.len();
152    let mut result = Mat::<T>::from_elem([n, m], T::zero());
153
154    // Evaluate kernel at all combinations of Gauss points
155    for i in 0..n {
156        for j in 0..m {
157            let x = gauss_x.x[i];
158            let y = gauss_y.x[j];
159            result[[i, j]] = kernel.compute_reduced(x, y, symmetry);
160        }
161    }
162
163    DiscretizedKernel::new(
164        result,
165        gauss_x.clone(),
166        gauss_y.clone(),
167        segments_x,
168        segments_y,
169    )
170}
171
172/// Compute matrix from Gauss quadrature rules (legacy version without segments)
173///
174/// This function evaluates the kernel at all combinations of Gauss points
175/// and returns a DiscretizedKernel containing the matrix and quadrature rules.
176pub fn matrix_from_gauss<T: CustomNumeric + Clone, K: ReducedKernel + SVEKernel>(
177    kernel: &K,
178    gauss_x: &Rule<T>,
179    gauss_y: &Rule<T>,
180    symmetry: SymmetryType,
181) -> DiscretizedKernel<T> {
182    // Check that Gauss points are within [0, xmax] and [0, ymax]
183    let kernel_xmax = kernel.xmax();
184    let kernel_ymax = kernel.ymax();
185    let tolerance = 1e-12;
186
187    // Check x points are in [0, xmax]
188    for &x in &gauss_x.x {
189        let x_f64 = x.to_f64();
190        assert!(
191            x_f64 >= -tolerance && x_f64 <= kernel_xmax + tolerance,
192            "Gauss x point {} is outside [0, {}]",
193            x_f64,
194            kernel_xmax
195        );
196    }
197
198    // Check y points are in [0, ymax]
199    for &y in &gauss_y.x {
200        let y_f64 = y.to_f64();
201        assert!(
202            y_f64 >= -tolerance && y_f64 <= kernel_ymax + tolerance,
203            "Gauss y point {} is outside [0, {}]",
204            y_f64,
205            kernel_ymax
206        );
207    }
208
209    let n = gauss_x.x.len();
210    let m = gauss_y.x.len();
211    let mut result = Mat::<T>::from_elem([n, m], T::zero());
212
213    // Evaluate kernel at all combinations of Gauss points
214    for i in 0..n {
215        for j in 0..m {
216            let x = gauss_x.x[i];
217            let y = gauss_y.x[j];
218
219            // Use T type directly for kernel computation
220            // Note: gauss_x and gauss_y should already be scaled to [0, 1] interval
221            result[[i, j]] = kernel.compute_reduced(x, y, symmetry);
222        }
223    }
224
225    let segments_x = vec![gauss_x.a, gauss_x.b];
226    let segments_y = vec![gauss_y.a, gauss_y.b];
227    DiscretizedKernel::new(
228        result,
229        gauss_x.clone(),
230        gauss_y.clone(),
231        segments_x,
232        segments_y,
233    )
234}
235
236/// Compute matrix from Gauss quadrature rules for non-centrosymmetric kernels
237///
238/// This function evaluates the kernel directly at all combinations of Gauss points
239/// without exploiting symmetry. It works with the full domain [-xmax, xmax] × [-ymax, ymax].
240///
241/// # Arguments
242///
243/// * `kernel` - The kernel implementing AbstractKernel
244/// * `gauss_x` - Gauss quadrature rule for x coordinates (full domain)
245/// * `gauss_y` - Gauss quadrature rule for y coordinates (full domain)
246/// * `hints` - SVE hints providing segment information
247///
248/// # Returns
249///
250/// DiscretizedKernel containing the matrix, quadrature rules, and segments
251pub fn matrix_from_gauss_noncentrosymmetric<
252    T: CustomNumeric + Clone + Send + Sync,
253    K: AbstractKernel + SVEKernel,
254    H: crate::kernel::SVEHints<T>,
255>(
256    kernel: &K,
257    gauss_x: &Rule<T>,
258    gauss_y: &Rule<T>,
259    hints: &H,
260) -> DiscretizedKernel<T> {
261    let segments_x = hints.segments_x();
262    let segments_y = hints.segments_y();
263
264    let n = gauss_x.x.len();
265    let m = gauss_y.x.len();
266    let mut result = Mat::<T>::from_elem([n, m], T::zero());
267
268    // Evaluate kernel directly at all combinations of Gauss points
269    for i in 0..n {
270        for j in 0..m {
271            let x = gauss_x.x[i];
272            let y = gauss_y.x[j];
273
274            // Direct kernel evaluation (no symmetry exploitation)
275            result[[i, j]] = kernel.compute(x, y);
276        }
277    }
278
279    DiscretizedKernel::new(
280        result,
281        gauss_x.clone(),
282        gauss_y.clone(),
283        segments_x,
284        segments_y,
285    )
286}
287
288#[cfg(test)]
289#[path = "kernelmatrix_tests.rs"]
290mod tests;