sparse-ir 0.10.0

Rust implementation of SparseIR functionality
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! SVE computation strategies

use crate::error::Error;
use crate::gauss::{Rule, legendre_generic};
use crate::kernel::{AbstractKernel, CentrosymmKernel, KernelProperties, SVEHints, SymmetryType};
use crate::kernelmatrix::{matrix_from_gauss_noncentrosymmetric, matrix_from_gauss_with_segments};
use crate::numeric::CustomNumeric;
use crate::poly::PiecewiseLegendrePolyVector;
use mdarray::DTensor;
use std::fmt::Debug;

use super::result::SVEResult;
use super::utils::{
    SvdBlock, canonicalize_signs, extend_to_full_domain, merge_blocks,
    mirror_segments_to_full_domain, remove_weights, svd_to_polynomials,
};

/// Trait for SVE computation strategies
pub trait SVEStrategy<T: CustomNumeric> {
    /// Compute the discretized matrices for SVD
    fn matrices(&self) -> Vec<DTensor<T, 2>>;

    /// Post-process SVD results to create SVEResult
    ///
    /// # Errors
    ///
    /// The errors of [`SVEResult::new`]
    fn postprocess(
        &self,
        u_list: Vec<DTensor<T, 2>>,
        s_list: Vec<Vec<T>>,
        v_list: Vec<DTensor<T, 2>>,
    ) -> Result<SVEResult, Error>;
}

/// Sampling-based SVE computation
///
/// This is the general SVE computation strategy that works with discretized kernels.
/// It does NOT know about symmetry - it just processes a given discretized kernel matrix.
///
/// # Responsibility
///
/// - Remove weights from SVD results
/// - Convert to polynomials on the domain specified by segments
/// - Domain extension is caller's responsibility
pub struct SamplingSVE<T>
where
    T: CustomNumeric + Send + Sync + 'static,
{
    segments_x: Vec<T>,
    segments_y: Vec<T>,
    gauss_x: Rule<T>,
    gauss_y: Rule<T>,
    #[allow(dead_code)]
    epsilon: f64,
    n_gauss: usize,
}

impl<T> SamplingSVE<T>
where
    T: CustomNumeric + Send + Sync + 'static,
{
    /// Create a new SamplingSVE
    ///
    /// This takes only the geometric information needed for polynomial conversion,
    /// not the kernel itself.
    pub fn new(
        segments_x: Vec<T>,
        segments_y: Vec<T>,
        gauss_x: Rule<T>,
        gauss_y: Rule<T>,
        epsilon: f64,
        n_gauss: usize,
    ) -> Self {
        Self {
            segments_x,
            segments_y,
            gauss_x,
            gauss_y,
            epsilon,
            n_gauss,
        }
    }

    /// Post-process a single SVD result to create polynomials
    ///
    /// This converts SVD results to piecewise Legendre polynomials
    /// on the domain specified by segments (e.g., [0, xmax] for reduced kernels).
    ///
    /// # Errors
    ///
    /// The errors of the crate-internal `svd_to_polynomials`, and
    /// [`Error::EmptyInput`] if the
    /// SVD result has no singular values
    pub fn postprocess_single(
        &self,
        u: &DTensor<T, 2>,
        s: &[T],
        v: &DTensor<T, 2>,
    ) -> Result<
        (
            PiecewiseLegendrePolyVector,
            Vec<f64>,
            PiecewiseLegendrePolyVector,
        ),
        Error,
    > {
        let (u_polys, s, v_polys) = self.postprocess_block(u, s, v)?;
        Ok((
            PiecewiseLegendrePolyVector::new(u_polys)?,
            s,
            PiecewiseLegendrePolyVector::new(v_polys)?,
        ))
    }

    /// [`Self::postprocess_single`] returning plain vectors, which may be
    /// empty
    fn postprocess_block(
        &self,
        u: &DTensor<T, 2>,
        s: &[T],
        v: &DTensor<T, 2>,
    ) -> Result<SvdBlock, Error> {
        // 1. Remove weights
        // Both U and V have rows corresponding to Gauss points, so is_row=true for both
        let u_unweighted = remove_weights(u, self.gauss_x.w.as_slice(), true);
        let v_unweighted = remove_weights(v, self.gauss_y.w.as_slice(), true);

        // 2. Convert to polynomials
        let gauss_rule_f64 = legendre_generic::<f64>(self.n_gauss);
        let u_polys = svd_to_polynomials(
            &u_unweighted,
            &self.segments_x,
            &gauss_rule_f64,
            self.n_gauss,
        )?;
        let v_polys = svd_to_polynomials(
            &v_unweighted,
            &self.segments_y,
            &gauss_rule_f64,
            self.n_gauss,
        )?;

        // Note: No domain extension here - that's the caller's responsibility
        Ok((u_polys, s.iter().map(|&x| x.to_f64()).collect(), v_polys))
    }
}

