rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
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
//! Reduction and statistical operations for tensors
//! テンソルのリダクション・統計演算
//!
//! This module provides reduction operations that aggregate tensor values along
//! specified dimensions or across the entire tensor.
//! このモジュールは指定次元または全テンソルにわたってテンソル値を集約するリダクション操作を提供します。

use crate::tensor::Tensor;
use num_traits::Float;

impl<T: Float + 'static + ndarray::ScalarOperand + num_traits::FromPrimitive> Tensor<T> {
    /// Sum all elements in the tensor
    /// テンソル内の全要素の合計
    pub fn sum(&self) -> T {
        self.as_array().sum()
    }

    /// Calculate mean of all elements
    /// 全要素の平均を計算
    pub fn mean(&self) -> T {
        let sum = self.sum();
        let count = T::from(self.numel()).unwrap_or(T::one());
        sum / count
    }

    /// Get tensor as a scalar value (tensor must have exactly one element)
    /// テンソルをスカラー値として取得(テンソルは正確に1つの要素を持つ必要がある)
    pub fn item(&self) -> T {
        if self.numel() != 1 {
            panic!("Tensor must have exactly one element to use item(), but has {}", self.numel());
        }
        
        if let Some(slice) = self.as_slice() {
            slice[0]
        } else {
            // Handle non-contiguous tensor
            *self.data.iter().next().unwrap()
        }
    }

    /// Sum along specified axis
    /// 指定軸に沿って合計
    pub fn sum_axis(&self, axis: usize) -> Result<Self, String> {
        if axis >= self.ndim() {
            return Err(format!("Axis {} is out of bounds for tensor with {} dimensions", axis, self.ndim()));
        }
        
        let result = self.data.sum_axis(ndarray::Axis(axis));
        Ok(Tensor::new(result))
    }

    /// Mean along specified axis
    /// 指定軸に沿って平均
    pub fn mean_axis(&self, axis: usize) -> Result<Self, String> {
        if axis >= self.ndim() {
            return Err(format!("Axis {} is out of bounds for tensor with {} dimensions", axis, self.ndim()));
        }
        
        let result = self.data.mean_axis(ndarray::Axis(axis));
        match result {
            Some(mean_array) => Ok(Tensor::new(mean_array)),
            None => Err("Mean calculation failed (empty tensor along axis)".to_string())
        }
    }

    /// Find maximum value in tensor
    /// テンソル内の最大値を検索
    pub fn max(&self) -> Option<T> {
        self.data.iter()
            .max_by(|&&a, &&b| a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal))
            .copied()
    }

    /// Find minimum value in tensor
    /// テンソル内の最小値を検索
    pub fn min(&self) -> Option<T> {
        self.data.iter()
            .min_by(|&&a, &&b| a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal))
            .copied()
    }

    /// Find maximum value along specified axis
    /// 指定軸に沿って最大値を検索
    pub fn max_axis(&self, axis: usize) -> Result<Self, String> {
        if axis >= self.ndim() {
            return Err(format!("Axis {} is out of bounds for tensor with {} dimensions", axis, self.ndim()));
        }
        
        // Manual implementation since ndarray doesn't have max_axis
        let shape = self.shape();
        let mut new_shape = shape.to_vec();
        new_shape.remove(axis);
        
        if new_shape.is_empty() {
            // Reducing to scalar
            let max_val = self.max().unwrap_or(T::zero());
            return Ok(Tensor::from_vec(vec![max_val], vec![]));
        }
        
        let new_size: usize = new_shape.iter().product();
        let mut result_data = Vec::with_capacity(new_size);
        
        // This is a simplified implementation
        // In practice, you'd want more efficient axis-specific reduction
        let axis_size = shape[axis];
        let stride_before: usize = shape[..axis].iter().product();
        let stride_after: usize = shape[axis+1..].iter().product();
        
        for i in 0..stride_before {
            for k in 0..stride_after {
                let mut max_val: Option<T> = None;
                for j in 0..axis_size {
                    let idx = i * (axis_size * stride_after) + j * stride_after + k;
                    if let Some(slice) = self.as_slice() {
                        if idx < slice.len() {
                            match max_val {
                                None => max_val = Some(slice[idx]),
                                Some(current) => {
                                    if slice[idx] > current {
                                        max_val = Some(slice[idx]);
                                    }
                                }
                            }
                        }
                    }
                }
                    result_data.push(val);
                } else {
                    result_data.push(T::zero()); // Default value if no data found
                }
        }
        
        Ok(Tensor::from_vec(result_data, new_shape))
    }

    /// Find minimum value along specified axis
    /// 指定軸に沿って最小値を検索
    pub fn min_axis(&self, axis: usize) -> Result<Self, String> {
        if axis >= self.ndim() {
            return Err(format!("Axis {} is out of bounds for tensor with {} dimensions", axis, self.ndim()));
        }
        
        let shape = self.shape();
        let mut new_shape = shape.to_vec();
        new_shape.remove(axis);
        
        if new_shape.is_empty() {
            // Reducing to scalar
            let min_val = self.min().unwrap_or(T::zero());
            return Ok(Tensor::from_vec(vec![min_val], vec![]));
        }
        
        let new_size: usize = new_shape.iter().product();
        let mut result_data = Vec::with_capacity(new_size);
        
        let axis_size = shape[axis];
        let stride_before: usize = shape[..axis].iter().product();
        let stride_after: usize = shape[axis+1..].iter().product();
        
        for i in 0..stride_before {
            for k in 0..stride_after {
                let mut min_val = T::infinity();
                for j in 0..axis_size {
                    let idx = i * (axis_size * stride_after) + j * stride_after + k;
                    if let Some(slice) = self.as_slice() {
                        if idx < slice.len() {
                            min_val = min_val.min(slice[idx]);
                        }
                    }
                }
                result_data.push(min_val);
            }
        }
        
        Ok(Tensor::from_vec(result_data, new_shape))
    }

    /// Calculate variance of all elements
    /// 全要素の分散を計算
    pub fn var(&self) -> T {
        let mean = self.mean();
        let sum_squared_diff = self.data.iter()
            .map(|&x| (x - mean) * (x - mean))
            .fold(T::zero(), |acc, x| acc + x);
        
        let count = T::from(self.numel()).unwrap_or(T::one());
        sum_squared_diff / count
    }

    /// Calculate standard deviation of all elements
    /// 全要素の標準偏差を計算
    pub fn std(&self) -> T {
        self.var().sqrt()
    }

    /// Calculate variance along specified axis
    /// 指定軸に沿って分散を計算
    pub fn var_axis(&self, axis: usize) -> Result<Self, String> {
        if axis >= self.ndim() {
            return Err(format!("Axis {} is out of bounds for tensor with {} dimensions", axis, self.ndim()));
        }
        
        let mean_tensor = self.mean_axis(axis)?;
        
        // Calculate squared differences
        let shape = self.shape();
        let axis_size = shape[axis];
        let mut new_shape = shape.to_vec();
        new_shape.remove(axis);
        
        let new_size: usize = new_shape.iter().product();
        let mut var_data = vec![T::zero(); new_size];
        
        let stride_before: usize = shape[..axis].iter().product();
        let stride_after: usize = shape[axis+1..].iter().product();
        let mean_data = mean_tensor.as_slice().unwrap();
        let tensor_data = self.as_slice().unwrap();
        
        for i in 0..stride_before {
            for k in 0..stride_after {
                let mean_idx = i * stride_after + k;
                let mean_val = mean_data[mean_idx];
                let mut sum_sq_diff = T::zero();
                
                for j in 0..axis_size {
                    let tensor_idx = i * (axis_size * stride_after) + j * stride_after + k;
                    let diff = tensor_data[tensor_idx] - mean_val;
                    sum_sq_diff = sum_sq_diff + diff * diff;
                }
                
                var_data[mean_idx] = sum_sq_diff / T::from(axis_size).unwrap();
            }
        }
        
        Ok(Tensor::from_vec(var_data, new_shape))
    }

    /// Calculate standard deviation along specified axis
    /// 指定軸に沿って標準偏差を計算
    pub fn std_axis(&self, axis: usize) -> Result<Self, String> {
        let var_tensor = self.var_axis(axis)?;
        let std_data: Vec<T> = var_tensor.data.iter().map(|&x| x.sqrt()).collect();
        Ok(Tensor::from_vec(std_data, var_tensor.shape().to_vec()))
    }

    /// Count non-zero elements
    /// 非ゼロ要素をカウント
    pub fn count_nonzero(&self) -> usize {
        self.data.iter()
            .filter(|&&x| x != T::zero())
            .count()
    }

    /// Count non-zero elements along specified axis
    /// 指定軸に沿って非ゼロ要素をカウント
    pub fn count_nonzero_axis(&self, axis: usize) -> Result<Tensor<T>, String> {
        if axis >= self.ndim() {
            return Err(format!("Axis {} is out of bounds for tensor with {} dimensions", axis, self.ndim()));
        }
        
        let shape = self.shape();
        let mut new_shape = shape.to_vec();
        new_shape.remove(axis);
        
        let new_size: usize = new_shape.iter().product();
        let mut count_data = vec![T::zero(); new_size];
        
        let axis_size = shape[axis];
        let stride_before: usize = shape[..axis].iter().product();
        let stride_after: usize = shape[axis+1..].iter().product();
        let tensor_data = self.as_slice().unwrap();
        
        for i in 0..stride_before {
            for k in 0..stride_after {
                let count_idx = i * stride_after + k;
                let mut count = 0;
                
                for j in 0..axis_size {
                    let tensor_idx = i * (axis_size * stride_after) + j * stride_after + k;
                    if tensor_data[tensor_idx] != T::zero() {
                        count += 1;
                    }
                }
                
                count_data[count_idx] = T::from(count).unwrap_or(T::zero());
            }
        }
        
        Ok(Tensor::from_vec(count_data, new_shape))
    }
}

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

    #[test]
    fn test_sum() {
        let tensor = Tensor::from_vec(vec![1.0f32, 2.0, 3.0, 4.0], vec![4]);
        assert_eq!(tensor.sum(), 10.0);
    }

    #[test]
    fn test_mean() {
        let tensor = Tensor::from_vec(vec![2.0f32, 4.0, 6.0, 8.0], vec![4]);
        assert_eq!(tensor.mean(), 5.0);
    }

    #[test]
    fn test_item() {
        let scalar = Tensor::from_vec(vec![42.0f32], vec![]);
        assert_eq!(scalar.item(), 42.0);
    }

    #[test]
    #[should_panic(expected = "Tensor must have exactly one element")]
    fn test_item_multiple_elements() {
        let tensor = Tensor::from_vec(vec![1.0f32, 2.0], vec![2]);
        tensor.item(); // Should panic
    }

    #[test]
    fn test_sum_axis() {
        let tensor = Tensor::from_vec(
            vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], 
            vec![2, 3]
        );
        
        let sum_axis_0 = tensor.sum_axis(0).unwrap();
        assert_eq!(sum_axis_0.shape(), &[3]);
        assert_eq!(sum_axis_0.as_slice().unwrap(), &[5.0f32, 7.0, 9.0]);
        
        let sum_axis_1 = tensor.sum_axis(1).unwrap();
        assert_eq!(sum_axis_1.shape(), &[2]);
        assert_eq!(sum_axis_1.as_slice().unwrap(), &[6.0f32, 15.0]);
    }

    #[test]
    fn test_mean_axis() {
        let tensor = Tensor::from_vec(
            vec![2.0f32, 4.0, 6.0, 8.0], 
            vec![2, 2]
        );
        
        let mean_axis_0 = tensor.mean_axis(0).unwrap();
        assert_eq!(mean_axis_0.shape(), &[2]);
        assert_eq!(mean_axis_0.as_slice().unwrap(), &[5.0f32, 5.0]);
        
        let mean_axis_1 = tensor.mean_axis(1).unwrap();
        assert_eq!(mean_axis_1.shape(), &[2]);
        assert_eq!(mean_axis_1.as_slice().unwrap(), &[3.0f32, 7.0]);
    }

    #[test]
    fn test_max_min() {
        let tensor = Tensor::from_vec(vec![3.0f32, 1.0, 4.0, 2.0], vec![4]);
        assert_eq!(tensor.max(), Some(4.0));
        assert_eq!(tensor.min(), Some(1.0));
    }

    #[test]
    fn test_var_std() {
        let tensor = Tensor::from_vec(vec![1.0f32, 2.0, 3.0, 4.0, 5.0], vec![5]);
        
        let var = tensor.var();
        let std = tensor.std();
        
        // Variance of [1,2,3,4,5] with mean=3 is ((1-3)² + (2-3)² + (3-3)² + (4-3)² + (5-3)²)/5 = 2
        assert!((var - 2.0).abs() < 1e-6);
        assert!((std - 2.0_f32.sqrt()).abs() < 1e-6);
    }

    #[test]
    fn test_count_nonzero() {
        let tensor = Tensor::from_vec(vec![1.0f32, 0.0, 3.0, 0.0, 5.0], vec![5]);
        assert_eq!(tensor.count_nonzero(), 3);
    }

    #[test]
    fn test_max_axis() {
        let tensor = Tensor::from_vec(
            vec![1.0f32, 4.0, 2.0, 5.0, 3.0, 6.0], 
            vec![2, 3]
        );
        
        let max_axis_0 = tensor.max_axis(0).unwrap();
        assert_eq!(max_axis_0.shape(), &[3]);
        assert_eq!(max_axis_0.as_slice().unwrap(), &[2.0f32, 5.0, 6.0]);
        
        let max_axis_1 = tensor.max_axis(1).unwrap();
        assert_eq!(max_axis_1.shape(), &[2]);
        assert_eq!(max_axis_1.as_slice().unwrap(), &[4.0f32, 6.0]);
    }

    #[test]
    fn test_axis_out_of_bounds() {
        let tensor = Tensor::from_vec(vec![1.0f32, 2.0], vec![2]);
        
        assert!(tensor.sum_axis(2).is_err());
        assert!(tensor.mean_axis(5).is_err());
        assert!(tensor.max_axis(10).is_err());
    }
}