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
//! A sparse implementation of a binary matrix optimized for row operations.
//!
//! The main object of this crate is the [`SparseBinMat`](SparseBinMat).
//! All elements in a binary matrix are element of the binary field GF2.
//! That is, they are either 0 or 1 and addition is modulo 2.
//!
//! # Quick start
//!
//! To instanciate a matrix, you need to specify the number of columns as well
//! as the position of 1 in each rows.
//!
//! ```
//! use sparse_bin_mat::SparseBinMat;
//!
//! // This is the matrix
//! // 1 0 1 0 1
//! // 0 1 0 1 0
//! // 0 0 1 0 0
//! let matrix = SparseBinMat::new(5, vec![vec![0, 2, 4], vec![1, 3], vec![2]]);
//! ```
//!
//! It is easy to access elements or rows of a matrix. However,
//! since the matrix are optimized for row operations, you need
//! to transpose the matrix if you want to perform column operations.
//!
//! ```
//! # use sparse_bin_mat::SparseBinMat;
//! let matrix = SparseBinMat::new(5, vec![vec![0, 2, 4], vec![1, 3], vec![2]]);
//! assert_eq!(matrix.row(1), Some([1, 3].as_ref()));
//! assert_eq!(matrix.get(0, 0), Some(1));
//! assert_eq!(matrix.get(0, 1), Some(0));
//! // The element (0, 7) is out of bound for a 3 x 5 matrix.
//! assert_eq!(matrix.get(0, 7), None);
//! ```
//!
//! Adition and multiplication are implemented between matrix references.
//!
//! ```
//! # use sparse_bin_mat::SparseBinMat;
//! let matrix = SparseBinMat::new(3, vec![vec![0, 1], vec![1, 2], vec![0, 2]]);
//! let identity = SparseBinMat::identity(3);
//!
//! let sum = SparseBinMat::new(3, vec![vec![1], vec![2], vec![0]]);
//! assert_eq!(&matrix + &identity, sum);
//!
//! assert_eq!(&matrix * &identity, matrix);
//! ```
//!
//! Many useful operations and decompositions are implemented.
//! These include, but are not limited to
//! - [`rank`](SparseBinMat::rank),
//! - [`echelon form`](SparseBinMat::echelon_form),
//! - [`nullspace`](SparseBinMat::nullspace),
//! - [`tranposition`](SparseBinMat::transposed),
//! - [`horizontal`](SparseBinMat::horizontal_concat_with) and
//! [`vertical`](SparseBinMat::vertical_concat_with) concatenations,
//! - and more ...
//!
//! Operations are implemented as I need them,
//! feel welcome to raise an issue if you need a new functionnality.

use itertools::Itertools;
use std::collections::HashMap;
use std::ops::{Add, Mul};

mod bitwise_operations;
use bitwise_operations::{rows_bitwise_sum, rows_dot_product};

mod concat;
use concat::{concat_horizontally, concat_vertically};

mod constructor_utils;
use constructor_utils::{assert_rows_are_inbound, initialize_from};

mod gauss_jordan;
use gauss_jordan::GaussJordan;

mod nullspace;
use nullspace::nullspace;

mod rows;
pub use crate::rows::Rows;

mod transpose;
use transpose::transpose;

type BinaryNumber = u8;

/// A sparse binary matrix optimized for row operations.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct SparseBinMat {
    row_ranges: Vec<usize>,
    column_indices: Vec<usize>,
    number_of_columns: usize,
}

impl SparseBinMat {
    /// Creates a new matrix with the given number of columns
    /// and list of rows.
    ///
    /// A row is a list of the positions where the elements have value 1.
    /// All rows are sorted during insertion.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::new(4, vec![vec![0, 1, 2], vec![0, 2, 3]]);
    ///
    /// assert_eq!(matrix.number_of_rows(), 2);
    /// assert_eq!(matrix.number_of_columns(), 4);
    /// assert_eq!(matrix.number_of_elements(), 8);
    /// ```
    ///
    /// # Panic
    ///
    /// Panics if a position in a row is greater or equal to
    /// the number of columns.
    ///
    /// ```should_panic
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::new(2, vec![vec![1, 2], vec![3, 0]]);
    /// ```
    pub fn new(number_of_columns: usize, rows: Vec<Vec<usize>>) -> Self {
        assert_rows_are_inbound(number_of_columns, &rows);
        let (row_ranges, column_indices) = initialize_from(rows);
        Self {
            row_ranges,
            column_indices,
            number_of_columns,
        }
    }

