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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
/*!
 * Generic views into a matrix.
 *
 * The concept of a view into a matrix is built from the low level [MatrixRef] and
 * [MatrixMut] traits which define having read and read/write access to Matrix data
 * respectively, and the high level API implemented on the [MatrixView] struct.
 *
 * Since a Matrix is itself a MatrixRef, the APIs for the traits are purposefully verbose to
 * avoid name clashes with methods defined on the Matrix and MatrixView types. You should
 * typically use MatrixRef and MatrixMut implementations via the MatrixView struct which provides
 * an API closely resembling Matrix.
 *
 * # Examples
 *
 * [Using trait objects with MatrixViews](erased)
 */

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

use crate::matrices::iterators::*;
use crate::matrices::{Column, Matrix, Row};

pub mod erased;
mod map;
mod partitions;
mod ranges;
mod reverse;
pub mod traits;

pub(crate) use map::*;
pub use partitions::*;
pub use ranges::*;
pub use reverse::*;

/**
* A shared/immutable reference to a matrix (or a portion of it) of some type.
*
* # Indexing
*
* Valid indexes into a MatrixRef range from 0 inclusive to `view_rows` exclusive for rows and
* from 0 inclusive to `view_columns` exclusive for columns. Even if a 4x4 matrix creates some
* 2x2 MatrixRef that can view only its center, the indexes used on the MatrixRef would be
* 0,0 to 1,1, not 1,1 to 2,2 as corresponding on the matrix. If the view_rows or view_columns are
* 0 then the MatrixRef has no valid indexes.
*
* # Safety
*
* In order to support returning references without bounds checking in a useful way, the
* implementing type is required to uphold several invariants.
*
* 1 - Any valid index as described in Indexing will yield a safe reference when calling
* `get_reference_unchecked` and `get_reference_unchecked_mut`.
*
* 2 - The `view_rows`/`view_columns` that define which indexes are valid may not
* be changed by a shared reference to the MatrixRef implementation. ie, the matrix may
* not be resized while a mutable reference is held to it, except by that reference.
*
* **NB: Version 2 of Easy ML makes NoInteriorMutability a supertrait of MatrixRef.** It is
* no longer possible to implement MatrixRef with interior mutability, which matches the
* 1.x TensorRef trait requirements. In a future major version, NoInteriorMutability will be removed
* and folded into the documentation on MatrixRef.
*
* Essentially, interior mutability causes problems, since code looping through the range of valid
* indexes in a MatrixRef needs to be able to rely on that range of valid indexes not changing.
* This is trivially the case by default since a [Matrix] does not have any form of
* interior mutability, and therefore an iterator holding a shared reference to a Matrix prevents
* that matrix being resized. However, a type *wrongly* implementing MatrixRef could introduce
* interior mutability by putting the Matrix in an `Arc<Mutex<>>` which would allow another thread
* to resize a matrix while an iterator was looping through previously valid indexes on a different
* thread.
*
* Note that it is okay to be able to resize any MatrixRef implementation if that always requires
* an exclusive reference to the MatrixRef/Matrix, since the exclusivity prevents the above
* scenario.
*/
pub unsafe trait MatrixRef<T>: NoInteriorMutability {
    /**
     * Gets a reference to the value at the index if the index is in range. Otherwise returns None.
     */
    fn try_get_reference(&self, row: Row, column: Column) -> Option<&T>;

    /**
     * The number of rows that this reference can view. This may be less than the actual number of
     * rows of data stored in the matrix implementation, and could be 0.
     */
    fn view_rows(&self) -> Row;

    /**
     * The number of columns that this reference can view. This may be less than the actual number
     * of columns of data stored in the matrix implementation, and could be 0.
     */
    fn view_columns(&self) -> Column;

    /**
     * Gets a reference to the value at the index without doing any bounds checking. For a safe
     * alternative see [try_get_reference](MatrixRef::try_get_reference).
     *
     * # Safety
     *
     * Calling this method with an out-of-bounds index is *[undefined behavior]* even if the
     * resulting reference is not used. Valid indexes are defined as in [MatrixRef].
     *
     * [undefined behavior]: <https://doc.rust-lang.org/reference/behavior-considered-undefined.html>
     * [MatrixRef]: MatrixRef
     */
    #[allow(clippy::missing_safety_doc)] // it's not missing
    unsafe fn get_reference_unchecked(&self, row: Row, column: Column) -> &T;

    /**
     * A hint for the data layout this MatrixView uses to store its data.
     *
     * See [Matrix layout and iterator performance](crate::matrices::iterators#matrix-layout-and-iterator-performance)
     */
    fn data_layout(&self) -> DataLayout;
}

/**
 * A unique/mutable reference to a matrix (or a portion of it) of some type.
 *
 * # Safety
 *
 * See [MatrixRef].
 */
