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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
//! SIMD-accelerated preprocessing operations for array normalization and standardization
//!
//! This module provides high-performance implementations of common data preprocessing
//! operations that are critical for machine learning pipelines, statistical analysis,
//! and scientific computing.
//!
//! # Operations
//!
//! - **L2 Normalization** (`normalize_simd`): Converts vectors to unit length
//! - **Z-Score Standardization** (`standardize_simd`): Zero mean, unit variance
//! - **Value Clipping** (`clip_simd`): Bounds values to a specified range
//!
//! # Performance
//!
//! All operations automatically use SIMD acceleration when:
//! - Platform supports AVX2 (x86_64) or NEON (ARM)
//! - Array size is large enough to benefit from vectorization
//! - Array memory layout is contiguous
//!
//! Falls back to scalar implementations for small arrays or unsupported platforms.
//!
//! # Examples
//!
//! ```
//! use scirs2_core::ndarray::array;
//! use scirs2_core::ndarray_ext::preprocessing::{normalize_simd, standardize_simd, clip_simd};
//!
//! // L2 normalization - convert to unit vector
//! let x = array![3.0, 4.0];  // norm = 5
//! let normalized = normalize_simd(&x.view());
//! // Result: [0.6, 0.8]
//!
//! // Z-score standardization
//! let data = array![2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
//! let standardized = standardize_simd(&data.view());
//! // Result: mean ≈ 0, std ≈ 1
//!
//! // Value clipping
//! let values = array![-10.0, -5.0, 0.0, 5.0, 10.0];
//! let clipped = clip_simd(&values.view(), -3.0, 7.0);
//! // Result: [-3.0, -3.0, 0.0, 5.0, 7.0]
//! ```

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

/// Normalize a 1D array to unit length using L2 norm (SIMD-accelerated).
///
/// Computes x / ||x||₂ where ||x||₂ is the Euclidean (L2) norm.
/// The resulting vector will have unit length (norm = 1).
///
/// # Arguments
///
/// * `x` - Input 1D array to normalize
///
/// # Returns
///
/// `Array1<F>` with the same length as input, normalized to unit length.
/// Returns zero array if input norm is zero or NaN.
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Scalar**: Used for small arrays or when SIMD unavailable
/// - **Speedup**: 2-4x for large f32 arrays on AVX2 systems
///
/// # Mathematical Definition
///
/// ```text
/// normalize(x) = x / ||x||₂
/// where ||x||₂ = sqrt(Σ xᵢ²)
/// ```
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::normalize_simd;
///
/// // 3-4-5 triangle
/// let x = array![3.0_f64, 4.0];
/// let result = normalize_simd(&x.view());
///
/// // norm = sqrt(9 + 16) = 5
/// // result = [3/5, 4/5] = [0.6, 0.8]
/// assert!((result[0] - 0.6_f64).abs() < 1e-10);
/// assert!((result[1] - 0.8_f64).abs() < 1e-10);
///
/// // Verify unit norm
/// let norm: f64 = result.iter().map(|x| x * x).sum::<f64>().sqrt();
/// assert!((norm - 1.0_f64).abs() < 1e-10);
/// ```
///
/// # Edge Cases
///
/// - **Empty array**: Returns empty array
/// - **Zero vector**: Returns zero array (undefined normalization)
/// - **Single element**: Returns array with single element ±1
/// - **NaN values**: Returns zero array
///
/// # Applications
///
/// - **Machine Learning**: Feature scaling for algorithms sensitive to magnitude
/// - **Cosine Similarity**: Prerequisite for efficient similarity computation
/// - **Direction Vectors**: Unit direction vectors in physics/graphics
/// - **Text Processing**: TF-IDF normalization in NLP
/// - **Signal Processing**: Normalized cross-correlation
pub fn normalize_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_normalize(x);
    }

    // Scalar fallback for small arrays
    let norm = x
        .iter()
        .map(|&val| val * val)
        .fold(F::zero(), |acc, val| acc + val)
        .sqrt();

    if norm == F::zero() || norm.is_nan() {
        return Array1::zeros(x.len());
    }

    x.mapv(|val| val / norm)
}

