dendritic_ndarray/ops/
unary.rs

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
use crate::ndarray::NDArray;


pub trait UnaryOps {
    fn transpose(self) -> Result<NDArray<f64>, String>;
    fn permute(self, indice_order: Vec<usize>) -> Result<NDArray<f64>, String>; 
    fn norm(&self, p: usize) -> Result<NDArray<f64>, String>;
    fn signum(&self) -> Result<NDArray<f64>, String>;
    fn sum_axis(&self, axis: usize) -> Result<NDArray<f64>, String>;
    fn select_axis(&self, axis: usize, indices: Vec<usize>) -> Result<NDArray<f64>, String>;
    fn apply(&self, loss_func: fn(value: f64) -> f64) -> Result<NDArray<f64>, String>;
    fn argmax(&self, axis: usize) -> NDArray<f64>;
    fn argmin(&self, axis: usize) -> Result<NDArray<f64>, String>;
    fn nonzero(&self) -> NDArray<f64>;
}


impl UnaryOps for NDArray<f64> {

    /// Tranpose current NDArray instance, works only on rank 2 values
    fn transpose(self) -> Result<NDArray<f64>, String> {

        if self.rank() != 2 {
            return Err("Transpose must contain on rank 2 values".to_string());
        }

        let mut index = 0;
        let mut result = NDArray::new(self.shape().reverse()).unwrap();

        for _item in self.values() {

            let indices = self.indices(index).unwrap();
            let mut reversed_indices = indices.clone();
            reversed_indices.reverse();

            let idx = self.index(indices).unwrap();
            let val = self.values()[idx]; 

            /* set value from reversed */ 
            let _ = result.set(reversed_indices ,val);
            index += 1; 
        }

        Ok(result)

    }

    /// Permute indices of NDArray. Can be used to peform transposes/contraction on rank 3 or higher values.
    fn permute(self, indice_order: Vec<usize>) -> Result<NDArray<f64>, String> {

        if indice_order.len() != self.rank() {
            return Err("Indice order must be same length as rank".to_string());
        }

        let mut index = 0;
        let permuted_shape = self.shape().permute(indice_order.clone());
        let mut result = NDArray::new(permuted_shape).unwrap();
        for _item in self.values() {

            let indices = self.indices(index).unwrap();
            let mut new_indice_order = Vec::new();
            for item in &indice_order {
                new_indice_order.push(indices[*item])
            }

            let idx = self.index(indices.clone()).unwrap();
            let val = self.values()[idx]; 

            /* set value from reversed */ 
            let _ = result.set(new_indice_order ,val);
            index += 1; 
        }

        Ok(result)
    }


    /// L2 norm can also be  x^t x
    fn norm(&self, p: usize) -> Result<NDArray<f64>, String> {

        let mut result = NDArray::new(self.shape().values()).unwrap();
        for index in 0..self.size() {
            let value = self.values()[index]; 
            let raised = value.powf(p as f64); 
            let _ = result.set_idx(index, raised);
        }
        Ok(result)
    }

    
    /// Adds values based on x < 0 < 1
    fn signum(&self) -> Result<NDArray<f64>, String> {

        let mut result = NDArray::new(self.shape().values()).unwrap();
        for index in 0..self.size() {
            let value = self.values()[index]; 
            if value < 0.0 {
                let _ = result.set_idx(index, -1.0);
            } else if value > 0.0 {
                let _ = result.set_idx(index, 1.0);
            } else { 
                let _ = result.set_idx(index, 0.0);
            }
        }

        Ok(result)
    }


