num-valid 0.6.0

A robust numerical library providing validated types for real and complex numbers to prevent common floating-point errors like NaN propagation. Features a generic, layered architecture with support for native f64 and optional arbitrary-precision arithmetic.
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
#![deny(rustdoc::broken_intra_doc_links)]

//! Absolute value computation for validated scalar types.
//!
//! This module provides the [`Abs`] trait for computing absolute values of both
//! real and complex numbers.

use crate::{
    RealScalar,
    core::traits::{raw::RawScalarValidate, validation::sealed::NativeReal},
    functions::FunctionErrors,
    kernels::{RawComplexTrait, RawScalarTrait},
    scalars::NonNegativeRealScalar,
};
use duplicate::duplicate_item;
use num::Complex;
use num_traits::Float;
use thiserror::Error;

#[cfg(debug_assertions)]
use try_create::TryNew;

//------------------------------------------------------------------------------------------------
/// Errors that can occur during the input validation phase when attempting to compute
/// the absolute value of a number.
///
/// This enum is used as a source for the `Input` variant of composed error types like
/// [`AbsRealErrors`] or [`AbsComplexErrors`]. It is generic over `RawScalar`, which
/// represents the specific scalar type being validated (e.g., [`f64`], [`Complex<f64>`], etc.).
#[derive(Debug, Error)]
pub enum AbsInputErrors<RawScalar: RawScalarTrait> {
    /// The input value failed basic validation checks.
    ///
    /// This error occurs if the input value itself is considered invalid
    /// according to the validation policy (e.g., [`StrictFinitePolicy`](crate::core::policies::StrictFinitePolicy)),
    /// such as being NaN or Infinity, before the absolute value calculation
    /// is attempted.
    #[error("the input value is invalid!")]
    ValidationError {
        /// The underlying validation error from the input type.
        ///
        /// This provides more specific details about why the input value
        /// was considered invalid.
        #[source]
        #[backtrace]
        source: <RawScalar as RawScalarValidate>::ValidationError,
    },
}

/// A type alias for [`FunctionErrors`], specialized for errors that can occur during
/// the computation of the absolute value of a real number.
///
/// It combines input validation errors specific to the `abs` operation on real numbers
/// with potential validation errors of the resulting real number.
///
/// # Generic Parameters
///
/// - `RawReal`: A type that implements [`RawRealTrait`](crate::kernels::RawRealTrait). This defines:
///   - The error type for the input: `AbsInputErrors<RawReal>`.
///   - The raw error type for the output: `<RawReal as RawScalarValidate>::ValidationError`.
///
/// # Variants
///
/// This type alias wraps [`FunctionErrors`], which has the following variants:
/// - `Input { source: AbsInputErrors<RawReal> }`: Indicates that the input real number
///   provided for absolute value computation was invalid. The `source` field contains
///   an [`AbsInputErrors`] detailing the specific input failure.
/// - `Output { source: <RawReal as RawScalarValidate>::ValidationError }`: Indicates that the computed absolute value (a real number)
///   itself failed validation. This typically means the result of the `abs` operation yielded
///   a non-finite value (NaN or Infinity). The `source` field contains the raw validation error
///   for the output.
pub type AbsRealErrors<RawReal> =
    FunctionErrors<AbsInputErrors<RawReal>, <RawReal as RawScalarValidate>::ValidationError>;

/// A type alias for [`FunctionErrors`], specialized for errors that can occur during
/// the computation of the absolute value (or modulus) of a complex number.
///
/// It combines input validation errors specific to the `abs` operation on complex numbers
/// with potential validation errors of the resulting real number (the modulus).
///
/// # Generic Parameters
///
/// - `RawComplex`: A type that implements [`RawComplexTrait`]. This defines:
///   - The error type for the input complex number: `AbsInputErrors<RawComplex>`.
///   - The raw error type for the output real number: `<<RawComplex as RawComplexTrait>::RawReal as RawScalarValidate>::ValidationError`.
///
/// # Variants
///
/// This type alias wraps [`FunctionErrors`], which has the following variants:
/// - `Input { source: AbsInputErrors<RawComplex> }`: Indicates that the input complex number
///   provided for absolute value computation was invalid. The `source` field contains
///   an [`AbsInputErrors`] detailing the specific input failure.
/// - `Output { source: <<RawComplex as RawComplexTrait>::RawReal as RawScalarValidate>::ValidationError }`: Indicates that the computed
///   absolute value (a real number) itself failed validation. This typically means the result of the
///   `norm()` operation yielded a non-finite value. The `source` field contains the raw validation
///   error for the output real number.
pub type AbsComplexErrors<RawComplex> = FunctionErrors<
    AbsInputErrors<RawComplex>,
    <<RawComplex as RawComplexTrait>::RawReal as RawScalarValidate>::ValidationError,