pub unsafe trait MatrixMut<T>: MatrixRef<T> {
    /**
     * Gets a mutable reference to the value at the index, if the index is in range. Otherwise
     * returns None.
     */
    fn try_get_reference_mut(&mut self, row: Row, column: Column) -> Option<&mut T>;

    /**
     * Gets a mutable reference to the value at the index without doing any bounds checking.
     * For a safe alternative see [try_get_reference_mut](MatrixMut::try_get_reference_mut).
     *
     * # Safety
     *
     * Calling this method with an out-of-bounds index is *[undefined behavior]* even if the
     * resulting reference is not used. Valid indexes are defined as in [MatrixRef].
     *
     * [undefined behavior]: <https://doc.rust-lang.org/reference/behavior-considered-undefined.html>
     * [MatrixRef]: MatrixRef
     */
    #[allow(clippy::missing_safety_doc)] // it's not missing
    unsafe fn get_reference_unchecked_mut(&mut self, row: Row, column: Column) -> &mut T;
}

/**
 * A marker trait that promises that the implementing type does not permit interior mutability.
 *
 * When combined with [MatrixRef] or [MatrixMut], other code can rely on
 * the type not being resizable or otherwise mutated through a shared reference.
 *
 * NB: This requirement is mandatory from Easy ML 2.0 to implement MatrixView.
 *
 * # Safety
 *
 * Implementing types must ensure that their internal state cannot be changed through a shared
 * reference to them.
 */
pub unsafe trait NoInteriorMutability {}

/**
 * The [data layout] used for storing the 2 dimensional data of a MatrixView.
 *
 * [data layout]: https://en.wikipedia.org/wiki/Row-_and_column-major_order
 */
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum DataLayout {
    RowMajor,
    ColumnMajor,
    Other,
}

/**
 * A view into some or all of a matrix.
 *
 * A MatrixView has a similar relationship to a [`Matrix`] as a
 * `&str` has to a `String`, or an array slice to an array. A MatrixView cannot resize
 * its source, and may span only a portion of the source Matrix in each dimension.
 *
 * However a MatrixView is generic not only over the type of the data in the Matrix,
 * but also over the way the Matrix is 'sliced' and the two are orthogonal to each other.
 *
 * MatrixView closely mirrors the API of Matrix, minus resizing methods which are not available.
 * Methods that create a new matrix do not return a MatrixView, they return a Matrix.
 */
#[derive(Clone, Debug)]
pub struct MatrixView<T, S> {
    source: S,
    _type: PhantomData<T>,
}

// TODO linear_algebra numeric functions, transpositions

/**
 * MatrixView methods which require only read access via a [MatrixRef] source.
 */
