numrs2 0.3.1

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
//! Activation functions for neural networks
//!
//! This module provides common activation functions optimized with SIMD operations.
//! All functions follow the SCIRS2 integration policy and use scirs2_core abstractions.
//!
//! # Mathematical Formulas
//!
//! - **ReLU**: `f(x) = max(0, x)`
//! - **GELU**: `f(x) = x * Φ(x)` where Φ is the cumulative distribution function of the standard normal
//! - **Swish/SiLU**: `f(x) = x * sigmoid(x)`
//! - **Mish**: `f(x) = x * tanh(softplus(x))`
//! - **ELU**: `f(x) = x if x > 0 else α(exp(x) - 1)`
//! - **SELU**: `f(x) = λ * (x if x > 0 else α(exp(x) - 1))`
//! - **Leaky ReLU**: `f(x) = x if x > 0 else α * x`
//! - **Softmax**: `f(x)_i = exp(x_i) / Σ exp(x_j)`

use super::NnResult;
use crate::error::NumRs2Error;
use scirs2_core::ndarray::{
    s, Array, Array1, Array2, ArrayView, ArrayView1, ArrayView2, Axis, ScalarOperand, Zip,
};
use scirs2_core::numeric::Float;
use scirs2_core::simd_ops::SimdUnifiedOps;

/// ReLU (Rectified Linear Unit) activation function
///
/// Computes `f(x) = max(0, x)` element-wise.
///
/// # Arguments
///
/// * `x` - Input array
///
/// # Returns
///
/// Array with ReLU applied element-wise
///
/// # Example
///
/// ```rust,ignore
/// use numrs2::nn::activation::relu;
/// use scirs2_core::ndarray::array;
///
/// let x = array![-1.0, 0.0, 1.0, 2.0];
/// let y = relu(&x.view()).unwrap();
/// // y = [0.0, 0.0, 1.0, 2.0]
/// ```
pub fn relu<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    let zero = T::zero();
    Ok(x.mapv(|v| if v > zero { v } else { zero }))
}

/// ReLU activation for 2D arrays (in-place along last axis)
pub fn relu_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    let zero = T::zero();
    Ok(x.mapv(|v| if v > zero { v } else { zero }))
}

/// In-place ReLU activation
pub fn relu_inplace<T>(x: &mut Array1<T>)
where
    T: Float + SimdUnifiedOps,
{
    let zero = T::zero();
    x.mapv_inplace(|v| if v > zero { v } else { zero });
}

/// Leaky ReLU activation function
///
/// Computes `f(x) = x if x > 0 else α * x` element-wise.
///
/// # Arguments
///
/// * `x` - Input array
/// * `alpha` - Negative slope coefficient (typically 0.01)
///
/// # Returns
///
/// Array with Leaky ReLU applied
pub fn leaky_relu<T>(x: &ArrayView1<T>, alpha: T) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    if alpha < T::zero() {
        return Err(NumRs2Error::InvalidOperation(
            "Leaky ReLU alpha must be non-negative".to_string(),
        ));
    }

    let zero = T::zero();
    Ok(x.mapv(|v| if v > zero { v } else { alpha * v }))
}

/// Leaky ReLU for 2D arrays
pub fn leaky_relu_2d<T>(x: &ArrayView2<T>, alpha: T) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    if alpha < T::zero() {
        return Err(NumRs2Error::InvalidOperation(
            "Leaky ReLU alpha must be non-negative".to_string(),
        ));
    }

    let zero = T::zero();
    Ok(x.mapv(|v| if v > zero { v } else { alpha * v }))
}

/// ELU (Exponential Linear Unit) activation function
///
/// Computes `f(x) = x if x > 0 else α(exp(x) - 1)` element-wise.
///
/// # Arguments
///
/// * `x` - Input array
/// * `alpha` - Scale for negative values (typically 1.0)
pub fn elu<T>(x: &ArrayView1<T>, alpha: T) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    if alpha <= T::zero() {
        return Err(NumRs2Error::InvalidOperation(
            "ELU alpha must be positive".to_string(),
        ));
    }

    let zero = T::zero();
    let one = T::one();
    Ok(x.mapv(|v| if v > zero { v } else { alpha * (v.exp() - one) }))
}

