Skip to main content

yscv_tensor/ops/
reduce.rs

1//! Reduction ops: sum/mean/min/max/argmin/argmax/var/std, axis + quantile.
2
3use super::super::error::TensorError;
4use super::super::simd;
5use super::super::tensor::Tensor;
6
7impl Tensor {
8    // ── Reductions ──────────────────────────────────────────────────────
9
10    /// Sum reduction over all elements.
11    pub fn sum(&self) -> f32 {
12        simd::sum_dispatch(self.data())
13    }
14
15    /// Mean reduction over all elements.
16    pub fn mean(&self) -> f32 {
17        if self.is_empty() {
18            return f32::NAN;
19        }
20        self.sum() / self.len() as f32
21    }
22
23    /// Global max reduction. Returns `f32::NEG_INFINITY` for empty tensors.
24    pub fn max_value(&self) -> f32 {
25        simd::max_dispatch(self.data())
26    }
27
28    /// Global min reduction. Returns `f32::INFINITY` for empty tensors.
29    pub fn min_value(&self) -> f32 {
30        simd::min_dispatch(self.data())
31    }
32
33    /// Global argmax (flat index of maximum value).
34    pub fn argmax(&self) -> Option<usize> {
35        if self.is_empty() {
36            return None;
37        }
38        let mut best = 0;
39        let mut best_val = self.data()[0];
40        for (i, &v) in self.data().iter().enumerate().skip(1) {
41            if v > best_val {
42                best_val = v;
43                best = i;
44            }
45        }
46        Some(best)
47    }
48
49    /// Global argmin (flat index of minimum value).
50    pub fn argmin(&self) -> Option<usize> {
51        if self.is_empty() {
52            return None;
53        }
54        let mut best = 0;
55        let mut best_val = self.data()[0];
56        for (i, &v) in self.data().iter().enumerate().skip(1) {
57            if v < best_val {
58                best_val = v;
59                best = i;
60            }
61        }
62        Some(best)
63    }
64
65    /// Variance over all elements (population variance).
66    pub fn var(&self) -> f32 {
67        if self.is_empty() {
68            return f32::NAN;
69        }
70        let m = self.mean();
71        self.data().iter().map(|&v| (v - m) * (v - m)).sum::<f32>() / self.len() as f32
72    }
73
74    /// Standard deviation over all elements (population).
75    pub fn std_dev(&self) -> f32 {
76        self.var().sqrt()
77    }
78
79    /// Sum reduction over one axis. Reduced axis is removed from output shape.
80    pub fn sum_axis(&self, axis: usize) -> Result<Self, TensorError> {
81        let shape = self.shape();
82        let rank = shape.len();
83        if axis >= rank {
84            return Err(TensorError::InvalidAxis { axis, rank });
85        }
86
87        // Fast path: 2D contiguous tensor, axis 0 → accumulate rows with SIMD
88        if rank == 2 && axis == 0 {
89            let (rows, cols) = (shape[0], shape[1]);
90            let data = self.data();
91            let mut out = vec![0.0f32; cols];
92            for row in 0..rows {
93                let row_start = row * cols;
94                simd::add_inplace_dispatch(&mut out, &data[row_start..row_start + cols]);
95            }
96            return Self::from_vec(vec![cols], out);
97        }
98
99        // Fast path: 2D contiguous tensor, axis 1 → sum each row with SIMD
100        if rank == 2 && axis == 1 {
101            let (rows, cols) = (shape[0], shape[1]);
102            let data = self.data();
103            let mut out = Vec::with_capacity(rows);
104            for row in 0..rows {
105                out.push(simd::sum_dispatch(&data[row * cols..(row + 1) * cols]));
106            }
107            return Self::from_vec(vec![rows], out);
108        }
109
110        self.reduce_axis(axis, 0.0, |acc, v| acc + v)
111    }
112
113    /// Mean reduction over one axis. Reduced axis is removed from output shape.
114    pub fn mean_axis(&self, axis: usize) -> Result<Self, TensorError> {
115        if axis >= self.rank() {
116            return Err(TensorError::InvalidAxis {
117                axis,
118                rank: self.rank(),
119            });
120        }
121        let axis_len = self.shape()[axis] as f32;
122        let sum = self.sum_axis(axis)?;
123        Ok(sum.scale(1.0 / axis_len))
124    }
125
126    /// Max reduction over one axis. Reduced axis is removed from output shape.
127    pub fn max_axis(&self, axis: usize) -> Result<Self, TensorError> {
128        let shape = self.shape();
129        let rank = shape.len();
130        if axis >= rank {
131            return Err(TensorError::InvalidAxis { axis, rank });
132        }
133
134        // Fast path: 2D contiguous tensor, axis 0 → accumulate rows with SIMD max
135        if rank == 2 && axis == 0 {
136            let (rows, cols) = (shape[0], shape[1]);
137            let data = self.data();
138            let mut out = data[..cols].to_vec();
139            for row in 1..rows {
140                let row_start = row * cols;
141                simd::max_inplace_dispatch(&mut out, &data[row_start..row_start + cols]);
142            }
143            return Self::from_vec(vec![cols], out);
144        }
145
146        // Fast path: 2D contiguous tensor, axis 1 → max each row with SIMD
147        if rank == 2 && axis == 1 {
148            let (rows, cols) = (shape[0], shape[1]);
149            let data = self.data();
150            let mut out = Vec::with_capacity(rows);
151            for row in 0..rows {
152                out.push(simd::max_dispatch(&data[row * cols..(row + 1) * cols]));
153            }
154            return Self::from_vec(vec![rows], out);
155        }
156
157        self.reduce_axis(axis, f32::NEG_INFINITY, f32::max)
158    }
159
160    /// Min reduction over one axis. Reduced axis is removed from output shape.
161    pub fn min_axis(&self, axis: usize) -> Result<Self, TensorError> {
162        self.reduce_axis(axis, f32::INFINITY, f32::min)
163    }
164
165    /// Variance reduction over one axis (population variance).
166    pub fn var_axis(&self, axis: usize) -> Result<Self, TensorError> {
167        let m = self.mean_axis(axis)?;
168        let diff = self.sub(&m.unsqueeze(axis)?)?;
169        let sq = diff.mul(&diff)?;
170        sq.mean_axis(axis)
171    }
172
173    /// Global median of all elements.
174    pub fn median(&self) -> f32 {
175        let mut sorted = self.data().to_vec();
176        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
177        let n = sorted.len();
178        if n == 0 {
179            return 0.0;
180        }
181        if n % 2 == 1 {
182            sorted[n / 2]
183        } else {
184            (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
185        }
186    }
187
188    /// Median along a given axis.
189    pub fn median_axis(&self, axis: usize) -> Result<Self, TensorError> {
190        let shape = self.shape();
191        let rank = shape.len();
192        if axis >= rank {
193            return Err(TensorError::InvalidAxis { axis, rank });
194        }
195        let axis_len = shape[axis];
196        let outer: usize = shape[..axis].iter().product();
197        let inner: usize = shape[axis + 1..].iter().product();
198        let mut new_shape = shape.to_vec();
199        new_shape.remove(axis);
200        if new_shape.is_empty() {
201            new_shape.push(1);
202        }
203        let data = self.data();
204        let mut result = Vec::with_capacity(outer * inner);
205        for o in 0..outer {
206            for i in 0..inner {
207                let mut vals: Vec<f32> = (0..axis_len)
208                    .map(|a| data[o * axis_len * inner + a * inner + i])
209                    .collect();
210                vals.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
211                let n = vals.len();
212                let med = if n % 2 == 1 {
213                    vals[n / 2]
214                } else {
215                    (vals[n / 2 - 1] + vals[n / 2]) / 2.0
216                };
217                result.push(med);
218            }
219        }
220        Self::from_vec(new_shape, result)
221    }
222
223    /// Returns true if any element is non-zero.
224    pub fn any(&self) -> bool {
225        self.data().iter().any(|&v| v != 0.0)
226    }
227
228    /// Returns true if all elements are non-zero.
229    pub fn all(&self) -> bool {
230        self.data().iter().all(|&v| v != 0.0)
231    }
232
233    /// Quantile of all elements. q must be in [0, 1].
234    pub fn quantile(&self, q: f32) -> f32 {
235        let mut sorted = self.data().to_vec();
236        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
237        let n = sorted.len();
238        if n == 0 {
239            return 0.0;
240        }
241        let idx = q * (n - 1) as f32;
242        let lo = idx.floor() as usize;
243        let hi = idx.ceil() as usize;
244        if lo == hi || hi >= n {
245            sorted[lo.min(n - 1)]
246        } else {
247            let frac = idx - lo as f32;
248            sorted[lo] * (1.0 - frac) + sorted[hi] * frac
249        }
250    }
251}