    /// Creates an identity matrix of the given length.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::identity(5);
    ///
    /// let identity_rows = (0..5).map(|x| vec![x]).collect();
    /// let identity_matrix = SparseBinMat::new(5, identity_rows);
    ///
    /// assert_eq!(matrix, identity_matrix);
    /// ```
    pub fn identity(length: usize) -> Self {
        Self {
            column_indices: (0..length).collect(),
            row_ranges: (0..length + 1).collect(),
            number_of_columns: length,
        }
    }

    /// Creates a matrix fill with zeros of the given dimensions.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::zeros(2, 3);
    ///
    /// assert_eq!(matrix.number_of_rows(), 2);
    /// assert_eq!(matrix.number_of_columns(), 3);
    /// assert_eq!(matrix.number_of_zeros(), 6);
    /// assert_eq!(matrix.number_of_ones(), 0);
    /// ```
    pub fn zeros(number_of_rows: usize, number_of_columns: usize) -> Self {
        Self::new(number_of_columns, vec![Vec::new(); number_of_rows])
    }

    /// Creates an empty matrix.
    ///
    /// This allocate minimally, so it is a good placeholder.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::empty();
    ///
    /// assert_eq!(matrix.number_of_rows(), 0);
    /// assert_eq!(matrix.number_of_columns(), 0); assert_eq!(matrix.number_of_elements(), 0);
    /// // Note that these are not equal since new preallocate some space
    /// // to store the data.
    /// assert_ne!(SparseBinMat::new(0, Vec::new()), SparseBinMat::empty());
    ///
    /// // To test for emptyness, you should prefer the following.
    /// assert!(matrix.is_empty());
    /// ```
    pub fn empty() -> Self {
        Self {
            column_indices: Vec::new(),
            row_ranges: Vec::new(),
            number_of_columns: 0,
        }
    }

    /// Returns the number of columns in the matrix.
    pub fn number_of_columns(&self) -> usize {
        self.number_of_columns
    }

    /// Returns the number of rows in the matrix
    pub fn number_of_rows(&self) -> usize {
        match self.row_ranges.len() {
            0 => 0,
            n => n - 1,
        }
    }

    /// Returns the number of rows and columns in the matrix.
    pub fn dimension(&self) -> (usize, usize) {
        (self.number_of_rows(), self.number_of_columns())
    }

    /// Returns the number of elements in the matrix.
    pub fn number_of_elements(&self) -> usize {
        self.number_of_rows() * self.number_of_columns()
    }

    /// Returns the number of elements with value 0 in the matrix.
    pub fn number_of_zeros(&self) -> usize {
        self.number_of_elements() - self.number_of_ones()
    }

    /// Returns the number of elements with value 1 in the matrix.
    pub fn number_of_ones(&self) -> usize {
        self.column_indices.len()
    }

    /// Returns true if the number of elements in the matrix is 0.
    pub fn is_empty(&self) -> bool {
        self.number_of_elements() == 0
    }

    /// Returns the value at the given row and column
    /// or None if one of the index is out of bound.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let rows = vec![vec![0, 1], vec![1, 2]];
    /// let matrix = SparseBinMat::new(3, rows);
    ///
    /// assert_eq!(matrix.get(0, 0), Some(1));
    /// assert_eq!(matrix.get(1, 0), Some(0));
    /// assert_eq!(matrix.get(2, 0), None);
    /// ```
    pub fn get(&self, row: usize, column: usize) -> Option<BinaryNumber> {
        if column < self.number_of_columns() {
            self.row(row)
                .map(|row| if row.contains(&column) { 1 } else { 0 })
        } else {
            None
        }
    }

    /// Returns true if the value at the given row and column is 0
    /// or None if one of the index is out of bound.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let rows = vec![vec![0, 1], vec![1, 2]];
    /// let matrix = SparseBinMat::new(3, rows);
    ///
    /// assert_eq!(matrix.is_zero_at(0, 0), Some(false));
    /// assert_eq!(matrix.is_zero_at(1, 0), Some(true));
    /// assert_eq!(matrix.is_zero_at(2, 0), None);
    /// ```
    pub fn is_zero_at(&self, row: usize, column: usize) -> Option<bool> {
        self.get(row, column).map(|value| value == 0)
    }

