ftl-numkernel 0.1.0

A library designed to provide numerical operations and error handling for both real and complex numbers, also supporting arbitrary precision types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#![deny(rustdoc::broken_intra_doc_links)]

//! This module defines error types and traits for validating real and complex values.
//!
//! The module provides:
//! - [`RealValueErrors`]: An enum representing errors that can occur during the validation of real (floating point) numbers.
//! - [`ComplexValueErrors`]: An enum representing errors that can occur during the validation of complex numbers.
//! - [`RealValueValidator`]: A trait for validating real values.
//! - [`ComplexValueValidator`]: A trait for validating complex values.

use num::Complex;
use std::{backtrace::Backtrace, num::FpCategory};
use thiserror::Error;

//-------------------------------------------------------------
/// Errors that can be generated from the validation of a real (floating point) number.
#[derive(Debug, Error)]
pub enum RealValueErrors<RealType> {
    /// The value is infinite.
    ///
    /// This error occurs when the value being validated is infinite.
    #[error("the value is infinite!")]
    Infinite {
        /// The backtrace of the error.
        backtrace: Backtrace,
    },

    /// The value is NaN (Not a Number).
    ///
    /// This error occurs when the value being validated is NaN (Not a Number).
    #[error("the value is NaN!")]
    NaN {
        /// The backtrace of the error.
        backtrace: Backtrace,
    },

    /// The value is [subnormal](https://en.wikipedia.org/wiki/Subnormal_number).
    ///
    /// This error occurs when the value being validated is subnormal.
    #[error("the value ({value:?}) is subnormal!")]
    Subnormal {
        /// The subnormal value.
        value: RealType,

        /// The backtrace of the error.
        backtrace: Backtrace,
    },
}

/// Errors that can be generated from the validation of a complex number.
#[derive(Debug, Error)]
pub enum ComplexValueErrors<RealType, ComplexType> {
    /// The real part is invalid.
    ///
    /// This error occurs when the real part of the complex number is invalid.
    #[error("the value ({value:?}) has an invalid real part!")]
    InvalidRealPart {
        /// The complex value that caused the error.
        value: ComplexType,

        /// The error that occurred while validating the real part.
        #[source]
        #[backtrace]
        real_part_error: RealValueErrors<RealType>,
    },

    /// The imaginary part is invalid.
    ///
    /// This error occurs when the imaginary part of the complex number is invalid.
    #[error("the value ({value:?}) has an invalid imaginary part!")]
    InvalidImaginaryPart {
        /// The complex value that caused the error.
        value: ComplexType,

        /// The error that occurred while validating the imaginary part.
        #[source]
        #[backtrace]
        imaginary_part_error: RealValueErrors<RealType>,
    },
}
//-------------------------------------------------------------

//-------------------------------------------------------------
/// A trait for validating real values.
///
/// This trait provides a method for validating real values, ensuring that they
/// are not infinite, NaN, or subnormal. If the value is valid, it returns `Ok(self)`.
/// Otherwise, it returns an appropriate error variant of `RealValueErrors`.
pub trait RealValueValidator: Sized {
    /// Validates the real value.
    ///
    /// # Returns
    ///
    /// * `Ok(self)` if the value is valid (i.e., it is not infinite, NaN, or subnormal).
    /// * `Err(RealValueErrors::Infinite)` if the value is infinite.
    /// * `Err(RealValueErrors::NaN)` if the value is NaN.
    /// * `Err(RealValueErrors::Subnormal)` if the value is subnormal.
    fn validate(self) -> Result<Self, RealValueErrors<Self>>;
}

impl RealValueValidator for f64 {
    /// Validates the `f64` value.
    ///
    /// This implementation checks the floating-point category of the value and
    /// returns an appropriate error if the value is infinite, NaN, or subnormal.
    ///
    /// # Returns
    ///
    /// * `Ok(self)` if the value is valid (i.e., it is not infinite, NaN, or subnormal).
    /// * `Err(RealValueErrors::Infinite)` if the value is infinite.
    /// * `Err(RealValueErrors::NaN)` if the value is NaN.
    /// * `Err(RealValueErrors::Subnormal)` if the value is subnormal.
    fn validate(self) -> Result<Self, RealValueErrors<Self>> {
        let fp_type = self.classify();
        match fp_type {
            FpCategory::Infinite => Err(RealValueErrors::Infinite {
                backtrace: Backtrace::force_capture(),
            }),
            FpCategory::Nan => Err(RealValueErrors::NaN {
                backtrace: Backtrace::force_capture(),
            }),
            FpCategory::Subnormal => Err(RealValueErrors::Subnormal {
                value: self,
                backtrace: Backtrace::force_capture(),
            }),
            FpCategory::Zero | FpCategory::Normal => Ok(self),
        }
    }
}