/// ELU for 2D arrays
pub fn elu_2d<T>(x: &ArrayView2<T>, alpha: T) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    if alpha <= T::zero() {
        return Err(NumRs2Error::InvalidOperation(
            "ELU alpha must be positive".to_string(),
        ));
    }

    let zero = T::zero();
    let one = T::one();
    Ok(x.mapv(|v| if v > zero { v } else { alpha * (v.exp() - one) }))
}

/// SELU (Scaled Exponential Linear Unit) activation function
///
/// Computes `f(x) = λ * (x if x > 0 else α(exp(x) - 1))` with specific constants
/// that ensure self-normalizing properties.
///
/// # Arguments
///
/// * `x` - Input array
pub fn selu<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    // SELU constants for self-normalizing properties
    let lambda = T::from(1.0507009873554804934193349852946).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert SELU lambda constant".to_string())
    })?;
    let alpha = T::from(1.6732632423543772848170429916717).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert SELU alpha constant".to_string())
    })?;

    let zero = T::zero();
    let one = T::one();
    Ok(x.mapv(|v| {
        if v > zero {
            lambda * v
        } else {
            lambda * alpha * (v.exp() - one)
        }
    }))
}

/// SELU for 2D arrays
pub fn selu_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    let lambda = T::from(1.0507009873554804934193349852946).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert SELU lambda constant".to_string())
    })?;
    let alpha = T::from(1.6732632423543772848170429916717).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert SELU alpha constant".to_string())
    })?;

    let zero = T::zero();
    let one = T::one();
    Ok(x.mapv(|v| {
        if v > zero {
            lambda * v
        } else {
            lambda * alpha * (v.exp() - one)
        }
    }))
}

/// Sigmoid activation function
///
/// Computes `f(x) = 1 / (1 + exp(-x))` element-wise.
///
/// # Arguments
///
/// * `x` - Input array
pub fn sigmoid<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    Ok(x.mapv(|v| one / (one + (-v).exp())))
}

/// Sigmoid for 2D arrays
pub fn sigmoid_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    Ok(x.mapv(|v| one / (one + (-v).exp())))
}

/// Hyperbolic tangent activation function
///
/// Computes `f(x) = tanh(x)` element-wise.
pub fn tanh<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    Ok(x.mapv(|v| v.tanh()))
}

/// Tanh for 2D arrays
pub fn tanh_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    Ok(x.mapv(|v| v.tanh()))
}

/// Swish/SiLU activation function
///
/// Computes `f(x) = x * sigmoid(x)` element-wise.
/// Also known as Sigmoid Linear Unit (SiLU).
///
/// # Arguments
///
/// * `x` - Input array
pub fn swish<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    Ok(x.mapv(|v| v / (one + (-v).exp())))
}

/// Swish for 2D arrays
pub fn swish_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    Ok(x.mapv(|v| v / (one + (-v).exp())))
}

/// SiLU (Sigmoid Linear Unit) - alias for Swish
pub fn silu<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    swish(x)
}

/// SiLU for 2D arrays
pub fn silu_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    swish_2d(x)
}

/// Mish activation function
///
/// Computes `f(x) = x * tanh(softplus(x))` where `softplus(x) = ln(1 + exp(x))`.
///
/// # Arguments
///
/// * `x` - Input array
pub fn mish<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    Ok(x.mapv(|v| {
        let softplus = (one + v.exp()).ln();
        v * softplus.tanh()
    }))
}

/// Mish for 2D arrays
pub fn mish_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    Ok(x.mapv(|v| {
        let softplus = (one + v.exp()).ln();
        v * softplus.tanh()
    }))
}

/// GELU (Gaussian Error Linear Unit) activation function
///
/// Computes an approximation of `f(x) = x * Φ(x)` where Φ is the cumulative
/// distribution function of the standard normal distribution.
///
/// Uses the approximation: `f(x) ≈ 0.5 * x * (1 + tanh(√(2/π) * (x + 0.044715 * x³)))`
///
/// # Arguments
///
/// * `x` - Input array
pub fn gelu<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    let half = T::from(0.5)
        .ok_or_else(|| NumRs2Error::InvalidOperation("Failed to convert 0.5".to_string()))?;
    let one = T::one();
    let coeff = T::from(0.7978845608028654).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert GELU coefficient".to_string())
    })?; // sqrt(2/pi)
    let cubic_coeff = T::from(0.044715).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert GELU cubic coefficient".to_string())
    })?;

    Ok(x.mapv(|v| {
        let three = T::from(3.0).unwrap_or(one + one + one);
        let cubic = v.powi(3);
        let inner = coeff * (v + cubic_coeff * cubic);
        half * v * (one + inner.tanh())
    }))
}

