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
/*!
 * Iterators over parts of a Matrix
 *
 * # Examples
 *
 * Extending a matrix with new columns
 * ```
 * use easy_ml::matrices::Matrix;
 *
 * // we start with some matrix where the first and second columns correspond
 * // to x and y points
 * let mut matrix = Matrix::from(vec![
 *     vec![ 3.0, 4.0 ],
 *     vec![ 8.0, 1.0 ],
 *     vec![ 2.0, 9.0 ]]);
 * // insert a third column based on the formula x * y
 * matrix.insert_column_with(2, matrix.column_iter(0)
 *     // join together the x and y columns
 *     .zip(matrix.column_iter(1))
 *     // compute the values for the new column
 *     .map(|(x, y)| x * y)
 *     // Collect into a vector so we stop immutably borrowing from `matrix`.
 *     // This is only neccessary when we use the data from a Matrix to modify itself,
 *     // because the rust compiler enforces that we do not mutably and immutably borrow
 *     // something at the same time. If we used data from a different Matrix to update
 *     // `matrix` then we could stop at map and pass the iterator directly.
 *     .collect::<Vec<f64>>()
 *     // now that the Vec created owns the data for the new column and we have stopped
 *     // borrowing immutably from `matrix` we turn the vec back into an iterator and
 *     // mutably borrow `matrix` to add the new column
 *     .drain(..));
 * assert_eq!(matrix.get(0, 2), 3.0 * 4.0);
 * assert_eq!(matrix.get(1, 2), 8.0 * 1.0);
 * assert_eq!(matrix.get(2, 2), 2.0 * 9.0);
 * ```
 *
 * # Matrix layout and iterator performance
 *
 * Internally the Matrix type uses a flattened array with [row major storage](https://en.wikipedia.org/wiki/Row-_and_column-major_order)
 * of the data. Due to [CPU cache lines](https://stackoverflow.com/questions/3928995/how-do-cache-lines-work)
 * this means row major access of elements is likely to be faster than column major indexing,
 * once a matrix is large enough, so you should favor iterating through each row.
 *
 * ```
 * use easy_ml::matrices::Matrix;
 * let matrix = Matrix::from(vec![
 *    vec![ 1, 2 ],
 *    vec![ 3, 4 ]]);
 * // storage of elements is [1, 2, 3, 4]
 *
 * // row major access
 * for row in 0..2 {
 *     for column in 0..2 {
 *         println!("{}", matrix.get(row, column));
 *     }
 * } // -> 1 2 3 4
 * matrix.row_major_iter().for_each(|e| println!("{}", e)); // -> 1 2 3 4
 *
 * // column major access
 * for column in 0..2 {
 *     for row in 0..2 {
 *         println!("{}", matrix.get(row, column));
 *     }
 * } // -> 1 3 2 4
 * matrix.column_major_iter().for_each(|e| println!("{}", e)); // -> 1 3 2 4
 * ```
 */

use std::iter::{ExactSizeIterator, FusedIterator};

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

/**
 * An iterator over a column in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * Depending on the column iterator you want to obtain,
 * can either iterate through 1, 3 or 2, 4.
 */
pub struct ColumnIterator<'a, T: Clone> {
    matrix: &'a Matrix<T>,
    column: Column,
    counter: usize,
    finished: bool,
}

impl <'a, T: Clone> ColumnIterator<'a, T> {
    /**
     * Constructs a column iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>, column: Column) -> ColumnIterator<T> {
        ColumnIterator {
            matrix,
            column,
            counter: 0,
            finished: false,
        }
    }
}

impl <'a, T: Clone> Iterator for ColumnIterator<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get(self.counter, self.column));

        if self.counter == self.matrix.rows() - 1 {
            self.finished = true;
        }

        self.counter += 1;

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.matrix.rows() - self.counter;
        (remaining, Some(remaining))
    }
}

impl <'a, T: Clone> FusedIterator for ColumnIterator<'a, T> {}
impl <'a, T: Clone> ExactSizeIterator for ColumnIterator<'a, T> {}

/**
 * An iterator over a row in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * Depending on the row iterator you want to obtain,
 * can either iterate through 1, 2 or 3, 4.
 */
pub struct RowIterator<'a, T: Clone> {
    matrix: &'a Matrix<T>,
    row: Row,
    counter: usize,
    finished: bool,
}

