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
#![deny(rustdoc::broken_intra_doc_links)]

use crate::{
    errors::{ComplexValueErrors, ComplexValueValidator, RealValueErrors, RealValueValidator},
    Native64, NumKernel, TryNew, Zero,
};
use num::Complex;
use std::{backtrace::Backtrace, fmt};
use thiserror::Error;

#[cfg(feature = "rug")]
use crate::{ComplexRug, RealRug, Rug};

//------------------------------------------------------------------------------------------------
/// Errors that can occur during the computation of the square root of a real number,
/// before the computation of the square root.
#[derive(Debug, Error)]
pub enum SqrtRealInputErrors<T: NumKernel + 'static> {
    /// The input value is negative.
    ///
    /// This error occurs when the input value for the square root computation is negative.
    #[error("the input value ({value:?}) is negative!")]
    NegativeValue {
        /// The negative input value.
        value: T::RawRealType,

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

    /// The input value (i.e. the value before the computation of the square root) is invalid.
    ///
    /// This error occurs when the input value for the square root computation is invalid
    /// (i.e. NaN, infinite or sub-normal).
    #[error("the input value is invalid!")]
    ValidationError {
        #[from]
        source: RealValueErrors<T::RawRealType>,
    },
}

/// Errors that can occur during the computation of the square root of a complex number,
/// before the computation of the square root.
#[derive(Debug, Error)]
pub enum SqrtComplexInputErrors<T: NumKernel + 'static> {
    /// The input value (i.e. the value before the computation of the square root) is invalid.
    ///
    /// This error occurs when the input value for the square root computation is invalid
    /// (i.e. the real or imaginary part of the complex number is NaN, infinite or sub-normal).
    #[error("the input value is invalid!")]
    ValidationError {
        /// The source error that occurred during validation.
        #[from]
        source: ComplexValueErrors<T::RawRealType, T::RawComplexType>,
    },
}

/// Errors that can occur during the computation of the square root of a real number.
#[derive(Debug, Error)]
pub enum SqrtRealErrors<T: NumKernel + 'static> {
    /// The input value (i.e. the value before the computation of the square root) is invalid.
    ///
    /// This error occurs when the input value for the square root computation is invalid.
    #[error("the input value is invalid!")]
    Input {
        /// The source error that occurred during validation.
        #[from]
        source: SqrtRealInputErrors<T>,
    },

    /// The output value (i.e. the value after the computation of the square root) is invalid.
    ///
    /// This error occurs when the output value of the square root computation is invalid.
    #[error("the output value is invalid!")]
    Output {
        /// The source error that occurred during validation.
        #[from]
        source: RealValueErrors<T::RawRealType>,
    },
}

/// Errors that can occur during the computation of the square root of a complex number.
#[derive(Debug, Error)]
pub enum SqrtComplexErrors<T: NumKernel + 'static> {
    /// The input value (i.e. the value before the computation of the square root) is invalid.
    ///
    /// This error occurs when the input value for the square root computation is invalid.
    #[error("the input value is invalid!")]
    Input {
        /// The source error that occurred during validation.
        #[from]
        source: SqrtComplexInputErrors<T>,
    },

    /// The output value (i.e. the value after the computation of the square root) is invalid.
    ///
    /// This error occurs when the output value of the square root computation is invalid.
    #[error("the output value is invalid!")]
    Output {
        /// The source error that occurred during validation.
        #[from]
        source: ComplexValueErrors<T::RawRealType, T::RawComplexType>,
    },
}

/// Validation of the input real value for the square root function.
///
/// The input value is valid if is *finite*, *positive* and *normal*;
fn sqrt_real_validate_input<T: NumKernel>(
    value: T::RawRealType,
) -> Result<T::RawRealType, SqrtRealInputErrors<T>> {
    let v = value.validate();
    match v {
        Ok(value) => {
            if value < 0. {
                Err(SqrtRealInputErrors::NegativeValue {
                    value,
                    backtrace: Backtrace::force_capture(),
                })
            } else {
                Ok(value)
            }
        }
        Err(e) => Err(SqrtRealInputErrors::ValidationError { source: e }),
    }
}