    /// Returns true if the value at the given row and column is 1
    /// or None if one of the index is out of bound.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let rows = vec![vec![0, 1], vec![1, 2]];
    /// let matrix = SparseBinMat::new(3, rows);
    ///
    /// assert_eq!(matrix.is_one_at(0, 0), Some(true));
    /// assert_eq!(matrix.is_one_at(1, 0), Some(false));
    /// assert_eq!(matrix.is_one_at(2, 0), None);
    /// ```
    pub fn is_one_at(&self, row: usize, column: usize) -> Option<bool> {
        self.get(row, column).map(|value| value == 1)
    }

    /// Returns a reference to the given row of the matrix
    /// or None if the row index is out of bound.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let rows = vec![vec![0, 1], vec![1, 2]];
    /// let matrix = SparseBinMat::new(3, rows);
    ///
    /// assert_eq!(matrix.row(0), Some([0, 1].as_ref()));
    /// assert_eq!(matrix.row(1), Some([1, 2].as_ref()));
    /// assert_eq!(matrix.row(2), None);
    /// ```
    pub fn row(&self, row: usize) -> Option<&[usize]> {
        let row_start = self.row_ranges.get(row)?;
        let row_end = self.row_ranges.get(row + 1)?;
        Some(&self.column_indices[*row_start..*row_end])
    }

    /// Returns an iterator yielding the rows of the matrix
    /// as slice of non zero positions.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let rows = vec![vec![0, 1, 2, 5], vec![1, 3, 4], vec![2, 4, 5], vec![0, 5]];
    /// let matrix = SparseBinMat::new(7, rows);
    ///
    /// let mut iter = matrix.rows();
    ///
    /// assert_eq!(iter.next(), Some([0, 1, 2, 5].as_ref()));
    /// assert_eq!(iter.next(), Some([1, 3, 4].as_ref()));
    /// assert_eq!(iter.next(), Some([2, 4, 5].as_ref()));
    /// assert_eq!(iter.next(), Some([0, 5].as_ref()));
    /// assert_eq!(iter.next(), None);
    /// ```
    pub fn rows(&self) -> Rows {
        Rows::from(self)
    }