    /// Sum values along a specified axis
    fn sum_axis(&self, axis: usize) -> Result<NDArray<f64>, String> {

        if axis > self.rank()-1 {
            return Err("Sum Axis: Axis greater than rank".to_string())
        }

        if self.rank() > 2 {
            return Err("Sum Axis: Not supported for rank 2 or higher values yet".to_string());
        }

        if axis == 0 {
            let mut result = NDArray::new(vec![1,1]).unwrap();
            let sum: f64 = self.values().iter().sum();
            let _ = result.set_idx(0, sum);
            return Ok(result);
        }


        let sum_stride = self.size() / self.shape().dim(axis);
        let axis_stride = self.shape().dim(axis.clone());
        let result_shape: Vec<usize> = vec![axis, axis_stride];
        let mut result = NDArray::new(result_shape.clone()).unwrap();

        let mut idx = 0; 
        let mut sum: f64 = 0.0; 
        let mut stride_counter = 0; 
        for item in self.values() {

            if stride_counter == sum_stride {
                let _ = result.set_idx(idx, sum);  
                stride_counter = 0;
                sum = 0.0;
                idx += 1;  
            }

            sum += item;
            stride_counter += 1;
        }

        let _ = result.set_idx(idx, sum); 
        Ok(result)
    }


    /// Select specific indices from an axis
    fn select_axis(&self, axis: usize, indices: Vec<usize>) -> Result<NDArray<f64>, String> {
 
        if axis > self.rank() - 1 { 
            return Err(
                "Axis Indices: Selected axis larger than rank".to_string()
            );
        }

        if self.rank() > 2 {
            return Err(
                "Select Axis: Only works on rank 2 values and lower".to_string()
            );

        }

        let mut curr_shape = self.shape().values(); 
        curr_shape[axis] = indices.len();

        let mut result: NDArray<f64> = NDArray::new(
            curr_shape.clone()
        ).unwrap();

        for (index, indice) in indices.iter().enumerate() {
            let axis_vals = self.axis(axis, *indice).unwrap();
            for (idx, val) in axis_vals.values().iter().enumerate() {
                let remainder_idx = self.rank() - 1 - axis;
                let mut indices: Vec<usize> = vec![0; self.rank()];
                indices[axis] = index; 
                indices[remainder_idx] = idx; 
                result.set(indices, *val).unwrap(); 
            }
        }

        Ok(result)
    }


    /// Apply loss function on values in ndarray
    fn apply(&self, loss_func: fn(value: f64) -> f64) -> Result<NDArray<f64>, String> {   
        let mut index = 0; 
        let mut result = NDArray::new(self.shape().values()).unwrap(); 
        for x in self.values() {
            let loss_val = loss_func(*x); 
            let _ = result.set_idx(index, loss_val);
            index += 1;  
        }
        Ok(result)
    }

    /// Get's the maximum values index along a specified axis
    fn argmax(&self, axis: usize) -> NDArray<f64> {

        // this only works for a row (for now)
        let mut results = Vec::new();
        let shape = self.shape().dim(axis);
        for idx in 0..shape {
            let axis_value = self.axis(axis, idx).unwrap();

            let mut curr_max = 0.0; 
            let mut index = 0; 
            let mut final_index = 0;
            for item in axis_value.values() {
                if item > &curr_max {
                    curr_max = *item;
                    final_index = index; 
                }
                index += 1;
            }

            results.push(final_index as f64);
        }

        let result = NDArray::array(
            vec![shape, 1],
            results
        ).unwrap();
        result

    }


    /// Get's the minimum values index along a specified axis
    fn argmin(&self, axis: usize) -> Result<NDArray<f64>, String> {

        if axis > self.rank() - 1 {
            let msg = "Argmin: Selected axis larger than rank";
            return Err(msg.to_string());
        }

        // this only works for a row (for now)
        let mut results: Vec<f64> = Vec::new();
        let shape = self.shape().dim(axis);
        for idx in 0..shape {
            let axis_value = self.axis(axis, idx).unwrap();
            let mut min_value = f64::INFINITY;
            let mut min_idx = 0;
            for (idx, val) in axis_value.values().iter().enumerate() {
                if *val < min_value {
                    min_value = *val; 
                    min_idx = idx;
                }
            }
            results.push(min_idx as f64);
        }

        Ok(NDArray::array(
            vec![shape, 1],
            results
        ).unwrap())

    }

    /// Retrieve all non zero elements in an ndarray
    fn nonzero(&self) -> NDArray<f64> {
        let mut vals: Vec<f64> = Vec::new();
        for item in self.values() {
            if *item != 0.0 {
                vals.push(*item);
            }
        }

        NDArray::array(vec![vals.len(), 1], vals).unwrap()
    }

}