Skip to main content

sparse_ir_sve/sve/
result.rs

1//! SVE result container
2
3use crate::checks::{require_nonzero_size, require_threshold};
4use crate::error::Error;
5use crate::matrix::Mat;
6use crate::poly::PiecewiseLegendrePolyVector;
7
8/// Result of Singular Value Expansion computation
9#[derive(Debug, Clone)]
10pub struct SVEResult {
11    /// Left singular functions (u)
12    pub(crate) u: PiecewiseLegendrePolyVector,
13    /// Singular values in non-increasing order
14    pub(crate) s: Vec<f64>,
15    /// Right singular functions (v)
16    pub(crate) v: PiecewiseLegendrePolyVector,
17    /// Accuracy parameter used for computation
18    pub(crate) epsilon: f64,
19}
20
21impl SVEResult {
22    /// Left singular functions, one per singular value
23    pub fn u(&self) -> &PiecewiseLegendrePolyVector {
24        &self.u
25    }
26
27    /// Singular values, in non-increasing order
28    pub fn s(&self) -> &[f64] {
29        &self.s
30    }
31
32    /// Right singular functions, one per singular value
33    pub fn v(&self) -> &PiecewiseLegendrePolyVector {
34        &self.v
35    }
36
37    /// Accuracy the expansion was computed to
38    pub fn epsilon(&self) -> f64 {
39        self.epsilon
40    }
41
42    /// Build an SVE from a kernel matrix discretized on the Gauss points of
43    /// `segments_x` x `segments_y`
44    ///
45    /// `matrix[i][j]` is `sqrt(w_x[i]) * K(x[i], y[j]) * sqrt(w_y[j])` for the
46    /// piecewise Gauss-Legendre rules `gauss_x` and `gauss_y` of `n_gauss`
47    /// points per segment, so `matrix` has `n_gauss * n_segments` rows and
48    /// columns. The weights are divided out of the singular vectors before
49    /// they become piecewise Legendre polynomials.
50    ///
51    /// # Errors
52    ///
53    /// * The errors of [`compute_svd_dtensor`](crate::tsvd::compute_svd_dtensor):
54    ///   [`Error::EmptyInput`], [`Error::NonFiniteInput`] and
55    ///   [`Error::DecompositionFailed`]
56    /// * [`Error::InvalidParameter`] if `matrix` does not have one row
57    ///   (column) per Gauss point of `segments_x` (`segments_y`), or if a
58    ///   segment array has fewer than 2 entries
59    /// * The errors of [`Self::new`], in particular [`Error::EmptyInput`] for
60    ///   a matrix of rank 0, which has no singular functions
61    pub fn from_discretized_matrix<T: crate::numeric::CustomNumeric + 'static>(
62        matrix: &Mat<T>,
63        gauss_x: &crate::gauss::Rule<T>,
64        gauss_y: &crate::gauss::Rule<T>,
65        segments_x: &[f64],
66        segments_y: &[f64],
67        n_gauss: usize,
68        epsilon: f64,
69    ) -> Result<Self, Error> {
70        require_gauss_point_count(matrix.shape().0, segments_x, n_gauss, "rows")?;
71        require_gauss_point_count(matrix.shape().1, segments_y, n_gauss, "columns")?;
72
73        let (u, s, v) = crate::tsvd::compute_svd_dtensor(matrix)?;
74
75        // The matrix carries the weights: divide them out of the singular
76        // vectors before they become polynomials.
77        let u_unweighted = crate::sve::utils::remove_weights(&u, gauss_x.w.as_slice(), true);
78        let v_unweighted = crate::sve::utils::remove_weights(&v, gauss_y.w.as_slice(), true);
79
80        let u_f64 = Mat::<f64>::from_fn(u_unweighted.dims(), |idx| u_unweighted[idx].to_f64());
81        let v_f64 = Mat::<f64>::from_fn(v_unweighted.dims(), |idx| v_unweighted[idx].to_f64());
82
83        let gauss_rule_f64 = crate::gauss::legendre::<f64>(n_gauss);
84        let u_polys =
85            crate::sve::utils::svd_to_polynomials(&u_f64, segments_x, &gauss_rule_f64, n_gauss)?;
86        let v_polys =
87            crate::sve::utils::svd_to_polynomials(&v_f64, segments_y, &gauss_rule_f64, n_gauss)?;
88
89        let s_f64: Vec<f64> = s.iter().map(|sv| sv.to_f64()).collect();
90
91        // A matrix of rank 0 has no singular functions. The vectors are built
92        // through the field (`PiecewiseLegendrePolyVector::new` rejects an
93        // empty vector), so that `Self::new` reports the empty `s`.
94        Self::new(
95            PiecewiseLegendrePolyVector::from_polys_unchecked(u_polys),
96            s_f64,
97            PiecewiseLegendrePolyVector::from_polys_unchecked(v_polys),
98            epsilon,
99        )
100    }
101
102    /// [`Self::from_discretized_matrix`] for a centrosymmetric kernel, whose
103    /// even and odd parts are discretized on the half domains
104    /// `segments_x` x `segments_y` and extended to `[-xmax, xmax]` and
105    /// `[-ymax, ymax]`
106    ///
107    /// `xmax` and `ymax` are unused: the domains follow from the segments.
108    ///
109    /// A block of rank 0 (the odd part of a kernel that is even in y, say)
110    /// contributes no singular function; only both blocks being empty is an
111    /// error.
112    ///
113    /// The decomposition runs in `T`, like [`Self::from_discretized_matrix`]:
114    /// a `Df64` matrix keeps its low-order parts through the SVD and is
115    /// narrowed to `f64` only when the singular vectors become piecewise
116    /// Legendre polynomials (which are `f64`).
117    ///
118    /// # Errors
119    ///
120    /// * The errors of [`Self::from_discretized_matrix`] for each block,
121    ///   except that an empty block is accepted
122    /// * The errors of the crate-internal `extend_to_full_domain` and
123    ///   `merge_results`, in particular [`Error::EmptyInput`] if both blocks
124    ///   are empty
125    #[allow(clippy::too_many_arguments)]
126    pub fn from_discretized_matrices_centrosymmetric<T: crate::numeric::CustomNumeric + 'static>(
127        even: &Mat<T>,
128        odd: &Mat<T>,
129        gauss_x: &crate::gauss::Rule<T>,
130        gauss_y: &crate::gauss::Rule<T>,
131        segments_x: &[f64],
132        segments_y: &[f64],
133        n_gauss: usize,
134        _xmax: f64,
135        _ymax: f64,
136        epsilon: f64,
137    ) -> Result<Self, Error> {
138        use crate::kernel::SymmetryType;
139        use crate::sve::utils::{extend_to_full_domain, merge_results, svd_to_polynomials};
140
141        for matrix in [even, odd] {
142            require_gauss_point_count(matrix.shape().0, segments_x, n_gauss, "rows")?;
143            require_gauss_point_count(matrix.shape().1, segments_y, n_gauss, "columns")?;
144        }
145
146        let gauss_rule_f64 = crate::gauss::legendre::<f64>(n_gauss);
147        // `svd_to_polynomials` takes the segments in the working precision; the
148        // public API keeps them f64, so widen them once here.
149        let segments_x_t: Vec<T> = segments_x
150            .iter()
151            .map(|&v| T::from_f64_unchecked(v))
152            .collect();
153        let segments_y_t: Vec<T> = segments_y
154            .iter()
155            .map(|&v| T::from_f64_unchecked(v))
156            .collect();
157        let block = |matrix: &Mat<T>, symmetry: SymmetryType| {
158            let (u, s, v) = crate::tsvd::compute_svd_dtensor(matrix)?;
159            let u_unweighted = crate::sve::utils::remove_weights(&u, gauss_x.w.as_slice(), true);
160            let v_unweighted = crate::sve::utils::remove_weights(&v, gauss_y.w.as_slice(), true);
161            let u_polys =
162                svd_to_polynomials(&u_unweighted, &segments_x_t, &gauss_rule_f64, n_gauss)?;
163            let v_polys =
164                svd_to_polynomials(&v_unweighted, &segments_y_t, &gauss_rule_f64, n_gauss)?;
165            let u_full = extend_to_full_domain(u_polys, symmetry)?;
166            let v_full = extend_to_full_domain(v_polys, symmetry)?;
167            Ok::<_, Error>((
168                PiecewiseLegendrePolyVector::from_polys_unchecked(u_full),
169                s.iter().map(|sv| sv.to_f64()).collect::<Vec<f64>>(),
170                PiecewiseLegendrePolyVector::from_polys_unchecked(v_full),
171            ))
172        };
173
174        let result_even = block(even, SymmetryType::Even)?;
175        let result_odd = block(odd, SymmetryType::Odd)?;
176        merge_results(result_even, result_odd, epsilon)
177    }
178
179    /// Create a new SVEResult
180    ///
181    /// # Errors
182    ///
183    /// * [`Error::EmptyInput`] if `s` is empty
184    /// * [`Error::InvalidParameter`] if `u` or `v` does not have one function
185    ///   per singular value, a singular value is not positive, the singular
186    ///   values are not non-increasing, or `epsilon` is not in [0, 1)
187    /// * [`Error::NonFiniteInput`] if a singular value is NaN or infinite
188    pub fn new(
189        u: PiecewiseLegendrePolyVector,
190        s: Vec<f64>,
191        v: PiecewiseLegendrePolyVector,
192        epsilon: f64,
193    ) -> Result<Self, Error> {
194        let result = Self { u, s, v, epsilon };
195        result.check()?;
196        Ok(result)
197    }
198
199    /// Check the invariants that [`Self::new`] guarantees
200    fn check(&self) -> Result<(), Error> {
201        let n = self.s.len();
202        if n == 0 {
203            return Err(Error::EmptyInput { name: "s" });
204        }
205        for (name, funcs) in [("u", &self.u), ("v", &self.v)] {
206            let len = funcs.polys().len();
207            if len != n {
208                return Err(Error::InvalidParameter {
209                    name,
210                    value: format!("{len} functions"),
211                    reason: format!("must have one function per singular value ({n})"),
212                });
213            }
214        }
215        for (i, &x) in self.s.iter().enumerate() {
216            if !x.is_finite() {
217                return Err(Error::NonFiniteInput {
218                    name: "s",
219                    index: vec![i],
220                    value: x,
221                });
222            }
223            if x <= 0.0 {
224                return Err(Error::InvalidParameter {
225                    name: "s",
226                    value: format!("{x:?} at index {i}"),
227                    reason: "singular values must be positive".to_string(),
228                });
229            }
230            if i > 0 && x > self.s[i - 1] {
231                return Err(Error::InvalidParameter {
232                    name: "s",
233                    value: format!("{x:?} at index {i}, after {:?}", self.s[i - 1]),
234                    reason: "singular values must be non-increasing".to_string(),
235                });
236            }
237        }
238        require_threshold("epsilon", Some(self.epsilon))
239    }
240
241    /// The expansion truncated to the singular values ≥ `eps` times the
242    /// largest one, at most `max_size` of them
243    ///
244    /// `eps` is [`Self::epsilon`] by default, and is the accuracy of the
245    /// result. At least the largest singular value is kept, since `eps` < 1.
246    ///
247    /// # Errors
248    ///
249    /// * [`Error::InvalidParameter`] if `eps` is not in [0, 1) (0 keeps every
250    ///   singular value) or `max_size` is `Some(0)`
251    pub fn truncate(&self, eps: Option<f64>, max_size: Option<usize>) -> Result<Self, Error> {
252        let (u, s, v) = self.part_impl(eps, max_size)?;
253        Self::new(u, s, v, eps.unwrap_or(self.epsilon))
254    }
255
256    /// The singular functions and values of [`Self::truncate`]
257    fn part_impl(
258        &self,
259        eps: Option<f64>,
260        max_size: Option<usize>,
261    ) -> Result<
262        (
263            PiecewiseLegendrePolyVector,
264            Vec<f64>,
265            PiecewiseLegendrePolyVector,
266        ),
267        Error,
268    > {
269        self.check()?;
270        require_threshold("eps", eps)?;
271        require_nonzero_size("max_size", max_size)?;
272        let eps = eps.unwrap_or(self.epsilon);
273        let threshold = eps * self.s[0];
274
275        let mut cut = 0;
276        for &val in self.s.iter() {
277            if val >= threshold {
278                cut += 1;
279            } else {
280                break;
281            }
282        }
283
284        if let Some(max) = max_size {
285            cut = cut.min(max);
286        }
287
288        // Extract subsets
289        let u_part = PiecewiseLegendrePolyVector::new(self.u.polys()[..cut].to_vec())?;
290        let s_part = self.s[..cut].to_vec();
291        let v_part = PiecewiseLegendrePolyVector::new(self.v.polys()[..cut].to_vec())?;
292
293        Ok((u_part, s_part, v_part))
294    }
295}
296
297/// The rows (columns) of a discretized kernel matrix are the Gauss points of
298/// the segments: `n_gauss` per segment.
299///
300/// # Errors
301/// * [`Error::InvalidParameter`] if `segments` has fewer than 2 entries or
302///   `len` is not `n_gauss * (segments.len() - 1)`
303fn require_gauss_point_count(
304    len: usize,
305    segments: &[f64],
306    n_gauss: usize,
307    what: &'static str,
308) -> Result<(), Error> {
309    if segments.len() < 2 {
310        return Err(Error::InvalidParameter {
311            name: "segments",
312            value: format!("{} boundaries", segments.len()),
313            reason: "must have at least 2 entries".to_string(),
314        });
315    }
316    let expected = n_gauss * (segments.len() - 1);
317    if len != expected {
318        return Err(Error::InvalidParameter {
319            name: "matrix",
320            value: format!("{len} {what}"),
321            reason: format!("must have one per Gauss point of the segments ({expected})"),
322        });
323    }
324    Ok(())
325}