impl<T, S> MatrixView<T, S>
where
    S: MatrixRef<T>,
{
    /**
     * Creates a MatrixView from a source of some type.
     *
     * The lifetime of the source determines the lifetime of the MatrixView created. If the
     * MatrixView is created from a reference to a Matrix, then the MatrixView cannot live
     * longer than the Matrix referenced.
     */
    pub fn from(source: S) -> MatrixView<T, S> {
        MatrixView {
            source,
            _type: PhantomData,
        }
    }

    /**
     * Consumes the matrix view, yielding the source it was created from.
     */
    pub fn source(self) -> S {
        self.source
    }

    /**
     * Gives a reference to the matrix view's source. This should typically not be needed
     * since Easy ML APIs which take [MatrixRef]s as inputs like iterators are
     * already wrapped for you as methods on MatrixView.
     */
    pub fn source_ref(&self) -> &S {
        &self.source
    }

    /**
     * Gives a mutable reference to the matrix view's source. This should typically not be needed
     * since Easy ML APIs which take [MatrixRef]s as inputs like iterators are
     * already wrapped for you as methods on MatrixView.
     */
    pub fn source_ref_mut(&mut self) -> &mut S {
        &mut self.source
    }

    /**
     * Returns the dimensionality of this matrix view in Row, Column format
     */
    pub fn size(&self) -> (Row, Column) {
        (self.rows(), self.columns())
    }

    /**
     * Gets the number of rows visible to this matrix view.
     */
    pub fn rows(&self) -> Row {
        self.source.view_rows()
    }

    /**
     * Gets the number of columns visible to this matrix view.
     */
    pub fn columns(&self) -> Column {
        self.source.view_columns()
    }

    /**
     * Gets the data layout this MatrixView's source uses to store its data.
     *
     * See [Matrix layout and iterator performance](crate::matrices::iterators#matrix-layout-and-iterator-performance)
     */
    pub fn data_layout(&self) -> DataLayout {
        self.source.data_layout()
    }

    /**
     * Gets a reference to the value at this row and column. Rows and Columns are 0 indexed.
     *
     * # Panics
     *
     * Panics if the index is out of range.
     */
    #[track_caller]
    pub fn get_reference(&self, row: Row, column: Column) -> &T {
        match self.source.try_get_reference(row, column) {
            Some(reference) => reference,
            None => panic!(
                "Index ({},{}) not in range, MatrixView range is (0,0) to ({},{}).",
                row,
                column,
                self.rows(),
                self.columns()
            ),
        }
    }

    /**
     * Gets a reference to the value at the row and column if the index is in range.
     * Otherwise returns None.
     */
    pub fn try_get_reference(&self, row: Row, column: Column) -> Option<&T> {
        self.source.try_get_reference(row, column)
    }

    /**
     * Gets a reference to the value at the index without doing any bounds checking. For a safe
     * alternative see [try_get_reference](MatrixView::try_get_reference).
     *
     * # Safety
     *
     * Calling this method with an out-of-bounds index is *[undefined behavior]* even if the
     * resulting reference is not used. Valid indexes are defined as in [MatrixRef].
     *
     * [undefined behavior]: <https://doc.rust-lang.org/reference/behavior-considered-undefined.html>
     * [MatrixRef]: MatrixRef
     */
    #[allow(clippy::missing_safety_doc)] // it's not missing
    pub unsafe fn get_reference_unchecked(&self, row: Row, column: Column) -> &T {
        unsafe { self.source.get_reference_unchecked(row, column) }
    }

    /**
     * Returns an iterator over references to a column vector in this matrix view.
     * Columns are 0 indexed.
     *
     * # Panics
     *
     * Panics if the column is not visible to this view.
     */
    #[track_caller]
    pub fn column_reference_iter(&self, column: Column) -> ColumnReferenceIterator<'_, T, S> {
        ColumnReferenceIterator::from(&self.source, column)
    }

    /**
     * Returns an iterator over references to a row vector in this matrix view.
     * Rows are 0 indexed.
     *
     * # Panics
     *
     * Panics if the row is not visible to this view.
     */
    #[track_caller]
    pub fn row_reference_iter(&self, row: Row) -> RowReferenceIterator<'_, T, S> {
        RowReferenceIterator::from(&self.source, row)
    }

    /**
     * Returns a column major iterator over references to all values in this matrix view,
     * proceeding through each column in order.
     */
    pub fn column_major_reference_iter(&self) -> ColumnMajorReferenceIterator<'_, T, S> {
        ColumnMajorReferenceIterator::from(&self.source)
    }

    /**
     * Returns a row major iterator over references to all values in this matrix view,
     * proceeding through each row in order.
     */
    pub fn row_major_reference_iter(&self) -> RowMajorReferenceIterator<'_, T, S> {
        RowMajorReferenceIterator::from(&self.source)
    }

    /**
     * Returns an iterator over references to the main diagonal in this matrix view.
     */
    pub fn diagonal_reference_iter(&self) -> DiagonalReferenceIterator<'_, T, S> {
        DiagonalReferenceIterator::from(&self.source)
    }

    /**
     * Returns a MatrixView giving a view of only the data within the row and column
     * [IndexRange]s.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::range`](Matrix::range).
     */
    pub fn range<R>(&self, rows: R, columns: R) -> MatrixView<T, MatrixRange<T, &S>>
    where
        R: Into<IndexRange>,
    {
        MatrixView::from(MatrixRange::from(&self.source, rows, columns))
    }

    /**
     * Returns a MatrixView giving a view of only the data within the row and column
     * [IndexRange]s. The MatrixRange mutably borrows the source, and can therefore
     * mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::range`](Matrix::range).
     */
    pub fn range_mut<R>(&mut self, rows: R, columns: R) -> MatrixView<T, MatrixRange<T, &mut S>>
    where
        R: Into<IndexRange>,
    {
        MatrixView::from(MatrixRange::from(&mut self.source, rows, columns))
    }

    /**
     * Returns a MatrixView giving a view of only the data within the row and column
     * [IndexRange]s. The MatrixRange takes ownership of the source, and
     * can therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::range`](Matrix::range).
     */
    pub fn range_owned<R>(self, rows: R, columns: R) -> MatrixView<T, MatrixRange<T, S>>
    where
        R: Into<IndexRange>,
    {
        MatrixView::from(MatrixRange::from(self.source, rows, columns))
    }

    /**
     * Returns a MatrixView giving a view of only the data outside the row and column
     * [IndexRange]s.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::mask`](Matrix::mask).
     */
    pub fn mask<R>(&self, rows: R, columns: R) -> MatrixView<T, MatrixMask<T, &S>>
    where
        R: Into<IndexRange>,
    {
        MatrixView::from(MatrixMask::from(&self.source, rows, columns))
    }

    /**
     * Returns a MatrixView giving a view of only the data outside the row and column
     * [IndexRange]s. The MatrixMask mutably borrows the source, and can therefore
     * mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::mask`](Matrix::mask).
     */
    pub fn mask_mut<R>(&mut self, rows: R, columns: R) -> MatrixView<T, MatrixMask<T, &mut S>>
    where
        R: Into<IndexRange>,
    {
        MatrixView::from(MatrixMask::from(&mut self.source, rows, columns))
    }

    /**
     * Returns a MatrixView giving a view of only the data outside the row and column
     * [IndexRange]s. The MatrixMask takes ownership of the source, and
     * can therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::mask`](Matrix::mask).
     */
    pub fn mask_owned<R>(self, rows: R, columns: R) -> MatrixView<T, MatrixMask<T, S>>
    where
        R: Into<IndexRange>,
    {
        MatrixView::from(MatrixMask::from(self.source, rows, columns))
    }

    /**
     * Returns a MatrixView giving a view of only the data within the provided
     * number of elements to retain at the start and end of the rows in the
     * matrix.
     *
     * This is a shorthand for constructing the MatrixView from this Matrix. See
     * [`Matrix::start_and_end_of_rows`](Matrix::start_and_end_of_rows).
     *
     * # Panics
     *
     * - If the number of elements to retain at the start and end are 0
     */
    #[track_caller]
    pub fn start_and_end_of_rows(&self, retain: usize) -> MatrixView<T, MatrixMask<T, &S>> {
        match NonZeroUsize::new(retain) {
            None => panic!(
                "Number of rows to retain at start and end of matrix view must be at least 1, 0 rows retained would remove all elements"
            ),
            Some(retain) => MatrixView::from(MatrixMask::start_and_end_of_rows(
                &self.source,
                Some(retain),
            )),
        }
    }

    /**
     * Returns a MatrixView giving a view of only the data within the provided
     * number of elements to retain at the start and end of the rows in the
     * matrix. The MatrixMask mutably borrows the source, and can
     * therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this Matrix. See
     * [`Matrix::start_and_end_of_rows`](Matrix::start_and_end_of_rows).
     *
     * # Panics
     *
     * - If the number of elements to retain at the start and end are 0
     */
    #[track_caller]
    pub fn start_and_end_of_rows_mut(
        &mut self,
        retain: usize,
    ) -> MatrixView<T, MatrixMask<T, &mut S>> {
        match NonZeroUsize::new(retain) {
            None => panic!(
                "Number of rows to retain at start and end of matrix view must be at least 1, 0 rows retained would remove all elements"
            ),
            Some(retain) => MatrixView::from(MatrixMask::start_and_end_of_rows(
                &mut self.source,
                Some(retain),
            )),
        }
    }

    /**
     * Returns a MatrixView giving a view of only the data within the provided
     * number of elements to retain at the start and end of the rows in the
     * matrix. The MatrixMask takes ownership of the source, and
     * can therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this Matrix. See
     * [`Matrix::start_and_end_of_rows`](Matrix::start_and_end_of_rows).
     *
     * # Panics
     *
     * - If the number of elements to retain at the start and end are 0
     */
    #[track_caller]
    pub fn start_and_end_of_rows_owned(self, retain: usize) -> MatrixView<T, MatrixMask<T, S>> {
        match NonZeroUsize::new(retain) {
            None => panic!(
                "Number of rows to retain at start and end of matrix view must be at least 1, 0 rows retained would remove all elements"
            ),
            Some(retain) => {
                MatrixView::from(MatrixMask::start_and_end_of_rows(self.source, Some(retain)))
            }
        }
    }

    /**
     * Returns a MatrixView giving a view of only the data within the provided
     * number of elements to retain at the start and end of the columns in the
     * matrix.
     *
     * This is a shorthand for constructing the MatrixView from this Matrix. See
     * [`Matrix::start_and_end_of_columns`](Matrix::start_and_end_of_columns).
     *
     * # Panics
     *
     * - If the number of elements to retain at the start and end are 0
     */
    #[track_caller]
    pub fn start_and_end_of_columns(&self, retain: usize) -> MatrixView<T, MatrixMask<T, &S>> {
        match NonZeroUsize::new(retain) {
            None => panic!(
                "Number of columns to retain at start and end of matrix view must be at least 1, 0 columns retained would remove all elements"
            ),
            Some(retain) => MatrixView::from(MatrixMask::start_and_end_of_columns(
                &self.source,
                Some(retain),
            )),
        }
    }

    /**
     * Returns a MatrixView giving a view of only the data within the provided
     * number of elements to retain at the start and end of the columns in the
     * matrix. The MatrixMask mutably borrows the source, and can
     * therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this Matrix. See
     * [`Matrix::start_and_end_of_columns`](Matrix::start_and_end_of_columns).
     *
     * # Panics
     *
     * - If the number of elements to retain at the start and end are 0
     */
    #[track_caller]
    pub fn start_and_end_of_columns_mut(
        &mut self,
        retain: usize,
    ) -> MatrixView<T, MatrixMask<T, &mut S>> {
        match NonZeroUsize::new(retain) {
            None => panic!(
                "Number of columns to retain at start and end of matrix view must be at least 1, 0 columns retained would remove all elements"
            ),
            Some(retain) => MatrixView::from(MatrixMask::start_and_end_of_columns(
                &mut self.source,
                Some(retain),
            )),
        }
    }

    /**
     * Returns a MatrixView giving a view of only the data within the provided
     * number of elements to retain at the start and end of the columns in the
     * matrix. The MatrixMask takes ownership of the source, and
     * can therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this Matrix. See
     * [`Matrix::start_and_end_of_columns`](Matrix::start_and_end_of_columns).
     *
     * # Panics
     *
     * - If the number of elements to retain at the start and end are 0
     */
    #[track_caller]
    pub fn start_and_end_of_columns_owned(self, retain: usize) -> MatrixView<T, MatrixMask<T, S>> {
        match NonZeroUsize::new(retain) {
            None => panic!(
                "Number of columns to retain at start and end of matrix view must be at least 1, 0 columns retained would remove all elements"
            ),
            Some(retain) => MatrixView::from(MatrixMask::start_and_end_of_columns(
                self.source,
                Some(retain),
            )),
        }
    }

    /**
     * Returns a MatrixView with the rows and columns specified reversed in iteration
     * order. The data of this matrix and the dimension lengths remain unchanged.
     *
     * This is a shorthand for constructing the MatrixView from this matrix. See
     * [`Matrix::reverse`](Matrix::reverse).
     */
    pub fn reverse(&self, reverse: Reverse) -> MatrixView<T, MatrixReverse<T, &S>> {
        MatrixView::from(MatrixReverse::from(&self.source, reverse))
    }

    /**
     * Returns a MatrixView with the rows and columns specified reversed in iteration
     * order. The data of this matrix and the dimension lengths remain unchanged. The MatrixReverse
     * mutably borrows the source, and can therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::reverse`](Matrix::reverse).
     */
    pub fn reverse_mut(&mut self, reverse: Reverse) -> MatrixView<T, MatrixReverse<T, &mut S>> {
        MatrixView::from(MatrixReverse::from(&mut self.source, reverse))
    }

    /**
     * Returns a MatrixView with the rows and columns specified reversed in iteration
     * order. The data of this matrix and the dimension lengths remain unchanged. The MatrixReverse
     * takes ownership of the source, and can therefore mutate it if it implements MatrixMut.
     *
     * This is a shorthand for constructing the MatrixView from this MatrixView. See
     * [`Matrix::reverse`](Matrix::reverse).
     */
    pub fn reverse_owned(self, reverse: Reverse) -> MatrixView<T, MatrixReverse<T, S>> {
        MatrixView::from(MatrixReverse::from(self.source, reverse))
    }
}