    /// Returns an iterator yielding the number
    /// of non zero elements in each row of the matrix.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let rows = vec![vec![0, 1, 2, 5], vec![1, 3, 4], vec![2, 4, 5], vec![0, 5]];
    /// let matrix = SparseBinMat::new(7, rows);
    ///
    /// assert_eq!(matrix.row_weights().collect::<Vec<usize>>(), vec![4, 3, 3, 2]);
    /// ```
    pub fn row_weights<'a>(&'a self) -> impl Iterator<Item = usize> + 'a {
        self.rows().map(|row| row.len())
    }

    /// Gets the transposed version of the matrix
    /// by swapping the columns with the rows.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    ///
    /// let rows = vec![vec![0, 1, 2], vec![1, 3], vec![0, 2, 3]];
    /// let matrix = SparseBinMat::new(4, rows);
    ///
    /// let transposed_matrix = matrix.transposed();
    ///
    /// let expected_rows = vec![vec![0, 2], vec![0, 1], vec![0, 2], vec![1, 2]];
    /// let expected_matrix = SparseBinMat::new(3, expected_rows);
    ///
    /// assert_eq!(transposed_matrix, expected_matrix);
    /// ```
    pub fn transposed(&self) -> Self {
        transpose(self)
    }

    /// Computes the rank of the matrix.
    /// That is, the number of linearly independent rows or columns.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    ///
    /// let rows = vec![vec![0, 1], vec![1, 2], vec![0, 2]];
    /// let matrix = SparseBinMat::new(3, rows);
    ///
    /// assert_eq!(matrix.rank(), 2);
    /// ```
    pub fn rank(&self) -> usize {
        GaussJordan::new(self).rank()
    }

    /// Returns an echeloned version of the matrix.
    ///
    /// A matrix in echelon form as the property that no
    /// rows any given row have a 1 in the first non trivial
    /// position of that row. Also, all rows are linearly
    /// independent.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let rows = vec![vec![0, 1, 2], vec![0], vec![1, 2], vec![0, 2]];
    /// let matrix = SparseBinMat::new(3, rows);
    ///
    /// let expected = SparseBinMat::new(3, vec![vec![0, 1, 2], vec![1], vec![2]]);
    ///
    /// assert_eq!(matrix.echelon_form(), expected);
    /// ```
    pub fn echelon_form(&self) -> Self {
        GaussJordan::new(self).echelon_form()
    }

    /// Returns a matrix for which the rows are the generators
    /// of the nullspace of the original matrix.
    ///
    /// The nullspace of a matrix M is the set of vectors N such that
    /// Mx = 0 for all x in N.
    /// Therefore, if N is the nullspace matrix obtain from this function,
    /// we have that M * N^T = 0.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::new(
    ///     6,
    ///     vec![vec![0, 1, 3, 5], vec![2, 3, 4], vec![2, 5], vec![0, 1, 3]],
    /// );
    ///
    /// let expected = SparseBinMat::new(6, vec![vec![0, 3, 4,], vec![0, 1]]);
    /// let nullspace = matrix.nullspace();
    ///
    /// assert_eq!(nullspace, expected);
    /// assert_eq!(&matrix * &nullspace.transposed(), SparseBinMat::zeros(4, 2));
    /// ```
    pub fn nullspace(&self) -> Self {
        nullspace(self)
    }

    /// Returns the horizontal concatenation of two matrices.
    ///
    /// If the matrix have different number of rows, the smallest
    /// one is padded with empty rows.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let left_matrix = SparseBinMat::new(3, vec![vec![0, 1], vec![1, 2]]);
    /// let right_matrix = SparseBinMat::new(4, vec![vec![1, 2, 3], vec![0, 1], vec![2, 3]]);
    ///
    /// let concatened = left_matrix.horizontal_concat_with(&right_matrix);
    ///
    /// let expected = SparseBinMat::new(7, vec![vec![0, 1, 4, 5, 6], vec![1, 2, 3, 4], vec![5, 6]]);
    ///
    /// assert_eq!(concatened, expected);
    /// ```
    pub fn horizontal_concat_with(&self, other: &SparseBinMat) -> SparseBinMat {
        concat_horizontally(self, other)
    }

    /// Returns the vertical concatenation of two matrices.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let left_matrix = SparseBinMat::new(3, vec![vec![0, 1], vec![1, 2]]);
    /// let right_matrix = SparseBinMat::identity(3);
    ///
    /// let concatened = left_matrix.vertical_concat_with(&right_matrix);
    ///
    /// let expected = SparseBinMat::new(3, vec![vec![0, 1], vec![1, 2], vec![0], vec![1], vec![2]]);
    ///
    /// assert_eq!(concatened, expected);
    /// ```
    ///
    /// # Panic
    ///
    /// Panics if the matrices have a different number of columns.
    pub fn vertical_concat_with(&self, other: &SparseBinMat) -> SparseBinMat {
        if self.number_of_columns() != other.number_of_columns() {
            panic!(
                "{} and {} matrices can't be concatenated vertically",
                dimension_to_string(self.dimension()),
                dimension_to_string(other.dimension()),
            );
        }
        concat_vertically(self, other)
    }

    /// Returns a new matrix keeping only the given rows.
    ///
    /// # Example
    ///
    /// ```
    /// use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::new(5, vec![
    ///     vec![0, 1, 2],
    ///     vec![2, 3, 4],
    ///     vec![0, 2, 4],
    ///     vec![1, 3],
    /// ]);
    ///
    /// let truncated = SparseBinMat::new(5, vec![
    ///     vec![0, 1, 2],
    ///     vec![0, 2, 4],
    /// ]);
    ///
    /// assert_eq!(matrix.keep_only_rows(&[0, 2]), truncated);
    /// assert_eq!(matrix.keep_only_rows(&[0, 2, 3]).number_of_rows(), 3);
    /// ```
    ///
    /// # Panic
    ///
    /// Panics if some rows are out of bound.
    pub fn keep_only_rows(&self, rows: &[usize]) -> Self {
        self.assert_rows_are_inbound(rows);
        let rows = self
            .rows()
            .enumerate()
            .filter(|(index, _)| rows.contains(index))
            .map(|(_, row)| row.to_vec())
            .collect();
        Self::new(self.number_of_columns(), rows)
    }

    /// Returns a truncated matrix where the given rows are removed.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::new(5, vec![
    ///     vec![0, 1, 2],
    ///     vec![2, 3, 4],
    ///     vec![0, 2, 4],
    ///     vec![1, 3],
    /// ]);
    ///
    /// let truncated = SparseBinMat::new(5, vec![
    ///     vec![2, 3, 4],
    ///     vec![1, 3],
    /// ]);
    ///
    /// assert_eq!(matrix.without_rows(&[0, 2]), truncated);
    /// assert_eq!(matrix.without_rows(&[1, 2, 3]).number_of_rows(), 1);
    /// ```
    ///
    /// # Panic
    ///
    /// Panics if some rows are out of bound.
    pub fn without_rows(&self, rows: &[usize]) -> Self {
        let to_keep: Vec<usize> = (0..self.number_of_rows())
            .filter(|x| !rows.contains(x))
            .collect();
        self.keep_only_rows(&to_keep)
    }

    fn assert_rows_are_inbound(&self, rows: &[usize]) {
        for row in rows {
            if *row >= self.number_of_columns() {
                panic!(
                    "row {} is out of bound for {} matrix",
                    row,
                    dimension_to_string(self.dimension())
                );
            }
        }
    }
    /// Returns a new matrix keeping only the given columns.
    ///
    /// Columns are relabeled to the fit new number of columns.
    ///
    /// # Example
    ///
    /// ```
    /// use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::new(5, vec![
    ///     vec![0, 1, 2],
    ///     vec![2, 3, 4],
    ///     vec![0, 2, 4],
    ///     vec![1, 3],
    /// ]);
    ///
    /// let truncated = SparseBinMat::new(3, vec![
    ///     vec![0, 1],
    ///     vec![2],
    ///     vec![0, 2],
    ///     vec![1],
    /// ]);
    ///
    /// assert_eq!(matrix.keep_only_columns(&[0, 1, 4]), truncated);
    /// assert_eq!(matrix.keep_only_columns(&[1, 2]).number_of_columns(), 2);
    /// ```
    ///
    /// # Panic
    ///
    /// Panics if some columns are out of bound.
    pub fn keep_only_columns(&self, columns: &[usize]) -> Self {
        self.assert_columns_are_inbound(columns);
        let old_to_new_column_map = columns
            .iter()
            .enumerate()
            .map(|(new, old)| (old, new))
            .collect::<HashMap<_, _>>();
        let rows = self
            .rows()
            .map(|row| {
                row.iter()
                    .filter_map(|column| old_to_new_column_map.get(column).cloned())
                    .collect()
            })
            .collect();
        Self::new(columns.len(), rows)
    }

    /// Returns a truncated matrix where the given columns are removed.
    ///
    /// Columns are relabeled to fit the new number of columns.
    ///
    /// # Example
    ///
    /// ```
    /// # use sparse_bin_mat::SparseBinMat;
    /// let matrix = SparseBinMat::new(5, vec![
    ///     vec![0, 1, 2],
    ///     vec![2, 3, 4],
    ///     vec![0, 2, 4],
    ///     vec![1, 3],
    /// ]);
    ///
    /// let truncated = SparseBinMat::new(3, vec![
    ///     vec![0],
    ///     vec![1, 2],
    ///     vec![2],
    ///     vec![0, 1],
    /// ]);
    ///
    /// assert_eq!(matrix.without_columns(&[0, 2]), truncated);
    /// ```
    ///
    /// # Panic
    ///
    /// Panics if some columns are out of bound.
    pub fn without_columns(&self, columns: &[usize]) -> Self {
        let to_keep: Vec<usize> = (0..self.number_of_columns)
            .filter(|x| !columns.contains(x))
            .collect();
        self.keep_only_columns(&to_keep)
    }

    fn assert_columns_are_inbound(&self, columns: &[usize]) {
        for column in columns {
            if *column >= self.number_of_columns() {
                panic!(
                    "column {} is out of bound for {} matrix",
                    column,
                    dimension_to_string(self.dimension())
                );
            }
        }
    }
}