/// Centrosymmetric SVE computation
///
/// Exploits even/odd symmetry for efficient computation.
/// This manages the symmetry: creating reduced kernels, extending to full domain, and merging.
pub struct CentrosymmSVE<T, K>
where
    T: CustomNumeric + Send + Sync + 'static,
    K: CentrosymmKernel + KernelProperties,
{
    kernel: K,
    epsilon: f64,
    hints: K::SVEHintsType<T>,
    #[allow(dead_code)]
    n_gauss: usize,

    // Geometric information (positive domain [0, xmax])
    #[allow(dead_code)]
    segments_x: Vec<T>,
    #[allow(dead_code)]
    segments_y: Vec<T>,
    gauss_x: Rule<T>,
    gauss_y: Rule<T>,

    // The general SVE processor (no symmetry knowledge)
    sampling_sve: SamplingSVE<T>,
}

impl<T, K> CentrosymmSVE<T, K>
where
    T: CustomNumeric + Send + Sync + Clone + 'static,
    K: CentrosymmKernel + KernelProperties + Clone,
    K::SVEHintsType<T>: SVEHints<T> + Clone,
{
    /// Create a new CentrosymmSVE
    ///
    /// # Errors
    ///
    /// [`Error::InvalidParameter`] if the SVE hints of the kernel give
    /// segments that are not finite and strictly increasing
    pub fn new(kernel: K, epsilon: f64) -> Result<Self, Error> {
        let hints = kernel.sve_hints::<T>(epsilon);

        // Get segments for positive domain [0, xmax]
        let segments_x = hints.segments_x();
        let segments_y = hints.segments_y();
        let n_gauss = hints.ngauss();

        // Create composite Gauss rules
        let rule = legendre_generic::<T>(n_gauss);
        let gauss_x = rule.piecewise(&segments_x)?;
        let gauss_y = rule.piecewise(&segments_y)?;

        // Create the general SVE processor
        let sampling_sve = SamplingSVE::new(
            segments_x.clone(),
            segments_y.clone(),
            gauss_x.clone(),
            gauss_y.clone(),
            epsilon,
            n_gauss,
        );

        Ok(Self {
            kernel,
            epsilon,
            hints,
            n_gauss,
            segments_x,
            segments_y,
            gauss_x,
            gauss_y,
            sampling_sve,
        })
    }

    /// Compute reduced kernel matrix for given symmetry
    fn compute_reduced_matrix(&self, symmetry: SymmetryType) -> DTensor<T, 2> {
        // Compute K_red(x, y) = K(x, y) + sign * K(x, -y)
        // where x, y are in [0, xmax] and [0, ymax]
        let discretized = matrix_from_gauss_with_segments(
            &self.kernel,
            &self.gauss_x,
            &self.gauss_y,
            symmetry,
            &self.hints,
        );

        // Apply weights for SVE

        discretized.apply_weights_for_sve()
    }

    /// Extend polynomials from [0, xmax] to [-xmax, xmax]
    fn extend_result_to_full_domain(
        &self,
        result: SvdBlock,
        symmetry: SymmetryType,
    ) -> Result<SvdBlock, Error> {
        let (u, s, v) = result;

        // Extend u and v from [0, xmax] to [-xmax, xmax]
        let u_full = extend_to_full_domain(u, symmetry, self.kernel.xmax())?;
        let v_full = extend_to_full_domain(v, symmetry, self.kernel.ymax())?;

        Ok((u_full, s, v_full))
    }
}

