mdarray 0.7.2

Multidimensional array for Rust
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use core::fmt::{Debug, Formatter, Result};

use crate::expr::expression::{Expression, IntoExpression};
use crate::expr::iter::Iter;
use crate::shape::Shape;

/// Expression that clones the elements of an underlying expression.
#[derive(Clone, Debug)]
pub struct Cloned<E> {
    expr: E,
}

/// Expression that copies the elements of an underlying expression.
#[derive(Clone, Debug)]
pub struct Copied<E> {
    expr: E,
}

/// Expression that gives the current count and the element during iteration.
#[derive(Clone)]
pub struct Enumerate<E> {
    expr: E,
    count: usize,
}

/// Expression that calls a closure on each element.
#[derive(Clone)]
pub struct Map<E, F> {
    expr: E,
    f: F,
}

/// Expression that gives tuples `(x, y)` of the elements from each expression.
#[derive(Clone)]
pub struct Zip<A: Expression, B: Expression> {
    a: A,
    b: B,
    shape: <Self as Expression>::Shape,
}

/// Creates an expression that clones the elements of the argument.
///
/// # Examples
///
/// ```
/// use mdarray::{expr, expr::Expression, view};
///
/// let v = view![0, 1, 2];
///
/// assert_eq!(expr::cloned(v).eval(), v);
/// ```
#[inline]
pub fn cloned<'a, T: 'a + Clone, I: IntoExpression<Item = &'a T>>(expr: I) -> Cloned<I::IntoExpr> {
    expr.into_expr().cloned()
}

/// Creates an expression that copies the elements of the argument.
///
/// # Examples
///
/// ```
/// use mdarray::{expr, expr::Expression, view};
///
/// let v = view![0, 1, 2];
///
/// assert_eq!(expr::copied(v).eval(), v);
/// ```
#[inline]
pub fn copied<'a, T: 'a + Copy, I: IntoExpression<Item = &'a T>>(expr: I) -> Copied<I::IntoExpr> {
    expr.into_expr().copied()
}

/// Creates an expression that enumerates the elements of the argument.
///
/// # Examples
///
/// ```
/// use mdarray::{expr, expr::Expression, tensor, view};
///
/// let t = tensor![3, 4, 5];
///
/// assert_eq!(expr::enumerate(t).eval(), view![(0, 3), (1, 4), (2, 5)]);
/// ```
#[inline]
pub fn enumerate<I: IntoExpression>(expr: I) -> Enumerate<I::IntoExpr> {
    expr.into_expr().enumerate()
}

/// Creates an expression that calls a closure on each element of the argument.
///
/// # Examples
///
/// ```
/// use mdarray::{expr, expr::Expression, view};
///
/// let v = view![0, 1, 2];
///
/// assert_eq!(expr::map(v, |x| 2 * x).eval(), view![0, 2, 4]);
/// ```
#[inline]
pub fn map<T, I: IntoExpression, F: FnMut(I::Item) -> T>(expr: I, f: F) -> Map<I::IntoExpr, F> {
    expr.into_expr().map(f)
}

/// Converts the arguments to expressions and zips them.
///
/// # Panics
///
/// Panics if the expressions cannot be broadcast to a common shape.
///
/// # Examples
///
/// ```
/// use mdarray::{expr, expr::Expression, tensor, view};
///
/// let a = tensor![0, 1, 2];
/// let b = tensor![3, 4, 5];
///
/// assert_eq!(expr::zip(a, b).eval(), view![(0, 3), (1, 4), (2, 5)]);
/// ```
#[inline]
pub fn zip<A: IntoExpression, B: IntoExpression>(a: A, b: B) -> Zip<A::IntoExpr, B::IntoExpr> {
    a.into_expr().zip(b)
}

impl<E> Cloned<E> {
    #[inline]
    pub(crate) fn new(expr: E) -> Self {
        Self { expr }
    }
}

impl<'a, T: 'a + Clone, E: Expression<Item = &'a T>> Expression for Cloned<E> {
    type Shape = E::Shape;

    const IS_REPEATABLE: bool = E::IS_REPEATABLE;

    #[inline]
    fn shape(&self) -> &E::Shape {
        self.expr.shape()
    }

    #[inline]
    unsafe fn get_unchecked(&mut self, index: usize) -> T {
        unsafe { self.expr.get_unchecked(index).clone() }
    }

    #[inline]
    fn inner_rank(&self) -> usize {
        self.expr.inner_rank()
    }

    #[inline]
    unsafe fn reset_dim(&mut self, index: usize, count: usize) {
        unsafe {
            self.expr.reset_dim(index, count);
        }
    }

    #[inline]
    unsafe fn step_dim(&mut self, index: usize) {
        unsafe {
            self.expr.step_dim(index);
        }
    }
}

impl<'a, T: 'a + Clone, E: Expression<Item = &'a T>> IntoIterator for Cloned<E> {
    type Item = T;
    type IntoIter = Iter<Self>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}

impl<E> Copied<E> {
    #[inline]
    pub(crate) fn new(expr: E) -> Self {
        Self { expr }
    }
}

impl<'a, T: 'a + Copy, E: Expression<Item = &'a T>> Expression for Copied<E> {
    type Shape = E::Shape;

    const IS_REPEATABLE: bool = E::IS_REPEATABLE;

    #[inline]
    fn shape(&self) -> &E::Shape {
        self.expr.shape()
    }

    #[inline]
    unsafe fn get_unchecked(&mut self, index: usize) -> T {
        unsafe { *self.expr.get_unchecked(index) }
    }

    #[inline]
    fn inner_rank(&self) -> usize {
        self.expr.inner_rank()
    }

    #[inline]
    unsafe fn reset_dim(&mut self, index: usize, count: usize) {
        unsafe {
            self.expr.reset_dim(index, count);
        }
    }

    #[inline]
    unsafe fn step_dim(&mut self, index: usize) {
        unsafe {
            self.expr.step_dim(index);
        }
    }
}

