scirs2-core 0.1.0-alpha.3

Core utilities and common functionality for SciRS2
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Numeric traits and utilities for SciRS2
//!
//! This module provides traits and utilities for working with numeric types
//! in scientific computing contexts.

use num_traits::{Float, Num, NumCast, One, Zero};
use std::fmt::Debug;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

/// A trait for numeric types that can be used in scientific calculations
///
/// This trait combines common numeric traits required for scientific computing
/// operations, providing a unified trait bound for generic code.
pub trait ScientificNumber:
    Num
    + Clone
    + Copy
    + PartialOrd
    + Debug
    + Zero
    + One
    + Add<Output = Self>
    + Sub<Output = Self>
    + Mul<Output = Self>
    + Div<Output = Self>
    + AddAssign
    + SubAssign
    + MulAssign
    + DivAssign
    + NumCast
{
    /// Absolute value
    fn abs(self) -> Self;

    /// Square root
    fn sqrt(self) -> Self;

    /// Square
    fn square(self) -> Self {
        self * self
    }

    /// Maximum of two values
    fn max(self, other: Self) -> Self;

    /// Minimum of two values
    fn min(self, other: Self) -> Self;

    /// Check if the value is finite
    fn is_finite(self) -> bool;

    /// Convert to f64
    fn to_f64(self) -> Option<f64>;

    /// Convert from f64
    fn from_f64(value: f64) -> Option<Self>;
}

/// A trait for real-valued floating point types
pub trait RealNumber: ScientificNumber + Float {
    /// Returns the machine epsilon (the difference between 1.0 and the least value greater than 1.0)
    fn epsilon() -> Self;

    /// Exponential function (e^x)
    fn exp(self) -> Self;

    /// Natural logarithm (ln(x))
    fn ln(self) -> Self;

    /// Base-10 logarithm
    fn log10(self) -> Self;

    /// Base-2 logarithm
    fn log2(self) -> Self;

    /// Sine function
    fn sin(self) -> Self;

    /// Cosine function
    fn cos(self) -> Self;

    /// Tangent function
    fn tan(self) -> Self;

    /// Hyperbolic sine
    fn sinh(self) -> Self;

    /// Hyperbolic cosine
    fn cosh(self) -> Self;

    /// Hyperbolic tangent
    fn tanh(self) -> Self;

    /// Inverse sine
    fn asin(self) -> Self;

    /// Inverse cosine
    fn acos(self) -> Self;

    /// Inverse tangent
    fn atan(self) -> Self;

    /// Inverse tangent of y/x with correct quadrant
    fn atan2(self, other: Self) -> Self;

    /// Power function
    fn powf(self, n: Self) -> Self;

    /// Integer power function
    fn powi(self, n: i32) -> Self;

    /// Factorial function (approximation for non-integers)
    fn factorial(self) -> Self;
}

/// A trait for complex number types
pub trait ComplexNumber: ScientificNumber {
    /// The real part of the complex number
    type RealPart: RealNumber;

    /// Returns the real part of the complex number
    fn re(&self) -> Self::RealPart;

    /// Returns the imaginary part of the complex number
    fn im(&self) -> Self::RealPart;

    /// Create a new complex number from real and imaginary parts
    fn new(re: Self::RealPart, im: Self::RealPart) -> Self;

    /// Returns the complex conjugate
    fn conj(self) -> Self;

    /// Returns the magnitude (absolute value)
    fn abs(self) -> Self::RealPart;

    /// Returns the argument (phase)
    fn arg(self) -> Self::RealPart;

    /// Returns the complex number in exponential form (r, theta)
    fn to_polar(self) -> (Self::RealPart, Self::RealPart);

    /// Creates a complex number from polar coordinates
    fn from_polar(r: Self::RealPart, theta: Self::RealPart) -> Self;

    /// Exponential function
    fn exp(self) -> Self;

    /// Natural logarithm
    fn ln(self) -> Self;

    /// Power function with complex exponent
    fn powc(self, exp: Self) -> Self;

    /// Power function with real exponent
    fn powf(self, exp: Self::RealPart) -> Self;

    /// Square root
    fn sqrt(self) -> Self;
}

/// A trait for integers that can be used in scientific calculations
pub trait ScientificInteger: ScientificNumber + Eq {
    /// Greatest common divisor
    fn gcd(self, other: Self) -> Self;

    /// Least common multiple
    fn lcm(self, other: Self) -> Self;

    /// Check if the number is prime
    fn is_prime(self) -> bool;

    /// Check if the number is even
    fn is_even(self) -> bool;

    /// Check if the number is odd
    fn is_odd(self) -> bool;

    /// Modular exponentiation (self^exp mod modulus)
    fn mod_pow(self, exp: Self, modulus: Self) -> Self;

    /// Factorial
    fn factorial(self) -> Self;