impl<T, K> SVEStrategy<T> for CentrosymmSVE<T, K>
where
    T: CustomNumeric + Send + Sync + Clone + 'static,
    K: CentrosymmKernel + KernelProperties + Clone,
    K::SVEHintsType<T>: SVEHints<T> + Clone,
{
    fn matrices(&self) -> Vec<DTensor<T, 2>> {
        // Compute reduced kernels for even and odd symmetries
        let even_matrix = self.compute_reduced_matrix(SymmetryType::Even);
        let odd_matrix = self.compute_reduced_matrix(SymmetryType::Odd);

        vec![even_matrix, odd_matrix]
    }

    fn postprocess(
        &self,
        u_list: Vec<DTensor<T, 2>>,
        s_list: Vec<Vec<T>>,
        v_list: Vec<DTensor<T, 2>>,
    ) -> Result<SVEResult, Error> {
        // Process even and odd results using SamplingSVE (which doesn't know
        // about symmetry). Keep plain vectors until the merge: truncation can
        // empty a block (keeping only the largest singular value empties the
        // odd one), and a PiecewiseLegendrePolyVector cannot be empty.
        let result_even = self
            .sampling_sve
            .postprocess_block(&u_list[0], &s_list[0], &v_list[0])?;
        let result_odd = self
            .sampling_sve
            .postprocess_block(&u_list[1], &s_list[1], &v_list[1])?;

        // Now extend to full domain (this is where symmetry comes in)
        let result_even_full =
            self.extend_result_to_full_domain(result_even, SymmetryType::Even)?;
        let result_odd_full = self.extend_result_to_full_domain(result_odd, SymmetryType::Odd)?;

        // Merge the results (at least one singular value is kept)
        merge_blocks(result_even_full, result_odd_full, self.epsilon)
    }
}

/// SVE hints of a kernel expressed on its full domain `[-xmax, xmax] × [-ymax, ymax]`
///
/// [`SVEHints`] reports the segments of a centrosymmetric kernel on the
/// half-domain `[0, xmax] × [0, ymax]` only, which is what [`CentrosymmSVE`]
/// discretizes. [`NonCentrosymmSVE`] discretizes the full domain, so for a
/// centrosymmetric kernel this wrapper mirrors the half-domain segments onto
/// the full domain; the segments of other kernels already cover the full
/// domain and are passed through unchanged.
#[derive(Debug, Clone)]
struct FullDomainHints<H> {
    inner: H,
    /// Whether `inner` reports half-domain segments (centrosymmetric kernel)
    half_domain: bool,
}

impl<H> FullDomainHints<H> {
    fn full_domain<T: CustomNumeric>(&self, segments: Vec<T>) -> Vec<T> {
        if self.half_domain {
            mirror_segments_to_full_domain(&segments)
        } else {
            segments
        }
    }
}

impl<T, H> SVEHints<T> for FullDomainHints<H>
where
    T: Copy + Debug + Send + Sync + CustomNumeric,
    H: SVEHints<T>,
{
    fn segments_x(&self) -> Vec<T> {
        self.full_domain(self.inner.segments_x())
    }

    fn segments_y(&self) -> Vec<T> {
        self.full_domain(self.inner.segments_y())
    }

    fn nsvals(&self) -> usize {
        self.inner.nsvals()
    }

    fn ngauss(&self) -> usize {
        self.inner.ngauss()
    }
}

/// Non-centrosymmetric SVE computation
///
/// This strategy computes the kernel matrix directly over the full domain
/// [-xmax, xmax] × [-ymax, ymax]. No symmetry exploitation is performed, so it
/// works for any kernel.
///
/// Centrosymmetric kernels are also expanded correctly: their [`SVEHints`]
/// segments cover only the half-domain `[0, xmax]` and are mirrored onto the
/// full domain before discretization. The singular values then agree with
/// [`CentrosymmSVE`] up to rounding, but the SVD is taken of a single matrix
/// with twice as many rows and columns as each even/odd block, and the
/// singular functions carry no parity tag.
///
/// The SVD sign gauge is fixed by demanding `u_l(xmax) >= 0`, as
/// [`CentrosymmSVE`] does and as libsparseir's `SamplingSVE::postprocess`
/// does via `canonicalize` (convention-matched with
/// `backend/cxx/include/sparseir/impl/sve_impl.ipp`, libsparseir commit
/// 4bc58ea).
#[allow(dead_code)]
pub struct NonCentrosymmSVE<T, K>
where
    T: CustomNumeric + Send + Sync + 'static,
    K: AbstractKernel + KernelProperties,
{
    kernel: K,
    epsilon: f64,
    hints: FullDomainHints<K::SVEHintsType<T>>,
    n_gauss: usize,

    // Geometric information (full domain [-xmax, xmax])
    segments_x: Vec<T>,
    segments_y: Vec<T>,
    gauss_x: Rule<T>,
    gauss_y: Rule<T>,

    // The general SVE processor
    sampling_sve: SamplingSVE<T>,
}