impl<'a, T: 'a + Copy, E: Expression<Item = &'a T>> IntoIterator for Copied<E> {
    type Item = T;
    type IntoIter = Iter<Self>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}

impl<E: Expression> Enumerate<E> {
    #[inline]
    pub(crate) fn new(expr: E) -> Self {
        Self { expr, count: 0 }
    }
}

impl<E: Debug> Debug for Enumerate<E> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("Enumerate").field("expr", &self.expr).finish()
    }
}

impl<E: Expression> Expression for Enumerate<E> {
    type Shape = E::Shape;

    const IS_REPEATABLE: bool = E::IS_REPEATABLE;

    #[inline]
    fn shape(&self) -> &E::Shape {
        self.expr.shape()
    }

    #[inline]
    unsafe fn get_unchecked(&mut self, index: usize) -> Self::Item {
        self.count += 1;

        unsafe { (self.count - 1, self.expr.get_unchecked(index)) }
    }

    #[inline]
    fn inner_rank(&self) -> usize {
        self.expr.inner_rank()
    }

    #[inline]
    unsafe fn reset_dim(&mut self, index: usize, count: usize) {
        unsafe {
            self.expr.reset_dim(index, count);
        }
    }

    #[inline]
    unsafe fn step_dim(&mut self, index: usize) {
        unsafe {
            self.expr.step_dim(index);
        }
    }
}

impl<E: Expression> IntoIterator for Enumerate<E> {
    type Item = (usize, E::Item);
    type IntoIter = Iter<Self>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}

impl<E, F> Map<E, F> {
    #[inline]
    pub(crate) fn new(expr: E, f: F) -> Self {
        Self { expr, f }
    }
}

impl<E: Debug, F> Debug for Map<E, F> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("Map").field("expr", &self.expr).finish()
    }
}

impl<T, E: Expression, F: FnMut(E::Item) -> T> Expression for Map<E, F> {
    type Shape = E::Shape;

    const IS_REPEATABLE: bool = E::IS_REPEATABLE;

    #[inline]
    fn shape(&self) -> &E::Shape {
        self.expr.shape()
    }

    #[inline]
    unsafe fn get_unchecked(&mut self, index: usize) -> T {
        unsafe { (self.f)(self.expr.get_unchecked(index)) }
    }

    #[inline]
    fn inner_rank(&self) -> usize {
        self.expr.inner_rank()
    }

    #[inline]
    unsafe fn reset_dim(&mut self, index: usize, count: usize) {
        unsafe {
            self.expr.reset_dim(index, count);
        }
    }

    #[inline]
    unsafe fn step_dim(&mut self, index: usize) {
        unsafe {
            self.expr.step_dim(index);
        }
    }
}

impl<T, E: Expression, F: FnMut(E::Item) -> T> IntoIterator for Map<E, F> {
    type Item = T;
    type IntoIter = Iter<Self>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}

impl<A: Expression, B: Expression> Zip<A, B> {
    #[inline]
    pub(crate) fn new(a: A, b: B) -> Self {
        assert!(A::IS_REPEATABLE || a.rank() >= b.rank(), "expression not repeatable");
        assert!(B::IS_REPEATABLE || b.rank() >= a.rank(), "expression not repeatable");

        let shape = a.shape().with_dims(|a_dims| {
            b.shape().with_dims(|b_dims| {
                let dims = if a_dims.len() < b_dims.len() { b_dims } else { a_dims };
                let inner_match =
                    a_dims[dims.len() - b_dims.len()..] == b_dims[dims.len() - a_dims.len()..];

                assert!(inner_match, "inner dimensions mismatch");

                Shape::from_dims(dims)
            })
        });

        Self { a, b, shape }
    }
}

impl<A: Expression + Debug, B: Expression + Debug> Debug for Zip<A, B> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("Zip").field("a", &self.a).field("b", &self.b).finish()
    }
}

impl<S: Shape, R: Shape, A, B> Expression for Zip<A, B>
where
    A: Expression<Shape = S>,
    B: Expression<Shape = R>,
{
    type Shape = <<S::Reverse as Shape>::Merge<R::Reverse> as Shape>::Reverse;

    const IS_REPEATABLE: bool = A::IS_REPEATABLE && B::IS_REPEATABLE;

    #[inline]
    fn shape(&self) -> &Self::Shape {
        &self.shape
    }

    #[inline]
    unsafe fn get_unchecked(&mut self, index: usize) -> Self::Item {
        unsafe { (self.a.get_unchecked(index), self.b.get_unchecked(index)) }
    }

    #[inline]
    fn inner_rank(&self) -> usize {
        self.a.inner_rank().min(self.b.inner_rank())
    }

    #[inline]
    unsafe fn reset_dim(&mut self, index: usize, count: usize) {
        let delta = self.shape.rank() - index;

        unsafe {
            if delta <= self.a.rank() {
                self.a.reset_dim(self.a.rank() - delta, count);
            }

            if delta <= self.b.rank() {
                self.b.reset_dim(self.b.rank() - delta, count);
            }
        }
    }

    #[inline]
    unsafe fn step_dim(&mut self, index: usize) {
        let delta = self.shape.rank() - index;

        unsafe {
            if delta <= self.a.rank() {
                self.a.step_dim(self.a.rank() - delta);
            }

            if delta <= self.b.rank() {
                self.b.step_dim(self.b.rank() - delta);
            }
        }
    }
}

impl<A: Expression, B: Expression> IntoIterator for Zip<A, B> {
    type Item = (A::Item, B::Item);
    type IntoIter = Iter<Self>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}