easy-ml 2.1.0

Machine learning library providing matrices, named tensors, linear algebra and automatic differentiation aimed at being easy to use
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
use crate::matrices::views::{DataLayout, MatrixMut, MatrixRef, NoInteriorMutability};
use crate::matrices::{Column, Row};

use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::ops::Range;

/**
 * A 2 dimensional range over a matrix, hiding the values **outside** the range from view.
 *
 * The entire source is still owned by the MatrixRange however, so this does not permit
 * creating multiple mutable ranges into a single matrix even if they wouldn't overlap.
 *
 * For non overlapping mutable ranges into a single matrix see
 * [`partition`](crate::matrices::Matrix::partition).
 *
 * See also: [MatrixMask](MatrixMask)
 */
#[derive(Clone, Debug)]
pub struct MatrixRange<T, S> {
    source: S,
    rows: IndexRange,
    columns: IndexRange,
    _type: PhantomData<T>,
}

/**
 * A 2 dimensional mask over a matrix, hiding the values **inside** the range from view.
 *
 * The entire source is still owned by the MatrixMask however, so this does not permit
 * creating multiple mutable masks into a single matrix even if they wouldn't overlap.
 *
 * See also: [MatrixRange](MatrixRange)
 */
#[derive(Clone, Debug)]
pub struct MatrixMask<T, S> {
    source: S,
    rows: IndexRange,
    columns: IndexRange,
    _type: PhantomData<T>,
}

impl<T, S> MatrixRange<T, S>
where
    S: MatrixRef<T>,
{
    /**
     * Creates a new MatrixRange giving a view of only the data within the row and column
     * [IndexRange](IndexRange)s.
     *
     * # Examples
     *
     * Creating a view and manipulating a matrix from it.
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::{MatrixView, MatrixRange};
     * let mut matrix = Matrix::from(vec![
     *     vec![ 2, 3, 4 ],
     *     vec![ 5, 1, 8 ]]);
     * {
     *     let mut view = MatrixView::from(MatrixRange::from(&mut matrix, 0..1, 1..3));
     *     assert_eq!(vec![3, 4], view.row_major_iter().collect::<Vec<_>>());
     *     view.map_mut(|x| x + 10);
     * }
     * assert_eq!(matrix, Matrix::from(vec![
     *     vec![ 2, 13, 14 ],
     *     vec![ 5,  1,  8 ]]));
     * ```
     *
     * Various ways to construct a MatrixRange
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::{IndexRange, MatrixRange};
     * let matrix = Matrix::from(vec![vec![1]]);
     * let index_range = MatrixRange::from(&matrix, IndexRange::new(0, 4), IndexRange::new(1, 3));
     * let tuple = MatrixRange::from(&matrix, (0, 4), (1, 3));
     * let array = MatrixRange::from(&matrix, [0, 4], [1, 3]);
     * // Note std::ops::Range is start..end not start and length!
     * let range = MatrixRange::from(&matrix, 0..4, 1..4);
     * ```
     *
     * NOTE: In previous versions (<=1.8.1), this erroneously did not clip the IndexRange input to
     * not exceed the rows and columns of the source, which led to the possibility to create
     * MatrixRanges that reported a greater number of rows and columns in their shape than their
     * actual data. This function will now correctly clip any ranges that exceed their sources.
     */
    pub fn from<R>(source: S, rows: R, columns: R) -> MatrixRange<T, S>
    where
        R: Into<IndexRange>,
    {
        let max_rows = source.view_rows();
        let max_columns = source.view_columns();
        MatrixRange {
            source,
            rows: {
                let mut rows = rows.into();
                rows.clip(max_rows);
                rows
            },
            columns: {
                let mut columns = columns.into();
                columns.clip(max_columns);
                columns
            },
            _type: PhantomData,
        }
    }

    /**
     * Consumes the MatrixRange, yielding the source it was created from.
     */
    #[allow(dead_code)]
    pub fn source(self) -> S {
        self.source
    }

    /**
     * Gives a reference to the MatrixRange's source (in which the data is not clipped).
     */
    // # Safety
    //
    // Giving out a mutable reference to our source could allow it to be changed out from under us
    // and make our range checks invalid. However, since the source implements MatrixRef
    // interior mutability is not allowed, so we can give out shared references without breaking
    // our own integrity.
    #[allow(dead_code)]
    pub fn source_ref(&self) -> &S {
        &self.source
    }
}