impl <'a, T: Clone> RowIterator<'a, T> {
    /**
     * Constructs a row iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>, row: Row) -> RowIterator<T> {
        RowIterator {
            matrix,
            row,
            counter: 0,
            finished: false,
        }
    }
}

impl <'a, T: Clone> Iterator for RowIterator<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get(self.row, self.counter));

        if self.counter == self.matrix.columns() - 1 {
            self.finished = true;
        }

        self.counter += 1;

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.matrix.columns() - self.counter;
        (remaining, Some(remaining))
    }
}

impl <'a, T: Clone> FusedIterator for RowIterator<'a, T> {}
impl <'a, T: Clone> ExactSizeIterator for RowIterator<'a, T> {}

/**
 * A column major iterator over all values in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * The elements will be iterated through as 1, 3, 2, 4
 */
pub struct ColumnMajorIterator<'a, T: Clone> {
    matrix: &'a Matrix<T>,
    column_counter: Column,
    row_counter: Row,
    finished: bool,
}

impl <'a, T: Clone> ColumnMajorIterator<'a, T> {
    /**
     * Constructs a column major iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>) -> ColumnMajorIterator<T> {
        ColumnMajorIterator {
            matrix,
            column_counter: 0,
            row_counter: 0,
            finished: false,
        }
    }
}

impl <'a, T: Clone> Iterator for ColumnMajorIterator<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get(self.row_counter, self.column_counter));

        if self.row_counter == self.matrix.rows() - 1
                && self.column_counter == self.matrix.columns() -1 {
            // reached end of matrix for next iteration
            self.finished = true;
        }

        if self.row_counter == self.matrix.rows() - 1 {
            // reached end of a column, need to reset to first element in next column
            self.row_counter = 0;
            self.column_counter += 1;
        } else {
            // keep incrementing through this column
            self.row_counter += 1;
        }

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining_columns = self.matrix.columns() - self.column_counter;
        match remaining_columns {
            0 => (0, Some(0)),
            1 => {
                // we're on the last column, so return how many items are left for us to
                // go through with the row counter
                let remaining_rows = self.matrix.rows() - self.row_counter;
                (remaining_rows, Some(remaining_rows))
            }
            x => {
                // we still have at least one full column left in addition to what's left
                // for this column's row counter
                let remaining_rows = self.matrix.rows() - self.row_counter;
                // each full column takes as many iterations as the matrix has rows
                let remaining_full_columns = (x - 1) * self.matrix.rows();
                let remaining = remaining_rows + remaining_full_columns;
                (remaining, Some(remaining))
            }
        }
    }
}

impl <'a, T: Clone> FusedIterator for ColumnMajorIterator<'a, T> {}
impl <'a, T: Clone> ExactSizeIterator for ColumnMajorIterator<'a, T> {}

/**
 * A row major iterator over all values in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * The elements will be iterated through as 1, 2, 3, 4
 */
pub struct RowMajorIterator<'a, T: Clone> {
    matrix: &'a Matrix<T>,
    column_counter: Column,
    row_counter: Row,
    finished: bool,
}