/**
 * MatrixView methods which require only read access via a [MatrixRef] source
 * and a clonable type.
 */
impl<T, S> MatrixView<T, S>
where
    T: Clone,
    S: MatrixRef<T>,
{
    /**
     * Gets a copy of the value at this row and column. Rows and Columns are 0 indexed.
     *
     * # Panics
     *
     * Panics if the index is out of range.
     */
    #[track_caller]
    pub fn get(&self, row: Row, column: Column) -> T {
        match self.source.try_get_reference(row, column) {
            Some(reference) => reference.clone(),
            None => panic!(
                "Index ({},{}) not in range, MatrixView range is (0,0) to ({},{}).",
                row,
                column,
                self.rows(),
                self.columns()
            ),
        }
    }

    /**
     * Computes and returns the transpose of this matrix
     *
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::MatrixView;
     * let x = MatrixView::from(Matrix::from(vec![
     *    vec![ 1, 2 ],
     *    vec![ 3, 4 ]]));
     * let y = Matrix::from(vec![
     *    vec![ 1, 3 ],
     *    vec![ 2, 4 ]]);
     * assert_eq!(x.transpose(), y);
     * ```
     */
    pub fn transpose(&self) -> Matrix<T> {
        Matrix::from_fn((self.columns(), self.rows()), |(column, row)| {
            self.get(row, column)
        })
    }

    /**
     * Returns an iterator over a column vector in this matrix view. Columns are 0 indexed.
     *
     * If you have a matrix such as:
     * ```ignore
     * [
     *    1, 2, 3
     *    4, 5, 6
     *    7, 8, 9
     * ]
     * ```
     * then a column of 0, 1, and 2 will yield [1, 4, 7], [2, 5, 8] and [3, 6, 9]
     * respectively. If you do not need to copy the elements use
     * [`column_reference_iter`](MatrixView::column_reference_iter) instead.
     *
     * # Panics
     *
     * Panics if the column does not exist in this matrix.
     */
    #[track_caller]
    pub fn column_iter(&self, column: Column) -> ColumnIterator<'_, T, S> {
        ColumnIterator::from(&self.source, column)
    }

    /**
     * Returns an iterator over a row vector in this matrix view. Rows are 0 indexed.
     *
     * If you have a matrix such as:
     * ```ignore
     * [
     *    1, 2, 3
     *    4, 5, 6
     *    7, 8, 9
     * ]
     * ```
     * then a row of 0, 1, and 2 will yield [1, 2, 3], [4, 5, 6] and [7, 8, 9]
     * respectively. If you do not need to copy the elements use
     * [`row_reference_iter`](MatrixView::row_reference_iter) instead.
     *
     * # Panics
     *
     * Panics if the row does not exist in this matrix.
     */
    #[track_caller]
    pub fn row_iter(&self, row: Row) -> RowIterator<'_, T, S> {
        RowIterator::from(&self.source, row)
    }

    /**
     * Returns a column major iterator over all values in this matrix view, proceeding through each
     * column in order.
     *
     * If you have a matrix such as:
     * ```ignore
     * [
     *    1, 2
     *    3, 4
     * ]
     * ```
     * then the iterator will yield [1, 3, 2, 4]. If you do not need to copy the
     * elements use [`column_major_reference_iter`](MatrixView::column_major_reference_iter)
     * instead.
     */
    pub fn column_major_iter(&self) -> ColumnMajorIterator<'_, T, S> {
        ColumnMajorIterator::from(&self.source)
    }

    /**
     * Returns a row major iterator over all values in this matrix view, proceeding through each
     * row in order.
     *
     * If you have a matrix such as:
     * ```ignore
     * [
     *    1, 2
     *    3, 4
     * ]
     * ```
     * then the iterator will yield [1, 2, 3, 4]. If you do not need to copy the
     * elements use [`row_major_reference_iter`](MatrixView::row_major_reference_iter) instead.
     */
    pub fn row_major_iter(&self) -> RowMajorIterator<'_, T, S> {
        RowMajorIterator::from(&self.source)
    }

    /**
     * Returns a iterator over the main diagonal of this matrix view.
     *
     * If you have a matrix such as:
     * ```ignore
     * [
     *    1, 2
     *    3, 4
     * ]
     * ```
     * then the iterator will yield [1, 4]. If you do not need to copy the
     * elements use [`diagonal_reference_iter`](MatrixView::diagonal_reference_iter) instead.
     *
     * # Examples
     *
     * Computing a [trace](https://en.wikipedia.org/wiki/Trace_(linear_algebra))
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::MatrixView;
     * let view = MatrixView::from(Matrix::from(vec![
     *     vec![ 1, 2, 3 ],
     *     vec![ 4, 5, 6 ],
     *     vec![ 7, 8, 9 ],
     * ]));
     * let trace: i32 = view.diagonal_iter().sum();
     * assert_eq!(trace, 1 + 5 + 9);
     * ```
     */
    pub fn diagonal_iter(&self) -> DiagonalIterator<'_, T, S> {
        DiagonalIterator::from(&self.source)
    }

    /**
     * Creates and returns a new matrix with all values from the original with the
     * function applied to each.
     *
     * # Exmples
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::MatrixView;
     * let x = MatrixView::from(Matrix::from(vec![
     *    vec![ 0.0, 1.2 ],
     *    vec![ 5.8, 6.9 ]]));
     * let y = x.map(|element| element > 2.0);
     * let result = Matrix::from(vec![
     *    vec![ false, false ],
     *    vec![ true, true ]]);
     * assert_eq!(&y, &result);
     * ```
     */
    pub fn map<U>(&self, mapping_function: impl Fn(T) -> U) -> Matrix<U>
    where
        U: Clone,
    {
        let mapped = self.row_major_iter().map(mapping_function).collect();
        Matrix::from_flat_row_major(self.size(), mapped)
    }

    /**
     * Creates and returns a new matrix with all values from the original
     * and the index of each value mapped by a function. This can be used
     * to perform elementwise operations that are not defined on the
     * Matrix type itself.
     */
    pub fn map_with_index<U>(&self, mapping_function: impl Fn(T, Row, Column) -> U) -> Matrix<U>
    where
        U: Clone,
    {
        let mapped = self
            .row_major_iter()
            .with_index()
            .map(|((i, j), x)| mapping_function(x, i, j))
            .collect();
        Matrix::from_flat_row_major(self.size(), mapped)
    }
}