>;

/// This trait provides the interface for the function used to compute the *absolute value*
/// (also known as modulus or magnitude) of a number, which can be real or complex.
///
/// The absolute value of a real number `x` is `|x|`, which is `x` if `x` is non-negative,
/// and `-x` if `x` is negative.
/// The absolute value (or modulus) of a complex number `z = a + b*i` is `sqrt(a^2 + b^2)`.
/// In both cases, the result is always a non-negative real number.
///
/// This trait provides four methods:
/// - [`try_abs`](Abs::try_abs): A fallible version that performs validation on the input
///   (and potentially the output) and returns a [`Result`]. This is the preferred method
///   when robust error handling is required.
/// - [`abs`](Abs::abs): A convenient infallible version that panics if `try_abs` would return
///   an error in debug builds, or directly computes the value in release builds.
///   Use this when the input is known to be valid or when panicking on error is acceptable.
/// - [`try_abs_squared`](Abs::try_abs_squared): A fallible version that computes the squared
///   absolute value (avoiding the square root). For complex numbers, this is `a^2 + b^2`.
/// - [`abs_squared`](Abs::abs_squared): A convenient infallible version of `try_abs_squared`.
///
/// # Associated types
///
/// - `Output`: The type of the result of the absolute value operation. This is constrained
///   by [`RealScalar`] to ensure it's a real number type.
/// - `Error` : The error type that can be returned by the [`try_abs`](Abs::try_abs) method.
pub trait Abs: Sized {
    /// The output type of the *absolute value* function.
    ///
    /// This is always a real number type, even when the input `Self` is a complex number.
    /// It must implement the [`RealScalar`] trait.
    ///
    type Output: Sized;

    /// The error type that can be returned by the [`try_abs`](Abs::try_abs) method.
    ///
    /// This type must implement [`std::error::Error`]. Specific implementations will
    /// use types like [`AbsRealErrors`] or [`AbsComplexErrors`] to provide detailed
    /// information about the failure.
    type Error: std::error::Error;

    /// Attempts to compute the absolute value of `self`.
    #[must_use = "this `Result` may contain an error that should be handled"]
    fn try_abs(self) -> Result<Self::Output, Self::Error>;

    /// Returns the *absolute value* of `self`.
    fn abs(self) -> Self::Output;

    /// Attempts to compute the squared absolute value of `self`.
    ///
    /// For real numbers, this computes `x^2`.
    /// For complex numbers `z = a + b*i`, this computes `a^2 + b^2` (equivalent to `|z|^2`).
    ///
    /// This method is useful when you need the squared magnitude without the expense
    /// of computing the square root, such as for distance comparisons or vector norms.
    #[must_use = "this `Result` may contain an error that should be handled"]
    fn try_abs_squared(self) -> Result<Self::Output, Self::Error>;

    /// Returns the *squared absolute value* of `self`.
    ///
    /// For real numbers, this computes `x^2`.
    /// For complex numbers `z = a + b*i`, this computes `a^2 + b^2`.
    ///
    /// # Behavior
    ///
    /// - In **debug builds** (`#[cfg(debug_assertions)]`): This method calls
    ///   [`try_abs_squared()`](Abs::try_abs_squared) and unwraps the result. It will panic
    ///   if `try_abs_squared` returns an error.
    /// - In **release builds** (`#[cfg(not(debug_assertions))]`): This method directly
    ///   computes the squared value for performance, bypassing the validations.
    ///
    /// # Panics
    ///
    /// This method will panic in debug builds if `try_abs_squared()` would return an `Err`.
    fn abs_squared(self) -> Self::Output;
}