impl<T, K> NonCentrosymmSVE<T, K>
where
    T: CustomNumeric + Send + Sync + Clone + 'static,
    K: AbstractKernel + KernelProperties + Clone,
    K::SVEHintsType<T>: SVEHints<T> + Clone,
{
    /// Create a new NonCentrosymmSVE
    ///
    /// # Errors
    ///
    /// [`Error::InvalidParameter`] if the SVE hints of the kernel give
    /// segments that are not finite and strictly increasing
    pub fn new(kernel: K, epsilon: f64) -> Result<Self, Error> {
        // SVEHints are half-domain for centrosymmetric kernels; this strategy
        // needs the full domain (issue #246).
        let hints = FullDomainHints {
            inner: kernel.sve_hints::<T>(epsilon),
            half_domain: kernel.is_centrosymmetric(),
        };

        // Get segments for full domain [-xmax, xmax]
        let segments_x = hints.segments_x();
        let segments_y = hints.segments_y();
        let n_gauss = hints.ngauss();

        // Create composite Gauss rules for full domain
        let rule = legendre_generic::<T>(n_gauss);
        let gauss_x = rule.piecewise(&segments_x)?;
        let gauss_y = rule.piecewise(&segments_y)?;

        // Create the general SVE processor
        let sampling_sve = SamplingSVE::new(
            segments_x.clone(),
            segments_y.clone(),
            gauss_x.clone(),
            gauss_y.clone(),
            epsilon,
            n_gauss,
        );

        Ok(Self {
            kernel,
            epsilon,
            hints,
            n_gauss,
            segments_x,
            segments_y,
            gauss_x,
            gauss_y,
            sampling_sve,
        })
    }

    /// Compute kernel matrix for non-centrosymmetric kernel
    fn compute_matrix(&self) -> DTensor<T, 2> {
        // Compute K(x, y) directly over full domain
        let discretized = matrix_from_gauss_noncentrosymmetric(
            &self.kernel,
            &self.gauss_x,
            &self.gauss_y,
            &self.hints,
        );

        // Apply weights for SVE
        discretized.apply_weights_for_sve()
    }
}

impl<T, K> SVEStrategy<T> for NonCentrosymmSVE<T, K>
where
    T: CustomNumeric + Send + Sync + Clone + 'static,
    K: AbstractKernel + KernelProperties + Clone,
    K::SVEHintsType<T>: SVEHints<T> + Clone,
{
    fn matrices(&self) -> Vec<DTensor<T, 2>> {
        // Single matrix for non-centrosymmetric kernel
        vec![self.compute_matrix()]
    }

    fn postprocess(
        &self,
        u_list: Vec<DTensor<T, 2>>,
        s_list: Vec<Vec<T>>,
        v_list: Vec<DTensor<T, 2>>,
    ) -> Result<SVEResult, Error> {
        // Process single result using SamplingSVE. The functions are
        // already on the full domain. Fix the sign gauge u_l(xmax) >= 0 as
        // CentrosymmSVE does in merge_results.
        let (u_polys, s, v_polys) = self
            .sampling_sve
            .postprocess_block(&u_list[0], &s_list[0], &v_list[0])?;
        let (u_polys, v_polys) = canonicalize_signs(u_polys, v_polys);
        // A matrix of rank 0 leaves empty vectors; SVEResult::new reports the
        // empty `s`.
        SVEResult::new(
            PiecewiseLegendrePolyVector::from_polys_unchecked(u_polys),
            s,
            PiecewiseLegendrePolyVector::from_polys_unchecked(v_polys),
            self.epsilon,
        )
    }
}