Skip to main content

sparse_ir_sve/
hints.rs

1//! SVE hints given by the segments of the domain
2//!
3//! A kernel implements [`SVEKernel::sve_hints`] by returning a type that
4//! implements [`SVEHints`]. [`SegmentHints`] is such a type for any kernel:
5//! it holds the segment boundaries and the number of Gauss points per
6//! segment, so that a kernel need not define a hints type of its own.
7
8use crate::error::Error;
9use crate::kernel::{SVEHints, SVEKernel};
10use crate::numeric::CustomNumeric;
11use std::fmt::Debug;
12
13/// [`SVEHints`] given by the segment boundaries of the domain
14///
15/// The boundaries are given on the full domain `[xmin, xmax] × [ymin, ymax]`
16/// of the kernel, whether it is centrosymmetric or not. A centrosymmetric
17/// kernel is discretized on `[0, xmax] × [0, ymax]` and the mirror images of
18/// its segments ([`SVEHints`]): the boundaries in `(0, xmax]` (`(0, ymax]`),
19/// with 0 added if it is not one of them.
20///
21/// The accuracy of the SVE depends on the segments: on each of them, the
22/// kernel must be resolved by polynomials of degree `ngauss - 1` in each
23/// variable. [`sve_residual`](crate::sve::sve_residual) measures how well the
24/// result reproduces the kernel.
25///
26/// # Example
27///
28/// ```
29/// use sparse_ir_sve::{AbstractKernel, CustomNumeric, SVEKernel, ExpandableKernel, SegmentHints};
30/// use std::fmt::Debug;
31///
32/// /// K(x, y) = exp(-(x - y)²) on [-1, 1] × [0, 2]
33/// #[derive(Clone)]
34/// struct Gaussian;
35///
36/// impl AbstractKernel for Gaussian {
37///     fn compute<T: CustomNumeric + Copy + Debug>(&self, x: T, y: T) -> T {
38///         (-(x - y) * (x - y)).exp()
39///     }
40/// }
41///
42/// impl SVEKernel for Gaussian {
43///     type SVEHintsType<T>
44///         = SegmentHints
45///     where
46///         T: Copy + Debug + Send + Sync + CustomNumeric + 'static;
47///
48///     fn xmax(&self) -> f64 {
49///         1.0
50///     }
51///
52///     fn ymax(&self) -> f64 {
53///         2.0
54///     }
55///
56///     fn ymin(&self) -> f64 {
57///         0.0
58///     }
59///
60///     fn sve_hints<T>(&self, _epsilon: f64) -> SegmentHints
61///     where
62///         T: Copy + Debug + Send + Sync + CustomNumeric + 'static,
63///     {
64///         // Four segments on each axis, 16 Gauss points on each segment
65///         SegmentHints::uniform(self, 4, 4, 16).unwrap()
66///     }
67/// }
68///
69/// // Not centrosymmetric: the SVE is taken over the full domain
70/// impl ExpandableKernel for Gaussian {}
71/// ```
72#[derive(Debug, Clone, PartialEq)]
73pub struct SegmentHints {
74    /// Boundaries on x
75    segments_x: Vec<f64>,
76    /// Boundaries on y
77    segments_y: Vec<f64>,
78    /// Gauss points per segment
79    ngauss: usize,
80}
81
82impl SegmentHints {
83    /// Hints with the segment boundaries `segments_x` and `segments_y` of the
84    /// full domain of `kernel` and `ngauss` Gauss points per segment
85    ///
86    /// # Errors
87    ///
88    /// [`Error::InvalidParameter`] if `ngauss` is 0, or the boundaries on an
89    /// axis are not finite and strictly increasing from the lower to the
90    /// upper bound of the domain of `kernel` on that axis (as
91    /// [`SVEKernel::xmin`] and [`SVEKernel::xmax`] return them)
92    pub fn new<K: SVEKernel>(
93        kernel: &K,
94        segments_x: &[f64],
95        segments_y: &[f64],
96        ngauss: usize,
97    ) -> Result<Self, Error> {
98        if ngauss == 0 {
99            return Err(Error::InvalidParameter {
100                name: "ngauss",
101                value: "0".to_string(),
102                reason: "must be positive".to_string(),
103            });
104        }
105        check_segments("segments_x", segments_x, kernel.xmin(), kernel.xmax())?;
106        check_segments("segments_y", segments_y, kernel.ymin(), kernel.ymax())?;
107        Ok(Self {
108            segments_x: segments_x.to_vec(),
109            segments_y: segments_y.to_vec(),
110            ngauss,
111        })
112    }
113
114    /// Hints with `nseg_x` and `nseg_y` segments of equal length on the full
115    /// domain of `kernel` and `ngauss` Gauss points per segment
116    ///
117    /// On a domain symmetric about 0, the boundaries are symmetric as well,
118    /// so a centrosymmetric kernel with an even number of segments is
119    /// discretized on half of them.
120    ///
121    /// # Errors
122    ///
123    /// [`Error::InvalidParameter`] if `nseg_x`, `nseg_y` or `ngauss` is 0, or
124    /// the domain of `kernel` is not a finite, non-empty interval on an axis
125    pub fn uniform<K: SVEKernel>(
126        kernel: &K,
127        nseg_x: usize,
128        nseg_y: usize,
129        ngauss: usize,
130    ) -> Result<Self, Error> {
131        let x = uniform_segments("nseg_x", nseg_x, kernel.xmin(), kernel.xmax())?;
132        let y = uniform_segments("nseg_y", nseg_y, kernel.ymin(), kernel.ymax())?;
133        Self::new(kernel, &x, &y, ngauss)
134    }
135}
136
137/// `n` segments of equal length on `[min, max]`: the boundaries
138/// `c + h (2i - n) / n` with `c` and `h` the midpoint and half-length,
139/// exactly symmetric about `c` and ending exactly at `min` and `max`
140fn uniform_segments(name: &'static str, n: usize, min: f64, max: f64) -> Result<Vec<f64>, Error> {
141    if n == 0 {
142        return Err(Error::InvalidParameter {
143            name,
144            value: "0".to_string(),
145            reason: "must be positive".to_string(),
146        });
147    }
148    let (c, h) = (0.5 * (min + max), 0.5 * (max - min));
149    let mut segments: Vec<f64> = (0..=n)
150        .map(|i| c + h * ((2 * i) as f64 - n as f64) / n as f64)
151        .collect();
152    segments[0] = min;
153    segments[n] = max;
154    Ok(segments)
155}
156
157/// `Ok` if `segments` has at least 2 finite, strictly increasing entries from
158/// `min` to `max`
159fn check_segments(name: &'static str, segments: &[f64], min: f64, max: f64) -> Result<(), Error> {
160    let invalid = |value: String, reason: String| Error::InvalidParameter {
161        name,
162        value,
163        reason,
164    };
165    if segments.len() < 2 {
166        return Err(invalid(
167            format!("{} boundaries", segments.len()),
168            "must have at least 2 entries".to_string(),
169        ));
170    }
171    if let Some((i, s)) = segments.iter().enumerate().find(|(_, s)| !s.is_finite()) {
172        return Err(invalid(
173            format!("{s:?} at index {i}"),
174            "must be finite".to_string(),
175        ));
176    }
177    if let Some(i) = (1..segments.len()).find(|&i| segments[i] <= segments[i - 1]) {
178        return Err(invalid(
179            format!("{:?} after {:?} at index {i}", segments[i], segments[i - 1]),
180            "must be strictly increasing".to_string(),
181        ));
182    }
183    let (first, last) = (segments[0], segments[segments.len() - 1]);
184    if first != min || last != max {
185        return Err(invalid(
186            format!("[{first:?}, {last:?}]"),
187            format!("must run from the lower to the upper bound of the domain, [{min:?}, {max:?}]"),
188        ));
189    }
190    Ok(())
191}
192
193impl<T> SVEHints<T> for SegmentHints
194where
195    T: Copy + Debug + Send + Sync + CustomNumeric,
196{
197    fn segments_x(&self) -> Vec<T> {
198        self.segments_x
199            .iter()
200            .map(|&s| T::from_f64_unchecked(s))
201            .collect()
202    }
203
204    fn segments_y(&self) -> Vec<T> {
205        self.segments_y
206            .iter()
207            .map(|&s| T::from_f64_unchecked(s))
208            .collect()
209    }
210
211    /// The number of singular values the discretization can resolve, at
212    /// most `ngauss` per segment on the axis with fewer segments; the SVE
213    /// does not use it
214    fn nsvals(&self) -> usize {
215        let segments = (self.segments_x.len()).min(self.segments_y.len()) - 1;
216        self.ngauss * segments
217    }
218
219    fn ngauss(&self) -> usize {
220        self.ngauss
221    }
222}
223
224#[cfg(test)]
225#[path = "hints_tests.rs"]
226mod hints_tests;