#[duplicate_item(
    T;
    [f64];
    [f32];
)]
impl Abs for T
//impl<T> Abs for T
//where
//    T: NativeReal<ValidationError = ErrorsValidationRawReal<Self>> + RealScalar<RawReal = Self>,
{
    type Output = NonNegativeRealScalar<T>;
    type Error = AbsRealErrors<T>;

    #[inline(always)]
    fn try_abs(self) -> Result<NonNegativeRealScalar<T>, Self::Error> {
        #[cfg(debug_assertions)]
        {
            self.validate_raw_scalar()
                .map_err(|e| AbsInputErrors::ValidationError { source: e }.into())
                .and_then(|v| {
                    <T as Float>::abs(v)
                        .validate_raw_scalar()
                        .map(|abs_v| NonNegativeRealScalar::try_new(abs_v).unwrap())
                        .map_err(|e| AbsRealErrors::Output { source: e })
                })
        }
        #[cfg(not(debug_assertions))]
        {
            Ok(NonNegativeRealScalar::new(<T as Float>::abs(self)))
        }
    }

    #[inline(always)]
    fn abs(self) -> NonNegativeRealScalar<T> {
        #[cfg(debug_assertions)]
        {
            self.try_abs()
                .expect("Error in the computation of the absolute value in debug mode")
        }
        #[cfg(not(debug_assertions))]
        {
            NonNegativeRealScalar::new(<T as Float>::abs(self))
        }
    }

    #[inline(always)]
    fn try_abs_squared(self) -> Result<NonNegativeRealScalar<T>, Self::Error> {
        #[cfg(debug_assertions)]
        {
            self.validate_raw_scalar()
                .map_err(|e| AbsInputErrors::ValidationError { source: e }.into())
                .and_then(|v| {
                    let abs_v = <T as Float>::abs(v);
                    (abs_v * abs_v)
                        .validate_raw_scalar()
                        .map(|abs_sq| NonNegativeRealScalar::try_new(abs_sq).unwrap())
                        .map_err(|e| AbsRealErrors::Output { source: e })
                })
        }
        #[cfg(not(debug_assertions))]
        {
            let abs_v = <T as Float>::abs(self);
            Ok(NonNegativeRealScalar::new(abs_v * abs_v))
        }
    }

    #[inline(always)]
    fn abs_squared(self) -> NonNegativeRealScalar<T> {
        #[cfg(debug_assertions)]
        {
            self.try_abs_squared()
                .expect("Error in the computation of the squared absolute value in debug mode")
        }
        #[cfg(not(debug_assertions))]
        {
            let abs_v = <T as Float>::abs(self);
            NonNegativeRealScalar::new(abs_v * abs_v)
        }
    }
}

impl<T> Abs for Complex<T>
where
    Self: RawComplexTrait<RawReal = T>,
    T: NativeReal + RealScalar,
{
    type Output = NonNegativeRealScalar<T>;
    type Error = AbsComplexErrors<Complex<T>>;

    #[inline(always)]
    fn try_abs(self) -> Result<NonNegativeRealScalar<T>, AbsComplexErrors<Complex<T>>> {
        #[cfg(debug_assertions)]
        {
            self.validate_raw_scalar()
                .map_err(|e| AbsInputErrors::ValidationError { source: e }.into())
                .and_then(|v| {
                    v.norm()
                        .validate_raw_scalar()
                        .map(|abs_v| NonNegativeRealScalar::try_new(abs_v).unwrap())
                        .map_err(|e| AbsComplexErrors::<Complex<T>>::Output { source: e })
                })
        }
        #[cfg(not(debug_assertions))]
        {
            Ok(NonNegativeRealScalar::new(self.norm()))
        }
    }

    #[inline(always)]
    fn abs(self) -> NonNegativeRealScalar<T> {
        #[cfg(debug_assertions)]
        {
            self.try_abs()
                .expect("Error in the computation of the absolute value in debug mode")
        }
        #[cfg(not(debug_assertions))]
        {
            NonNegativeRealScalar::new(self.norm())
        }
    }

    #[inline(always)]
    fn try_abs_squared(self) -> Result<NonNegativeRealScalar<T>, AbsComplexErrors<Complex<T>>> {
        #[cfg(debug_assertions)]
        {
            self.validate_raw_scalar()
                .map_err(|e| AbsInputErrors::ValidationError { source: e }.into())
                .and_then(|v| {
                    let norm_sq = v.norm_sqr();
                    norm_sq
                        .validate_raw_scalar()
                        .map(|abs_sq| NonNegativeRealScalar::try_new(abs_sq).unwrap())
                        .map_err(|e| AbsComplexErrors::<Complex<T>>::Output { source: e })
                })
        }
        #[cfg(not(debug_assertions))]
        {
            Ok(NonNegativeRealScalar::new(self.norm_sqr()))
        }
    }

    #[inline(always)]
    fn abs_squared(self) -> NonNegativeRealScalar<T> {
        #[cfg(debug_assertions)]
        {
            self.try_abs_squared()
                .expect("Error in the computation of the squared absolute value in debug mode")
        }
        #[cfg(not(debug_assertions))]
        {
            NonNegativeRealScalar::new(self.norm_sqr())
        }
    }
}

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

