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
/*
    Appellation: sigmoid <mod>
    Contrib: FL03 <jo3mccain@icloud.com>
*/
use ndarray::*;
use num::complex::ComplexFloat;
use num::{Float, Zero};

pub fn relu<T>(args: &T) -> T
where
    T: Clone + PartialOrd + Zero,
{
    if args > &T::zero() {
        return args.clone();
    }
    T::zero()
}

pub fn sigmoid<T>(args: &T) -> T
where
    T: ComplexFloat,
{
    (T::one() + (*args).neg().exp()).recip()
}

pub fn softmax<T, D>(args: &Array<T, D>) -> Array<T, D>
where
    D: Dimension,
    T: Float,
{
    let denom = args.mapv(|x| x.exp()).sum();
    args.mapv(|x| x.exp() / denom)
}

pub fn softmax_axis<T, D>(args: &Array<T, D>, axis: Option<usize>) -> Array<T, D>
where
    D: Dimension + RemoveAxis,
    T: NdFloat,
{
    let exp = args.mapv(|x| x.exp());
    if let Some(axis) = axis {
        let denom = exp.sum_axis(Axis(axis));
        exp / denom
    } else {
        let denom = exp.sum();
        exp / denom
    }
}

pub fn tanh<T>(args: &T) -> T
where
    T: ComplexFloat,
{
    args.tanh()
}

build_unary_trait!(ReLU.relu, Sigmoid.sigmoid, Softmax.softmax, Tanh.tanh,);

/*
 ********** Implementations **********
*/
macro_rules! nonlinear {
    ($($rho:ident<$($T:ty),* $(,)?>::$call:ident),* $(,)? ) => {
        $(
            nonlinear!(@loop $rho<$($T),*>::$call);
        )*
    };
    (@loop $rho:ident<$($T:ty),* $(,)?>::$call:ident ) => {
        $(
            nonlinear!(@impl $rho<$T>::$call);
        )*

        nonlinear!(@arr $rho::$call);
    };
    (@impl $rho:ident<$T:ty>::$call:ident) => {
        impl $rho for $T {
            type Output = $T;

            fn $call(&self) -> Self::Output {
                $call(self)
            }
        }

        impl<'a> $rho for &'a $T {
            type Output = $T;

            fn $call(&self) -> Self::Output {
                $call(*self)
            }
        }

    };
    (@arr $name:ident::$call:ident) => {
        impl<A, S, D> $name for ArrayBase<S, D>
        where
            A: Clone + $name,
            D: Dimension,
            S: Data<Elem = A>
        {
            type Output = Array<<A as $name>::Output, D>;

            fn $call(&self) -> Self::Output {
                self.map($name::$call)
            }
        }
    };

}

nonlinear!(
    ReLU < f32,
    f64,
    i8,
    i16,
    i32,
    i64,
    i128,
    isize,
    u8,
    u16,
    u32,
    u64,
    u128,
    usize > ::relu,
    Sigmoid < f32,
    f64,
    num::Complex<f32>,
    num::Complex < f64 >> ::sigmoid,
    Tanh < f32,
    f64,
    num::Complex<f32>,
    num::Complex < f64 >> ::tanh,
);