/// Standardize a 1D array to zero mean and unit variance (SIMD-accelerated).
///
/// Computes (x - μ) / σ where μ is the mean and σ is the sample standard deviation.
/// The resulting array will have mean ≈ 0 and standard deviation ≈ 1.
///
/// # Arguments
///
/// * `x` - Input 1D array to standardize
///
/// # Returns
///
/// `Array1<F>` with the same length as input, standardized to zero mean and unit variance.
/// Returns zero array if input has <= 1 element or zero standard deviation.
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Scalar**: Used for small arrays or when SIMD unavailable
/// - **Speedup**: 2-4x for large f32 arrays on AVX2 systems
///
/// # Mathematical Definition
///
/// ```text
/// standardize(x) = (x - μ) / σ
/// where:
///   μ = (1/n) Σ xᵢ         (sample mean)
///   σ = sqrt((1/(n-1)) Σ (xᵢ - μ)²)  (sample std, ddof=1)
/// ```
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::standardize_simd;
///
/// let x = array![2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
/// let result = standardize_simd(&x.view());
///
/// // Verify mean ≈ 0
/// let mean: f64 = result.iter().sum::<f64>() / result.len() as f64;
/// assert!(mean.abs() < 1e-10);
///
/// // Verify std ≈ 1 (sample std with ddof=1)
/// let variance: f64 = result.iter()
///     .map(|&x| x * x)
///     .sum::<f64>() / (result.len() - 1) as f64;
/// let std = variance.sqrt();
/// assert!((std - 1.0).abs() < 1e-10);
/// ```
///
/// # Edge Cases
///
/// - **Empty array**: Returns empty array
/// - **Single element**: Returns zero array (std undefined for n=1)
/// - **Constant array**: Returns zero array (std = 0)
/// - **NaN values**: Returns zero array
///
/// # Applications
///
/// - **Machine Learning**: Feature preprocessing for models assuming normally distributed features
/// - **Statistical Analysis**: Z-score computation for outlier detection
/// - **Time Series**: Detrending and variance normalization
/// - **Data Science**: Preparing features for PCA, clustering, regression
/// - **Neural Networks**: Input normalization for faster convergence
///
/// # Implementation Notes
///
/// Uses **sample standard deviation** (ddof=1, Bessel's correction) rather than
/// population standard deviation (ddof=0). This is consistent with NumPy, SciPy,
/// and pandas default behavior.
pub fn standardize_simd<F>(x: &ArrayView1<F>) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Array1::zeros(0);
    }

    if x.len() <= 1 {
        return Array1::zeros(x.len());
    }

    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_standardize(x);
    }

    // Scalar fallback for small arrays
    let n = F::from(x.len()).expect("Operation failed");
    let mean = x.iter().fold(F::zero(), |acc, &val| acc + val) / n;

    let n_minus_1 = F::from(x.len() - 1).expect("Operation failed");
    let variance = x
        .iter()
        .map(|&val| {
            let diff = val - mean;
            diff * diff
        })
        .fold(F::zero(), |acc, val| acc + val)
        / n_minus_1;

    let std = variance.sqrt();

    if std == F::zero() || std.is_nan() {
        return Array1::zeros(x.len());
    }

    x.mapv(|val| (val - mean) / std)
}

