Skip to main content

sparse_ir_sve/
numeric.rs

1//! Custom numeric traits for high-precision computation
2//!
3//! This module provides custom numeric traits that work with both f64 and the xprec Df64 backend
4//! for high-precision numerical computation in gauss quadrature and matrix operations.
5
6use crate::Df64;
7use libm::expm1;
8use simba::scalar::ComplexField;
9use std::fmt::Debug;
10
11/// Custom numeric trait for high-precision numerical computation
12///
13/// This trait provides the essential numeric operations needed for gauss module
14/// and matrix_from_gauss functions. Supports both f64 and Df64 types.
15///
16/// Uses standard traits for common operations:
17/// - num_traits::Zero for zero()
18/// - simba::scalar::ComplexField for mathematical functions (abs, sqrt, cos, sin, exp, etc.)
19/// - ComplexField::is_finite() for is_finite()
20///
21/// It is implemented for `f64` and `Df64` only (sealed), so that methods can
22/// be added without breaking code that uses it. Both are real:
23/// `ComplexField::abs` returns `Self`.
24pub trait CustomNumeric:
25    sealed::Sealed
26    + Copy
27    + Debug
28    + PartialOrd
29    + std::fmt::Display
30    + std::ops::Add<Output = Self>
31    + std::ops::Sub<Output = Self>
32    + std::ops::Mul<Output = Self>
33    + std::ops::Div<Output = Self>
34    + std::ops::Neg<Output = Self>
35    + num_traits::Zero                    // zero()
36    + simba::scalar::ComplexField<RealField = Self> // abs, cos, sin, exp, sqrt, etc.
37{
38    /// Convert from f64 to Self (direct conversion, no Option)
39    ///
40    /// This is a static method that can be called as T::from_f64_unchecked(x)
41    /// Renamed to avoid conflict with num_traits::FromPrimitive::from_f64
42    fn from_f64_unchecked(x: f64) -> Self;
43
44    /// Convert from any CustomNumeric type to Self (generic conversion)
45    ///
46    /// This allows conversion between different numeric types while preserving precision.
47    /// Can be called as T::convert_from(other_numeric_value)
48    fn convert_from<U: CustomNumeric + 'static>(value: U) -> Self;
49
50
51    /// Convert to f64
52    fn to_f64(self) -> f64;
53
54    /// Get machine epsilon
55    fn epsilon() -> Self;
56
57    /// Get high-precision PI constant
58    fn pi() -> Self;
59
60    /// Maximum of two values (not provided by ComplexField)
61    fn max(self, other: Self) -> Self;
62
63    /// Minimum of two values (not provided by ComplexField)
64    fn min(self, other: Self) -> Self;
65
66    /// Compute exp(self) - 1 with higher precision for small values
67    ///
68    /// This is more accurate than `self.exp() - 1` when self is close to zero,
69    /// avoiding catastrophic cancellation.
70    fn exp_m1(self) -> Self;
71}
72
73/// The types that implement [`CustomNumeric`]
74mod sealed {
75    pub trait Sealed {}
76    impl Sealed for f64 {}
77    impl Sealed for crate::Df64 {}
78}
79
80/// f64 implementation of CustomNumeric
81impl CustomNumeric for f64 {
82    fn from_f64_unchecked(x: f64) -> Self {
83        x
84    }
85
86    fn convert_from<U: CustomNumeric + 'static>(value: U) -> Self {
87        // Use match to optimize conversion based on the source type
88        // Note: Using TypeId for compile-time optimization, but falling back to safe conversion
89        match std::any::TypeId::of::<U>() {
90            // For f64 to f64, this is just a copy (no conversion needed)
91            id if id == std::any::TypeId::of::<f64>() => {
92                // Safe: f64 to f64 conversion
93                // This is a no-op for f64
94                value.to_f64()
95            }
96            // For Df64 to f64, use the conversion method
97            id if id == std::any::TypeId::of::<Df64>() => {
98                // Safe: Df64 to f64 conversion
99                value.to_f64()
100            }
101            // Fallback: convert via f64 for unknown types
102            _ => value.to_f64(),
103        }
104    }
105
106    fn to_f64(self) -> f64 {
107        self
108    }
109
110    fn epsilon() -> Self {
111        f64::EPSILON
112    }
113
114    fn pi() -> Self {
115        std::f64::consts::PI
116    }
117
118    fn max(self, other: Self) -> Self {
119        self.max(other)
120    }
121
122    fn min(self, other: Self) -> Self {
123        self.min(other)
124    }
125
126    fn exp_m1(self) -> Self {
127        expm1(self)
128    }
129}
130
131/// Df64 implementation of CustomNumeric
132impl CustomNumeric for Df64 {
133    fn from_f64_unchecked(x: f64) -> Self {
134        Df64::from(x)
135    }
136
137    fn convert_from<U: CustomNumeric + 'static>(value: U) -> Self {
138        // Use match to optimize conversion based on the source type
139        // Note: Using TypeId for compile-time optimization, but falling back to safe conversion
140        match std::any::TypeId::of::<U>() {
141            // For f64 to Df64, use the conversion method
142            id if id == std::any::TypeId::of::<f64>() => {
143                // Safe: f64 to Df64 conversion
144                let f64_value = value.to_f64();
145                Self::from_f64_unchecked(f64_value)
146            }
147            // For Df64 to Df64, this is just a copy (no conversion needed)
148            // (keeps both parts, unlike going through f64)
149            id if id == std::any::TypeId::of::<Df64>() => *(&value as &dyn std::any::Any)
150                .downcast_ref::<Df64>()
151                .expect("U is Df64"),
152            // Fallback: convert via f64 for unknown types
153            _ => Self::from_f64_unchecked(value.to_f64()),
154        }
155    }
156
157    fn to_f64(self) -> f64 {
158        // Use hi() and lo() methods for better precision
159        let hi = self.hi();
160        let lo = self.lo();
161        hi + lo
162    }
163
164    fn epsilon() -> Self {
165        // Df64::EPSILON = f64::EPSILON * f64::EPSILON / 2.0
166        let epsilon_value = f64::EPSILON * f64::EPSILON / 2.0;
167        Df64::from(epsilon_value)
168    }
169
170    fn pi() -> Self {
171        Df64::from(std::f64::consts::PI)
172    }
173
174    fn max(self, other: Self) -> Self {
175        if self > other { self } else { other }
176    }
177
178    fn min(self, other: Self) -> Self {
179        if self < other { self } else { other }
180    }
181
182    fn exp_m1(self) -> Self {
183        // Use ComplexField::exp_m1() for Df64
184        ComplexField::exp_m1(self)
185    }
186}
187
188// Note: ScalarOperand implementations for f64 and Df64 are provided by ndarray
189// We cannot implement them here due to Orphan Rules, but they are already implemented
190// in the ndarray crate for standard numeric types.
191
192// Note: Df64ArrayOps trait and impl removed after ndarray migration
193// Array operations should now be done on tenferro tensors directly
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn test_f64_custom_numeric() {
201        let x = 1.5_f64;
202        let y = -2.0_f64;
203
204        // Test basic operations
205        assert_eq!(x.abs(), 1.5);
206        assert_eq!(y.abs(), 2.0);
207
208        // Test mathematical functions
209        let cos_x = x.cos();
210        assert!(f64::from(cos_x).is_finite());
211
212        let sqrt_x = x.sqrt();
213        assert!(f64::from(sqrt_x).is_finite());
214
215        // Test conversion
216        assert_eq!(x.to_f64(), 1.5);
217        assert_eq!(<f64 as CustomNumeric>::epsilon(), f64::EPSILON);
218    }
219
220    #[test]
221    fn test_twofloat_custom_numeric() {
222        let x = Df64::from_f64_unchecked(1.5);
223        let y = Df64::from_f64_unchecked(-2.0);
224
225        // Test basic operations
226        assert_eq!(x.abs(), Df64::from_f64_unchecked(1.5));
227        assert_eq!(y.abs(), Df64::from_f64_unchecked(2.0));
228
229        // Test mathematical functions
230        let cos_x = x.cos();
231        assert!(f64::from(cos_x).is_finite());
232
233        let sqrt_x = x.sqrt();
234        assert!(f64::from(sqrt_x).is_finite());
235
236        // Test conversion
237        let x_f64 = x.to_f64();
238        assert!((x_f64 - 1.5).abs() < 1e-15);
239
240        // Test epsilon
241        let eps = Df64::epsilon();
242        assert!(eps > Df64::from_f64_unchecked(0.0));
243        assert!(eps < Df64::from_f64_unchecked(1.0));
244    }
245
246    // Note: Df64ArrayOps tests removed after ndarray migration
247
248    #[test]
249    fn test_precision_comparison() {
250        // Test that Df64 provides higher precision than f64
251        let pi_f64 = std::f64::consts::PI;
252        let pi_tf = Df64::from_f64_unchecked(pi_f64);
253
254        // Both should be finite
255        assert!(pi_f64.is_finite());
256        assert!(f64::from(pi_tf).is_finite());
257
258        // Df64 should convert back to f64 with minimal loss
259        let pi_back = pi_tf.to_f64();
260        assert!((pi_back - pi_f64).abs() < f64::EPSILON);
261    }
262}