/// GELU for 2D arrays
pub fn gelu_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    let half = T::from(0.5)
        .ok_or_else(|| NumRs2Error::InvalidOperation("Failed to convert 0.5".to_string()))?;
    let one = T::one();
    let coeff = T::from(0.7978845608028654).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert GELU coefficient".to_string())
    })?;
    let cubic_coeff = T::from(0.044715).ok_or_else(|| {
        NumRs2Error::InvalidOperation("Failed to convert GELU cubic coefficient".to_string())
    })?;

    Ok(x.mapv(|v| {
        let three = T::from(3.0).unwrap_or(one + one + one);
        let cubic = v.powi(3);
        let inner = coeff * (v + cubic_coeff * cubic);
        half * v * (one + inner.tanh())
    }))
}

/// Softmax activation function
///
/// Computes `f(x)_i = exp(x_i) / Σ exp(x_j)` with numerical stability.
///
/// # Arguments
///
/// * `x` - Input array
///
/// # Returns
///
/// Probability distribution over input elements
pub fn softmax<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps + ScalarOperand,
{
    if x.is_empty() {
        return Err(NumRs2Error::DimensionMismatch(
            "Softmax requires non-empty input".to_string(),
        ));
    }

    // Numerical stability: subtract max value
    let max_val = x.fold(T::neg_infinity(), |acc, &v| if v > acc { v } else { acc });

    if !max_val.is_finite() {
        return Err(NumRs2Error::InvalidOperation(
            "Softmax input contains non-finite values".to_string(),
        ));
    }

    let shifted = x.mapv(|v| (v - max_val).exp());
    let sum = shifted.sum();

    if sum == T::zero() || !sum.is_finite() {
        return Err(NumRs2Error::InvalidOperation(
            "Softmax normalization failed (sum is zero or non-finite)".to_string(),
        ));
    }

    Ok(shifted / sum)
}

/// Softmax for 2D arrays (along specified axis)
///
/// # Arguments
///
/// * `x` - Input array
/// * `axis` - Axis along which to apply softmax (typically last axis)
pub fn softmax_2d<T>(x: &ArrayView2<T>, axis: usize) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps + ScalarOperand,
{
    if x.is_empty() {
        return Err(NumRs2Error::DimensionMismatch(
            "Softmax requires non-empty input".to_string(),
        ));
    }

    if axis >= 2 {
        return Err(NumRs2Error::InvalidOperation(format!(
            "Invalid axis {} for 2D array",
            axis
        )));
    }

    let mut result = Array2::zeros(x.raw_dim());

    if axis == 1 {
        // Apply softmax along rows
        for (i, row) in x.axis_iter(Axis(0)).enumerate() {
            let softmax_row = softmax(&row)?;
            result.row_mut(i).assign(&softmax_row);
        }
    } else {
        // Apply softmax along columns
        for (j, col) in x.axis_iter(Axis(1)).enumerate() {
            let softmax_col = softmax(&col)?;
            result.column_mut(j).assign(&softmax_col);
        }
    }

    Ok(result)
}

/// Log-softmax activation function
///
/// Computes `f(x)_i = log(exp(x_i) / Σ exp(x_j))` with numerical stability.
/// More numerically stable than computing log(softmax(x)).
///
/// # Arguments
///
/// * `x` - Input array
pub fn log_softmax<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    if x.is_empty() {
        return Err(NumRs2Error::DimensionMismatch(
            "Log-softmax requires non-empty input".to_string(),
        ));
    }

    // Numerical stability: subtract max value
    let max_val = x.fold(T::neg_infinity(), |acc, &v| if v > acc { v } else { acc });

    if !max_val.is_finite() {
        return Err(NumRs2Error::InvalidOperation(
            "Log-softmax input contains non-finite values".to_string(),
        ));
    }

    let shifted = x.mapv(|v| v - max_val);
    let log_sum_exp = shifted.mapv(|v| v.exp()).sum().ln();

    if !log_sum_exp.is_finite() {
        return Err(NumRs2Error::InvalidOperation(
            "Log-softmax computation failed (non-finite log_sum_exp)".to_string(),
        ));
    }

    Ok(shifted.mapv(|v| v - log_sum_exp))
}