#[cfg(feature = "rug")]
impl RealValueValidator for rug::Float {
    /// Validates the `rug::Float` value.
    ///
    /// This implementation checks the floating-point category of the value and
    /// returns an appropriate error if the value is infinite, NaN, or subnormal.
    ///
    /// # Returns
    ///
    /// * `Ok(self)` if the value is valid (i.e., it is not infinite, NaN, or subnormal).
    /// * `Err(RealValueErrors::Infinite)` if the value is infinite.
    /// * `Err(RealValueErrors::NaN)` if the value is NaN.
    /// * `Err(RealValueErrors::Subnormal)` if the value is subnormal.
    fn validate(self) -> Result<Self, RealValueErrors<Self>> {
        let fp_type = self.classify();
        match fp_type {
            FpCategory::Infinite => Err(RealValueErrors::Infinite {
                backtrace: Backtrace::force_capture(),
            }),
            FpCategory::Nan => Err(RealValueErrors::NaN {
                backtrace: Backtrace::force_capture(),
            }),
            FpCategory::Subnormal => Err(RealValueErrors::Subnormal {
                value: self,
                backtrace: Backtrace::force_capture(),
            }),
            FpCategory::Zero | FpCategory::Normal => Ok(self),
        }
    }
}
//-------------------------------------------------------------

//-------------------------------------------------------------
/// A trait for validating complex values.
///
/// This trait provides a method for validating complex values, ensuring that their
/// real and imaginary parts are not infinite, NaN, or subnormal. If the value is valid,
/// it returns `Ok(self)`. Otherwise, it returns an appropriate error variant of `ComplexValueErrors`.
pub trait ComplexValueValidator: Sized {
    type RealType: Sized;

    /// Validates the complex value.
    ///
    /// # Returns
    ///
    /// * `Ok(self)` if the value is valid (i.e., both the real and imaginary parts are not infinite, NaN, or subnormal).
    /// * `Err(ComplexValueErrors::InvalidRealPart)` if the real part is invalid.
    /// * `Err(ComplexValueErrors::InvalidImaginaryPart)` if the imaginary part is invalid.
    fn validate(self) -> Result<Self, ComplexValueErrors<Self::RealType, Self>>;
}

impl ComplexValueValidator for Complex<f64> {
    type RealType = f64;

    /// Validates the `Complex<f64>` value.
    ///
    /// This implementation checks the floating-point category of the real and imaginary parts
    /// of the complex value and returns an appropriate error if either part is infinite, NaN, or subnormal.
    ///
    /// # Returns
    ///
    /// * `Ok(self)` if the value is valid (i.e., both the real and imaginary parts are not infinite, NaN, or subnormal).
    /// * `Err(ComplexValueErrors::InvalidRealPart)` if the real part is invalid.
    /// * `Err(ComplexValueErrors::InvalidImaginaryPart)` if the imaginary part is invalid.
    fn validate(self) -> Result<Self, ComplexValueErrors<Self::RealType, Self>> {
        let real_part = match self.re.validate() {
            Ok(real_part) => real_part,
            Err(real_part_error) => {
                return Err(ComplexValueErrors::InvalidRealPart {
                    value: self,
                    real_part_error,
                })
            }
        };
        let imaginary_part = match self.im.validate() {
            Ok(imaginary_part) => imaginary_part,
            Err(imaginary_part_error) => {
                return Err(ComplexValueErrors::InvalidImaginaryPart {
                    value: self,
                    imaginary_part_error,
                })
            }
        };
        Ok(Self {
            re: real_part,
            im: imaginary_part,
        })
    }
}

#[cfg(feature = "rug")]
impl ComplexValueValidator for rug::Complex {
    type RealType = rug::Float;