/// Clip (clamp) array values to a specified range (SIMD-accelerated).
///
/// Constrains each element to be within [min_val, max_val]:
/// - Values < min_val are set to min_val
/// - Values > max_val are set to max_val
/// - Values within range are unchanged
///
/// # Arguments
///
/// * `x` - Input 1D array to clip
/// * `min_val` - Minimum allowed value
/// * `max_val` - Maximum allowed value
///
/// # Returns
///
/// `Array1<F>` with the same length as input, with values clipped to [min_val, max_val].
///
/// # Panics
///
/// Panics if `min_val > max_val`.
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Scalar**: Used for small arrays or when SIMD unavailable
/// - **Speedup**: 2-4x for large f32 arrays on AVX2 systems
///
/// # Mathematical Definition
///
/// ```text
/// clip(x, min, max) = {
///     min     if x < min
///     max     if x > max
///     x       otherwise
/// }
/// ```
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::clip_simd;
///
/// let x = array![-10.0, -5.0, 0.0, 5.0, 10.0];
/// let result = clip_simd(&x.view(), -3.0, 7.0);
///
/// // Values clipped to [-3.0, 7.0]
/// assert_eq!(result[0], -3.0);  // -10 -> -3
/// assert_eq!(result[1], -3.0);  // -5 -> -3
/// assert_eq!(result[2], 0.0);   // 0 unchanged
/// assert_eq!(result[3], 5.0);   // 5 unchanged
/// assert_eq!(result[4], 7.0);   // 10 -> 7
/// ```
///
/// # Edge Cases
///
/// - **Empty array**: Returns empty array
/// - **min_val == max_val**: All values set to that value
/// - **NaN values**: Behavior is platform-dependent (typically become min_val)
/// - **Infinite values**: Clipped to min/max as appropriate
///
/// # Applications
///
/// - **Gradient Clipping**: Prevent exploding gradients in neural network training
/// - **Outlier Handling**: Remove or bound extreme values in statistical analysis
/// - **Data Preprocessing**: Enforce valid ranges for features
/// - **Numerical Stability**: Prevent overflow/underflow in computations
/// - **Image Processing**: Clamp pixel values to valid ranges
/// - **Audio Processing**: Prevent clipping distortion
///
/// # Example: Gradient Clipping
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::clip_simd;
///
/// // Clip gradients to prevent exploding gradients
/// let gradients = array![10.5, -8.2, 0.3, 15.7, -12.1];
/// let clipped = clip_simd(&gradients.view(), -5.0, 5.0);
///
/// // All gradients now in [-5.0, 5.0]
/// assert_eq!(clipped[0], 5.0);   // 10.5 -> 5.0
/// assert_eq!(clipped[1], -5.0);  // -8.2 -> -5.0
/// assert_eq!(clipped[2], 0.3);   // unchanged
/// assert_eq!(clipped[3], 5.0);   // 15.7 -> 5.0
/// assert_eq!(clipped[4], -5.0);  // -12.1 -> -5.0
/// ```
pub fn clip_simd<F>(x: &ArrayView1<F>, min_val: F, max_val: F) -> Array1<F>
where
    F: Float + SimdUnifiedOps,
{
    assert!(min_val <= max_val, "min_val must be <= max_val");

    if x.is_empty() {
        return Array1::zeros(0);
    }

    let optimizer = AutoOptimizer::new();
    if optimizer.should_use_simd(x.len()) {
        return F::simd_clip(x, min_val, max_val);
    }

    // Scalar fallback for small arrays
    x.mapv(|val| {
        if val < min_val {
            min_val
        } else if val > max_val {
            max_val
        } else {
            val
        }
    })
}