/// Log-softmax for 2D arrays (along specified axis)
pub fn log_softmax_2d<T>(x: &ArrayView2<T>, axis: usize) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps + ScalarOperand,
{
    if x.is_empty() {
        return Err(NumRs2Error::DimensionMismatch(
            "Log-softmax requires non-empty input".to_string(),
        ));
    }

    if axis >= 2 {
        return Err(NumRs2Error::InvalidOperation(format!(
            "Invalid axis {} for 2D array",
            axis
        )));
    }

    let mut result = Array2::zeros(x.raw_dim());

    if axis == 1 {
        for (i, row) in x.axis_iter(Axis(0)).enumerate() {
            let log_softmax_row = log_softmax(&row)?;
            result.row_mut(i).assign(&log_softmax_row);
        }
    } else {
        for (j, col) in x.axis_iter(Axis(1)).enumerate() {
            let log_softmax_col = log_softmax(&col)?;
            result.column_mut(j).assign(&log_softmax_col);
        }
    }

    Ok(result)
}

/// Softplus activation function
///
/// Computes `f(x) = ln(1 + exp(x))` element-wise with numerical stability.
///
/// # Arguments
///
/// * `x` - Input array
pub fn softplus<T>(x: &ArrayView1<T>) -> NnResult<Array1<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    let threshold = T::from(20.0)
        .ok_or_else(|| NumRs2Error::InvalidOperation("Failed to convert threshold".to_string()))?;

    // For numerical stability, use x directly when x > threshold
    Ok(x.mapv(|v| {
        if v > threshold {
            v
        } else {
            (one + v.exp()).ln()
        }
    }))
}

/// Softplus for 2D arrays
pub fn softplus_2d<T>(x: &ArrayView2<T>) -> NnResult<Array2<T>>
where
    T: Float + SimdUnifiedOps,
{
    let one = T::one();
    let threshold = T::from(20.0)
        .ok_or_else(|| NumRs2Error::InvalidOperation("Failed to convert threshold".to_string()))?;

    Ok(x.mapv(|v| {
        if v > threshold {
            v
        } else {
            (one + v.exp()).ln()
        }
    }))
}

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

    #[test]
    fn test_relu() {
        let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
        let y = relu(&x.view()).unwrap();
        assert_abs_diff_eq!(y[0], 0.0, epsilon = 1e-6);
        assert_abs_diff_eq!(y[1], 0.0, epsilon = 1e-6);
        assert_abs_diff_eq!(y[2], 0.0, epsilon = 1e-6);
        assert_abs_diff_eq!(y[3], 1.0, epsilon = 1e-6);
        assert_abs_diff_eq!(y[4], 2.0, epsilon = 1e-6);
    }

    #[test]
    fn test_sigmoid() {
        let x = array![0.0];
        let y = sigmoid(&x.view()).unwrap();
        assert_abs_diff_eq!(y[0], 0.5, epsilon = 1e-6);
    }

    #[test]
    fn test_softmax() {
        let x = array![1.0, 2.0, 3.0];
        let y = softmax(&x.view()).unwrap();

        // Sum should be 1.0
        let sum: f64 = y.sum();
        assert_abs_diff_eq!(sum, 1.0, epsilon = 1e-6);

        // Values should be positive
        assert!(y.iter().all(|&v| v > 0.0));
    }

    #[test]
    fn test_softmax_numerical_stability() {
        // Large values that would overflow exp
        let x = array![1000.0, 1001.0, 1002.0];
        let y = softmax(&x.view()).unwrap();

        // Should not contain NaN or Inf
        assert!(y.iter().all(|&v| v.is_finite()));

        // Sum should still be 1.0
        let sum: f64 = y.sum();
        assert_abs_diff_eq!(sum, 1.0, epsilon = 1e-6);
    }

    #[test]
    fn test_gelu() {
        let x = array![0.0];
        let y = gelu(&x.view()).unwrap();
        // GELU(0) ≈ 0
        assert_abs_diff_eq!(y[0], 0.0, epsilon = 1e-6);
    }

    #[test]
    fn test_swish() {
        let x = array![0.0];
        let y = swish(&x.view()).unwrap();
        // Swish(0) = 0
        assert_abs_diff_eq!(y[0], 0.0, epsilon = 1e-6);
    }
}