    /// Binomial coefficient (n choose k)
    fn binomial(self, k: Self) -> Self;
}

// Implement ScientificNumber for f32
impl ScientificNumber for f32 {
    fn abs(self) -> Self {
        self.abs()
    }

    fn sqrt(self) -> Self {
        self.sqrt()
    }

    fn max(self, other: Self) -> Self {
        self.max(other)
    }

    fn min(self, other: Self) -> Self {
        self.min(other)
    }

    fn is_finite(self) -> bool {
        self.is_finite()
    }

    fn to_f64(self) -> Option<f64> {
        Some(self as f64)
    }

    fn from_f64(value: f64) -> Option<Self> {
        if value.is_finite() && value <= f32::MAX as f64 && value >= f32::MIN as f64 {
            Some(value as f32)
        } else {
            None
        }
    }
}

// Implement RealNumber for f32
impl RealNumber for f32 {
    fn epsilon() -> Self {
        f32::EPSILON
    }

    fn exp(self) -> Self {
        self.exp()
    }

    fn ln(self) -> Self {
        self.ln()
    }

    fn log10(self) -> Self {
        self.log10()
    }

    fn log2(self) -> Self {
        self.log2()
    }

    fn sin(self) -> Self {
        self.sin()
    }

    fn cos(self) -> Self {
        self.cos()
    }

    fn tan(self) -> Self {
        self.tan()
    }

    fn sinh(self) -> Self {
        self.sinh()
    }

    fn cosh(self) -> Self {
        self.cosh()
    }

    fn tanh(self) -> Self {
        self.tanh()
    }

    fn asin(self) -> Self {
        self.asin()
    }

    fn acos(self) -> Self {
        self.acos()
    }

    fn atan(self) -> Self {
        self.atan()
    }

    fn atan2(self, other: Self) -> Self {
        self.atan2(other)
    }

    fn powf(self, n: Self) -> Self {
        self.powf(n)
    }

    fn powi(self, n: i32) -> Self {
        self.powi(n)
    }

    fn factorial(self) -> Self {
        if self < 0.0 {
            return f32::NAN;
        }

        // Use Stirling's approximation for non-integers or large values
        if self != self.trunc() || self > 100.0 {
            const SQRT_TWO_PI: f32 = 2.506_628_3;
            return SQRT_TWO_PI * self.powf(self + 0.5) * (-self).exp();
        }

        let mut result = 1.0;
        let n = self as u32;
        for i in 2..=n {
            result *= i as f32;
        }

        result
    }
}

// Implement ScientificNumber for f64
impl ScientificNumber for f64 {
    fn abs(self) -> Self {
        self.abs()
    }

    fn sqrt(self) -> Self {
        self.sqrt()
    }

    fn max(self, other: Self) -> Self {
        self.max(other)
    }

    fn min(self, other: Self) -> Self {
        self.min(other)
    }

    fn is_finite(self) -> bool {
        self.is_finite()
    }

    fn to_f64(self) -> Option<f64> {
        Some(self)
    }

    fn from_f64(value: f64) -> Option<Self> {
        Some(value)
    }
}

// Implement RealNumber for f64
impl RealNumber for f64 {
    fn epsilon() -> Self {
        f64::EPSILON
    }

    fn exp(self) -> Self {
        self.exp()
    }

    fn ln(self) -> Self {
        self.ln()
    }

    fn log10(self) -> Self {
        self.log10()
    }

    fn log2(self) -> Self {
        self.log2()
    }

    fn sin(self) -> Self {
        self.sin()
    }

    fn cos(self) -> Self {
        self.cos()
    }

    fn tan(self) -> Self {
        self.tan()
    }

    fn sinh(self) -> Self {
        self.sinh()
    }

    fn cosh(self) -> Self {
        self.cosh()
    }

    fn tanh(self) -> Self {
        self.tanh()
    }

    fn asin(self) -> Self {
        self.asin()
    }

    fn acos(self) -> Self {
        self.acos()
    }

    fn atan(self) -> Self {
        self.atan()
    }

    fn atan2(self, other: Self) -> Self {
        self.atan2(other)
    }

    fn powf(self, n: Self) -> Self {
        self.powf(n)
    }

    fn powi(self, n: i32) -> Self {
        self.powi(n)
    }

    fn factorial(self) -> Self {
        if self < 0.0 {
            return f64::NAN;
        }

        // Use Stirling's approximation for non-integers or large values
        if self != self.trunc() || self > 170.0 {
            const SQRT_TWO_PI: f64 = 2.5066282746310002;
            return SQRT_TWO_PI * self.powf(self + 0.5) * (-self).exp();
        }

        let mut result = 1.0;
        let n = self as u32;
        for i in 2..=n {
            result *= i as f64;
        }

        result
    }
}