/// Validation of the input complex value for the square root function.
///
/// The input value is valid if is *finite* and *normal*;
fn sqrt_complex_validate_input<T: NumKernel>(
    value: T::RawComplexType,
) -> Result<T::RawComplexType, SqrtComplexInputErrors<T>> {
    Ok(value.validate()?)
}
//--------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------
/// This trait provides the interface for the function used to compute the square root of a number.
pub trait Sqrt: TryNew {
    /// The error type that can be returned by the `try_sqrt` method.
    type Error: fmt::Debug;

    /// Computes the square root of `self`, checking the input and output values for validity.
    ///
    /// # Validity
    ///
    /// - For the square root of a real number:
    ///   - the input value is valid if is *finite*, *positive* and *normal*;
    ///   - the output value is valid if is *finite* and *normal*.
    /// - For the square root of a complex number:
    ///   - The input and output values are valid if they are *finite* and *normal*.
    ///
    /// # Returns
    ///
    /// - `Ok(self)` if the square root computation is successful and the input and output values are valid.
    /// - `Err(Self::Error)` if the input or output values are invalid.
    fn try_sqrt(self) -> Result<Self, <Self as Sqrt>::Error>;

    /// Computes the square root of `self`, with no checks (in Release mode) on the validity of the input and output values.
    ///
    /// In Debug mode, this function internally calls the function [`Sqrt::try_sqrt()`] and a `panic!` is raised if the function returns an error.
    ///
    /// # Panics
    ///
    /// This function will panic in Debug mode if the input or output values are invalid.
    fn sqrt(self) -> Self;
}

#[duplicate::duplicate_item(
    T E input_validation trait_comment;
    [f64] [SqrtRealErrors::<Native64>] [sqrt_real_validate_input] ["Implementation of the [`Sqrt`] trait for [`f64`]."];
    [Complex::<f64>] [SqrtComplexErrors::<Native64>] [sqrt_complex_validate_input] ["Implementation of the [`Sqrt`] trait for [`Complex`]."];
)]
#[doc = trait_comment]
impl Sqrt for T {
    type Error = E;

    #[inline(always)]
    fn try_sqrt(self) -> Result<Self, <Self as Sqrt>::Error> {
        let value = input_validation(self)?;

        match T::try_new(value.sqrt()) {
            Ok(sqrt) => Ok(sqrt),
            Err(e) => Err(E::Output { source: e }),
        }
    }

    #[inline(always)]
    fn sqrt(self) -> Self {
        if cfg!(debug_assertions) {
            self.try_sqrt().unwrap()
        } else {
            self.sqrt()
        }
    }
}

#[cfg(feature = "rug")]
#[duplicate::duplicate_item(
    T E input_validation trait_comment;
    [RealRug::<PRECISION>] [SqrtRealErrors::<Rug<PRECISION>>] [sqrt_real_validate_input] ["Implementation of the [`Sqrt`] trait for [`RealRug`]."];
    [ComplexRug::<PRECISION>] [SqrtComplexErrors::<Rug<PRECISION>>] [sqrt_complex_validate_input] ["Implementation of the [`Sqrt`] trait for [`ComplexRug`]."];
)]
#[doc = trait_comment]
impl<const PRECISION: u32> Sqrt for T {
    type Error = E;

    #[inline(always)]
    fn try_sqrt(self) -> Result<Self, <Self as Sqrt>::Error> {
        let value = input_validation(self.0)?;

        match T::try_new(value.sqrt()) {
            Ok(sqrt) => Ok(sqrt),
            Err(e) => Err(E::Output { source: e }),
        }
    }

    #[inline(always)]
    fn sqrt(self) -> Self {
        if cfg!(debug_assertions) {
            self.try_sqrt().unwrap()
        } else {
            Self(self.0.sqrt())
        }
    }
}

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