//------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;
    use num::Complex;
    use num::Zero;

    #[cfg(debug_assertions)]
    use std::assert_matches;

    mod abs {
        use super::*;

        mod native {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn abs_valid() {
                    let value = 4.0;
                    assert_eq!(<f64 as Abs>::try_abs(value).unwrap().into_inner(), 4.0);
                    assert_eq!(<f64 as Float>::abs(value), 4.0);
                    assert_eq!(<f64 as Abs>::abs(value).into_inner(), 4.0);
                }

                #[test]
                fn abs_negative() {
                    let value = -4.0;
                    assert_eq!(<f64 as Abs>::try_abs(value).unwrap().into_inner(), 4.0);
                    assert_eq!(<f64 as Float>::abs(value), 4.0);
                    assert_eq!(<f64 as Abs>::abs(value).into_inner(), 4.0);
                }

                #[test]
                fn abs_zero() {
                    let value = 0.0;
                    assert_eq!(<f64 as Abs>::try_abs(value).unwrap().into_inner(), 0.0);
                    assert_eq!(<f64 as Float>::abs(value), 0.0);
                    assert_eq!(<f64 as Abs>::abs(value).into_inner(), 0.0);
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_nan() {
                    let value = f64::NAN;
                    let result = value.try_abs().unwrap_err();
                    assert_matches!(result, AbsRealErrors::Input(..));
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_infinity() {
                    let value = f64::INFINITY;
                    assert_matches!(value.try_abs().unwrap_err(), AbsRealErrors::Input(..));
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_subnormal() {
                    let value = f64::MIN_POSITIVE / 2.0;
                    assert_matches!(value.try_abs().unwrap_err(), AbsRealErrors::Input(..));
                }

                #[test]
                fn abs_squared_positive() {
                    let value = 4.0;
                    assert_eq!(
                        <f64 as Abs>::try_abs_squared(value).unwrap().into_inner(),
                        16.0
                    );
                    assert_eq!(value.abs_squared().into_inner(), 16.0);
                }

                #[test]
                fn abs_squared_negative() {
                    let value = -4.0;
                    assert_eq!(
                        <f64 as Abs>::try_abs_squared(value).unwrap().into_inner(),
                        16.0
                    );
                    assert_eq!(value.abs_squared().into_inner(), 16.0);
                }

                #[test]
                fn abs_squared_zero() {
                    let value = 0.0;
                    assert_eq!(
                        <f64 as Abs>::try_abs_squared(value).unwrap().into_inner(),
                        0.0
                    );
                    assert_eq!(value.abs_squared().into_inner(), 0.0);
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_squared_nan() {
                    let value = f64::NAN;
                    let result = value.try_abs_squared().unwrap_err();
                    assert_matches!(result, AbsRealErrors::Input(..));
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_squared_infinity() {
                    let value = f64::INFINITY;
                    assert_matches!(
                        value.try_abs_squared().unwrap_err(),
                        AbsRealErrors::Input(..)
                    );
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn abs_valid() {
                    let value = Complex::new(4.0, 0.0);
                    assert_eq!(value.try_abs().unwrap().into_inner(), 4.0);
                    assert_eq!(value.abs().into_inner(), 4.0);
                }

                #[test]
                fn abs_negative() {
                    let value = Complex::new(-4.0, 0.0);
                    assert_eq!(value.try_abs().unwrap().into_inner(), 4.0);
                    assert_eq!(value.abs().into_inner(), 4.0);
                }

                #[test]
                fn abs_zero() {
                    let value = Complex::new(0.0, 0.0);
                    assert_eq!(value.try_abs().unwrap(), NonNegativeRealScalar::zero());
                    assert_eq!(value.abs(), NonNegativeRealScalar::zero());
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(
                        value.try_abs(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(
                        value.try_abs(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(
                        value.try_abs(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(
                        value.try_abs(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_subnormal() {
                    let value = Complex::new(f64::MIN_POSITIVE / 2.0, 0.0);
                    assert!(matches!(
                        value.try_abs(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));

                    let value = Complex::new(0.0, f64::MIN_POSITIVE / 2.0);
                    assert!(matches!(
                        value.try_abs(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));
                }

                #[test]
                fn abs_squared_valid() {
                    let value = Complex::new(3.0, 4.0);
                    assert_eq!(value.try_abs_squared().unwrap().into_inner(), 25.0);
                    assert_eq!(value.abs_squared().into_inner(), 25.0);
                }

                #[test]
                fn abs_squared_zero() {
                    let value = Complex::new(0.0, 0.0);
                    assert_eq!(
                        value.try_abs_squared().unwrap(),
                        NonNegativeRealScalar::zero()
                    );
                    assert_eq!(value.abs_squared(), NonNegativeRealScalar::zero());
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_squared_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(
                        value.try_abs_squared(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(
                        value.try_abs_squared(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));
                }

                #[test]
                #[cfg(debug_assertions)]
                fn abs_squared_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(
                        value.try_abs_squared(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(
                        value.try_abs_squared(),
                        Err(AbsComplexErrors::<Complex<f64>>::Input(..))
                    ));
                }
            }
        }
    }
}
//------------------------------------------------------------------------------------------------