Skip to main content

sparse_ir/sve/
strategy.rs

1//! SVE computation strategies
2
3use crate::error::Error;
4use crate::gauss::{Rule, legendre_generic};
5use crate::kernel::{AbstractKernel, CentrosymmKernel, KernelProperties, SVEHints, SymmetryType};
6use crate::kernelmatrix::{matrix_from_gauss_noncentrosymmetric, matrix_from_gauss_with_segments};
7use crate::numeric::CustomNumeric;
8use crate::poly::PiecewiseLegendrePolyVector;
9use mdarray::DTensor;
10use std::fmt::Debug;
11
12use super::result::SVEResult;
13use super::utils::{
14    SvdBlock, canonicalize_signs, extend_to_full_domain, merge_blocks,
15    mirror_segments_to_full_domain, remove_weights, svd_to_polynomials,
16};
17
18/// Trait for SVE computation strategies
19pub trait SVEStrategy<T: CustomNumeric> {
20    /// Compute the discretized matrices for SVD
21    fn matrices(&self) -> Vec<DTensor<T, 2>>;
22
23    /// Post-process SVD results to create SVEResult
24    ///
25    /// # Errors
26    ///
27    /// The errors of [`SVEResult::new`]
28    fn postprocess(
29        &self,
30        u_list: Vec<DTensor<T, 2>>,
31        s_list: Vec<Vec<T>>,
32        v_list: Vec<DTensor<T, 2>>,
33    ) -> Result<SVEResult, Error>;
34}
35
36/// Sampling-based SVE computation
37///
38/// This is the general SVE computation strategy that works with discretized kernels.
39/// It does NOT know about symmetry - it just processes a given discretized kernel matrix.
40///
41/// # Responsibility
42///
43/// - Remove weights from SVD results
44/// - Convert to polynomials on the domain specified by segments
45/// - Domain extension is caller's responsibility
46pub struct SamplingSVE<T>
47where
48    T: CustomNumeric + Send + Sync + 'static,
49{
50    segments_x: Vec<T>,
51    segments_y: Vec<T>,
52    gauss_x: Rule<T>,
53    gauss_y: Rule<T>,
54    #[allow(dead_code)]
55    epsilon: f64,
56    n_gauss: usize,
57}
58
59impl<T> SamplingSVE<T>
60where
61    T: CustomNumeric + Send + Sync + 'static,
62{
63    /// Create a new SamplingSVE
64    ///
65    /// This takes only the geometric information needed for polynomial conversion,
66    /// not the kernel itself.
67    pub fn new(
68        segments_x: Vec<T>,
69        segments_y: Vec<T>,
70        gauss_x: Rule<T>,
71        gauss_y: Rule<T>,
72        epsilon: f64,
73        n_gauss: usize,
74    ) -> Self {
75        Self {
76            segments_x,
77            segments_y,
78            gauss_x,
79            gauss_y,
80            epsilon,
81            n_gauss,
82        }
83    }
84
85    /// Post-process a single SVD result to create polynomials
86    ///
87    /// This converts SVD results to piecewise Legendre polynomials
88    /// on the domain specified by segments (e.g., [0, xmax] for reduced kernels).
89    ///
90    /// # Errors
91    ///
92    /// The errors of the crate-internal `svd_to_polynomials`, and
93    /// [`Error::EmptyInput`] if the
94    /// SVD result has no singular values
95    pub fn postprocess_single(
96        &self,
97        u: &DTensor<T, 2>,
98        s: &[T],
99        v: &DTensor<T, 2>,
100    ) -> Result<
101        (
102            PiecewiseLegendrePolyVector,
103            Vec<f64>,
104            PiecewiseLegendrePolyVector,
105        ),
106        Error,
107    > {
108        let (u_polys, s, v_polys) = self.postprocess_block(u, s, v)?;
109        Ok((
110            PiecewiseLegendrePolyVector::new(u_polys)?,
111            s,
112            PiecewiseLegendrePolyVector::new(v_polys)?,
113        ))
114    }
115
116    /// [`Self::postprocess_single`] returning plain vectors, which may be
117    /// empty
118    fn postprocess_block(
119        &self,
120        u: &DTensor<T, 2>,
121        s: &[T],
122        v: &DTensor<T, 2>,
123    ) -> Result<SvdBlock, Error> {
124        // 1. Remove weights
125        // Both U and V have rows corresponding to Gauss points, so is_row=true for both
126        let u_unweighted = remove_weights(u, self.gauss_x.w.as_slice(), true);
127        let v_unweighted = remove_weights(v, self.gauss_y.w.as_slice(), true);
128
129        // 2. Convert to polynomials
130        let gauss_rule_f64 = legendre_generic::<f64>(self.n_gauss);
131        let u_polys = svd_to_polynomials(
132            &u_unweighted,
133            &self.segments_x,
134            &gauss_rule_f64,
135            self.n_gauss,
136        )?;
137        let v_polys = svd_to_polynomials(
138            &v_unweighted,
139            &self.segments_y,
140            &gauss_rule_f64,
141            self.n_gauss,
142        )?;
143
144        // Note: No domain extension here - that's the caller's responsibility
145        Ok((u_polys, s.iter().map(|&x| x.to_f64()).collect(), v_polys))
146    }
147}
148
149/// Centrosymmetric SVE computation
150///
151/// Exploits even/odd symmetry for efficient computation.
152/// This manages the symmetry: creating reduced kernels, extending to full domain, and merging.
153pub struct CentrosymmSVE<T, K>
154where
155    T: CustomNumeric + Send + Sync + 'static,
156    K: CentrosymmKernel + KernelProperties,
157{
158    kernel: K,
159    epsilon: f64,
160    hints: K::SVEHintsType<T>,
161    #[allow(dead_code)]
162    n_gauss: usize,
163
164    // Geometric information (positive domain [0, xmax])
165    #[allow(dead_code)]
166    segments_x: Vec<T>,
167    #[allow(dead_code)]
168    segments_y: Vec<T>,
169    gauss_x: Rule<T>,
170    gauss_y: Rule<T>,
171
172    // The general SVE processor (no symmetry knowledge)
173    sampling_sve: SamplingSVE<T>,
174}
175
176impl<T, K> CentrosymmSVE<T, K>
177where
178    T: CustomNumeric + Send + Sync + Clone + 'static,
179    K: CentrosymmKernel + KernelProperties + Clone,
180    K::SVEHintsType<T>: SVEHints<T> + Clone,
181{
182    /// Create a new CentrosymmSVE
183    ///
184    /// # Errors
185    ///
186    /// [`Error::InvalidParameter`] if the SVE hints of the kernel give
187    /// segments that are not finite and strictly increasing
188    pub fn new(kernel: K, epsilon: f64) -> Result<Self, Error> {
189        let hints = kernel.sve_hints::<T>(epsilon);
190
191        // Get segments for positive domain [0, xmax]
192        let segments_x = hints.segments_x();
193        let segments_y = hints.segments_y();
194        let n_gauss = hints.ngauss();
195
196        // Create composite Gauss rules
197        let rule = legendre_generic::<T>(n_gauss);
198        let gauss_x = rule.piecewise(&segments_x)?;
199        let gauss_y = rule.piecewise(&segments_y)?;
200
201        // Create the general SVE processor
202        let sampling_sve = SamplingSVE::new(
203            segments_x.clone(),
204            segments_y.clone(),
205            gauss_x.clone(),
206            gauss_y.clone(),
207            epsilon,
208            n_gauss,
209        );
210
211        Ok(Self {
212            kernel,
213            epsilon,
214            hints,
215            n_gauss,
216            segments_x,
217            segments_y,
218            gauss_x,
219            gauss_y,
220            sampling_sve,
221        })
222    }
223
224    /// Compute reduced kernel matrix for given symmetry
225    fn compute_reduced_matrix(&self, symmetry: SymmetryType) -> DTensor<T, 2> {
226        // Compute K_red(x, y) = K(x, y) + sign * K(x, -y)
227        // where x, y are in [0, xmax] and [0, ymax]
228        let discretized = matrix_from_gauss_with_segments(
229            &self.kernel,
230            &self.gauss_x,
231            &self.gauss_y,
232            symmetry,
233            &self.hints,
234        );
235
236        // Apply weights for SVE
237
238        discretized.apply_weights_for_sve()
239    }
240
241    /// Extend polynomials from [0, xmax] to [-xmax, xmax]
242    fn extend_result_to_full_domain(
243        &self,
244        result: SvdBlock,
245        symmetry: SymmetryType,
246    ) -> Result<SvdBlock, Error> {
247        let (u, s, v) = result;
248
249        // Extend u and v from [0, xmax] to [-xmax, xmax]
250        let u_full = extend_to_full_domain(u, symmetry, self.kernel.xmax())?;
251        let v_full = extend_to_full_domain(v, symmetry, self.kernel.ymax())?;
252
253        Ok((u_full, s, v_full))
254    }
255}
256
257impl<T, K> SVEStrategy<T> for CentrosymmSVE<T, K>
258where
259    T: CustomNumeric + Send + Sync + Clone + 'static,
260    K: CentrosymmKernel + KernelProperties + Clone,
261    K::SVEHintsType<T>: SVEHints<T> + Clone,
262{
263    fn matrices(&self) -> Vec<DTensor<T, 2>> {
264        // Compute reduced kernels for even and odd symmetries
265        let even_matrix = self.compute_reduced_matrix(SymmetryType::Even);
266        let odd_matrix = self.compute_reduced_matrix(SymmetryType::Odd);
267
268        vec![even_matrix, odd_matrix]
269    }
270
271    fn postprocess(
272        &self,
273        u_list: Vec<DTensor<T, 2>>,
274        s_list: Vec<Vec<T>>,
275        v_list: Vec<DTensor<T, 2>>,
276    ) -> Result<SVEResult, Error> {
277        // Process even and odd results using SamplingSVE (which doesn't know
278        // about symmetry). Keep plain vectors until the merge: truncation can
279        // empty a block (keeping only the largest singular value empties the
280        // odd one), and a PiecewiseLegendrePolyVector cannot be empty.
281        let result_even = self
282            .sampling_sve
283            .postprocess_block(&u_list[0], &s_list[0], &v_list[0])?;
284        let result_odd = self
285            .sampling_sve
286            .postprocess_block(&u_list[1], &s_list[1], &v_list[1])?;
287
288        // Now extend to full domain (this is where symmetry comes in)
289        let result_even_full =
290            self.extend_result_to_full_domain(result_even, SymmetryType::Even)?;
291        let result_odd_full = self.extend_result_to_full_domain(result_odd, SymmetryType::Odd)?;
292
293        // Merge the results (at least one singular value is kept)
294        merge_blocks(result_even_full, result_odd_full, self.epsilon)
295    }
296}
297
298/// SVE hints of a kernel expressed on its full domain `[-xmax, xmax] × [-ymax, ymax]`
299///
300/// [`SVEHints`] reports the segments of a centrosymmetric kernel on the
301/// half-domain `[0, xmax] × [0, ymax]` only, which is what [`CentrosymmSVE`]
302/// discretizes. [`NonCentrosymmSVE`] discretizes the full domain, so for a
303/// centrosymmetric kernel this wrapper mirrors the half-domain segments onto
304/// the full domain; the segments of other kernels already cover the full
305/// domain and are passed through unchanged.
306#[derive(Debug, Clone)]
307struct FullDomainHints<H> {
308    inner: H,
309    /// Whether `inner` reports half-domain segments (centrosymmetric kernel)
310    half_domain: bool,
311}
312
313impl<H> FullDomainHints<H> {
314    fn full_domain<T: CustomNumeric>(&self, segments: Vec<T>) -> Vec<T> {
315        if self.half_domain {
316            mirror_segments_to_full_domain(&segments)
317        } else {
318            segments
319        }
320    }
321}
322
323impl<T, H> SVEHints<T> for FullDomainHints<H>
324where
325    T: Copy + Debug + Send + Sync + CustomNumeric,
326    H: SVEHints<T>,
327{
328    fn segments_x(&self) -> Vec<T> {
329        self.full_domain(self.inner.segments_x())
330    }
331
332    fn segments_y(&self) -> Vec<T> {
333        self.full_domain(self.inner.segments_y())
334    }
335
336    fn nsvals(&self) -> usize {
337        self.inner.nsvals()
338    }
339
340    fn ngauss(&self) -> usize {
341        self.inner.ngauss()
342    }
343}
344
345/// Non-centrosymmetric SVE computation
346///
347/// This strategy computes the kernel matrix directly over the full domain
348/// [-xmax, xmax] × [-ymax, ymax]. No symmetry exploitation is performed, so it
349/// works for any kernel.
350///
351/// Centrosymmetric kernels are also expanded correctly: their [`SVEHints`]
352/// segments cover only the half-domain `[0, xmax]` and are mirrored onto the
353/// full domain before discretization. The singular values then agree with
354/// [`CentrosymmSVE`] up to rounding, but the SVD is taken of a single matrix
355/// with twice as many rows and columns as each even/odd block, and the
356/// singular functions carry no parity tag.
357///
358/// The SVD sign gauge is fixed by demanding `u_l(xmax) >= 0`, as
359/// [`CentrosymmSVE`] does and as libsparseir's `SamplingSVE::postprocess`
360/// does via `canonicalize` (convention-matched with
361/// `backend/cxx/include/sparseir/impl/sve_impl.ipp`, libsparseir commit
362/// 4bc58ea).
363#[allow(dead_code)]
364pub struct NonCentrosymmSVE<T, K>
365where
366    T: CustomNumeric + Send + Sync + 'static,
367    K: AbstractKernel + KernelProperties,
368{
369    kernel: K,
370    epsilon: f64,
371    hints: FullDomainHints<K::SVEHintsType<T>>,
372    n_gauss: usize,
373
374    // Geometric information (full domain [-xmax, xmax])
375    segments_x: Vec<T>,
376    segments_y: Vec<T>,
377    gauss_x: Rule<T>,
378    gauss_y: Rule<T>,
379
380    // The general SVE processor
381    sampling_sve: SamplingSVE<T>,
382}
383
384impl<T, K> NonCentrosymmSVE<T, K>
385where
386    T: CustomNumeric + Send + Sync + Clone + 'static,
387    K: AbstractKernel + KernelProperties + Clone,
388    K::SVEHintsType<T>: SVEHints<T> + Clone,
389{
390    /// Create a new NonCentrosymmSVE
391    ///
392    /// # Errors
393    ///
394    /// [`Error::InvalidParameter`] if the SVE hints of the kernel give
395    /// segments that are not finite and strictly increasing
396    pub fn new(kernel: K, epsilon: f64) -> Result<Self, Error> {
397        // SVEHints are half-domain for centrosymmetric kernels; this strategy
398        // needs the full domain (issue #246).
399        let hints = FullDomainHints {
400            inner: kernel.sve_hints::<T>(epsilon),
401            half_domain: kernel.is_centrosymmetric(),
402        };
403
404        // Get segments for full domain [-xmax, xmax]
405        let segments_x = hints.segments_x();
406        let segments_y = hints.segments_y();
407        let n_gauss = hints.ngauss();
408
409        // Create composite Gauss rules for full domain
410        let rule = legendre_generic::<T>(n_gauss);
411        let gauss_x = rule.piecewise(&segments_x)?;
412        let gauss_y = rule.piecewise(&segments_y)?;
413
414        // Create the general SVE processor
415        let sampling_sve = SamplingSVE::new(
416            segments_x.clone(),
417            segments_y.clone(),
418            gauss_x.clone(),
419            gauss_y.clone(),
420            epsilon,
421            n_gauss,
422        );
423
424        Ok(Self {
425            kernel,
426            epsilon,
427            hints,
428            n_gauss,
429            segments_x,
430            segments_y,
431            gauss_x,
432            gauss_y,
433            sampling_sve,
434        })
435    }
436
437    /// Compute kernel matrix for non-centrosymmetric kernel
438    fn compute_matrix(&self) -> DTensor<T, 2> {
439        // Compute K(x, y) directly over full domain
440        let discretized = matrix_from_gauss_noncentrosymmetric(
441            &self.kernel,
442            &self.gauss_x,
443            &self.gauss_y,
444            &self.hints,
445        );
446
447        // Apply weights for SVE
448        discretized.apply_weights_for_sve()
449    }
450}
451
452impl<T, K> SVEStrategy<T> for NonCentrosymmSVE<T, K>
453where
454    T: CustomNumeric + Send + Sync + Clone + 'static,
455    K: AbstractKernel + KernelProperties + Clone,
456    K::SVEHintsType<T>: SVEHints<T> + Clone,
457{
458    fn matrices(&self) -> Vec<DTensor<T, 2>> {
459        // Single matrix for non-centrosymmetric kernel
460        vec![self.compute_matrix()]
461    }
462
463    fn postprocess(
464        &self,
465        u_list: Vec<DTensor<T, 2>>,
466        s_list: Vec<Vec<T>>,
467        v_list: Vec<DTensor<T, 2>>,
468    ) -> Result<SVEResult, Error> {
469        // Process single result using SamplingSVE. The functions are
470        // already on the full domain. Fix the sign gauge u_l(xmax) >= 0 as
471        // CentrosymmSVE does in merge_results.
472        let (u_polys, s, v_polys) = self
473            .sampling_sve
474            .postprocess_block(&u_list[0], &s_list[0], &v_list[0])?;
475        let (u_polys, v_polys) = canonicalize_signs(u_polys, v_polys);
476        // A matrix of rank 0 leaves empty vectors; SVEResult::new reports the
477        // empty `s`.
478        SVEResult::new(
479            PiecewiseLegendrePolyVector::from_polys_unchecked(u_polys),
480            s,
481            PiecewiseLegendrePolyVector::from_polys_unchecked(v_polys),
482            self.epsilon,
483        )
484    }
485}