    /// Validates the `rug::Complex` value.
    ///
    /// This implementation checks the floating-point category of the real and imaginary parts
    /// of the complex value and returns an appropriate error if either part is infinite, NaN, or subnormal.
    ///
    /// # Returns
    ///
    /// * `Ok(self)` if the value is valid (i.e., both the real and imaginary parts are not infinite, NaN, or subnormal).
    /// * `Err(ComplexValueErrors::InvalidRealPart)` if the real part is invalid.
    /// * `Err(ComplexValueErrors::InvalidImaginaryPart)` if the imaginary part is invalid.
    fn validate(self) -> Result<Self, ComplexValueErrors<Self::RealType, Self>> {
        let (re, im) = self.clone().into_real_imag();

        let _real_part = match re.validate() {
            Ok(real_part) => real_part,
            Err(real_part_error) => {
                return Err(ComplexValueErrors::InvalidRealPart {
                    value: self,
                    real_part_error,
                })
            }
        };
        let _imaginary_part = match im.validate() {
            Ok(imaginary_part) => imaginary_part,
            Err(imaginary_part_error) => {
                return Err(ComplexValueErrors::InvalidImaginaryPart {
                    value: self,
                    imaginary_part_error,
                })
            }
        };
        Ok(self)
    }
}
//-------------------------------------------------------------

//-------------------------------------------------------------
/// Errors that can be generated by the conversion from a `f64` value.
#[derive(Debug, Error)]
pub enum TryFromf64Errors {
    /// The input value is invalid.
    ///
    /// This error occurs when the input value being converted is invalid.
    #[error("the input value is invalid!")]
    ValidationError {
        /// The source error that occurred during validation.
        #[from]
        source: RealValueErrors<f64>,
    },

    /// The input `value` is not representable exactly with the asked `precision`.
    ///
    /// This error occurs when the input `f64` value cannot be exactly represented with the specified precision.
    #[error("the input f64 value ({value:?}) cannot be exactly represented with the specific precision ({precision:?}). Try to increase the precision.")]
    NonRepresentableExactly {
        /// The input `f64` value.
        value: f64,

        /// The precision that was requested.
        precision: u32,

        /// The backtrace of the error.
        backtrace: Backtrace,
    },
}

// Conditional compilation for the `rug` feature
#[cfg(feature = "rug")]
/// Errors that can be generated by the conversion from a `rug::Float` value.
#[derive(Debug, Error)]
pub enum TryFromRugFloatErrors {
    /// The input value is invalid.
    ///
    /// This error occurs when the input value being converted is invalid.
    #[error("the input value is invalid!")]
    ValidationError {
        /// The source error that occurred during validation.
        #[from]
        source: RealValueErrors<f64>,
    },

    /// The input `value` is not representable exactly with the asked precision.
    ///
    /// This error occurs when the input `rug::Float` value cannot be exactly represented with the specified precision.
    #[error("the input rug::Float value ({value:?}) has a precision of {precision_in:?} and cannot be exactly represented with the specific asked precision ({precision_asked:?}). The input value is approximated to ({value_approx:?}). Try to increase the precision.")]
    NonRepresentableExactly {
        /// The input `rug::Float` value.
        value: rug::Float,

        /// The precision of the input value.
        precision_in: u32,

        /// The precision that was requested.
        precision_asked: u32,

        /// The approximated value.
        value_approx: rug::Float,

        /// The backtrace of the error.
        backtrace: Backtrace,
    },
}
//-------------------------------------------------------------