//------------------------------------------------------------------------------------------------
/// Errors that can occur during the computation of the reciprocal of a real number.
#[derive(Debug, Error)]
pub enum RecipRealInputErrors<T: NumKernel + 'static> {
    /// The input value is zero.
    ///
    /// This error occurs when the input value for the reciprocal computation is zero.
    #[error("division by zero!")]
    DivisionByZero {
        /// The backtrace of the error.
        backtrace: Backtrace,
    },

    /// The input value is invalid.
    ///
    /// This error occurs when the input value for the reciprocal computation is invalid.
    #[error("the input value is invalid!")]
    ValidationError {
        /// The source error that occurred during validation.
        #[from]
        source: RealValueErrors<T::RawRealType>,
    },
}

/// Errors that can occur during the computation of the reciprocal of a complex number.
#[derive(Debug, Error)]
pub enum RecipComplexInputErrors<T: NumKernel + 'static> {
    /// The input value is zero.
    ///
    /// This error occurs when the input value for the reciprocal computation is zero.
    #[error("division by zero!")]
    DivisionByZero {
        /// The backtrace of the error.
        backtrace: Backtrace,
    },

    /// The input value is invalid.
    ///
    /// This error occurs when the input value for the reciprocal computation is invalid.
    #[error("the input value is invalid!")]
    ValidationError {
        /// The source error that occurred during validation.
        #[from]
        source: ComplexValueErrors<T::RawRealType, T::RawComplexType>,
    },
}

/// Errors that can occur during the computation of the reciprocal of a real number.
#[derive(Debug, Error)]
pub enum RecipRealErrors<T: NumKernel + 'static> {
    /// The input value is invalid.
    ///
    /// This error occurs when the input value for the reciprocal computation is invalid.
    #[error("the input value is invalid!")]
    Input {
        /// The source error that occurred during validation.
        #[from]
        source: RecipRealInputErrors<T>,
    },

    /// The output value is invalid.
    ///
    /// This error occurs when the output value of the reciprocal computation is invalid.
    #[error("the output value is invalid!")]
    Output {
        /// The source error that occurred during validation.
        #[from]
        source: RealValueErrors<T::RawRealType>,
    },
}

/// Errors that can occur during the computation of the reciprocal of a complex number.
#[derive(Debug, Error)]
pub enum RecipComplexErrors<T: NumKernel + 'static> {
    /// The input value is invalid.
    ///
    /// This error occurs when the input value for the reciprocal computation is invalid.
    #[error("the input value is invalid!")]
    Input {
        /// The source error that occurred during validation.
        #[from]
        source: RecipComplexInputErrors<T>,
    },

    /// The output value is invalid.
    ///
    /// This error occurs when the output value of the reciprocal computation is invalid.
    #[error("the output value is invalid!")]
    Output {
        /// The source error that occurred during validation.
        #[from]
        source: ComplexValueErrors<T::RawRealType, T::RawComplexType>,
    },
}

/// A trait for computing the reciprocal of a number.
pub trait Reciprocal: TryNew {
    /// The error type that can be returned by the `try_recip` method.
    type Error: fmt::Debug;

    /// Computes the reciprocal of `self`, checking the input and output values for validity.
    ///
    /// # Validity
    ///
    /// - The input value is valid if it is *finite*, *non-zero*, and *normal*.
    ///
    /// # Returns
    ///
    /// - `Ok(self)` if the reciprocal computation is successful and the input and output values are valid.
    /// - `Err(Self::Error)` if the input or output values are invalid.
    fn try_reciprocal(self) -> Result<Self, <Self as Reciprocal>::Error>;

    /// Computes the reciprocal of `self`, with no checks (in Release mode) on the validity of the input and output values.
    ///
    /// In Debug mode, this function internally calls the function [`Reciprocal::try_reciprocal()`] and a `panic!` is raised if the function returns an error.
    ///
    /// # Panics
    ///
    /// This function will panic in Debug mode if the input or output values are invalid.
    fn reciprocal(self) -> Self;
}

#[duplicate::duplicate_item(
    T implementation E  InputError trait_comment;
    [f64] [recip()] [RecipRealErrors::<Native64>] [RecipRealInputErrors] ["Implementation of the [`Reciprocal`] trait for [`f64`]."];
    [Complex::<f64>] [inv()]  [RecipComplexErrors::<Native64>] [RecipComplexInputErrors] ["Implementation of the [`Reciprocal`] trait for [`Complex`]."];
)]
impl Reciprocal for T {
    type Error = E;