impl <'a, T: Clone> RowMajorIterator<'a, T> {
    /**
     * Constructs a row major iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>) -> RowMajorIterator<T> {
        RowMajorIterator {
            matrix,
            column_counter: 0,
            row_counter: 0,
            finished: false,
        }
    }
}

impl <'a, T: Clone> Iterator for RowMajorIterator<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get(self.row_counter, self.column_counter));

        if self.column_counter == self.matrix.columns() - 1
                && self.row_counter == self.matrix.rows() -1 {
            // reached end of matrix for next iteration
            self.finished = true;
        }

        if self.column_counter == self.matrix.columns() - 1 {
            // reached end of a row, need to reset to first element in next row
            self.column_counter = 0;
            self.row_counter += 1;
        } else {
            // keep incrementing through this row
            self.column_counter += 1;
        }

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining_rows = self.matrix.rows() - self.row_counter;
        match remaining_rows {
            0 => (0, Some(0)),
            1 => {
                // we're on the last row, so return how many items are left for us to
                // go through with the column counter
                let remaining_columns = self.matrix.columns() - self.column_counter;
                (remaining_columns, Some(remaining_columns))
            }
            x => {
                // we still have at least one full row left in addition to what's left
                // for this row's column counter
                let remaining_columns = self.matrix.columns() - self.column_counter;
                // each full row takes as many iterations as the matrix has columns
                let remaining_full_rows = (x - 1) * self.matrix.columns();
                let remaining = remaining_columns + remaining_full_rows;
                (remaining, Some(remaining))
            }
        }
    }
}

impl <'a, T: Clone> FusedIterator for RowMajorIterator<'a, T> {}
impl <'a, T: Clone> ExactSizeIterator for RowMajorIterator<'a, T> {}

/**
 * An iterator over references to a column in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * Depending on the row iterator you want to obtain,
 * can either iterate through &1, &3 or &2, &4.
 */
pub struct ColumnReferenceIterator<'a, T> {
    matrix: &'a Matrix<T>,
    column: Column,
    counter: usize,
    finished: bool,
}

impl <'a, T> ColumnReferenceIterator<'a, T> {
    /**
     * Constructs a column iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>, column: Column) -> ColumnReferenceIterator<T> {
        ColumnReferenceIterator {
            matrix,
            column,
            counter: 0,
            finished: false,
        }
    }
}

impl <'a, T> Iterator for ColumnReferenceIterator<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get_reference(self.counter, self.column));

        if self.counter == self.matrix.rows() - 1 {
            self.finished = true;
        }

        self.counter += 1;

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.matrix.rows() - self.counter;
        (remaining, Some(remaining))
    }
}

impl <'a, T> FusedIterator for ColumnReferenceIterator<'a, T> {}
impl <'a, T> ExactSizeIterator for ColumnReferenceIterator<'a, T> {}

/**
 * An iterator over references to a row in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * Depending on the row iterator you want to obtain,
 * can either iterate through &1, &2 or &3, &4.
 */
pub struct RowReferenceIterator<'a, T> {
    matrix: &'a Matrix<T>,
    row: Row,
    counter: usize,
    finished: bool,
}

impl <'a, T> RowReferenceIterator<'a, T> {
    /**
     * Constructs a row iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>, row: Row) -> RowReferenceIterator<T> {
        RowReferenceIterator {
            matrix,
            row,
            counter: 0,
            finished: false,
        }
    }
}

impl <'a, T> Iterator for RowReferenceIterator<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get_reference(self.row, self.counter));

        if self.counter == self.matrix.columns() - 1 {
            self.finished = true;
        }

        self.counter += 1;

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.matrix.columns() - self.counter;
        (remaining, Some(remaining))
    }
}

impl <'a, T> FusedIterator for RowReferenceIterator<'a, T> {}
impl <'a, T> ExactSizeIterator for RowReferenceIterator<'a, T> {}

/**
 * A column major iterator over references to all values in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * The elements will be iterated through as &1, &3, &2, &4
 */
pub struct ColumnMajorReferenceIterator<'a, T> {
    matrix: &'a Matrix<T>,
    column_counter: Column,
    row_counter: Row,
    finished: bool,
}