// Implement ScientificNumber for i32
impl ScientificNumber for i32 {
    fn abs(self) -> Self {
        self.abs()
    }

    fn sqrt(self) -> Self {
        (self as f64).sqrt() as i32
    }

    fn max(self, other: Self) -> Self {
        std::cmp::max(self, other)
    }

    fn min(self, other: Self) -> Self {
        std::cmp::min(self, other)
    }

    fn is_finite(self) -> bool {
        true // integers are always finite
    }

    fn to_f64(self) -> Option<f64> {
        Some(self as f64)
    }

    fn from_f64(value: f64) -> Option<Self> {
        if value.is_finite() && value <= i32::MAX as f64 && value >= i32::MIN as f64 {
            Some(value as i32)
        } else {
            None
        }
    }
}

// Implement ScientificInteger for i32
impl ScientificInteger for i32 {
    fn gcd(self, other: Self) -> Self {
        let mut a = self.abs();
        let mut b = other.abs();

        if a == 0 {
            return b;
        }
        if b == 0 {
            return a;
        }

        while b != 0 {
            let temp = b;
            b = a % b;
            a = temp;
        }

        a
    }

    fn lcm(self, other: Self) -> Self {
        if self == 0 || other == 0 {
            return 0;
        }

        let gcd = self.gcd(other);

        (self / gcd) * other
    }

    fn is_prime(self) -> bool {
        if self <= 1 {
            return false;
        }
        if self <= 3 {
            return true;
        }
        if self % 2 == 0 || self % 3 == 0 {
            return false;
        }

        let mut i = 5;
        while i * i <= self {
            if self % i == 0 || self % (i + 2) == 0 {
                return false;
            }
            i += 6;
        }

        true
    }

    fn is_even(self) -> bool {
        self % 2 == 0
    }

    fn is_odd(self) -> bool {
        self % 2 != 0
    }

    fn mod_pow(self, exp: Self, modulus: Self) -> Self {
        if modulus == 1 {
            return 0;
        }

        let mut base = self % modulus;
        let mut result = 1;
        let mut exponent = exp;

        while exponent > 0 {
            if exponent % 2 == 1 {
                result = (result * base) % modulus;
            }
            exponent >>= 1;
            base = (base * base) % modulus;
        }

        result
    }

    fn factorial(self) -> Self {
        if self < 0 {
            panic!("Factorial not defined for negative numbers");
        }

        let mut result = 1;
        for i in 2..=self {
            result *= i;
        }

        result
    }

    fn binomial(self, k: Self) -> Self {
        if k < 0 || k > self {
            return 0;
        }

        let k = std::cmp::min(k, self - k);
        let mut result = 1;

        for i in 0..k {
            result = result * (self - i) / (i + 1);
        }

        result
    }
}

/// Conversion between different numeric types
pub trait NumericConversion<T> {
    /// Try to convert to the target type
    fn try_convert(self) -> Option<T>;

    /// Convert to the target type, or a default value if conversion fails
    fn convert_or(self, default: T) -> T;

    /// Convert to the target type, or panic if conversion fails
    fn convert(self) -> T;
}

/// Implement NumericConversion for all types that implement NumCast
impl<F, T> NumericConversion<T> for F
where
    F: NumCast,
    T: NumCast,
{
    fn try_convert(self) -> Option<T> {
        num_traits::cast(self)
    }

    fn convert_or(self, default: T) -> T {
        self.try_convert().unwrap_or(default)
    }

    fn convert(self) -> T {
        self.try_convert().expect("Numeric conversion failed")
    }
}

/// Trait for converting between degrees and radians
pub trait AngleConversion {
    /// Convert from degrees to radians
    fn to_radians(self) -> Self;

    /// Convert from radians to degrees
    fn to_degrees(self) -> Self;
}

/// Implement AngleConversion for all RealNumber types
impl<T: RealNumber> AngleConversion for T {
    fn to_radians(self) -> Self {
        let pi = T::from_f64(std::f64::consts::PI).unwrap();
        self * pi / T::from_f64(180.0).unwrap()
    }

    fn to_degrees(self) -> Self {
        let pi = T::from_f64(std::f64::consts::PI).unwrap();
        self * T::from_f64(180.0).unwrap() / pi
    }
}

/// Type-safe representation of a unitless quantity
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Scalar<T: ScientificNumber>(pub T);

impl<T: ScientificNumber> Scalar<T> {
    /// Create a new scalar
    pub fn new(value: T) -> Self {
        Scalar(value)
    }

    /// Get the underlying value
    pub fn value(&self) -> T {
        self.0
    }
}

impl<T: ScientificNumber> From<T> for Scalar<T> {
    fn from(value: T) -> Self {
        Scalar(value)
    }
}

impl<T: ScientificNumber> Add for Scalar<T> {
    type Output = Self;