impl<T, S> MatrixMask<T, S>
where
    S: MatrixRef<T>,
{
    /**
     * Creates a new MatrixMask giving a view of only the data outside the row and column
     * [IndexRange](IndexRange)s. If the index range given for rows or columns exceeds the
     * size of the matrix, they will be clipped to fit the actual size without an error.
     *
     * # Examples
     *
     * Creating a view and manipulating a matrix from it.
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::{MatrixView, MatrixMask};
     * let mut matrix = Matrix::from(vec![
     *     vec![ 2, 3, 4 ],
     *     vec![ 5, 1, 8 ]]);
     * {
     *     let mut view = MatrixView::from(MatrixMask::from(&mut matrix, 0..1, 2..3));
     *     assert_eq!(vec![5, 1], view.row_major_iter().collect::<Vec<_>>());
     *     view.map_mut(|x| x + 10);
     * }
     * assert_eq!(matrix, Matrix::from(vec![
     *     vec![ 2,   3,  4 ],
     *     vec![ 15, 11,  8 ]]));
     * ```
     *
     * Various ways to construct a MatrixMask
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::{IndexRange, MatrixMask};
     * let matrix = Matrix::from(vec![vec![1]]);
     * let index_range = MatrixMask::from(&matrix, IndexRange::new(0, 4), IndexRange::new(1, 3));
     * let tuple = MatrixMask::from(&matrix, (0, 4), (1, 3));
     * let array = MatrixMask::from(&matrix, [0, 4], [1, 3]);
     * // Note std::ops::Range is start..end not start and length!
     * let range = MatrixMask::from(&matrix, 0..4, 1..4);
     * ```
     */
    pub fn from<R>(source: S, rows: R, columns: R) -> MatrixMask<T, S>
    where
        R: Into<IndexRange>,
    {
        let max_rows = source.view_rows();
        let max_columns = source.view_columns();
        MatrixMask {
            source,
            rows: {
                let mut rows = rows.into();
                rows.clip(max_rows);
                rows
            },
            columns: {
                let mut columns = columns.into();
                columns.clip(max_columns);
                columns
            },
            _type: PhantomData,
        }
    }

    /**
     * Creates a MatrixMask of this source that retains only the specified
     * number of elements at both the start and end of the rows.
     * If twice the provided number of elements for the rows exceeds the
     * number of rows in the matrix, then all elements are retained. Similarly,
     * passing None retains all elements.
     *
     * ```
     * use std::num::NonZeroUsize;
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::{MatrixView, MatrixMask};
     * let matrix = Matrix::from_flat_row_major((5, 5), (0..25).collect());
     * let start_and_end = MatrixView::from(
     *     MatrixMask::start_and_end_of_rows(
     *         matrix, NonZeroUsize::new(1)
     *     )
     * );
     * assert_eq!(
     *     start_and_end,
     *     Matrix::from_flat_row_major((2, 5), vec![
     *          0,  1,  2,  3,  4,
     *         20, 21, 22, 23, 24,
     *     ])
     * );
     * ```
     */
    pub fn start_and_end_of_rows(source: S, retain: Option<NonZeroUsize>) -> MatrixMask<T, S> {
        let rows = match retain {
            None => IndexRange::new(0, 0),
            Some(x) => {
                let x = x.get();
                let length = source.view_rows();
                let retain_start = std::cmp::min(x, length - 1);
                let retain_end = length.saturating_sub(x);
                let mut range: IndexRange = (retain_start..retain_end).into();
                range.clip(length - 1);
                range
            }
        };
        let columns = IndexRange::new(0, 0);
        MatrixMask::from(source, rows, columns)
    }

    /**
     * Creates a MatrixMask of this source that retains only the specified
     * number of elements at both the start and end of the columns.
     * If twice the provided number of elements for the columns exceeds the
     * number of columns in the matrix, then all elements are retained. Similarly,
     * passing None retains all elements.
     *
     * ```
     * use std::num::NonZeroUsize;
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::{MatrixView, MatrixMask};
     * let matrix = Matrix::from_flat_row_major((5, 5), (0..25).collect());
     * let start_and_end = MatrixView::from(
     *     MatrixMask::start_and_end_of_columns(
     *         matrix, NonZeroUsize::new(1)
     *     )
     * );
     * assert_eq!(
     *     start_and_end,
     *     Matrix::from_flat_row_major((5, 2), vec![
     *          0,  4,
     *          5,  9,
     *         10, 14,
     *         15, 19,
     *         20, 24,
     *     ])
     * );
     * ```
     */
    pub fn start_and_end_of_columns(source: S, retain: Option<NonZeroUsize>) -> MatrixMask<T, S> {
        let rows = IndexRange::new(0, 0);
        let columns = match retain {
            None => IndexRange::new(0, 0),
            Some(x) => {
                let x = x.get();
                let length = source.view_columns();
                let retain_start = std::cmp::min(x, length - 1);
                let retain_end = length.saturating_sub(x);
                let mut range: IndexRange = (retain_start..retain_end).into();
                range.clip(length - 1);
                range
            }
        };
        MatrixMask::from(source, rows, columns)
    }

    /**
     * Consumes the MatrixMask, yielding the source it was created from.
     */
    #[allow(dead_code)]
    pub fn source(self) -> S {
        self.source
    }

    /**
     * Gives a reference to the MatrixMask's source (in which the data is not masked).
     */
    // # Safety
    //
    // Giving out a mutable reference to our source could allow it to be changed out from under us
    // and make our mask checks invalid. However, since the source implements MatrixRef
    // interior mutability is not allowed, so we can give out shared references without breaking
    // our own integrity.
    #[allow(dead_code)]
    pub fn source_ref(&self) -> &S {
        &self.source
    }
}

