1use crate::error::Error;
4use crate::gauss::{Rule, sve_legendre};
5use crate::kernel::{AbstractKernel, ReducedKernel, SVEHints, SVEKernel, 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;
10
11use super::result::SVEResult;
12use super::utils::{
13 SvdBlock, canonicalize_signs, extend_to_full_domain, half_domain_segments, merge_blocks,
14 remove_weights, svd_to_polynomials,
15};
16
17pub struct KernelBlock<'a, T> {
24 nrows: usize,
25 ncols: usize,
26 entry: Box<dyn Fn(usize, usize) -> T + Sync + 'a>,
27}
28
29impl<'a, T: CustomNumeric> KernelBlock<'a, T> {
30 pub fn new(nrows: usize, ncols: usize, entry: impl Fn(usize, usize) -> T + Sync + 'a) -> Self {
32 Self {
33 nrows,
34 ncols,
35 entry: Box::new(entry),
36 }
37 }
38
39 pub fn nrows(&self) -> usize {
41 self.nrows
42 }
43
44 pub fn ncols(&self) -> usize {
46 self.ncols
47 }
48
49 pub fn entry(&self, i: usize, j: usize) -> T {
51 (self.entry)(i, j)
52 }
53}
54
55pub trait SVEStrategy<T: CustomNumeric> {
57 fn matrices(&self) -> Vec<Mat<T>>;
59
60 fn blocks(&self) -> Vec<KernelBlock<'_, T>>
68 where
69 T: Send + Sync + 'static,
70 {
71 self.matrices()
72 .into_iter()
73 .map(|m| {
74 let (nrows, ncols) = *m.shape();
75 KernelBlock::new(nrows, ncols, move |i, j| m[[i, j]])
76 })
77 .collect()
78 }
79
80 fn postprocess(
86 &self,
87 u_list: Vec<Mat<T>>,
88 s_list: Vec<Vec<T>>,
89 v_list: Vec<Mat<T>>,
90 ) -> Result<SVEResult, Error>;
91}
92
93pub struct SamplingSVE<T>
104where
105 T: CustomNumeric + Send + Sync + 'static,
106{
107 segments_x: Vec<T>,
108 segments_y: Vec<T>,
109 gauss_x: Rule<T>,
110 gauss_y: Rule<T>,
111 #[allow(dead_code)]
112 epsilon: f64,
113 n_gauss: usize,
114}
115
116impl<T> SamplingSVE<T>
117where
118 T: CustomNumeric + Send + Sync + 'static,
119{
120 pub fn new(
125 segments_x: Vec<T>,
126 segments_y: Vec<T>,
127 gauss_x: Rule<T>,
128 gauss_y: Rule<T>,
129 epsilon: f64,
130 n_gauss: usize,
131 ) -> Self {
132 Self {
133 segments_x,
134 segments_y,
135 gauss_x,
136 gauss_y,
137 epsilon,
138 n_gauss,
139 }
140 }
141
142 pub(crate) fn weighted_block<'a>(
145 &'a self,
146 k: impl Fn(T, T) -> T + Sync + 'a,
147 ) -> KernelBlock<'a, T> {
148 let wx: Vec<T> = self.gauss_x.w.iter().map(|w| w.sqrt()).collect();
149 let wy: Vec<T> = self.gauss_y.w.iter().map(|w| w.sqrt()).collect();
150 let (x, y) = (&self.gauss_x.x, &self.gauss_y.x);
151 KernelBlock::new(x.len(), y.len(), move |i, j| k(x[i], y[j]) * wx[i] * wy[j])
152 }
153
154 pub fn postprocess_single(
165 &self,
166 u: &Mat<T>,
167 s: &[T],
168 v: &Mat<T>,
169 ) -> Result<
170 (
171 PiecewiseLegendrePolyVector,
172 Vec<f64>,
173 PiecewiseLegendrePolyVector,
174 ),
175 Error,
176 > {
177 let (u_polys, s, v_polys) = self.postprocess_block(u, s, v)?;
178 Ok((
179 PiecewiseLegendrePolyVector::new(u_polys)?,
180 s,
181 PiecewiseLegendrePolyVector::new(v_polys)?,
182 ))
183 }
184
185 fn postprocess_block(&self, u: &Mat<T>, s: &[T], v: &Mat<T>) -> Result<SvdBlock, Error> {
188 let u_unweighted = remove_weights(u, self.gauss_x.w.as_slice(), true);
191 let v_unweighted = remove_weights(v, self.gauss_y.w.as_slice(), true);
192
193 let gauss_rule_f64 = sve_legendre::<f64>(self.n_gauss);
195 let u_polys = svd_to_polynomials(
196 &u_unweighted,
197 &self.segments_x,
198 &gauss_rule_f64,
199 self.n_gauss,
200 )?;
201 let v_polys = svd_to_polynomials(
202 &v_unweighted,
203 &self.segments_y,
204 &gauss_rule_f64,
205 self.n_gauss,
206 )?;
207
208 Ok((u_polys, s.iter().map(|&x| x.to_f64()).collect(), v_polys))
210 }
211}
212
213pub struct CentrosymmSVE<T, K>
218where
219 T: CustomNumeric + Send + Sync + 'static,
220 K: ReducedKernel + SVEKernel,
221{
222 kernel: K,
223 epsilon: f64,
224 hints: K::SVEHintsType<T>,
225 #[allow(dead_code)]
226 n_gauss: usize,
227
228 #[allow(dead_code)]
230 segments_x: Vec<T>,
231 #[allow(dead_code)]
232 segments_y: Vec<T>,
233 gauss_x: Rule<T>,
234 gauss_y: Rule<T>,
235
236 sampling_sve: SamplingSVE<T>,
238}
239
240impl<T, K> CentrosymmSVE<T, K>
241where
242 T: CustomNumeric + Send + Sync + Clone + 'static,
243 K: ReducedKernel + SVEKernel + Clone,
244 K::SVEHintsType<T>: SVEHints<T> + Clone,
245{
246 pub fn new(kernel: K, epsilon: f64) -> Result<Self, Error> {
255 for (name, min, max) in [
258 ("kernel domain [xmin, xmax]", kernel.xmin(), kernel.xmax()),
259 ("kernel domain [ymin, ymax]", kernel.ymin(), kernel.ymax()),
260 ] {
261 if min != -max {
262 return Err(Error::InvalidParameter {
263 name,
264 value: format!("[{min:?}, {max:?}]"),
265 reason: "must be symmetric about 0 for a centrosymmetric kernel".to_string(),
266 });
267 }
268 }
269 let hints = kernel.sve_hints::<T>(epsilon);
270
271 let segments_x = half_domain_segments(&hints.segments_x());
274 let segments_y = half_domain_segments(&hints.segments_y());
275 let n_gauss = hints.ngauss();
276
277 let rule = sve_legendre::<T>(n_gauss);
279 let gauss_x = rule.piecewise(&segments_x)?;
280 let gauss_y = rule.piecewise(&segments_y)?;
281
282 let sampling_sve = SamplingSVE::new(
284 segments_x.clone(),
285 segments_y.clone(),
286 gauss_x.clone(),
287 gauss_y.clone(),
288 epsilon,
289 n_gauss,
290 );
291
292 Ok(Self {
293 kernel,
294 epsilon,
295 hints,
296 n_gauss,
297 segments_x,
298 segments_y,
299 gauss_x,
300 gauss_y,
301 sampling_sve,
302 })
303 }
304
305 fn compute_reduced_matrix(&self, symmetry: SymmetryType) -> Mat<T> {
307 let discretized = matrix_from_gauss_with_segments(
310 &self.kernel,
311 &self.gauss_x,
312 &self.gauss_y,
313 symmetry,
314 &self.hints,
315 );
316
317 discretized.apply_weights_for_sve()
320 }
321
322 fn extend_result_to_full_domain(
324 &self,
325 result: SvdBlock,
326 symmetry: SymmetryType,
327 ) -> Result<SvdBlock, Error> {
328 let (u, s, v) = result;
329
330 let u_full = extend_to_full_domain(u, symmetry)?;
332 let v_full = extend_to_full_domain(v, symmetry)?;
333
334 Ok((u_full, s, v_full))
335 }
336}
337
338impl<T, K> SVEStrategy<T> for CentrosymmSVE<T, K>
339where
340 T: CustomNumeric + Send + Sync + Clone + 'static,
341 K: ReducedKernel + SVEKernel + Clone,
342 K::SVEHintsType<T>: SVEHints<T> + Clone,
343{
344 fn matrices(&self) -> Vec<Mat<T>> {
345 let even_matrix = self.compute_reduced_matrix(SymmetryType::Even);
347 let odd_matrix = self.compute_reduced_matrix(SymmetryType::Odd);
348
349 vec![even_matrix, odd_matrix]
350 }
351
352 fn blocks(&self) -> Vec<KernelBlock<'_, T>> {
353 [SymmetryType::Even, SymmetryType::Odd]
355 .into_iter()
356 .map(|symmetry| {
357 self.sampling_sve
358 .weighted_block(move |x, y| self.kernel.compute_reduced(x, y, symmetry))
359 })
360 .collect()
361 }
362
363 fn postprocess(
364 &self,
365 u_list: Vec<Mat<T>>,
366 s_list: Vec<Vec<T>>,
367 v_list: Vec<Mat<T>>,
368 ) -> Result<SVEResult, Error> {
369 let result_even = self
374 .sampling_sve
375 .postprocess_block(&u_list[0], &s_list[0], &v_list[0])?;
376 let result_odd = self
377 .sampling_sve
378 .postprocess_block(&u_list[1], &s_list[1], &v_list[1])?;
379
380 let result_even_full =
382 self.extend_result_to_full_domain(result_even, SymmetryType::Even)?;
383 let result_odd_full = self.extend_result_to_full_domain(result_odd, SymmetryType::Odd)?;
384
385 merge_blocks(result_even_full, result_odd_full, self.epsilon)
387 }
388}
389
390#[allow(dead_code)]
408pub struct NonCentrosymmSVE<T, K>
409where
410 T: CustomNumeric + Send + Sync + 'static,
411 K: AbstractKernel + SVEKernel,
412{
413 kernel: K,
414 epsilon: f64,
415 hints: K::SVEHintsType<T>,
416 n_gauss: usize,
417
418 segments_x: Vec<T>,
420 segments_y: Vec<T>,
421 gauss_x: Rule<T>,
422 gauss_y: Rule<T>,
423
424 sampling_sve: SamplingSVE<T>,
426}
427
428impl<T, K> NonCentrosymmSVE<T, K>
429where
430 T: CustomNumeric + Send + Sync + Clone + 'static,
431 K: AbstractKernel + SVEKernel + Clone,
432 K::SVEHintsType<T>: SVEHints<T> + Clone,
433{
434 pub fn new(kernel: K, epsilon: f64) -> Result<Self, Error> {
444 let hints = kernel.sve_hints::<T>(epsilon);
445
446 let segments_x = hints.segments_x();
448 let segments_y = hints.segments_y();
449 let n_gauss = hints.ngauss();
450
451 let rule = sve_legendre::<T>(n_gauss);
453 let gauss_x = rule.piecewise(&segments_x)?;
454 let gauss_y = rule.piecewise(&segments_y)?;
455 check_segment_ends(
456 "SVE hints segments_x",
457 &segments_x,
458 kernel.xmin(),
459 kernel.xmax(),
460 )?;
461 check_segment_ends(
462 "SVE hints segments_y",
463 &segments_y,
464 kernel.ymin(),
465 kernel.ymax(),
466 )?;
467
468 let sampling_sve = SamplingSVE::new(
470 segments_x.clone(),
471 segments_y.clone(),
472 gauss_x.clone(),
473 gauss_y.clone(),
474 epsilon,
475 n_gauss,
476 );
477
478 Ok(Self {
479 kernel,
480 epsilon,
481 hints,
482 n_gauss,
483 segments_x,
484 segments_y,
485 gauss_x,
486 gauss_y,
487 sampling_sve,
488 })
489 }
490
491 fn compute_matrix(&self) -> Mat<T> {
493 let discretized = matrix_from_gauss_noncentrosymmetric(
495 &self.kernel,
496 &self.gauss_x,
497 &self.gauss_y,
498 &self.hints,
499 );
500
501 discretized.apply_weights_for_sve()
503 }
504}
505
506fn check_segment_ends<T: CustomNumeric>(
512 name: &'static str,
513 segments: &[T],
514 min: f64,
515 max: f64,
516) -> Result<(), Error> {
517 let (first, last) = (segments[0].to_f64(), segments[segments.len() - 1].to_f64());
518 if first != min || last != max {
519 return Err(Error::InvalidParameter {
520 name,
521 value: format!("[{first:?}, {last:?}]"),
522 reason: format!(
523 "must run from the lower to the upper bound of the domain, [{min:?}, {max:?}]"
524 ),
525 });
526 }
527 Ok(())
528}
529
530impl<T, K> SVEStrategy<T> for NonCentrosymmSVE<T, K>
531where
532 T: CustomNumeric + Send + Sync + Clone + 'static,
533 K: AbstractKernel + SVEKernel + Clone,
534 K::SVEHintsType<T>: SVEHints<T> + Clone,
535{
536 fn matrices(&self) -> Vec<Mat<T>> {
537 vec![self.compute_matrix()]
539 }
540
541 fn blocks(&self) -> Vec<KernelBlock<'_, T>> {
542 vec![
544 self.sampling_sve
545 .weighted_block(|x, y| self.kernel.compute(x, y)),
546 ]
547 }
548
549 fn postprocess(
550 &self,
551 u_list: Vec<Mat<T>>,
552 s_list: Vec<Vec<T>>,
553 v_list: Vec<Mat<T>>,
554 ) -> Result<SVEResult, Error> {
555 let (u_polys, s, v_polys) = self
559 .sampling_sve
560 .postprocess_block(&u_list[0], &s_list[0], &v_list[0])?;
561 let (u_polys, v_polys) = canonicalize_signs(u_polys, v_polys);
562 SVEResult::new(
565 PiecewiseLegendrePolyVector::from_polys_unchecked(u_polys),
566 s,
567 PiecewiseLegendrePolyVector::from_polys_unchecked(v_polys),
568 self.epsilon,
569 )
570 }
571}