/// Compute softmax activation function with SIMD acceleration (Phase 33).
///
/// The softmax function converts a vector of real numbers into a probability distribution
/// where all values are in (0, 1) and sum to 1. It is numerically stable using the
/// max-subtraction trick.
///
/// # Arguments
///
/// * `x` - Input 1D array
///
/// # Returns
///
/// `Array1<F>` containing the softmax probabilities, where:
/// - All values are in the range (0, 1)
/// - Sum of all values equals 1.0
/// - Empty input returns empty array
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Scalar**: Used for small arrays or when SIMD unavailable
/// - **Speedup**: 4-8x for large arrays on AVX2/NEON systems
/// - Uses newly implemented min_simd (Phase 29) and sum_simd (Phase 30)
///
/// # Mathematical Definition
///
/// ```text
/// softmax(x)ᵢ = exp(xᵢ - max(x)) / Σⱼ exp(xⱼ - max(x))
/// ```
///
/// The max-subtraction trick (xᵢ - max(x)) ensures numerical stability by preventing
/// overflow in the exponential function.
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::softmax_simd;
///
/// let x = array![1.0, 2.0, 3.0];
/// let result = softmax_simd(&x.view());
///
/// // Verify probabilities sum to 1
/// let sum: f64 = result.iter().sum();
/// assert!((sum - 1.0).abs() < 1e-10);
///
/// // Verify all values in (0, 1)
/// for &val in result.iter() {
///     assert!(val > 0.0 && val < 1.0);
/// }
/// ```
///
/// # Applications
///
/// - **Attention Mechanisms**: Compute attention weights in Transformers (PRIMARY USE CASE)
/// - **Multi-class Classification**: Convert logits to class probabilities
/// - **Neural Networks**: Final layer activation for multi-class problems
/// - **Reinforcement Learning**: Action probability distributions
/// - **Natural Language Processing**: Token probability distributions
///
/// # Numerical Stability
///
/// The implementation subtracts the maximum value before exponentiation to prevent
/// overflow. This is mathematically equivalent to the standard softmax but numerically
/// stable even for large input values.
///
/// # Example: Attention Weights
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::softmax_simd;
///
/// // Attention scores (before softmax)
/// let scores = array![2.0, 4.0, 1.0, 3.0];
/// let attention_weights = softmax_simd(&scores.view());
///
/// // Highest score (4.0) gets highest probability
/// let max_idx = attention_weights
///     .iter()
///     .enumerate()
///     .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("Operation failed"))
///     .map(|(idx, _)| idx)
///     .expect("Operation failed");
/// assert_eq!(max_idx, 1); // Index of score 4.0
///
/// // All weights sum to 1
/// let sum: f64 = attention_weights.iter().sum();
/// assert!((sum - 1.0).abs() < 1e-10);
/// ```
#[allow(dead_code)]
pub fn softmax_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()) {
        // SIMD fast path using Phase 29-30 operations
        // 1. Find max for numerical stability (Phase 29: max_simd)
        let max_val = F::simd_max_element(x);

        // 2. Subtract max and exponentiate (SIMD exp)
        let shifted = x.mapv(|val| val - max_val);
        let exp_vals = F::simd_exp(&shifted.view());

        // 3. Sum the exponents (Phase 30: sum_simd)
        let sum = F::simd_sum(&exp_vals.view());

        // 4. Normalize by dividing by sum (scalar multiplication with 1/sum)
        if sum > F::zero() {
            let inv_sum = F::one() / sum;
            F::simd_scalar_mul(&exp_vals.view(), inv_sum)
        } else {
            Array1::zeros(x.len())
        }
    } else {
        // Scalar fallback for small arrays
        // Find max for numerical stability
        let max_val = x.fold(F::neg_infinity(), |max, &val| max.max(val));

        // Subtract max and exponentiate
        let mut exp_vals = x.mapv(|val| (val - max_val).exp());

        // Sum the exponents
        let sum = exp_vals.iter().fold(F::zero(), |acc, &val| acc + val);

        // Normalize
        if sum > F::zero() {
            exp_vals.mapv_inplace(|val| val / sum);
        }

        exp_vals
    }
}

// ============================================================================
// Activation Functions (Phase 33.5)
// ============================================================================

/// Compute ReLU (Rectified Linear Unit) activation with SIMD acceleration.
///
/// ReLU is one of the most common activation functions in deep learning, defined as:
/// ReLU(x) = max(0, x)
///
/// # Arguments
///
/// * `x` - Input 1D array
///
/// # Returns
///
/// `Array1<F>` containing the ReLU activation output, where negative values are zeroed
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Scalar**: Used for small arrays or when SIMD unavailable
/// - **Speedup**: 3-5x for large arrays on AVX2/NEON systems
/// - Most common activation in CNNs, ResNets, and modern architectures
///
/// # Mathematical Definition
///
/// ```text
/// ReLU(x) = { x  if x > 0
///           { 0  if x ≤ 0
/// ```
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::relu_simd;
///
/// let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
/// let result = relu_simd(&x.view());
///
/// assert_eq!(result[0], 0.0); // -2.0 -> 0.0
/// assert_eq!(result[1], 0.0); // -1.0 -> 0.0
/// assert_eq!(result[2], 0.0); //  0.0 -> 0.0
/// assert_eq!(result[3], 1.0); //  1.0 -> 1.0
/// assert_eq!(result[4], 2.0); //  2.0 -> 2.0
/// ```
///
/// # Applications
///
/// - **Convolutional Neural Networks**: Primary activation in CNN layers
/// - **ResNet/DenseNet**: Core activation in residual blocks
/// - **Fully Connected Layers**: Standard activation for hidden layers
/// - **Feature Extraction**: Non-linear transformation in deep networks
/// - **Modern Architectures**: Default choice for most deep learning models
///
/// # Advantages of ReLU
///
/// - **Computational Efficiency**: Very fast to compute (simple max operation)
/// - **No Gradient Vanishing**: Gradients don't saturate for positive values
/// - **Sparse Activation**: Promotes sparsity (zeros out negative values)
/// - **SIMD-Friendly**: Perfect for vectorization
#[allow(dead_code)]
pub fn relu_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()) {
        F::simd_relu(x)
    } else {
        // Scalar fallback: max(0, x)
        x.mapv(|val| if val > F::zero() { val } else { F::zero() })
    }
}