/**
 * MatrixView methods which require mutable access via a [MatrixMut] source.
 */
impl<T, S> MatrixView<T, S>
where
    S: MatrixMut<T>,
{
    /**
     * Gets a mutable reference to the value at this row and column.
     * Rows and Columns are 0 indexed.
     *
     * # Panics
     *
     * Panics if the index is out of range.
     */
    #[track_caller]
    pub fn get_reference_mut(&mut self, row: Row, column: Column) -> &mut T {
        let size = self.size();
        // borrow for size ends
        match self.source.try_get_reference_mut(row, column) {
            Some(reference) => reference,
            None => panic!(
                "Index ({},{}) not in range, MatrixView range is (0,0) to ({},{}).",
                row, column, size.0, size.1
            ),
        }
    }

    /**
     * Sets a new value to this row and column. Rows and Columns are 0 indexed.
     *
     * # Panics
     *
     * Panics if the index is out of range.
     */
    #[track_caller]
    pub fn set(&mut self, row: Row, column: Column, value: T) {
        match self.source.try_get_reference_mut(row, column) {
            Some(reference) => *reference = value,
            None => panic!(
                "Index ({},{}) not in range, MatrixView range is (0,0) to ({},{}).",
                row,
                column,
                self.rows(),
                self.columns()
            ),
        }
    }

    /**
     * Gets a mutable reference to the value at the row and column if the index is in range.
     * Otherwise returns None.
     */
    pub fn try_get_reference_mut(&mut self, row: Row, column: Column) -> Option<&mut T> {
        self.source.try_get_reference_mut(row, column)
    }

    /**
     * Gets a mutable reference to the value at the index without doing any bounds checking.
     * For a safe alternative see [try_get_reference_mut](MatrixView::try_get_reference_mut).
     *
     * # Safety
     *
     * Calling this method with an out-of-bounds index is *[undefined behavior]* even if the
     * resulting reference is not used. Valid indexes are defined as in [MatrixRef].
     *
     * [undefined behavior]: <https://doc.rust-lang.org/reference/behavior-considered-undefined.html>
     * [MatrixRef]: MatrixRef
     */
    #[allow(clippy::missing_safety_doc)] // it's not missing
    pub unsafe fn get_reference_unchecked_mut(&mut self, row: Row, column: Column) -> &mut T {
        unsafe { self.source.get_reference_unchecked_mut(row, column) }
    }
}

