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
//! Indexing operations
//!
//! This module defines the `i` indexing operation. This can be used in various
//! scenarios.
//!
//! Using an integer index returns the slice obtained by selecting elements with
//! the specified index. Negative values can be used for the index, and `..` can
//! be used to get all the indexes from a given dimension.
//!
//! ```ignore
//! use crate::tch::{IndexOp, Tensor};
//! let tensor = Tensor::from_slice(&[1, 2, 3, 4, 5, 6]).view((2, 3));
//! let t = tensor.i(1);
//! let t = tensor.i((.., -2));
//! ```
//!
//! Indexes like `1..`, `..1`, or `1..2`, can be used to narrow a dimension.
//!
//! ```ignore
//! use crate::tch::{IndexOp, Tensor};
//! let tensor = Tensor::from_slice(&[1, 2, 3, 4, 5, 6]).view((2, 3));
//! let t = tensor.i((.., 1..));
//! assert_eq!(t.size(), [2, 2]);
//! assert_eq!(Vec::<i64>::from(t.contiguous().view(-1)), [2, 3, 5, 6]);
//! let t = tensor.i((..1, ..));
//! assert_eq!(t.size(), [1, 3]);
//! assert_eq!(Vec::<i64>::from(t.contiguous().view(-1)), [1, 2, 3]);
//! let t = tensor.i((.., 1..2));
//! assert_eq!(t.size(), [2, 1]);
//! assert_eq!(Vec::<i64>::from(t.contiguous().view(-1)), [2, 5]);
//! let t = tensor.i((.., 1..=2));
//! assert_eq!(t.size(), [2, 2]);
//! assert_eq!(Vec::<i64>::from(t.contiguous().view(-1)), [2, 3, 5, 6]);
//! ```
//!
//! The `NewAxis` index can be used to insert a dimension.
//!
//! ```ignore
//! use crate::tch::{IndexOp, NewAxis, Tensor};
//! let tensor = Tensor::from_slice(&[1, 2, 3, 4, 5, 6]).view((2, 3));
//! let t = tensor.i((NewAxis,));
//! assert_eq!(t.size(), &[1, 2, 3]);
//! let t = tensor.i((.., .., NewAxis));
//! assert_eq!(t.size(), &[2, 3, 1]);
//! ```
//!
//! Unlike NumPy, the `i` operation does not support advanced indexing.
//! The result can be different from NumPy with same set of arguments.
//! For example, `tensor.i(..1, vec![0, 3], vec![2, 1, 3])` does narrowing
//! on first dimension, and index selection on second and third dimensions.
//! The analogous NumPy indexing `array[:1, [0, 3], [2, 1, 3]]` throws
//! shape mismatch error due to advanced indexing rule. Another distinction
//! is that `i` guarantees the input and result tensor shares the same
//! underlying storage, while NumPy may copy the tensor in certain scenarios.
use crate::{TchError, Tensor};
use std::ops::{
    Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
};

#[derive(Debug, PartialEq, Eq)]
pub struct NewAxis;

#[derive(Debug, PartialEq)]
pub enum TensorIndexer {
    Select(i64),
    Narrow(Bound<i64>, Bound<i64>),
    IndexSelect(Tensor),
    InsertNewAxis,
}

impl From<NewAxis> for TensorIndexer {
    fn from(_index: NewAxis) -> Self {
        TensorIndexer::InsertNewAxis
    }
}

impl From<i64> for TensorIndexer {
    fn from(index: i64) -> Self {
        TensorIndexer::Select(index)
    }
}

impl From<&[i64]> for TensorIndexer {
    fn from(index: &[i64]) -> Self {
        let tensor = index.into();
        TensorIndexer::IndexSelect(tensor)
    }
}

impl From<Vec<i64>> for TensorIndexer {
    fn from(index: Vec<i64>) -> Self {
        let tensor = Tensor::from_slice(&index);
        TensorIndexer::IndexSelect(tensor)
    }
}

impl From<&Tensor> for TensorIndexer {
    fn from(tensor: &Tensor) -> Self {
        TensorIndexer::IndexSelect(tensor.shallow_clone())
    }
}