impl <'a, T> ColumnMajorReferenceIterator<'a, T> {
    /**
     * Constructs a column major iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>) -> ColumnMajorReferenceIterator<T> {
        ColumnMajorReferenceIterator {
            matrix,
            column_counter: 0,
            row_counter: 0,
            finished: false,
        }
    }
}

impl <'a, T> Iterator for ColumnMajorReferenceIterator<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get_reference(self.row_counter, self.column_counter));

        if self.row_counter == self.matrix.rows() - 1
                && self.column_counter == self.matrix.columns() -1 {
            // reached end of matrix for next iteration
            self.finished = true;
        }

        if self.row_counter == self.matrix.rows() - 1 {
            // reached end of a column, need to reset to first element in next column
            self.row_counter = 0;
            self.column_counter += 1;
        } else {
            // keep incrementing through this column
            self.row_counter += 1;
        }

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining_columns = self.matrix.columns() - self.column_counter;
        match remaining_columns {
            0 => (0, Some(0)),
            1 => {
                // we're on the last column, so return how many items are left for us to
                // go through with the row counter
                let remaining_rows = self.matrix.rows() - self.row_counter;
                (remaining_rows, Some(remaining_rows))
            }
            x => {
                // we still have at least one full column left in addition to what's left
                // for this column's row counter
                let remaining_rows = self.matrix.rows() - self.row_counter;
                // each full column takes as many iterations as the matrix has rows
                let remaining_full_columns = (x - 1) * self.matrix.rows();
                let remaining = remaining_rows + remaining_full_columns;
                (remaining, Some(remaining))
            }
        }
    }
}

impl <'a, T> FusedIterator for ColumnMajorReferenceIterator<'a, T> {}
impl <'a, T> ExactSizeIterator for ColumnMajorReferenceIterator<'a, T> {}

/**
 * A row major iterator over references to all values in a matrix.
 *
 * For a 2x2 matrix such as `[ 1, 2; 3, 4]`: ie
 * ```ignore
 * [
 *   1, 2
 *   3, 4
 * ]
 * ```
 * The elements will be iterated through as &1, &2, &3, &4
 */
    pub struct RowMajorReferenceIterator<'a, T> {
    matrix: &'a Matrix<T>,
    column_counter: Column,
    row_counter: Row,
    finished: bool,
}

impl <'a, T> RowMajorReferenceIterator<'a, T> {
    /**
     * Constructs a column major iterator over this matrix.
     */
    pub fn new(matrix: &Matrix<T>) -> RowMajorReferenceIterator<T> {
        RowMajorReferenceIterator {
            matrix,
            column_counter: 0,
            row_counter: 0,
            finished: false,
        }
    }
}

impl <'a, T> Iterator for RowMajorReferenceIterator<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None
        }

        let value = Some(self.matrix.get_reference(self.row_counter, self.column_counter));

        if self.column_counter == self.matrix.columns() - 1
                && self.row_counter == self.matrix.rows() -1 {
            // reached end of matrix for next iteration
            self.finished = true;
        }

        if self.column_counter == self.matrix.columns() - 1 {
            // reached end of a row, need to reset to first element in next row
            self.column_counter = 0;
            self.row_counter += 1;
        } else {
            // keep incrementing through this row
            self.column_counter += 1;
        }

        value
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining_rows = self.matrix.rows() - self.row_counter;
        match remaining_rows {
            0 => (0, Some(0)),
            1 => {
                // we're on the last row, so return how many items are left for us to
                // go through with the column counter
                let remaining_columns = self.matrix.columns() - self.column_counter;
                (remaining_columns, Some(remaining_columns))
            }
            x => {
                // we still have at least one full row left in addition to what's left
                // for this row's column counter
                let remaining_columns = self.matrix.columns() - self.column_counter;
                // each full row takes as many iterations as the matrix has columns
                let remaining_full_rows = (x - 1) * self.matrix.columns();
                let remaining = remaining_columns + remaining_full_rows;
                (remaining, Some(remaining))
            }
        }
    }
}

impl <'a, T> FusedIterator for RowMajorReferenceIterator<'a, T> {}
impl <'a, T> ExactSizeIterator for RowMajorReferenceIterator<'a, T> {}