    fn add(self, other: Self) -> Self::Output {
        Scalar(self.0 + other.0)
    }
}

impl<T: ScientificNumber> Sub for Scalar<T> {
    type Output = Self;

    fn sub(self, other: Self) -> Self::Output {
        Scalar(self.0 - other.0)
    }
}

impl<T: ScientificNumber> Mul for Scalar<T> {
    type Output = Self;

    fn mul(self, other: Self) -> Self::Output {
        Scalar(self.0 * other.0)
    }
}

impl<T: ScientificNumber> Div for Scalar<T> {
    type Output = Self;

    fn div(self, other: Self) -> Self::Output {
        Scalar(self.0 / other.0)
    }
}

impl<T: ScientificNumber + Neg<Output = T>> Neg for Scalar<T> {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Scalar(self.0.neg())
    }
}

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

    #[test]
    fn test_scientific_number_f32() {
        let a: f32 = 3.0;
        let b: f32 = 4.0;

        assert_eq!(a.abs(), 3.0);
        assert_eq!(a.sqrt(), (3.0_f32).sqrt());
        assert_eq!(a.square(), 9.0);
        assert_eq!(a.max(b), 4.0);
        assert_eq!(a.min(b), 3.0);
        assert!(a.is_finite());
        assert_eq!(a.to_f64(), Some(3.0));
        assert_eq!(f32::from_f64(3.5), Some(3.5));
    }

    #[test]
    fn test_scientific_number_f64() {
        let a: f64 = 3.0;
        let b: f64 = 4.0;

        assert_eq!(a.abs(), 3.0);
        assert_eq!(a.sqrt(), (3.0_f64).sqrt());
        assert_eq!(a.square(), 9.0);
        assert_eq!(a.max(b), 4.0);
        assert_eq!(a.min(b), 3.0);
        assert!(a.is_finite());
        assert_eq!(a.to_f64(), Some(3.0));
        assert_eq!(f64::from_f64(3.5), Some(3.5));
    }

    #[test]
    fn test_real_number_f32() {
        let a: f32 = 3.0;

        assert_eq!(<f32 as RealNumber>::epsilon(), f32::EPSILON);
        assert_eq!(a.exp(), (3.0_f32).exp());
        assert_eq!(a.ln(), (3.0_f32).ln());
        assert_eq!(a.sin(), (3.0_f32).sin());
        assert_eq!(a.cos(), (3.0_f32).cos());
        assert_eq!(a.powf(2.0), 9.0);
    }

    #[test]
    fn test_real_number_f64() {
        let a: f64 = 3.0;

        assert_eq!(<f64 as RealNumber>::epsilon(), f64::EPSILON);
        assert_eq!(a.exp(), (3.0_f64).exp());
        assert_eq!(a.ln(), (3.0_f64).ln());
        assert_eq!(a.sin(), (3.0_f64).sin());
        assert_eq!(a.cos(), (3.0_f64).cos());
        assert_eq!(a.powf(2.0), 9.0);
    }

    #[test]
    fn test_scientific_integer_i32() {
        let a: i32 = 12;
        let b: i32 = 8;

        assert_eq!(a.gcd(b), 4);
        assert_eq!(a.lcm(b), 24);
        assert!(!a.is_prime());
        assert!(11_i32.is_prime());
        assert!(a.is_even());
        assert!(!a.is_odd());
        assert_eq!(a.mod_pow(2, 10), 4); // 12^2 mod 10 = 4
        assert_eq!(5_i32.factorial(), 120);
        assert_eq!(5_i32.binomial(2), 10); // 5 choose 2 = 10
    }

    #[test]
    fn test_numeric_conversion() {
        let a: f64 = 3.5;
        let b: i32 = a.try_convert().unwrap();
        assert_eq!(b, 3);

        let c: f32 = 100.5;
        let d: f64 = c.convert();
        assert_eq!(d, 100.5);

        let e: i32 = 100;
        let f: f32 = e.convert();
        assert_eq!(f, 100.0);
    }

    #[test]
    fn test_angle_conversion() {
        let degrees: f64 = 180.0;
        let radians = degrees.to_radians();
        assert_eq!(radians, std::f64::consts::PI);

        let radians: f64 = std::f64::consts::PI / 2.0;
        let degrees = radians.to_degrees();
        assert_eq!(degrees, 90.0);
    }

    #[test]
    fn test_scalar() {
        let a = Scalar::new(3.0_f64);
        let b = Scalar::new(4.0_f64);

        assert_eq!((a + b).value(), 7.0);
        assert_eq!((a - b).value(), -1.0);
        assert_eq!((a * b).value(), 12.0);
        assert_eq!((a / b).value(), 0.75);
        assert_eq!((-a).value(), -3.0);

        let c: Scalar<f64> = 5.0.into();
        assert_eq!(c.value(), 5.0);
    }
}