/**
 * A range bounded between `start` inclusive and `start + length` exclusive.
 *
 * # Examples
 *
 * Converting between [Range](std::ops::Range) and IndexRange.
 * ```
 * use std::ops::Range;
 * use easy_ml::matrices::views::IndexRange;
 * assert_eq!(IndexRange::new(3, 2), (3..5).into());
 * assert_eq!(IndexRange::new(1, 5), (1..6).into());
 * assert_eq!(IndexRange::new(0, 4), (0..4).into());
 * ```
 *
 * Creating a Range
 *
 * ```
 * use easy_ml::matrices::views::IndexRange;
 * let range = IndexRange::new(3, 2);
 * let also_range: IndexRange = (3, 2).into();
 * let also_also_range: IndexRange = [3, 2].into();
 * ```
 *
 * NB: You can construct an IndexRange where start+length exceeds isize::MAX or even
 * usize::MAX, however matrices and tensors themselves cannot contain more than isize::MAX
 * elements. Concerned readers should note that on a 64 bit computer this maximum
 * value is 9,223,372,036,854,775,807 so running out of memory is likely to occur first.
 */
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IndexRange {
    pub(crate) start: usize,
    pub(crate) length: usize,
}

impl IndexRange {
    pub fn new(start: usize, length: usize) -> IndexRange {
        IndexRange { start, length }
    }

    // TODO: If we make these public we need to disambiguate Range from Mask behaviour better
    /**
     * Maps from a coordinate space of the ith index accessible by this range to the actual index
     * into the entire dimension's data.
     */
    #[inline]
    pub(crate) fn map(&self, index: usize) -> Option<usize> {
        if index < self.length {
            Some(index + self.start)
        } else {
            None
        }
    }

    // NOTE: This doesn't perform bounds checks, adding the length of the mask could push
    // the index out of the valid bounds of the dimension it is for, but if we performed
    // bounds checks here they would be redundant since performing the get with the masked index
    // will bounds check if required
    #[inline]
    pub(crate) fn mask(&self, index: usize) -> usize {
        if index < self.start {
            index
        } else {
            index + self.length
        }
    }

    // Clips the range or mask to not exceed an index. Note, this may yield 0 length ranges
    // that have non zero starting positions, however map and mask will still calculate correctly.
    pub(crate) fn clip(&mut self, max_index: usize) {
        let end = self.start + self.length;
        let end = std::cmp::min(end, max_index);
        let length = end.saturating_sub(self.start);
        self.length = length;
    }
}