//-------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    mod native64 {
        use super::*;

        mod real {
            use super::*;

            #[test]
            fn test_f64_validate_infinite() {
                let value = f64::INFINITY;
                let result = value.validate();
                assert!(matches!(result, Err(RealValueErrors::Infinite { .. })));
            }

            #[test]
            fn test_f64_validate_nan() {
                let value = f64::NAN;
                let result = value.validate();
                assert!(matches!(result, Err(RealValueErrors::NaN { .. })));
            }

            #[test]
            fn test_f64_validate_subnormal() {
                let value = f64::MIN_POSITIVE / 2.0;
                let result = value.validate();
                assert!(matches!(result, Err(RealValueErrors::Subnormal { .. })));
            }

            #[test]
            fn test_f64_validate_zero() {
                let value = 0.0;
                let result = value.validate();
                assert!(matches!(result, Ok(0.0)));
            }

            #[test]
            fn test_f64_validate_normal() {
                let value = 1.0;
                let result = value.validate();
                assert!(matches!(result, Ok(1.0)));
            }
        }

        mod complex {
            use super::*;

            #[test]
            fn test_complex_f64_validate_invalid_real_part() {
                let value = Complex::new(f64::INFINITY, 1.0);
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidRealPart { .. })
                ));

                let value = Complex::new(f64::NAN, 1.0);
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidRealPart { .. })
                ));

                let value = Complex::new(f64::MIN_POSITIVE / 2.0, 1.0);
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidRealPart { .. })
                ));
            }

            #[test]
            fn test_complex_f64_validate_invalid_imaginary_part() {
                let value = Complex::new(1.0, f64::INFINITY);
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidImaginaryPart { .. })
                ));

                let value = Complex::new(1.0, f64::NAN);
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidImaginaryPart { .. })
                ));

                let value = Complex::new(1.0, f64::MIN_POSITIVE / 2.0);
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidImaginaryPart { .. })
                ));
            }

            #[test]
            fn test_complex_f64_validate_zero() {
                let value = Complex::new(0.0, 0.0);
                let result = value.validate();
                assert!(matches!(result, Ok(_)));
            }

            #[test]
            fn test_complex_f64_validate_normal() {
                let value = Complex::new(1.0, 1.0);
                let result = value.validate();
                assert!(matches!(result, Ok(_)));
            }
        }
    }

    #[cfg(feature = "rug")]
    mod rug53 {
        use super::*;
        use rug::Float;

        mod real {
            use super::*;

            #[test]
            fn test_rug_float_validate_infinite() {
                let value = Float::with_val(53, f64::INFINITY);
                let result = value.validate();
                assert!(matches!(result, Err(RealValueErrors::Infinite { .. })));
            }

            #[test]
            fn test_rug_float_validate_nan() {
                let value = Float::with_val(53, f64::NAN);
                let result = value.validate();
                assert!(matches!(result, Err(RealValueErrors::NaN { .. })));
            }

            #[test]
            fn test_rug_float_validate_subnormal() {
                let value = Float::with_val(53, f64::MIN_POSITIVE);
                println!("value: {:?}", value);
                let value = Float::with_val(53, f64::MIN_POSITIVE / 2.0);
                println!("value: {:?}", value);
                let result = value.validate();
                println!("result: {:?}", result);
                //        assert!(matches!(result, Err(RealValueErrors::Subnormal { .. })));

                // rug::Float is never subnormal
                assert!(matches!(result, Ok(..)));
            }

            #[test]
            fn test_rug_float_validate_zero() {
                let value = Float::with_val(53, 0.0);
                let result = value.validate();
                assert!(matches!(result, Ok(_)));
            }

            #[test]
            fn test_rug_float_validate_normal() {
                let value = Float::with_val(53, 1.0);
                let result = value.validate();
                assert!(matches!(result, Ok(_)));
            }
        }

        mod complex {
            use super::*;
            use rug::Complex;

            #[test]
            fn test_complex_rug_float_validate_invalid_real_part() {
                let value = Complex::with_val(
                    53,
                    (Float::with_val(53, f64::INFINITY), Float::with_val(53, 1.0)),
                );
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidRealPart { .. })
                ));

                let value = Complex::with_val(
                    53,
                    (Float::with_val(53, f64::NAN), Float::with_val(53, 1.0)),
                );
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidRealPart { .. })
                ));

                let value = Complex::with_val(
                    53,
                    (
                        Float::with_val(53, f64::MIN_POSITIVE / 2.0),
                        Float::with_val(53, 1.0),
                    ),
                );
                let result = value.validate();
                // rug::Float is never subnormal
                assert!(matches!(result, Ok(_)));
            }

            #[test]
            fn test_complex_rug_float_validate_invalid_imaginary_part() {
                let value = Complex::with_val(
                    53,
                    (Float::with_val(53, 1.0), Float::with_val(53, f64::INFINITY)),
                );
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidImaginaryPart { .. })
                ));

                let value = Complex::with_val(
                    53,
                    (Float::with_val(53, 1.0), Float::with_val(53, f64::NAN)),
                );
                let result = value.validate();
                assert!(matches!(
                    result,
                    Err(ComplexValueErrors::InvalidImaginaryPart { .. })
                ));

                let value = Complex::with_val(
                    53,
                    (
                        Float::with_val(53, 1.0),
                        Float::with_val(53, f64::MIN_POSITIVE / 2.0),
                    ),
                );
                let result = value.validate();
                // rug::Float is never subnormal
                assert!(matches!(result, Ok(_)));
            }

            #[test]
            fn test_complex_rug_float_validate_zero() {
                let zero =
                    Complex::with_val(53, (Float::with_val(53, 0.0), Float::with_val(53, 0.0)));
                let result = zero.validate();
                assert!(matches!(result, Ok(_)));
            }

            #[test]
            fn test_complex_rug_float_validate_normal() {
                let value =
                    Complex::with_val(53, (Float::with_val(53, 1.0), Float::with_val(53, 1.0)));
                let result = value.validate();
                assert!(matches!(result, Ok(_)));
            }
        }
    }
}