Skip to main content

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