macro_rules! impl_from_range {
    ($range_type:ty) => {
        impl From<$range_type> for TensorIndexer {
            fn from(range: $range_type) -> Self {
                use std::ops::Bound::*;

                let start = match range.start_bound() {
                    Included(idx) => Included(*idx),
                    Excluded(idx) => Excluded(*idx),
                    Unbounded => Unbounded,
                };

                let end = match range.end_bound() {
                    Included(idx) => Included(*idx),
                    Excluded(idx) => Excluded(*idx),
                    Unbounded => Unbounded,
                };

                TensorIndexer::Narrow(start, end)
            }
        }
    };
}

impl_from_range!(Range<i64>);
impl_from_range!(RangeFrom<i64>);
impl_from_range!(RangeFull);
impl_from_range!(RangeInclusive<i64>);
impl_from_range!(RangeTo<i64>);
impl_from_range!(RangeToInclusive<i64>);

pub trait IndexOp<T> {
    fn i(&self, index: T) -> Tensor;
}

impl<A> IndexOp<A> for Tensor
where
    A: Into<TensorIndexer>,
{
    fn i(&self, index: A) -> Tensor {
        self.indexer(&[index.into()])
    }
}

impl<A> IndexOp<(A,)> for Tensor
where
    A: Into<TensorIndexer>,
{
    fn i(&self, index: (A,)) -> Tensor {
        let idx_a = index.0.into();
        self.indexer(&[idx_a])
    }
}

impl<A, B> IndexOp<(A, B)> for Tensor
where
    A: Into<TensorIndexer>,
    B: Into<TensorIndexer>,
{
    fn i(&self, index: (A, B)) -> Tensor {
        let idx_a = index.0.into();
        let idx_b = index.1.into();
        self.indexer(&[idx_a, idx_b])
    }
}

impl<A, B, C> IndexOp<(A, B, C)> for Tensor
where
    A: Into<TensorIndexer>,
    B: Into<TensorIndexer>,
    C: Into<TensorIndexer>,
{
    fn i(&self, index: (A, B, C)) -> Tensor {
        let idx_a = index.0.into();
        let idx_b = index.1.into();
        let idx_c = index.2.into();
        self.indexer(&[idx_a, idx_b, idx_c])
    }
}

impl<A, B, C, D> IndexOp<(A, B, C, D)> for Tensor
where
    A: Into<TensorIndexer>,
    B: Into<TensorIndexer>,
    C: Into<TensorIndexer>,
    D: Into<TensorIndexer>,
{
    fn i(&self, index: (A, B, C, D)) -> Tensor {
        let idx_a = index.0.into();
        let idx_b = index.1.into();
        let idx_c = index.2.into();
        let idx_d = index.3.into();
        self.indexer(&[idx_a, idx_b, idx_c, idx_d])
    }
}

impl<A, B, C, D, E> IndexOp<(A, B, C, D, E)> for Tensor
where
    A: Into<TensorIndexer>,
    B: Into<TensorIndexer>,
    C: Into<TensorIndexer>,
    D: Into<TensorIndexer>,
    E: Into<TensorIndexer>,
{
    fn i(&self, index: (A, B, C, D, E)) -> Tensor {
        let idx_a = index.0.into();
        let idx_b = index.1.into();
        let idx_c = index.2.into();
        let idx_d = index.3.into();
        let idx_e = index.4.into();
        self.indexer(&[idx_a, idx_b, idx_c, idx_d, idx_e])
    }
}

impl<A, B, C, D, E, F> IndexOp<(A, B, C, D, E, F)> for Tensor
where
    A: Into<TensorIndexer>,
    B: Into<TensorIndexer>,
    C: Into<TensorIndexer>,
    D: Into<TensorIndexer>,
    E: Into<TensorIndexer>,
    F: Into<TensorIndexer>,
{
    fn i(&self, index: (A, B, C, D, E, F)) -> Tensor {
        let idx_a = index.0.into();
        let idx_b = index.1.into();
        let idx_c = index.2.into();
        let idx_d = index.3.into();
        let idx_e = index.4.into();
        let idx_f = index.5.into();
        self.indexer(&[idx_a, idx_b, idx_c, idx_d, idx_e, idx_f])
    }
}