/// Compute Leaky ReLU activation with SIMD acceleration.
///
/// Leaky ReLU is a variant of ReLU that allows small negative values:
/// LeakyReLU(x) = max(αx, x) where α is a small constant (typically 0.01)
///
/// # Arguments
///
/// * `x` - Input 1D array
/// * `alpha` - Negative slope coefficient (typically 0.01)
///
/// # Returns
///
/// `Array1<F>` containing the Leaky ReLU activation output
///
/// # Performance
///
/// - **SIMD**: Automatically used for large arrays (1000+ elements)
/// - **Speedup**: 3-5x for large arrays
///
/// # Mathematical Definition
///
/// ```text
/// LeakyReLU(x) = { x     if x > 0
///                { αx    if x ≤ 0
/// ```
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::preprocessing::leaky_relu_simd;
///
/// let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
/// let result = leaky_relu_simd(&x.view(), 0.01);
///
/// assert_eq!(result[0], -0.02); // -2.0 * 0.01
/// assert_eq!(result[1], -0.01); // -1.0 * 0.01
/// assert_eq!(result[2], 0.0);   //  0.0 * 0.01
/// assert_eq!(result[3], 1.0);   //  1.0 (unchanged)
/// assert_eq!(result[4], 2.0);   //  2.0 (unchanged)
/// ```
///
/// # Applications
///
/// - **Addressing Dying ReLU Problem**: Allows gradient flow for negative values
/// - **GANs**: Common in discriminator networks
/// - **ResNet Variants**: Alternative to standard ReLU
#[allow(dead_code)]
pub fn leaky_relu_simd<F>(x: &ArrayView1<F>, alpha: 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()) {
        F::simd_leaky_relu(x, alpha)
    } else {
        // Scalar fallback: max(alpha * x, x)
        x.mapv(|val| if val > F::zero() { val } else { val * alpha })
    }
}

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

    #[test]
    fn test_normalize_simd_basic_f64() {
        let x = array![3.0, 4.0];
        let result = normalize_simd(&x.view());

        // 3-4-5 triangle: norm = 5, so [0.6, 0.8]
        assert!((result[0] - 0.6).abs() < 1e-10);
        assert!((result[1] - 0.8).abs() < 1e-10);

        // Verify unit norm
        let norm: f64 = result.iter().map(|x| x * x).sum::<f64>().sqrt();
        assert!((norm - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_normalize_simd_basic_f32() {
        let x = array![3.0f32, 4.0];
        let result = normalize_simd(&x.view());

        assert!((result[0] - 0.6).abs() < 1e-6);
        assert!((result[1] - 0.8).abs() < 1e-6);

        // Verify unit norm
        let norm: f32 = result.iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_normalize_simd_empty() {
        let x: Array1<f64> = array![];
        let result = normalize_simd(&x.view());
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_normalize_simd_zero_vector() {
        let x = array![0.0, 0.0, 0.0];
        let result = normalize_simd(&x.view());

        // Zero norm should return zero array
        assert_eq!(result[0], 0.0);
        assert_eq!(result[1], 0.0);
        assert_eq!(result[2], 0.0);
    }

    #[test]
    fn test_standardize_simd_basic_f64() {
        let x = array![2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
        let result = standardize_simd(&x.view());

        // Verify mean ≈ 0
        let mean: f64 = result.iter().sum::<f64>() / result.len() as f64;
        assert!(mean.abs() < 1e-10, "Mean should be ~0, got {}", mean);

        // Verify std ≈ 1 (sample std with ddof=1)
        let variance: f64 = result.iter().map(|&x| x * x).sum::<f64>() / (result.len() - 1) as f64;
        let std = variance.sqrt();
        assert!((std - 1.0).abs() < 1e-10, "Std should be ~1, got {}", std);
    }

    #[test]
    fn test_standardize_simd_basic_f32() {
        let x = array![1.0f32, 2.0, 3.0, 4.0, 5.0];
        let result = standardize_simd(&x.view());

        // Verify mean ≈ 0
        let mean: f32 = result.iter().sum::<f32>() / result.len() as f32;
        assert!(mean.abs() < 1e-5, "Mean should be ~0, got {}", mean);

        // Verify std ≈ 1
        let variance: f32 = result.iter().map(|&x| x * x).sum::<f32>() / (result.len() - 1) as f32;
        let std = variance.sqrt();
        assert!((std - 1.0).abs() < 1e-5, "Std should be ~1, got {}", std);
    }

    #[test]
    fn test_standardize_simd_empty() {
        let x: Array1<f64> = array![];
        let result = standardize_simd(&x.view());
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_standardize_simd_single_element() {
        let x = array![5.0];
        let result = standardize_simd(&x.view());

        // Single element has undefined std, should return zero
        assert_eq!(result[0], 0.0);
    }

    #[test]
    fn test_standardize_simd_constant() {
        let x = array![5.0, 5.0, 5.0, 5.0];
        let result = standardize_simd(&x.view());

        // Constant array has zero std, should return zero array
        assert_eq!(result[0], 0.0);
        assert_eq!(result[1], 0.0);
        assert_eq!(result[2], 0.0);
        assert_eq!(result[3], 0.0);
    }

    // ========================================================================
    // Tests for Phase 33: softmax_simd
    // ========================================================================

    #[test]
    fn test_softmax_simd_f64_basic() {
        let x = array![1.0f64, 2.0, 3.0];
        let result = softmax_simd(&x.view());

        // Verify probabilities sum to 1
        let sum: f64 = result.iter().sum();
        assert!((sum - 1.0).abs() < 1e-10);

        // Verify all values in (0, 1)
        for &val in result.iter() {
            assert!(val > 0.0 && val < 1.0);
        }

        // Verify highest input gets highest probability
        let max_idx = result
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("Operation failed"))
            .map(|(idx, _)| idx)
            .expect("Operation failed");
        assert_eq!(max_idx, 2); // Index of value 3.0
    }

    #[test]
    fn test_softmax_simd_f32_basic() {
        let x = array![1.0f32, 2.0, 3.0, 4.0];
        let result = softmax_simd(&x.view());

        // Verify probabilities sum to 1
        let sum: f32 = result.iter().sum();
        assert!((sum - 1.0).abs() < 1e-6);

        // Verify all values in (0, 1)
        for &val in result.iter() {
            assert!(val > 0.0 && val < 1.0);
        }
    }

    #[test]
    fn test_softmax_simd_empty() {
        let x: Array1<f64> = array![];
        let result = softmax_simd(&x.view());
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_softmax_simd_single() {
        let x = array![42.0f64];
        let result = softmax_simd(&x.view());

        // Single element softmax should be 1.0
        assert!((result[0] - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_softmax_simd_uniform() {
        let x = array![2.0f64, 2.0, 2.0, 2.0];
        let result = softmax_simd(&x.view());

        // Uniform input should give uniform probabilities (0.25 each)
        for &val in result.iter() {
            assert!((val - 0.25).abs() < 1e-10);
        }

        let sum: f64 = result.iter().sum();
        assert!((sum - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_softmax_simd_large_values() {
        // Test numerical stability with large values
        let x = array![1000.0f64, 1001.0, 1002.0];
        let result = softmax_simd(&x.view());

        // Should not overflow
        assert!(!result.iter().any(|&v| v.is_infinite() || v.is_nan()));

        // Should still sum to 1
        let sum: f64 = result.iter().sum();
        assert!((sum - 1.0).abs() < 1e-10);

        // Highest value should get highest probability
        let max_idx = result
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("Operation failed"))
            .map(|(idx, _)| idx)
            .expect("Operation failed");
        assert_eq!(max_idx, 2);
    }

    #[test]
    fn test_softmax_simd_negative_values() {
        let x = array![-10.0f64, -5.0, -2.0, -8.0];
        let result = softmax_simd(&x.view());

        // Should sum to 1
        let sum: f64 = result.iter().sum();
        assert!((sum - 1.0).abs() < 1e-10);

        // Highest value (-2.0) should get highest probability
        let max_idx = result
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("Operation failed"))
            .map(|(idx, _)| idx)
            .expect("Operation failed");
        assert_eq!(max_idx, 2); // Index of -2.0
    }

    #[test]
    fn test_softmax_simd_attention_scores() {
        // Realistic attention scores scenario
        let scores = array![2.0f64, 4.0, 1.0, 3.0];
        let attention_weights = softmax_simd(&scores.view());

        // Verify it's a valid probability distribution
        let sum: f64 = attention_weights.iter().sum();
        assert!((sum - 1.0).abs() < 1e-10);

        // Highest score (4.0) should get highest weight
        let max_idx = attention_weights
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("Operation failed"))
            .map(|(idx, _)| idx)
            .expect("Operation failed");
        assert_eq!(max_idx, 1); // Index of score 4.0

        // Verify all weights are positive
        for &weight in attention_weights.iter() {
            assert!(weight > 0.0);
        }
    }

    #[test]
    fn test_softmax_simd_large_array() {
        // Test SIMD path with large array (>1000 elements)
        let x: Array1<f64> = Array1::from_vec((0..5000).map(|i| (i as f64) * 0.01).collect());
        let result = softmax_simd(&x.view());

        // Should sum to 1
        let sum: f64 = result.iter().sum();
        assert!((sum - 1.0).abs() < 1e-9);

        // All values should be positive
        assert!(result.iter().all(|&v| v > 0.0));

        // Highest input should give highest probability
        let max_idx = result
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("Operation failed"))
            .map(|(idx, _)| idx)
            .expect("Operation failed");
        assert_eq!(max_idx, 4999); // Last element has highest value
    }

    #[test]
    fn test_softmax_simd_temperature_scaling() {
        // Test temperature scaling (dividing logits by temperature)
        let logits = array![1.0f64, 2.0, 3.0];

        // High temperature (T=2.0) -> more uniform distribution
        let high_temp = softmax_simd(&logits.mapv(|x| x / 2.0).view());

        // Low temperature (T=0.5) -> more peaked distribution
        let low_temp = softmax_simd(&logits.mapv(|x| x * 2.0).view());

        // Both should sum to 1
        let sum_high: f64 = high_temp.iter().sum();
        let sum_low: f64 = low_temp.iter().sum();
        assert!((sum_high - 1.0).abs() < 1e-10);
        assert!((sum_low - 1.0).abs() < 1e-10);

        // Low temperature should have higher max probability (more peaked)
        let max_high = high_temp.iter().cloned().fold(0.0f64, f64::max);
        let max_low = low_temp.iter().cloned().fold(0.0f64, f64::max);
        assert!(max_low > max_high);
    }

    // ========================================================================
    // Tests for Phase 33.5: relu_simd and leaky_relu_simd
    // ========================================================================

    #[test]
    fn test_relu_simd_f64_basic() {
        let x = array![-2.0f64, -1.0, 0.0, 1.0, 2.0];
        let result = relu_simd(&x.view());

        assert_eq!(result[0], 0.0);
        assert_eq!(result[1], 0.0);
        assert_eq!(result[2], 0.0);
        assert_eq!(result[3], 1.0);
        assert_eq!(result[4], 2.0);
    }

    #[test]
    fn test_relu_simd_f32_basic() {
        let x = array![-2.0f32, -1.0, 0.0, 1.0, 2.0];
        let result = relu_simd(&x.view());

        assert_eq!(result[0], 0.0);
        assert_eq!(result[1], 0.0);
        assert_eq!(result[2], 0.0);
        assert_eq!(result[3], 1.0);
        assert_eq!(result[4], 2.0);
    }

    #[test]
    fn test_relu_simd_all_positive() {
        let x = array![1.0f64, 2.0, 3.0, 4.0, 5.0];
        let result = relu_simd(&x.view());

        // All values should remain unchanged
        for i in 0..5 {
            assert_eq!(result[i], x[i]);
        }
    }

    #[test]
    fn test_relu_simd_all_negative() {
        let x = array![-5.0f64, -4.0, -3.0, -2.0, -1.0];
        let result = relu_simd(&x.view());

        // All values should be zero
        for i in 0..5 {
            assert_eq!(result[i], 0.0);
        }
    }

    #[test]
    fn test_relu_simd_empty() {
        let x: Array1<f64> = array![];
        let result = relu_simd(&x.view());
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_relu_simd_large_array() {
        // Test SIMD path with large array (>1000 elements)
        let x: Array1<f64> = Array1::from_vec((0..5000).map(|i| (i as f64) - 2500.0).collect());
        let result = relu_simd(&x.view());

        // First 2500 should be zero (negative)
        for i in 0..2500 {
            assert_eq!(result[i], 0.0);
        }

        // Element at 2500 is exactly 0 (2500 - 2500 = 0)
        assert_eq!(result[2500], 0.0);

        // Last 2499 should be positive (2501-2500=1, ..., 4999-2500=2499)
        for i in 2501..5000 {
            assert!(result[i] > 0.0);
        }
    }

    #[test]
    fn test_leaky_relu_simd_f64_basic() {
        let x = array![-2.0f64, -1.0, 0.0, 1.0, 2.0];
        let result = leaky_relu_simd(&x.view(), 0.01);

        assert_eq!(result[0], -0.02);
        assert_eq!(result[1], -0.01);
        assert_eq!(result[2], 0.0);
        assert_eq!(result[3], 1.0);
        assert_eq!(result[4], 2.0);
    }

    #[test]
    fn test_leaky_relu_simd_f32_basic() {
        let x = array![-2.0f32, -1.0, 0.0, 1.0, 2.0];
        let result = leaky_relu_simd(&x.view(), 0.01);

        assert!((result[0] - (-0.02)).abs() < 1e-6);
        assert!((result[1] - (-0.01)).abs() < 1e-6);
        assert_eq!(result[2], 0.0);
        assert_eq!(result[3], 1.0);
        assert_eq!(result[4], 2.0);
    }

    #[test]
    fn test_leaky_relu_simd_different_alpha() {
        let x = array![-10.0f64, -5.0, 0.0, 5.0, 10.0];

        // Test with alpha = 0.1
        let result_01 = leaky_relu_simd(&x.view(), 0.1);
        assert_eq!(result_01[0], -1.0); // -10.0 * 0.1
        assert_eq!(result_01[1], -0.5); // -5.0 * 0.1

        // Test with alpha = 0.2
        let result_02 = leaky_relu_simd(&x.view(), 0.2);
        assert_eq!(result_02[0], -2.0); // -10.0 * 0.2
        assert_eq!(result_02[1], -1.0); // -5.0 * 0.2
    }

    #[test]
    fn test_leaky_relu_simd_preserves_positive() {
        let x = array![1.0f64, 2.0, 3.0, 4.0, 5.0];
        let result = leaky_relu_simd(&x.view(), 0.01);

        // All positive values should remain unchanged
        for i in 0..5 {
            assert_eq!(result[i], x[i]);
        }
    }

    #[test]
    fn test_leaky_relu_simd_empty() {
        let x: Array1<f64> = array![];
        let result = leaky_relu_simd(&x.view(), 0.01);
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_relu_vs_leaky_relu() {
        let x = array![-2.0f64, -1.0, 0.0, 1.0, 2.0];

        let relu_result = relu_simd(&x.view());
        let leaky_result = leaky_relu_simd(&x.view(), 0.01);

        // Positive values should be the same
        assert_eq!(relu_result[3], leaky_result[3]);
        assert_eq!(relu_result[4], leaky_result[4]);

        // Negative values should differ
        assert!(relu_result[0] != leaky_result[0]);
        assert!(relu_result[1] != leaky_result[1]);

        // ReLU zeros negatives, Leaky ReLU scales them
        assert_eq!(relu_result[0], 0.0);
        assert_eq!(leaky_result[0], -0.02);
    }
}