/**
 * MatrixView methods which require mutable access via a [MatrixMut] source and
 * no interior mutability.
 */
impl<T, S> MatrixView<T, S>
where
    S: MatrixMut<T> + NoInteriorMutability,
{
    /**
     * Returns an iterator over mutable references to a column vector in this matrix view.
     * Columns are 0 indexed.
     *
     * # Panics
     *
     * Panics if the column is not visible to this view.
     */
    #[track_caller]
    pub fn column_reference_mut_iter(
        &mut self,
        column: Column,
    ) -> ColumnReferenceMutIterator<'_, T, S> {
        ColumnReferenceMutIterator::from(&mut self.source, column)
    }

    /**
     * Returns an iterator over mutable references to a row vector in this matrix view.
     * Rows are 0 indexed.
     *
     * # Panics
     *
     * Panics if the row is not visible to this view.
     */
    #[track_caller]
    pub fn row_reference_mut_iter(&mut self, row: Row) -> RowReferenceMutIterator<'_, T, S> {
        RowReferenceMutIterator::from(&mut self.source, row)
    }

    /**
     * Returns a column major iterator over mutable references to all values in this matrix view,
     * proceeding through each column in order.
     */
    pub fn column_major_reference_mut_iter(&mut self) -> ColumnMajorReferenceMutIterator<'_, T, S> {
        ColumnMajorReferenceMutIterator::from(&mut self.source)
    }

    /**
     * Returns a row major iterator over mutable references to all values in this matrix view,
     * proceeding through each row in order.
     */
    pub fn row_major_reference_mut_iter(&mut self) -> RowMajorReferenceMutIterator<'_, T, S> {
        RowMajorReferenceMutIterator::from(&mut self.source)
    }

    /**
     * Returns an iterator over mutable references to the main diagonal in this matrix view.
     */
    pub fn diagonal_reference_mut_iter(&mut self) -> DiagonalReferenceMutIterator<'_, T, S> {
        DiagonalReferenceMutIterator::from(&mut self.source)
    }
}