impl<A, B, C, D, E, F, G> IndexOp<(A, B, C, D, E, F, G)> for Tensor
where
    A: Into<TensorIndexer>,
    B: Into<TensorIndexer>,
    C: Into<TensorIndexer>,
    D: Into<TensorIndexer>,
    E: Into<TensorIndexer>,
    F: Into<TensorIndexer>,
    G: Into<TensorIndexer>,
{
    fn i(&self, index: (A, B, C, D, E, F, G)) -> Tensor {
        let idx_a = index.0.into();
        let idx_b = index.1.into();
        let idx_c = index.2.into();
        let idx_d = index.3.into();
        let idx_e = index.4.into();
        let idx_f = index.5.into();
        let idx_g = index.6.into();
        self.indexer(&[idx_a, idx_b, idx_c, idx_d, idx_e, idx_f, idx_g])
    }
}

impl Tensor {
    fn f_indexer(&self, index_spec: &[TensorIndexer]) -> Result<Tensor, TchError> {
        use std::ops::Bound::*;
        use TensorIndexer::*;

        // Make sure n. non-newaxis does not exceed n. of dimensions
        let n_newaxis = index_spec.iter().filter(|spec| *spec == &InsertNewAxis).count();

        if index_spec.len() > self.size().len() + n_newaxis {
            return Err(TchError::Shape(format!(
                "too many indices for tensor of dimension {}",
                self.size().len()
            )));
        }

        // Make sure tensors conform the format
        for spec in index_spec.iter() {
            use super::Kind::*;
            if let IndexSelect(tensor) = spec {
                if tensor.size().len() != 1 {
                    return Err(TchError::Shape(
                        "Multi-dimensional tensor is not supported for indexing".to_string(),
                    ));
                }
                match tensor.f_kind()? {
                    Int64 => {}
                    Int16 => {}
                    Int8 => {}
                    Int => {}
                    _ => {
                        return Err(TchError::Kind(format!("the kind of tensors used as indices must be one of {Int64:?}, {Int16:?}, {Int8:?}, {Int:?}")));
                    }
                }
            }
        }

        // Apply indexing from left to right
        let mut curr_tensor = self.shallow_clone();
        let mut curr_idx: i64 = 0;

        for spec in index_spec.iter() {
            let (next_tensor, next_idx) = match spec {
                InsertNewAxis => (curr_tensor.unsqueeze(curr_idx), curr_idx + 1),
                Select(index) => (
                    curr_tensor.select(curr_idx, *index),
                    curr_idx, // not advanced because select() squeezes dimension
                ),
                Narrow(Unbounded, Unbounded) => (curr_tensor, curr_idx + 1),
                Narrow(Included(start), Unbounded) => {
                    let dim_len = curr_tensor.size()[curr_idx as usize];
                    (curr_tensor.narrow(curr_idx, *start, dim_len - *start), curr_idx + 1)
                }
                Narrow(Excluded(start), Unbounded) => {
                    let dim_len = curr_tensor.size()[curr_idx as usize];
                    (curr_tensor.narrow(curr_idx, *start + 1, dim_len - *start - 1), curr_idx + 1)
                }
                Narrow(Unbounded, Included(end)) => {
                    (curr_tensor.narrow(curr_idx, 0, *end + 1), curr_idx + 1)
                }
                Narrow(Unbounded, Excluded(end)) => {
                    (curr_tensor.narrow(curr_idx, 0, *end), curr_idx + 1)
                }
                Narrow(Included(start), Included(end)) => {
                    (curr_tensor.narrow(curr_idx, *start, *end - *start + 1), curr_idx + 1)
                }
                Narrow(Included(start), Excluded(end)) => {
                    (curr_tensor.narrow(curr_idx, *start, *end - *start), curr_idx + 1)
                }
                Narrow(Excluded(start), Included(end)) => {
                    (curr_tensor.narrow(curr_idx, *start + 1, *end - *start), curr_idx + 1)
                }
                Narrow(Excluded(start), Excluded(end)) => {
                    (curr_tensor.narrow(curr_idx, *start + 1, *end - *start - 1), curr_idx + 1)
                }
                IndexSelect(index_tensor) => {
                    let index_tensor = index_tensor.to_device(curr_tensor.device());
                    (curr_tensor.index_select(curr_idx, &index_tensor), curr_idx + 1)
                }
            };

            curr_tensor = next_tensor;
            curr_idx = next_idx;
        }

        Ok(curr_tensor)
    }

    fn indexer(&self, index_spec: &[TensorIndexer]) -> Tensor {
        self.f_indexer(index_spec).unwrap()
    }
}