impl Add<&SparseBinMat> for &SparseBinMat {
    type Output = SparseBinMat;

    fn add(self, other: &SparseBinMat) -> SparseBinMat {
        if self.dimension() != other.dimension() {
            panic!(
                "{} and {} matrices can't be added",
                dimension_to_string(self.dimension()),
                dimension_to_string(other.dimension()),
            );
        }
        let rows = self
            .rows()
            .zip(other.rows())
            .map(|(row, other_row)| rows_bitwise_sum(row, other_row))
            .collect();
        SparseBinMat::new(self.number_of_columns(), rows)
    }
}

impl Mul<&SparseBinMat> for &SparseBinMat {
    type Output = SparseBinMat;

    fn mul(self, other: &SparseBinMat) -> SparseBinMat {
        if self.number_of_columns() != other.number_of_rows() {
            panic!(
                "{} and {} matrices can't be multiplied",
                dimension_to_string(self.dimension()),
                dimension_to_string(other.dimension()),
            );
        }
        let other_transposed = other.transposed();
        let rows = self
            .rows()
            .map(|row| {
                other_transposed
                    .rows()
                    .positions(|column| rows_dot_product(row, column) == 1)
                    .collect()
            })
            .collect();
        SparseBinMat::new(other.number_of_columns(), rows)
    }
}