/**
 * MatrixView methods which require mutable access via a [MatrixMut] source
 * and a clonable type.
 */
impl<T, S> MatrixView<T, S>
where
    T: Clone,
    S: MatrixMut<T>,
{
    /**
     * Applies a function to all values in the matrix view, modifying the source in place.
     *
     * # Examples
     *
     * ```
     * use easy_ml::matrices::Matrix;
     * use easy_ml::matrices::views::MatrixView;
     * let mut matrix = Matrix::from(vec![
     *    vec![ 0.0, 1.2 ],
     *    vec![ 5.8, 6.9 ]]);
     * {
     *    let mut view = MatrixView::from(&mut matrix);
     *    view.map_mut(|x| x + 1.0);
     * }
     * let result = Matrix::from(vec![
     *    vec![ 1.0, 2.2 ],
     *    vec![ 6.8, 7.9 ]]);
     * assert_eq!(result, matrix);
     */
    pub fn map_mut(&mut self, mapping_function: impl Fn(T) -> T) {
        self.map_mut_with_index(|x, _, _| mapping_function(x))
    }

    /**
     * Applies a function to all values and each value's index in the matrix view,
     * modifying the source in place.
     */
    pub fn map_mut_with_index(&mut self, mapping_function: impl Fn(T, Row, Column) -> T) {
        match self.data_layout() {
            DataLayout::ColumnMajor => {
                self.column_major_reference_mut_iter()
                    .with_index()
                    .for_each(|((i, j), x)| {
                        *x = mapping_function(x.clone(), i, j);
                    });
            }
            _ => {
                self.row_major_reference_mut_iter()
                    .with_index()
                    .for_each(|((i, j), x)| {
                        *x = mapping_function(x.clone(), i, j);
                    });
            }
        }
    }
}