/**
 * Converts from a range of start..end to an IndexRange of start and length
 *
 * NOTE: In previous versions (<=1.8.1) this did not saturate when attempting to subtract the
 * start of the range from the end to calculate the length. It will now correctly produce an
 * IndexRange with a length of 0 if the end is before or equal to the start.
 */
impl From<Range<usize>> for IndexRange {
    fn from(range: Range<usize>) -> IndexRange {
        IndexRange::new(range.start, range.end.saturating_sub(range.start))
    }
}

/** Converts from an IndexRange of start and length to a range of start..end */
impl From<IndexRange> for Range<usize> {
    fn from(range: IndexRange) -> Range<usize> {
        Range {
            start: range.start,
            end: range.start + range.length,
        }
    }
}

/**
 * Converts from a tuple of start and length to an IndexRange
 *
 * NOTE: In previous versions (<=1.8.1), this was erroneously implemented as conversion from a
 * tuple of start and end, not start and length as documented.
 */
impl From<(usize, usize)> for IndexRange {
    fn from(range: (usize, usize)) -> IndexRange {
        let (start, length) = range;
        IndexRange::new(start, length)
    }
}

/**
 * Converts from an array of start and length to an IndexRange
 *
 * NOTE: In previous versions (<=1.8.1), this was erroneously implemented as conversion from an
 * array of start and end, not start and length as documented.
 */
impl From<[usize; 2]> for IndexRange {
    fn from(range: [usize; 2]) -> IndexRange {
        let [start, length] = range;
        IndexRange::new(start, length)
    }
}

#[test]
fn test_index_range_clipping() {
    let mut range: IndexRange = (0..6).into();
    range.clip(4);
    assert_eq!(range, (0..4).into());
    let mut range: IndexRange = (1..4).into();
    range.clip(5);
    assert_eq!(range, (1..4).into());
    range.clip(2);
    assert_eq!(range, (1..2).into());
    let mut range: IndexRange = (3..5).into();
    range.clip(2);
    assert_eq!(range, (3..2).into());
    assert_eq!(range.map(0), None);
    assert_eq!(range.map(1), None);
    assert_eq!(range.mask(0), 0);
    assert_eq!(range.mask(1), 1);
}

// # Safety
//
// Since the MatrixRef we own must implement MatrixRef correctly, so do we by delegating to it,
// as we don't introduce any interior mutability.
/**
 * A MatrixRange of a MatrixRef type implements MatrixRef.
 */
unsafe impl<T, S> MatrixRef<T> for MatrixRange<T, S>
where
    S: MatrixRef<T>,
{
    fn try_get_reference(&self, row: Row, column: Column) -> Option<&T> {
        let row = self.rows.map(row)?;
        let column = self.columns.map(column)?;
        self.source.try_get_reference(row, column)
    }

    fn view_rows(&self) -> Row {
        self.rows.length
    }

    fn view_columns(&self) -> Column {
        self.columns.length
    }

    unsafe fn get_reference_unchecked(&self, row: Row, column: Column) -> &T {
        unsafe {
            // It is the caller's responsibiltiy to always call with row/column indexes in range,
            // therefore the unwrap() case should never happen because on an arbitary MatrixRef
            // it would be undefined behavior.
            let row = self.rows.map(row).unwrap();
            let column = self.columns.map(column).unwrap();
            self.source.get_reference_unchecked(row, column)
        }
    }

    fn data_layout(&self) -> DataLayout {
        self.source.data_layout()
    }
}

// # Safety
//
// Since the MatrixMut we own must implement MatrixMut correctly, so do we by delegating to it,
// as we don't introduce any interior mutability.
/**
 * A MatrixRange of a MatrixMut type implements MatrixMut.
 */
unsafe impl<T, S> MatrixMut<T> for MatrixRange<T, S>
where
    S: MatrixMut<T>,
{
    fn try_get_reference_mut(&mut self, row: Row, column: Column) -> Option<&mut T> {
        let row = self.rows.map(row)?;
        let column = self.columns.map(column)?;
        self.source.try_get_reference_mut(row, column)
    }

    unsafe fn get_reference_unchecked_mut(&mut self, row: Row, column: Column) -> &mut T {
        unsafe {
            // It is the caller's responsibility to always call with row/column indexes in range,
            // therefore the unwrap() case should never happen because on an arbitary MatrixRef
            // it would be undefined behavior.
            let row = self.rows.map(row).unwrap();
            let column = self.columns.map(column).unwrap();
            self.source.get_reference_unchecked_mut(row, column)
        }
    }
}

