Skip to main content

sparse_ir_sve/sve/
types.rs

1//! Type definitions for SVE computation
2
3use crate::checks::require_accuracy;
4use crate::error::Error;
5
6/// Working precision type for SVE computations
7///
8/// Values match the C-API constants defined in sparseir.h
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum TworkType {
11    /// Use double precision (64-bit)
12    Float64 = 0, // SPIR_TWORK_FLOAT64
13    /// Use extended precision (128-bit double-double)
14    Float64X2 = 1, // SPIR_TWORK_FLOAT64X2
15    /// Automatically choose precision based on epsilon
16    Auto = -1, // SPIR_TWORK_AUTO
17}
18
19/// Smallest epsilon for which `TworkType::Auto` selects `Float64`
20const AUTO_FLOAT64_MIN_EPSILON: f64 = 1e-8;
21
22impl TworkType {
23    /// The working precision that [`TworkType::Auto`] selects for `epsilon`
24    ///
25    /// This is the single owner of the automatic selection: the SVE and the
26    /// C API helper `spir_choose_working_type` both use it.
27    ///
28    /// # Errors
29    ///
30    /// [`Error::InvalidParameter`] if `epsilon` is not in (0, 1), the range
31    /// every SVE accepts.
32    pub fn auto_for(epsilon: f64) -> Result<Self, Error> {
33        require_accuracy("epsilon", Some(epsilon))?;
34        Ok(auto_twork(Some(epsilon)))
35    }
36}
37
38/// `TworkType::Auto` for a validated epsilon; `None` asks for the best
39/// accuracy and so the extended precision
40fn auto_twork(epsilon: Option<f64>) -> TworkType {
41    match epsilon {
42        Some(eps) if eps >= AUTO_FLOAT64_MIN_EPSILON => TworkType::Float64,
43        _ => TworkType::Float64X2, // MAX_DTYPE equivalent
44    }
45}
46
47/// Determine safe epsilon and working precision
48///
49/// This function determines the safe epsilon value based on the working precision,
50/// and automatically selects the working precision if TworkType::Auto is specified.
51///
52/// # Arguments
53///
54/// * `epsilon` - Required accuracy (non-negative); `None` selects the best
55///   accuracy of the working precision
56/// * `twork` - Working precision type (Auto for automatic selection)
57///
58/// # Returns
59///
60/// Tuple of (safe_epsilon, actual_twork)
61///
62/// # Panics
63///
64/// Panics if epsilon is negative or NaN. [`compute_sve`](crate::sve::compute_sve)
65/// checks it first.
66pub(crate) fn safe_epsilon(epsilon: Option<f64>, twork: TworkType) -> (f64, TworkType) {
67    // Check for a negative or NaN epsilon (following the C++ implementation
68    // for negative values; NaN used to select the automatic accuracy)
69    if let Some(eps) = epsilon.filter(|eps| !(*eps >= 0.0)) {
70        panic!("eps_required must be non-negative, got {eps:?}");
71    }
72
73    // First, choose the working dtype based on the eps required
74    let twork_actual = match twork {
75        TworkType::Auto => auto_twork(epsilon),
76        other => other,
77    };
78
79    // Next, work out the actual epsilon.
80    // The precision floor is the smallest epsilon achievable with the chosen
81    // working type.  The returned epsilon is the *larger* of the user's
82    // request and this floor so that (a) we never promise more accuracy than
83    // the arithmetic can deliver and (b) a user who asks for *less* accuracy
84    // actually gets what they asked for.
85    let precision_floor = match twork_actual {
86        TworkType::Float64 => {
87            // This is technically a bit too low (the true value is about 1.5e-8),
88            // but it's not too far off and easier to remember for the user.
89            1e-8
90        }
91        TworkType::Float64X2 => {
92            // sqrt(Df64 epsilon) ≈ sqrt(2.465e-32) ≈ 1.57e-16
93            use crate::numeric::CustomNumeric;
94            crate::Df64::epsilon().sqrt().to_f64()
95        }
96        _ => 1e-8,
97    };
98    let safe_eps = epsilon.map_or(precision_floor, |eps| eps.max(precision_floor));
99
100    (safe_eps, twork_actual)
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn test_safe_epsilon_auto_float64() {
109        // epsilon=1e-7 > floor=1e-8 → safe_eps should honour the user's request
110        let (safe_eps, twork) = safe_epsilon(Some(1e-7), TworkType::Auto);
111        assert_eq!(twork, TworkType::Float64);
112        assert_eq!(safe_eps, 1e-7);
113    }
114
115    #[test]
116    fn test_safe_epsilon_auto_float64x2() {
117        // epsilon=1e-10 > floor≈1.57e-16 → safe_eps should be the user's epsilon
118        let (safe_eps, twork) = safe_epsilon(Some(1e-10), TworkType::Auto);
119        assert_eq!(twork, TworkType::Float64X2);
120        assert_eq!(safe_eps, 1e-10);
121    }
122
123    #[test]
124    fn test_safe_epsilon_explicit_precision() {
125        // epsilon=1e-7 > floor≈1.57e-16 → safe_eps should honour the user's epsilon
126        let (safe_eps, twork) = safe_epsilon(Some(1e-7), TworkType::Float64X2);
127        assert_eq!(twork, TworkType::Float64X2);
128        assert_eq!(safe_eps, 1e-7);
129    }
130
131    /// `auto_for` splits at 1e-8 like the SVE and rejects every epsilon the
132    /// SVE rejects (#345)
133    #[test]
134    fn test_auto_for_matches_sve_policy() {
135        assert_eq!(TworkType::auto_for(1e-6).unwrap(), TworkType::Float64);
136        assert_eq!(TworkType::auto_for(1e-8).unwrap(), TworkType::Float64);
137        assert_eq!(TworkType::auto_for(0.99e-8).unwrap(), TworkType::Float64X2);
138        assert_eq!(TworkType::auto_for(1e-15).unwrap(), TworkType::Float64X2);
139        for eps in [1e-6, 1e-8, 0.99e-8, 1e-15] {
140            let (_, twork) = safe_epsilon(Some(eps), TworkType::Auto);
141            assert_eq!(TworkType::auto_for(eps).unwrap(), twork);
142        }
143        for eps in [0.0, -1.0, f64::NAN, f64::INFINITY, 1.0, 2.0] {
144            assert!(
145                matches!(
146                    TworkType::auto_for(eps),
147                    Err(Error::InvalidParameter { .. })
148                ),
149                "epsilon {eps:?} must be rejected"
150            );
151        }
152    }
153
154    #[test]
155    #[should_panic(expected = "eps_required must be non-negative")]
156    fn test_negative_epsilon_panics() {
157        safe_epsilon(Some(-1.0), TworkType::Auto);
158    }
159
160    /// NaN is not an accuracy: it used to select the automatic accuracy.
161    /// compute_sve rejects it first; the public helper panics like it does
162    /// for a negative epsilon.
163    #[test]
164    #[should_panic(expected = "eps_required must be non-negative, got NaN")]
165    fn test_nan_epsilon_panics() {
166        safe_epsilon(Some(f64::NAN), TworkType::Auto);
167    }
168}