// Common formatting logic used for Matrix and MatrixView Display implementations
pub(crate) fn format_view<T, S>(view: &S, f: &mut std::fmt::Formatter) -> std::fmt::Result
where
    T: std::fmt::Display,
    S: MatrixRef<T>,
{
    let rows = view.view_rows();
    let columns = view.view_columns();
    // It would be nice to default to some precision for f32 and f64 but I can't
    // work out how to easily check if T matches. If we use precision for all T
    // then strings get truncated which is even worse for debugging.
    write!(f, "[ ")?;
    for row in 0..rows {
        if row > 0 {
            write!(f, "  ")?;
        }
        for column in 0..columns {
            let value = match view.try_get_reference(row, column) {
                Some(x) => x,
                None => panic!(
                    "Expected ({},{}) to be in range of (0,0) to ({},{})",
                    row, column, rows, columns
                ),
            };
            match f.precision() {
                Some(precision) => write!(f, "{:.*}", precision, value)?,
                None => write!(f, "{}", value)?,
            };
            if column < columns - 1 {
                write!(f, ", ")?;
            }
        }
        if row < rows - 1 {
            writeln!(f)?;
        }
    }
    write!(f, " ]")
}

/**
 * Any matrix view of a Displayable type implements Display
 *
 * You can control the precision of the formatting using format arguments, i.e.
 * `format!("{:.3}", matrix)`
 */
impl<T, S> std::fmt::Display for MatrixView<T, S>
where
    T: std::fmt::Display,
    S: MatrixRef<T>,
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        format_view(&self.source, f)
    }
}

#[test]
fn printing_matrices() {
    use crate::matrices::Matrix;
    let view = MatrixView::from(Matrix::from(vec![vec![1.0, 2.0], vec![3.0, 4.0]]));
    let formatted = format!("{:.3}", view);
    assert_eq!("[ 1.000, 2.000\n  3.000, 4.000 ]", formatted);
    assert_eq!("[ 1, 2\n  3, 4 ]", view.to_string());
}

// Common matrix equality definition
#[inline]
pub(crate) fn matrix_equality<T, S1, S2>(left: &S1, right: &S2) -> bool
where
    T: PartialEq,
    S1: MatrixRef<T>,
    S2: MatrixRef<T>,
{
    if left.view_rows() != right.view_rows() {
        return false;
    }
    if left.view_columns() != right.view_columns() {
        return false;
    }
    // perform elementwise check, return true only if every element in
    // each matrix is the same
    match (left.data_layout(), right.data_layout()) {
        (DataLayout::ColumnMajor, DataLayout::ColumnMajor) => {
            ColumnMajorReferenceIterator::from(left)
                .zip(ColumnMajorReferenceIterator::from(right))
                .all(|(x, y)| x == y)
        }
        _ => RowMajorReferenceIterator::from(left)
            .zip(RowMajorReferenceIterator::from(right))
            .all(|(x, y)| x == y),
    }
}

/**
 * PartialEq is implemented as two matrix views are equal if and only if all their elements
 * are equal and they have the same size. Differences in their source types are ignored.
 */
impl<T, S1, S2> PartialEq<MatrixView<T, S2>> for MatrixView<T, S1>
where
    T: PartialEq,
    S1: MatrixRef<T>,
    S2: MatrixRef<T>,
{
    #[inline]
    fn eq(&self, other: &MatrixView<T, S2>) -> bool {
        matrix_equality(&self.source, &other.source)
    }
}

/**
 * A MatrixView and a Matrix can be compared for equality. PartialEq is implemented as they are
 * equal if and only if all their elements are equal and they have the same size.
 */
impl<T, S> PartialEq<Matrix<T>> for MatrixView<T, S>
where
    T: PartialEq,
    S: MatrixRef<T>,
{
    #[inline]
    fn eq(&self, other: &Matrix<T>) -> bool {
        matrix_equality(&self.source, &other)
    }
}

/**
 * A Matrix and a MatrixView can be compared for equality. PartialEq is implemented as they are
 * equal if and only if all their elements are equal and they have the same size.
 */
impl<T, S> PartialEq<MatrixView<T, S>> for Matrix<T>
where
    T: PartialEq,
    S: MatrixRef<T>,
{
    #[inline]
    fn eq(&self, other: &MatrixView<T, S>) -> bool {
        matrix_equality(&self, &other.source)
    }
}

#[test]
fn creating_matrix_views_erased() {
    let matrix = Matrix::from(vec![vec![1.0]]);
    let boxed: Box<dyn MatrixMut<f32>> = Box::new(matrix);
    let mut view = MatrixView::from(boxed);
    view.set(0, 0, view.get(0, 0) + 1.0);
    assert_eq!(2.0, view.get(0, 0));
}