fn dimension_to_string(dimension: (usize, usize)) -> String {
    format!("({} x {})", dimension.0, dimension.1)
}

//impl std::fmt::Display for SparseBinMat {
//fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//for row in self.rows() {
//write!(f, "[ ")?;
//for column in row.iter() {
//write!(f, "{} ", column)?;
//}
//write!(f, "]")?;
//}
//Ok(())
//}
//}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn rows_are_sorted_on_construction() {
        let rows = vec![vec![1, 0], vec![0, 2, 1], vec![1, 2, 3]];
        let matrix = SparseBinMat::new(4, rows);

        assert_eq!(matrix.row(0).unwrap().as_ref(), &[0, 1]);
        assert_eq!(matrix.row(1).unwrap().as_ref(), &[0, 1, 2]);
        assert_eq!(matrix.row(2).unwrap().as_ref(), &[1, 2, 3]);
    }

    #[test]
    #[should_panic]
    fn panics_on_construction_if_rows_are_out_of_bound() {
        let rows = vec![vec![0, 1, 5], vec![2, 3, 4]];
        SparseBinMat::new(5, rows);
    }

    #[test]
    fn addition() {
        let first_matrix = SparseBinMat::new(6, vec![vec![0, 2, 4], vec![1, 3, 5]]);
        let second_matrix = SparseBinMat::new(6, vec![vec![0, 1, 2], vec![3, 4, 5]]);
        let sum = SparseBinMat::new(6, vec![vec![1, 4], vec![1, 4]]);
        assert_eq!(&first_matrix + &second_matrix, sum);
    }

    #[test]
    fn panics_on_addition_if_different_dimensions() {
        let matrix_6_2 = SparseBinMat::new(6, vec![vec![0, 2, 4], vec![1, 3, 5]]);
        let matrix_6_3 = SparseBinMat::new(6, vec![vec![0, 1, 2], vec![3, 4, 5], vec![0, 3]]);
        let matrix_2_2 = SparseBinMat::new(2, vec![vec![0], vec![1]]);

        let result = std::panic::catch_unwind(|| &matrix_6_2 + &matrix_6_3);
        assert!(result.is_err());

        let result = std::panic::catch_unwind(|| &matrix_6_2 + &matrix_2_2);
        assert!(result.is_err());

        let result = std::panic::catch_unwind(|| &matrix_6_3 + &matrix_2_2);
        assert!(result.is_err());
    }

    #[test]
    fn multiplication_with_other_matrix() {
        let first_matrix = SparseBinMat::new(3, vec![vec![0, 1], vec![1, 2]]);
        let second_matrix = SparseBinMat::new(5, vec![vec![0, 2], vec![1, 3], vec![2, 4]]);
        let product = SparseBinMat::new(5, vec![vec![0, 1, 2, 3], vec![1, 2, 3, 4]]);
        assert_eq!(&first_matrix * &second_matrix, product);
    }

    #[test]
    fn panics_on_matrix_multiplication_if_wrong_dimension() {
        let matrix_6_3 = SparseBinMat::new(6, vec![vec![0, 1, 2], vec![3, 4, 5], vec![0, 3]]);
        let matrix_2_2 = SparseBinMat::new(2, vec![vec![0], vec![1]]);
        let result = std::panic::catch_unwind(|| &matrix_6_3 * &matrix_2_2);
        assert!(result.is_err());
    }
}