// # Safety
//
// Since the NoInteriorMutability we own must implement NoInteriorMutability correctly, so
// do we by delegating to it, as we don't introduce any interior mutability.
/**
 * A MatrixRange of a NoInteriorMutability type implements NoInteriorMutability.
 */
unsafe impl<T, S> NoInteriorMutability for MatrixRange<T, S> where S: NoInteriorMutability {}

#[test]
fn test_matrix_range_shape_clips() {
    use crate::matrices::Matrix;
    let matrix = Matrix::from(vec![vec![1, 2, 3], vec![4, 5, 6]]);
    let range = MatrixRange::from(&matrix, 0..7, 1..4);
    assert_eq!(2, range.view_rows());
    assert_eq!(2, range.view_columns());
    assert_eq!(2, range.rows.length);
    assert_eq!(2, range.columns.length);
}

// # Safety
//
// Since the MatrixRef we own must implement MatrixRef correctly, so do we by delegating to it,
// as we don't introduce any interior mutability.
/**
 * A MatrixMask of a MatrixRef type implements MatrixRef.
 */
unsafe impl<T, S> MatrixRef<T> for MatrixMask<T, S>
where
    S: MatrixRef<T>,
{
    fn try_get_reference(&self, row: Row, column: Column) -> Option<&T> {
        let row = self.rows.mask(row);
        let column = self.columns.mask(column);
        self.source.try_get_reference(row, column)
    }

    fn view_rows(&self) -> Row {
        // We enforce in the constructor that the mask is clipped to the size of our actual
        // matrix, hence the mask cannot be longer than our data in either dimension. If the
        // mask is the same length as our data, we'd return 0 which for MatrixRef is allowed.
        self.source.view_rows() - self.rows.length
    }

    fn view_columns(&self) -> Column {
        // We enforce in the constructor that the mask is clipped to the size of our actual
        // matrix, hence the mask cannot be longer than our data in either dimension. If the
        // mask is the same length as our data, we'd return 0 which for MatrixRef is allowed.
        self.source.view_columns() - self.columns.length
    }

    unsafe fn get_reference_unchecked(&self, row: Row, column: Column) -> &T {
        unsafe {
            // It is the caller's responsibility to always call with row/column indexes in range,
            // therefore calling get_reference_unchecked with indexes beyond the size of the matrix
            // should never happen because on an arbitary MatrixRef it would be undefined behavior.
            let row = self.rows.mask(row);
            let column = self.columns.mask(column);
            self.source.get_reference_unchecked(row, column)
        }
    }

    fn data_layout(&self) -> DataLayout {
        self.source.data_layout()
    }
}

// # Safety
//
// Since the MatrixMut we own must implement MatrixMut correctly, so do we by delegating to it,
// as we don't introduce any interior mutability.
/**
 * A MatrixMask of a MatrixMut type implements MatrixMut.
 */
unsafe impl<T, S> MatrixMut<T> for MatrixMask<T, S>
where
    S: MatrixMut<T>,
{
    fn try_get_reference_mut(&mut self, row: Row, column: Column) -> Option<&mut T> {
        let row = self.rows.mask(row);
        let column = self.columns.mask(column);
        self.source.try_get_reference_mut(row, column)
    }

    unsafe fn get_reference_unchecked_mut(&mut self, row: Row, column: Column) -> &mut T {
        unsafe {
            // It is the caller's responsibility to always call with row/column indexes in range,
            // therefore calling get_reference_unchecked with indexes beyond the size of the matrix
            // should never happen because on an arbitary MatrixRef it would be undefined behavior.
            let row = self.rows.mask(row);
            let column = self.columns.mask(column);
            self.source.get_reference_unchecked_mut(row, column)
        }
    }
}

// # Safety
//
// Since the NoInteriorMutability we own must implement NoInteriorMutability correctly, so
// do we by delegating to it, as we don't introduce any interior mutability.
/**
 * A MatrixMask of a NoInteriorMutability type implements NoInteriorMutability.
 */
unsafe impl<T, S> NoInteriorMutability for MatrixMask<T, S> where S: NoInteriorMutability {}