Skip to main content

yscv_tensor/ops/
indexing.rs

1//! Advanced indexing/selection: where/masked_fill/scatter/gather/topk/tri/pad.
2
3use super::super::error::TensorError;
4use super::super::tensor::Tensor;
5
6impl Tensor {
7    // ── Advanced indexing/selection ─────────────────────────────────────
8
9    /// Element-wise where: `condition ? self : other`.
10    /// `condition` has 1.0 for true, 0.0 for false.
11    pub fn where_cond(&self, condition: &Self, other: &Self) -> Result<Self, TensorError> {
12        if self.shape() != condition.shape() || self.shape() != other.shape() {
13            return Err(TensorError::ShapeMismatch {
14                left: self.shape().to_vec(),
15                right: condition.shape().to_vec(),
16            });
17        }
18        let data: Vec<f32> = condition
19            .data()
20            .iter()
21            .zip(self.data().iter())
22            .zip(other.data().iter())
23            .map(|((&c, &t), &f)| if c != 0.0 { t } else { f })
24            .collect();
25        Tensor::from_vec(self.shape().to_vec(), data)
26    }
27
28    /// Replace elements where `mask != 0` with `value`.
29    pub fn masked_fill(&self, mask: &Self, value: f32) -> Result<Self, TensorError> {
30        if self.shape() != mask.shape() {
31            return Err(TensorError::ShapeMismatch {
32                left: self.shape().to_vec(),
33                right: mask.shape().to_vec(),
34            });
35        }
36        let data: Vec<f32> = self
37            .data()
38            .iter()
39            .zip(mask.data().iter())
40            .map(|(&v, &m)| if m != 0.0 { value } else { v })
41            .collect();
42        Tensor::from_vec(self.shape().to_vec(), data)
43    }
44
45    /// Scatter values into self along `axis` at positions given by `index`.
46    /// `src` provides the values. `index` has same shape as `src`.
47    pub fn scatter(&self, axis: usize, index: &Self, src: &Self) -> Result<Self, TensorError> {
48        if index.shape() != src.shape() {
49            return Err(TensorError::ShapeMismatch {
50                left: index.shape().to_vec(),
51                right: src.shape().to_vec(),
52            });
53        }
54        if axis >= self.rank() {
55            return Err(TensorError::InvalidAxis {
56                axis,
57                rank: self.rank(),
58            });
59        }
60        let mut out = self.data().to_vec();
61        let shape = index.shape();
62        let outer: usize = shape[..axis].iter().product();
63        let dim = shape[axis];
64        let inner: usize = shape[axis + 1..].iter().product();
65        let self_dim = self.shape()[axis];
66        let self_inner: usize = self.shape()[axis + 1..].iter().product();
67
68        for o in 0..outer {
69            for d in 0..dim {
70                for i in 0..inner {
71                    let src_idx = (o * dim + d) * inner + i;
72                    let target_d = index.data()[src_idx] as usize;
73                    if target_d < self_dim {
74                        let out_idx = (o * self_dim + target_d) * self_inner + i;
75                        if out_idx < out.len() {
76                            out[out_idx] = src.data()[src_idx];
77                        }
78                    }
79                }
80            }
81        }
82        Tensor::from_vec(self.shape().to_vec(), out)
83    }
84
85    /// Gather elements along `axis` at positions given by `index`.
86    pub fn gather(&self, axis: usize, index: &Self) -> Result<Self, TensorError> {
87        if axis >= self.rank() {
88            return Err(TensorError::InvalidAxis {
89                axis,
90                rank: self.rank(),
91            });
92        }
93        let shape = index.shape();
94        let outer: usize = shape[..axis].iter().product();
95        let dim = shape[axis];
96        let inner: usize = shape[axis + 1..].iter().product();
97        let self_dim = self.shape()[axis];
98        let self_inner: usize = self.shape()[axis + 1..].iter().product();
99
100        let mut out = vec![0.0f32; index.len()];
101        for o in 0..outer {
102            for d in 0..dim {
103                for i in 0..inner {
104                    let idx_pos = (o * dim + d) * inner + i;
105                    let src_d = index.data()[idx_pos] as usize;
106                    if src_d < self_dim {
107                        let src_pos = (o * self_dim + src_d) * self_inner + i;
108                        if src_pos < self.len() {
109                            out[idx_pos] = self.data()[src_pos];
110                        }
111                    }
112                }
113            }
114        }
115        Tensor::from_vec(shape.to_vec(), out)
116    }
117
118    /// Returns the top-k values and their indices along the last axis.
119    pub fn topk(&self, k: usize) -> Result<(Self, Self), TensorError> {
120        if self.rank() == 0 {
121            return Err(TensorError::InvalidAxis { axis: 0, rank: 0 });
122        }
123        let last_dim = *self.shape().last().expect("non-empty shape");
124        let k = k.min(last_dim);
125        let outer: usize = self.len() / last_dim;
126
127        let mut values = Vec::with_capacity(outer * k);
128        let mut indices = Vec::with_capacity(outer * k);
129
130        for o in 0..outer {
131            let start = o * last_dim;
132            let slice = &self.data()[start..start + last_dim];
133            let mut idx_vec: Vec<usize> = (0..last_dim).collect();
134            idx_vec.sort_unstable_by(|&a, &b| {
135                slice[b]
136                    .partial_cmp(&slice[a])
137                    .unwrap_or(std::cmp::Ordering::Equal)
138            });
139            for &i in &idx_vec[..k] {
140                values.push(slice[i]);
141                indices.push(i as f32);
142            }
143        }
144
145        let mut out_shape = self.shape().to_vec();
146        *out_shape.last_mut().expect("non-empty shape") = k;
147        let val_t = Tensor::from_vec(out_shape.clone(), values)?;
148        let idx_t = Tensor::from_vec(out_shape, indices)?;
149        Ok((val_t, idx_t))
150    }
151
152    /// Upper triangular mask: zero below diagonal, keep above.
153    /// `diagonal` shifts: 0 = main, positive = above, negative = below.
154    pub fn triu(&self, diagonal: i64) -> Result<Self, TensorError> {
155        if self.rank() < 2 {
156            return Err(TensorError::InvalidAxis {
157                axis: 0,
158                rank: self.rank(),
159            });
160        }
161        let shape = self.shape();
162        let rows = shape[shape.len() - 2];
163        let cols = shape[shape.len() - 1];
164        let batch: usize = shape[..shape.len() - 2].iter().product();
165        let mut out = self.data().to_vec();
166        for b in 0..batch {
167            for r in 0..rows {
168                for c in 0..cols {
169                    if (c as i64) < (r as i64) + diagonal {
170                        out[b * rows * cols + r * cols + c] = 0.0;
171                    }
172                }
173            }
174        }
175        Tensor::from_vec(shape.to_vec(), out)
176    }
177
178    /// Lower triangular mask: zero above diagonal, keep below.
179    pub fn tril(&self, diagonal: i64) -> Result<Self, TensorError> {
180        if self.rank() < 2 {
181            return Err(TensorError::InvalidAxis {
182                axis: 0,
183                rank: self.rank(),
184            });
185        }
186        let shape = self.shape();
187        let rows = shape[shape.len() - 2];
188        let cols = shape[shape.len() - 1];
189        let batch: usize = shape[..shape.len() - 2].iter().product();
190        let mut out = self.data().to_vec();
191        for b in 0..batch {
192            for r in 0..rows {
193                for c in 0..cols {
194                    if (c as i64) > (r as i64) + diagonal {
195                        out[b * rows * cols + r * cols + c] = 0.0;
196                    }
197                }
198            }
199        }
200        Tensor::from_vec(shape.to_vec(), out)
201    }
202
203    /// Identity matrix `[n, n]`.
204    pub fn eye(n: usize) -> Result<Self, TensorError> {
205        let mut data = vec![0.0f32; n * n];
206        for i in 0..n {
207            data[i * n + i] = 1.0;
208        }
209        Tensor::from_vec(vec![n, n], data)
210    }
211
212    /// Create a diagonal matrix from a 1D vector.
213    pub fn diag(vector: &Tensor) -> Result<Self, TensorError> {
214        let shape = vector.shape();
215        if shape.len() != 1 {
216            return Err(TensorError::UnsupportedOperation {
217                msg: format!("diag requires a 1D tensor, got shape {:?}", shape),
218            });
219        }
220        let n = shape[0];
221        let mut data = vec![0.0f32; n * n];
222        for i in 0..n {
223            data[i * n + i] = vector.data()[i];
224        }
225        Self::from_vec(vec![n, n], data)
226    }
227
228    /// Extract the diagonal of a 2D matrix as a 1D vector.
229    pub fn diag_extract(&self) -> Result<Self, TensorError> {
230        let shape = self.shape();
231        if shape.len() != 2 {
232            return Err(TensorError::UnsupportedOperation {
233                msg: format!("diag_extract requires a 2D tensor, got shape {:?}", shape),
234            });
235        }
236        let n = shape[0].min(shape[1]);
237        let cols = shape[1];
238        let data: Vec<f32> = (0..n).map(|i| self.data()[i * cols + i]).collect();
239        Self::from_vec(vec![n], data)
240    }
241
242    /// Pad the tensor with a constant value. `padding` is a slice of (before, after) per dimension.
243    pub fn pad(&self, padding: &[(usize, usize)], value: f32) -> Result<Self, TensorError> {
244        let shape = self.shape();
245        if padding.len() != shape.len() {
246            return Err(TensorError::InvalidIndexRank {
247                expected: shape.len(),
248                got: padding.len(),
249            });
250        }
251        let new_shape: Vec<usize> = shape
252            .iter()
253            .zip(padding)
254            .map(|(&s, &(b, a))| s + b + a)
255            .collect();
256        let new_size: usize = new_shape.iter().product();
257        let mut result = vec![value; new_size];
258        let ndim = shape.len();
259
260        // Compute strides for both old and new shapes
261        let mut old_strides = vec![1usize; ndim];
262        for i in (0..ndim.saturating_sub(1)).rev() {
263            old_strides[i] = old_strides[i + 1] * shape[i + 1];
264        }
265        let mut new_strides = vec![1usize; ndim];
266        for i in (0..ndim.saturating_sub(1)).rev() {
267            new_strides[i] = new_strides[i + 1] * new_shape[i + 1];
268        }
269
270        let old_size: usize = shape.iter().product();
271        let data = self.data();
272        for flat_idx in 0..old_size {
273            let mut remaining = flat_idx;
274            let mut new_flat = 0;
275            for d in 0..ndim {
276                let coord = remaining / old_strides[d];
277                remaining %= old_strides[d];
278                new_flat += (coord + padding[d].0) * new_strides[d];
279            }
280            result[new_flat] = data[flat_idx];
281        }
282
283        Self::from_vec(new_shape, result)
284    }
285
286    /// Repeat tensor along each axis by the given counts.
287    pub fn repeat(&self, counts: &[usize]) -> Result<Self, TensorError> {
288        if counts.len() != self.rank() {
289            return Err(TensorError::InvalidIndexRank {
290                expected: self.rank(),
291                got: counts.len(),
292            });
293        }
294        let mut out = self.clone();
295        for (axis, &count) in counts.iter().enumerate() {
296            if count > 1 {
297                let refs: Vec<&Tensor> = std::iter::repeat_n(&out, count).collect();
298                out = Tensor::cat(&refs, axis)?;
299            }
300        }
301        Ok(out)
302    }
303}