scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! Auto-generated module
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)

use crate::numeric::Float;
use crate::simd_ops::{AutoOptimizer, SimdUnifiedOps};
use ::ndarray::{Array1, ArrayView1};

/// Compute the base-2 logarithm of each element (SIMD-accelerated).
///
/// Computes log₂(x) for each element, where log₂(x) = ln(x) / ln(2).
///
/// # Arguments
///
/// * `x` - Input 1D array with positive values
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is the base-2
/// logarithm. Returns NaN for x ≤ 0, and -∞ for x = 0.
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Scalar**: Used for small arrays or when SIMD is unavailable
///
/// # Mathematical Properties
///
/// - Domain: (0, ∞)
/// - Range: (-∞, ∞)
/// - log₂(1) = 0
/// - log₂(2) = 1
/// - log₂(2ⁿ) = n
/// - log₂(x * y) = log₂(x) + log₂(y)
/// - log₂(x / y) = log₂(x) - log₂(y)
/// - log₂(xⁿ) = n * log₂(x)
/// - Returns NaN for x ≤ 0
/// - Returns -∞ for x = 0
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::log2_simd;
///
/// let x = array![1.0_f64, 2.0, 4.0, 8.0, 16.0];
/// let result = log2_simd(&x.view());
/// // Result: [0.0, 1.0, 2.0, 3.0, 4.0]
/// ```
///
/// # Applications
///
/// - **Information Theory**: Shannon entropy (bits), channel capacity
/// - **Computer Science**: Binary tree depth, algorithm complexity analysis
/// - **Machine Learning**: Decision trees, information gain
/// - **Signal Processing**: Octave scales, frequency resolution
/// - **Data Compression**: Optimal coding, Huffman coding
/// - **Cryptography**: Key size representation, security levels
/// - **Scientific Computing**: Binary logarithmic plots
/// - **Digital Systems**: Bit depth calculations
///
/// # See Also
///
/// - `ln_simd`: Natural logarithm (base e)
/// - `log10_simd`: Base-10 logarithm
/// - `exp_simd`: Exponential function (inverse of ln)
pub fn log2_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_log2(x);
    }
    x.mapv(|val| val.log2())
}
/// Clamp each element to a specified range [min, max] (SIMD-accelerated).
///
/// Constrains each element x to satisfy min ≤ x ≤ max. Values below min are set
/// to min, values above max are set to max, and values within range are unchanged.
///
/// # Arguments
///
/// * `x` - Input 1D array
/// * `min` - Minimum value (lower bound)
/// * `max` - Maximum value (upper bound)
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is clamped to [min, max].
///
/// # Panics
///
/// Panics if min > max (invalid range).
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Scalar**: Used for small arrays or when SIMD is unavailable
///
/// # Mathematical Properties
///
/// - clamp(x, min, max) = max(min, min(x, max))
/// - clamp(x, min, max) ∈ [min, max] for all x
/// - clamp(min, min, max) = min
/// - clamp(max, min, max) = max
/// - clamp is idempotent: clamp(clamp(x, a, b), a, b) = clamp(x, a, b)
/// - clamp preserves monotonicity: if x₁ ≤ x₂, then clamp(x₁) ≤ clamp(x₂)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::clamp_simd;
///
/// let x = array![-1.0_f64, 0.5, 1.5, 2.5, 3.5];
/// let result = clamp_simd(&x.view(), 0.0, 2.0);
/// // Result: [0.0, 0.5, 1.5, 2.0, 2.0]
/// ```
///
/// # Applications
///
/// - **Image Processing**: Pixel value normalization (0-255, 0.0-1.0)
/// - **Neural Networks**: Gradient clipping, activation bounding
/// - **Computer Vision**: Color space conversions, contrast limiting
/// - **Signal Processing**: Dynamic range compression, amplitude limiting
/// - **Data Normalization**: Feature scaling, outlier handling
/// - **Numerical Stability**: Preventing overflow/underflow in computations
/// - **Game Development**: Velocity limiting, position constraints
/// - **Robotics**: Joint angle limits, actuator bounds
/// - **Audio Processing**: Volume limiting, signal clipping prevention
/// - **Machine Learning**: Learning rate bounds, weight constraints
///
/// # See Also
///
/// - `abs_simd`: Absolute value (clamping negative values to positive)
/// - `floor_simd`: Lower bound only (ceiling at integers)
/// - `ceil_simd`: Upper bound only (floor at integers)
pub fn clamp_simd<F>(x: &ArrayView1<F>, min: F, max: F) -> Array1<F>
where
    F: Float + SimdUnifiedOps + std::fmt::Debug,
{
    assert!(
        min <= max,
        "clamp_simd: min ({:?}) must be <= max ({:?})",
        min,
        max
    );
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_clamp(x, min, max);
    }
    x.mapv(|val| val.clamp(min, max))
}
/// Compute 2^x for each element (SIMD-accelerated).
///
/// Computes the base-2 exponential function 2^x for each element.
///
/// # Arguments
///
/// * `x` - Input 1D array
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is 2 raised to the
/// corresponding input power.
///
/// # Performance
///
/// Uses the identity 2^x = exp(x * ln(2)) with SIMD-accelerated exp and scalar multiply.
///
/// # Mathematical Properties
///
/// - 2^0 = 1
/// - 2^1 = 2
/// - 2^(-1) = 0.5
/// - 2^n for integer n is exact for small n
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::exp2_simd;
///
/// let x = array![0.0_f64, 1.0, 2.0, 3.0, -1.0];
/// let result = exp2_simd(&x.view());
/// // Result: [1.0, 2.0, 4.0, 8.0, 0.5]
/// ```
///
/// # Applications
///
/// - **Audio Processing**: Octave/semitone calculations
/// - **Computer Graphics**: Level of detail (LOD) calculations
/// - **Floating-Point**: Exponent manipulation
pub fn exp2_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_exp2(x);
    }
    F::simd_exp2(x)
}
/// Compute the cube root of each element (SIMD-accelerated).
///
/// Computes cbrt(x) = x^(1/3) for each element, correctly handling negative values.
///
/// # Arguments
///
/// * `x` - Input 1D array
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is the cube root.
///
/// # Mathematical Properties
///
/// - cbrt(x^3) = x (exact inverse of cubing)
/// - cbrt(-x) = -cbrt(x) (handles negative numbers)
/// - cbrt(0) = 0
/// - cbrt(1) = 1, cbrt(8) = 2, cbrt(27) = 3
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::cbrt_simd;
///
/// let x = array![0.0_f64, 1.0, 8.0, 27.0, -8.0];
/// let result = cbrt_simd(&x.view());
/// // Result: [0.0, 1.0, 2.0, 3.0, -2.0]
/// ```
///
/// # Applications
///
/// - **Statistics**: Transforming skewed data
/// - **Physics**: Volume calculations from cubic dimensions
/// - **Numerical Analysis**: Root-finding algorithms
pub fn cbrt_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_cbrt(x);
    }
    x.mapv(|val| val.cbrt())
}
/// Compute ln(1+x) for each element (SIMD-accelerated, numerically stable).
///
/// Computes the natural logarithm of (1+x) with improved accuracy for small x values
/// where direct computation of ln(1+x) would lose precision.
///
/// # Arguments
///
/// * `x` - Input 1D array with values > -1
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is ln(1+x).
///
/// # Mathematical Properties
///
/// - ln_1p(0) = 0
/// - ln_1p(x) ≈ x for |x| << 1 (Taylor series first term)
/// - More accurate than ln(1+x) when |x| is small
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::ln_1p_simd;
///
/// let x = array![0.0_f64, 1.0, 1e-15, -0.5];
/// let result = ln_1p_simd(&x.view());
/// // Result: [0.0, ln(2), ≈1e-15, -ln(2)]
/// ```
///
/// # Applications
///
/// - **Finance**: Continuous compound interest rates
/// - **Statistics**: Log-likelihood computations
/// - **Numerical Analysis**: Avoiding catastrophic cancellation
pub fn ln_1p_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_ln_1p(x);
    }
    x.mapv(|val| val.ln_1p())
}
/// Compute exp(x)-1 for each element (SIMD-accelerated, numerically stable).
///
/// Computes e^x - 1 with improved accuracy for small x values where direct
/// computation would lose precision.
///
/// # Arguments
///
/// * `x` - Input 1D array
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is exp(x)-1.
///
/// # Mathematical Properties
///
/// - exp_m1(0) = 0
/// - exp_m1(x) ≈ x for |x| << 1 (Taylor series first term)
/// - exp_m1(-x) = -exp_m1(x) / (1 + exp_m1(x))
/// - More accurate than exp(x)-1 when |x| is small
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::exp_m1_simd;
///
/// let x = array![0.0_f64, 1.0, 1e-15, -1.0];
/// let result = exp_m1_simd(&x.view());
/// // Result: [0.0, e-1, ≈1e-15, 1/e - 1]
/// ```
///
/// # Applications
///
/// - **Finance**: Continuous compounding calculations
/// - **Physics**: Small perturbation calculations
/// - **Numerical Analysis**: Avoiding catastrophic cancellation
pub fn exp_m1_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_exp_m1(x);
    }
    x.mapv(|val| val.exp_m1())
}
/// Convert degrees to radians for each element (SIMD-accelerated).
///
/// Computes x * π / 180 for each element, converting angle measurements
/// from degrees to radians.
///
/// # Arguments
///
/// * `x` - Input 1D array of angles in degrees
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is the
/// corresponding angle in radians.
///
/// # Performance
///
/// Uses SIMD scalar multiplication for optimal performance.
///
/// # Mathematical Properties
///
/// - to_radians(0) = 0
/// - to_radians(90) = π/2
/// - to_radians(180) = π
/// - to_radians(360) = 2π
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::to_radians_simd;
///
/// let degrees = array![0.0, 90.0, 180.0, 360.0];
/// let radians = to_radians_simd(&degrees.view());
/// // Result: [0.0, π/2, π, 2π]
/// ```
///
/// # Applications
///
/// - **Trigonometry**: Converting human-readable angles to radian form
/// - **Graphics**: Rotation transformations
/// - **Physics**: Angular velocity and position calculations
/// - **Navigation**: Bearing and heading conversions
pub fn to_radians_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_to_radians(x);
    }
    F::simd_to_radians(x)
}
/// Convert radians to degrees for each element (SIMD-accelerated).
///
/// Computes x * 180 / π for each element, converting angle measurements
/// from radians to degrees.
///
/// # Arguments
///
/// * `x` - Input 1D array of angles in radians
///
/// # Returns
///
/// `Array1<F>` with the same length as input, where each element is the
/// corresponding angle in degrees.
///
/// # Performance
///
/// Uses SIMD scalar multiplication for optimal performance.
///
/// # Mathematical Properties
///
/// - to_degrees(0) = 0
/// - to_degrees(π/2) = 90
/// - to_degrees(π) = 180
/// - to_degrees(2π) = 360
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::elementwise::to_degrees_simd;
/// use std::f64::consts::PI;
///
/// let radians = array![0.0, PI/2.0, PI, 2.0*PI];
/// let degrees = to_degrees_simd(&radians.view());
/// // Result: [0.0, 90.0, 180.0, 360.0]
/// ```
///
/// # Applications
///
/// - **Trigonometry**: Converting calculation results to human-readable form
/// - **Graphics**: Displaying rotation angles
/// - **Physics**: Reporting angular measurements
/// - **Navigation**: Displaying compass headings
pub fn to_degrees_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_to_degrees(x);
    }
    F::simd_to_degrees(x)
}
/// Computes the element-wise digamma function ψ(x) = d/dx ln(Γ(x)) using SIMD acceleration.
///
/// The digamma function is the logarithmic derivative of the gamma function.
/// It is essential for:
/// - Bayesian variational inference (Dirichlet, Beta priors)
/// - Maximum likelihood estimation for gamma distributions
/// - Statistical special function computations
///
/// # Implementation Details
///
/// The implementation uses three techniques for high accuracy:
/// 1. **Reflection formula**: For x < 0.5, uses ψ(1-x) - π/tan(πx)
/// 2. **Recurrence relation**: For small x, uses ψ(x+1) = ψ(x) + 1/x
/// 3. **Asymptotic expansion**: For large x, uses Bernoulli number series
///
/// # Arguments
///
/// * `x` - Input array of values. Should avoid non-positive integers where digamma has poles.
///
/// # Returns
///
/// Array of ψ(x) values, same shape as input.
///
/// # Mathematical Properties
///
/// - ψ(1) = -γ (Euler-Mascheroni constant ≈ -0.5772)
/// - ψ(n) = -γ + Σ(k=1 to n-1) 1/k for positive integers
/// - ψ(x+1) = ψ(x) + 1/x
/// - ψ(1-x) - ψ(x) = π·cot(πx)
///
/// # Example
///
/// ```ignore
/// use scirs2_core::ndarray_ext::elementwise::digamma_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![1.0f64, 2.0, 3.0, 4.0];
/// let result = digamma_simd(&x.view());
/// // ψ(1) ≈ -0.5772, ψ(2) ≈ 0.4228, ψ(3) ≈ 0.9228, ψ(4) ≈ 1.2561
/// ```
pub fn digamma_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_digamma(x);
    }
    F::simd_digamma(x)
}
/// Computes the element-wise trigamma function ψ'(x) = d²/dx² ln(Γ(x)) using SIMD acceleration.
///
/// The trigamma function is the second derivative of the log-gamma function (first derivative
/// of digamma). It is critical for:
/// - Fisher information computation in Bayesian inference
/// - Variance of gamma and beta distribution parameters
/// - Maximum likelihood estimation for gamma distributions
/// - Sensitivity analysis in Bayesian variational inference
///
/// # Implementation Details
///
/// The implementation uses three techniques for high accuracy:
/// 1. **Reflection formula**: For x < 0, uses ψ'(1-x) + ψ'(x) = π²/sin²(πx)
/// 2. **Recurrence relation**: For small x, uses ψ'(x+1) = ψ'(x) - 1/x²
/// 3. **Asymptotic expansion**: For large x, uses ψ'(x) ≈ 1/x + 1/(2x²) + B₂/x³ - B₄/x⁵ + ...
///
/// # Arguments
///
/// * `x` - Input array of values. Should avoid non-positive integers where trigamma has poles.
///
/// # Returns
///
/// Array of ψ'(x) values, same shape as input.
///
/// # Mathematical Properties
///
/// - ψ'(1) = π²/6 ≈ 1.6449340668 (Basel problem)
/// - ψ'(n) = π²/6 - Σ(k=1 to n-1) 1/k² for positive integers
/// - ψ'(x+1) = ψ'(x) - 1/x²
/// - For large x: ψ'(x) → 1/x
///
/// # Example
///
/// ```ignore
/// use scirs2_core::ndarray_ext::elementwise::trigamma_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![1.0f64, 2.0, 3.0, 4.0];
/// let result = trigamma_simd(&x.view());
/// // ψ'(1) ≈ 1.6449, ψ'(2) ≈ 0.6449, ψ'(3) ≈ 0.3949, ψ'(4) ≈ 0.2838
/// ```
pub fn trigamma_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_trigamma(x);
    }
    F::simd_trigamma(x)
}
/// Computes the element-wise log-gamma function ln(Γ(x)) using SIMD acceleration.
///
/// The log-gamma function is more numerically stable than computing `gamma(x).ln()`
/// since it avoids overflow for large arguments and handles the full range of inputs.
/// This function is extensively used in:
/// - Statistical distributions (gamma, beta, binomial, Poisson)
/// - Bayesian inference (prior/posterior computations)
/// - Maximum likelihood estimation
/// - Combinatorics (log of binomial coefficients)
///
/// # Implementation Details
///
/// Uses the Lanczos approximation with reflection formula:
/// - For x >= 0.5: ln(Γ(z)) = ln(√(2π)) + (z-0.5)·ln(t) - t + ln(sum) where t = z + g - 0.5
/// - For x < 0.5: ln(Γ(z)) = ln(π) - ln(|sin(πz)|) - ln(Γ(1-z))
///
/// # Arguments
///
/// * `x` - Input array of values. Poles at non-positive integers (returns +∞).
///
/// # Returns
///
/// Array of ln(Γ(x)) values, same shape as input.
///
/// # Mathematical Properties
///
/// - ln(Γ(1)) = ln(Γ(2)) = 0
/// - ln(Γ(n)) = ln((n-1)!) for positive integers
/// - ln(Γ(1/2)) = ln(√π) ≈ 0.5724
/// - For large x: ln(Γ(x)) ≈ (x-0.5)·ln(x) - x + ln(√(2π))
///
/// # Example
///
/// ```ignore
/// use scirs2_core::ndarray_ext::elementwise::ln_gamma_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![1.0f64, 2.0, 3.0, 4.0, 5.0];
/// let result = ln_gamma_simd(&x.view());
/// // ln(Γ(1)) = 0, ln(Γ(2)) = 0, ln(Γ(3)) = ln(2!) ≈ 0.693
/// // ln(Γ(4)) = ln(3!) ≈ 1.792, ln(Γ(5)) = ln(4!) ≈ 3.178
/// ```
pub fn ln_gamma_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_ln_gamma(x);
    }
    F::simd_ln_gamma(x)
}
/// Element-wise error function erf(x) = (2/√π) ∫₀ˣ e^(-t²) dt
///
/// Uses SIMD acceleration when available for optimal performance.
/// Critical for normal distribution CDF: Φ(x) = 0.5 * (1 + erf(x/√2))
///
/// # Properties
/// - erf(0) = 0
/// - erf(∞) = 1, erf(-∞) = -1
/// - erf(-x) = -erf(x) (odd function)
/// - erf(1) ≈ 0.8427007929497148
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::erf_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![0.0_f64, 1.0, 2.0, -1.0];
/// let result = erf_simd(&x.view());
/// assert!((result[0] - 0.0_f64).abs() < 1e-10);  // erf(0) = 0
/// assert!((result[1] - 0.8427007929497148_f64).abs() < 1e-6);  // erf(1)
/// assert!((result[3] + 0.8427007929497148_f64).abs() < 1e-6);  // erf(-1) = -erf(1)
/// ```
pub fn erf_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_erf(x);
    }
    F::simd_erf(x)
}
/// Element-wise complementary error function erfc(x) = 1 - erf(x)
///
/// More numerically stable than computing 1 - erf(x) directly for large x.
/// Uses SIMD acceleration when available for optimal performance.
///
/// # Properties
/// - erfc(0) = 1
/// - erfc(∞) = 0, erfc(-∞) = 2
/// - erfc(x) = 1 - erf(x)
/// - erfc(-x) = 2 - erfc(x)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::erfc_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![0.0f64, 1.0, 2.0, 3.0];
/// let result = erfc_simd(&x.view());
/// assert!((result[0] - 1.0).abs() < 1e-10);  // erfc(0) = 1
/// assert!((result[1] - 0.1572992070502852).abs() < 1e-6);  // erfc(1)
/// ```
pub fn erfc_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_erfc(x);
    }
    F::simd_erfc(x)
}
/// Element-wise inverse error function erfinv(y) = x such that erf(x) = y
///
/// Uses SIMD acceleration when available for optimal performance.
/// Critical for inverse normal CDF (probit function): Φ⁻¹(p) = √2 * erfinv(2p - 1)
///
/// # Domain and Range
/// - Domain: (-1, 1)
/// - Range: (-∞, ∞)
/// - erfinv(-1) = -∞, erfinv(1) = ∞
///
/// # Properties
/// - erfinv(0) = 0
/// - erfinv(-y) = -erfinv(y) (odd function)
/// - erf(erfinv(y)) = y
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::erfinv_simd;
/// use scirs2_core::ndarray::array;
///
/// let y = array![0.0f64, 0.5, -0.5, 0.9];
/// let result = erfinv_simd(&y.view());
/// assert!((result[0] - 0.0).abs() < 1e-10);  // erfinv(0) = 0
/// ```
pub fn erfinv_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_erfinv(x);
    }
    F::simd_erfinv(x)
}
/// Element-wise inverse complementary error function erfcinv(y) = x such that erfc(x) = y
///
/// More numerically stable than erfinv(1 - y) for y close to 0.
/// Uses SIMD acceleration when available for optimal performance.
///
/// # Domain and Range
/// - Domain: (0, 2)
/// - Range: (-∞, ∞)
/// - erfcinv(0) = ∞, erfcinv(2) = -∞
///
/// # Properties
/// - erfcinv(1) = 0
/// - erfcinv(y) = erfinv(1 - y)
/// - erfc(erfcinv(y)) = y
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::erfcinv_simd;
/// use scirs2_core::ndarray::array;
///
/// let y = array![1.0f64, 0.5, 1.5];
/// let result = erfcinv_simd(&y.view());
/// assert!((result[0] - 0.0).abs() < 1e-10);  // erfcinv(1) = 0
/// ```
pub fn erfcinv_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_erfcinv(x);
    }
    F::simd_erfcinv(x)
}
/// Compute the element-wise sigmoid (logistic) function of an array.
///
/// The sigmoid function is defined as:
/// σ(x) = 1 / (1 + exp(-x))
///
/// This is critical for neural networks, logistic regression, and probability modeling.
/// The implementation is numerically stable, avoiding overflow for large |x|.
///
/// # Properties
///
/// - Range: (0, 1)
/// - σ(0) = 0.5
/// - σ(-x) = 1 - σ(x)
/// - Derivative: σ'(x) = σ(x)(1 - σ(x))
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::sigmoid_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![0.0f64, 1.0, -1.0];
/// let result = sigmoid_simd(&x.view());
/// assert!((result[0] - 0.5).abs() < 1e-10);  // sigmoid(0) = 0.5
/// ```
pub fn sigmoid_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_sigmoid(x);
    }
    F::simd_sigmoid(x)
}
/// Compute the element-wise GELU (Gaussian Error Linear Unit) of an array.
///
/// The GELU function is defined as:
/// GELU(x) = x * Φ(x) = x * 0.5 * (1 + erf(x / √2))
///
/// Where Φ(x) is the cumulative distribution function of the standard normal distribution.
/// GELU is critical for Transformer models (BERT, GPT, etc.) and provides a smooth
/// approximation of ReLU.
///
/// # Properties
///
/// - GELU(0) = 0
/// - GELU(x) ≈ x for large positive x
/// - GELU(x) ≈ 0 for large negative x
/// - Smooth and differentiable everywhere
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::gelu_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![0.0f64, 1.0, -1.0];
/// let result = gelu_simd(&x.view());
/// assert!(result[0].abs() < 1e-10);  // GELU(0) = 0
/// ```
pub fn gelu_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_gelu(x);
    }
    F::simd_gelu(x)
}
/// SIMD-accelerated Swish (SiLU - Sigmoid Linear Unit) activation function
///
/// Computes the Swish activation function element-wise:
/// `Swish(x) = x * sigmoid(x) = x / (1 + exp(-x))`
///
/// Swish is a self-gated activation function discovered through neural architecture
/// search that has become a popular choice for modern neural networks.
///
/// # Key Properties
///
/// - Swish(0) = 0
/// - Swish is smooth and non-monotonic
/// - Has a small negative region (unlike ReLU)
/// - Self-gating: x modulates its own activation via sigmoid
/// - Unbounded above, bounded below (minimum ≈ -0.278 at x ≈ -1.278)
///
/// # Usage in Deep Learning
///
/// Swish is used in:
/// - EfficientNet and EfficientNetV2
/// - GPT-NeoX and other large language models
/// - MobileNetV3
/// - Many modern vision and NLP architectures
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::swish_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![0.0f64, 1.0, -1.0];
/// let result = swish_simd(&x.view());
/// assert!(result[0].abs() < 1e-10);  // Swish(0) = 0
/// // Swish(1) ≈ 0.7311
/// assert!((result[1] - 0.7310585786).abs() < 1e-6);
/// // Swish(-1) ≈ -0.2689
/// assert!((result[2] - (-0.2689414214)).abs() < 1e-6);
/// ```
pub fn swish_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_swish(x);
    }
    F::simd_swish(x)
}
/// SIMD-accelerated Softplus activation function
///
/// Computes the Softplus activation function element-wise:
/// `Softplus(x) = ln(1 + exp(x))`
///
/// Softplus is a smooth approximation of ReLU and is commonly used in
/// probabilistic models, Bayesian deep learning, and smooth counting.
///
/// # Key Properties
///
/// - Softplus(0) = ln(2) ≈ 0.693
/// - Always positive (> 0 for all x)
/// - Derivative: softplus'(x) = sigmoid(x)
/// - Approaches ReLU for x → +∞: softplus(x) ≈ x
/// - Approaches 0 for x → -∞: softplus(x) ≈ exp(x) ≈ 0
///
/// # Usage
///
/// Softplus is used in:
/// - Probabilistic models (output layer for positive quantities)
/// - Bayesian deep learning
/// - Smooth counting applications
/// - As a smooth ReLU replacement
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::softplus_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![0.0f64, 1.0, -1.0];
/// let result = softplus_simd(&x.view());
/// // Softplus(0) = ln(2) ≈ 0.693
/// assert!((result[0] - 0.6931471805599453).abs() < 1e-10);
/// // Softplus(1) = ln(1 + e) ≈ 1.3133
/// assert!((result[1] - 1.3132616875182228).abs() < 1e-10);
/// // Softplus(-1) = ln(1 + 1/e) ≈ 0.3133
/// assert!((result[2] - 0.31326168751822286).abs() < 1e-10);
/// ```
pub fn softplus_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_softplus(x);
    }
    F::simd_softplus(x)
}
/// SIMD-accelerated Mish activation function
///
/// Computes the Mish activation function element-wise:
/// `Mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + exp(x)))`
///
/// Mish is a self-regularized non-monotonic activation function that combines
/// the benefits of ReLU, Swish, and other modern activations.
///
/// # Key Properties
///
/// - Mish(0) = 0
/// - Smooth and non-monotonic
/// - Self-regularizing (bounded negative region)
/// - Unbounded above, bounded below (minimum ≈ -0.31 at x ≈ -1.2)
/// - Derivative: complex but well-behaved
///
/// # Usage in Deep Learning
///
/// Mish is used in:
/// - YOLOv4 and YOLOv5 object detection
/// - Modern convolutional neural networks
/// - Image classification and segmentation tasks
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray_ext::elementwise::mish_simd;
/// use scirs2_core::ndarray::array;
///
/// let x = array![0.0f64, 1.0, -1.0];
/// let result = mish_simd(&x.view());
/// // Mish(0) = 0
/// assert!(result[0].abs() < 1e-10);
/// // Mish(1) = 1 * tanh(ln(1 + e)) ≈ 0.8651
/// assert!((result[1] - 0.8650983882673103).abs() < 1e-10);
/// ```
pub fn mish_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }
    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_mish(x);
    }
    F::simd_mish(x)
}