    #[inline(always)]
    fn try_reciprocal(self) -> Result<Self, <Self as Reciprocal>::Error> {
        match self.validate() {
            Ok(value) => {
                if value.is_zero() {
                    Err(E::Input {
                        source: InputError::DivisionByZero {
                            backtrace: Backtrace::force_capture(),
                        },
                    })
                } else {
                    // value is different from zero, so we can "safely" compute the reciprocal
                    match Self::try_new(value.implementation) {
                        Ok(recip) => Ok(recip),
                        Err(e) => Err(E::Output { source: e }),
                    }
                }
            }
            Err(e) => Err(E::Input {
                source: InputError::ValidationError { source: e },
            }),
        }
    }

    #[inline(always)]
    fn reciprocal(self) -> Self {
        if cfg!(debug_assertions) {
            self.try_reciprocal().unwrap()
        } else {
            self.implementation
        }
    }
}

#[cfg(feature = "rug")]
#[duplicate::duplicate_item(
    T E InputError trait_comment;
    [RealRug::<PRECISION>] [RecipRealErrors::<Rug<PRECISION>>] [RecipRealInputErrors] ["Implementation of the [`Reciprocal`] trait for [`f64`]."];
    [ComplexRug::<PRECISION>] [RecipComplexErrors::<Rug<PRECISION>>] [RecipComplexInputErrors] ["Implementation of the [`Reciprocal`] trait for [`Complex`]."];
)]
impl<const PRECISION: u32> Reciprocal for T {
    type Error = E;

    #[inline(always)]
    fn try_reciprocal(self) -> Result<Self, <Self as Reciprocal>::Error> {
        match self.0.validate() {
            Ok(value) => {
                if value.is_zero() {
                    Err(E::Input {
                        source: InputError::DivisionByZero {
                            backtrace: Backtrace::force_capture(),
                        },
                    })
                } else {
                    // value is different from zero, so we can "safely" compute the reciprocal
                    match Self::try_new(value.recip()) {
                        Ok(recip) => Ok(recip),
                        Err(e) => Err(E::Output { source: e }),
                    }
                }
            }
            Err(e) => Err(E::Input {
                source: InputError::ValidationError { source: e },
            }),
        }
    }

    #[inline(always)]
    fn reciprocal(self) -> Self {
        if cfg!(debug_assertions) {
            self.try_reciprocal().unwrap()
        } else {
            Self(self.0.recip())
        }
    }
}
//--------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// This trait provides the interface for the function used to compute the *absolute value* of a number.
pub trait Abs {
    /// The return type of the *absolute value* function. It is always a real number (also when the input is a complex number).
    type Output;

    /// Returns the *absolute value* of `self`. The return type is always a real number (also when `self` is a complex number)
    fn abs(self) -> Self::Output;
}

#[duplicate::duplicate_item(
    T implementation trait_comment;
    [f64] [self.abs()] ["Implementation of the [`Abs`] trait for `f64`."];
    [Complex<f64>] [self.norm()] ["Implementation of the [`Abs`] trait for `Complex<f64>`."];
)]
#[doc = trait_comment]
impl Abs for T {
    /// The return type of the *absolute value* function.
    type Output = f64;

    /// Returns the *absolute value* of `self`.
    #[inline(always)]
    fn abs(self) -> Self::Output {
        implementation
    }
}

#[cfg(feature = "rug")]
#[duplicate::duplicate_item(
    T implementation trait_comment;
    [RealRug<PRECISION>] [RealRug(self.0.abs())] ["Implementation of the [`Abs`] trait for [`RealRug`]."];
    [ComplexRug<PRECISION>] [RealRug(self.0.abs().real().clone())] ["Implementation of the [`Abs`] trait for [`ComplexRug`]."];
)]
#[doc = trait_comment]
impl<const PRECISION: u32> Abs for T {
    /// The return type of the *absolute value* function.
    type Output = RealRug<PRECISION>;

    /// Returns the *absolute value* of `self`.
    #[inline(always)]
    fn abs(self) -> Self::Output {
        implementation
    }
}
//------------------------------------------------------------------------------------------------