graphrox 1.2.0

A graph library for graph compression and fast processing of graph approximations
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
use std::collections::hash_map::Entry;
use std::collections::hash_map::Iter as HashMapIter;
use std::collections::HashMap;
use std::fmt::{Debug, Display};
use std::iter::{IntoIterator, Iterator};
use std::mem::MaybeUninit;
use std::ptr;

use crate::matrix::MatrixRepresentation;
use crate::util::Numeric;

/// A matrix in CSR (Compressed Sparse Row) format. The matrix uses a HashMap to map columns
/// to a HashMap mapping rows to entry values. Any matrix entry not contained in a row HashMap
/// is assumed to be zero.
///
/// ```
/// use graphrox::matrix::{CsrSquareMatrix, MatrixRepresentation};
///
/// let mut matrix = CsrSquareMatrix::new();
///
/// matrix.set_entry(5.7, 0, 0);
/// matrix.set_entry(-17.1, 1, 2);
///
/// assert_eq!(matrix.get_entry(0, 0), 5.7);
/// assert_eq!(matrix.get_entry(1, 2), -17.1);
/// assert_eq!(matrix.get_entry(2, 2), 0.0);
/// ```
#[derive(Clone, Debug)]
pub struct CsrSquareMatrix<T: Debug + Display + Numeric> {
    dimension: u64,
    edges_table: HashMap<u64, HashMap<u64, T>>,
    entry_count: u64,
}

impl<T: Debug + Display + Numeric> Default for CsrSquareMatrix<T> {
    fn default() -> Self {
        CsrSquareMatrix::new()
    }
}

impl<T: Debug + Display + Numeric> CsrSquareMatrix<T> {
    /// Creates a new, empty `CsrSquareMatrix`.
    ///
    /// ```
    /// use graphrox::matrix::{CsrSquareMatrix, MatrixRepresentation};
    ///
    /// let matrix: CsrSquareMatrix<f64> = CsrSquareMatrix::new();
    /// assert_eq!(matrix.dimension(), 0);
    /// assert_eq!(matrix.entry_count(), 0);
    /// ```
    pub fn new() -> Self {
        Self {
            dimension: 0,
            edges_table: HashMap::default(),
            entry_count: 0,
        }
    }

    /// Adds one to the specified entry.
    ///
    /// ```
    /// use graphrox::matrix::{CsrSquareMatrix, MatrixRepresentation};
    ///
    /// let mut matrix: CsrSquareMatrix<f64> = CsrSquareMatrix::new();
    ///
    /// matrix.increment_entry(3, 4);
    /// assert_eq!(matrix.get_entry(3, 4), 1.0);
    ///
    /// matrix.increment_entry(3, 4);
    /// assert_eq!(matrix.get_entry(3, 4), 2.0);
    ///
    /// assert_eq!(matrix.entry_count(), 1);
    /// assert_eq!(matrix.dimension(), 5);
    ///
    /// matrix.set_entry(3.2, 0, 1);
    ///
    /// matrix.increment_entry(0, 1);
    /// assert_eq!(matrix.get_entry(0, 1), 4.2);
    /// ```
    pub fn increment_entry(&mut self, col: u64, row: u64) {
        if col + 1 > self.dimension {
            self.dimension = col + 1
        }

        if row + 1 > self.dimension {
            self.dimension = row + 1
        }

        let row_table = self.edges_table.entry(col).or_default();
        let entry = row_table.entry(row);

        if let Entry::Vacant(_) = entry {
            self.entry_count += 1;
        }

        entry
            .and_modify(|e| *e = e.add_one())
            .or_insert_with(T::one);
    }

    /// Generates a string representation of a `CsrSquareMatrix`. Each entry in the matrix
    /// string will have `decimal_digits` digits after the decimal. If `decimal_digits` is 0,
    /// entries will not have a decimal.
    ///
    /// ```
    /// use graphrox::matrix::{CsrSquareMatrix, MatrixRepresentation};
    ///
    /// let mut matrix = CsrSquareMatrix::new();
    ///
    /// matrix.set_entry(1.3, 0, 0);
    /// matrix.set_entry(1.0, 1, 2);
    /// matrix.set_entry(0.847724, 2, 1);
    /// matrix.set_entry(1.7, 1, 0);
    ///
    /// println!("{}", matrix.to_string_with_precision(3));
    ///
    /// /* Output:
    ///
    /// [ 1.300, 1.700, 0.000 ]
    /// [ 0.000, 0.000, 0.848 ]
    /// [ 0.000, 1.000, 0.000 ]
    ///
    /// */
    ///
    /// matrix.set_entry(-10.12, 2, 2);
    ///
    /// println!("{}", matrix.to_string_with_precision(1));
    ///
    /// /* Output:
    ///
    /// [   1.3,   1.7,   0.0 ]
    /// [   0.0,   0.0,   0.8 ]
    /// [   0.0,   1.0, -10.1 ]
    ///
    /// */
    /// ```
    pub fn to_string_with_precision(&self, decimal_digits: usize) -> String {
        const EXTRA_CHARS_PER_ROW_AT_FRONT: usize = 2; // "[ "
        const EXTRA_CHARS_PER_ROW_AT_BACK: usize = 3; // "]\r\n"

        // Minus one to account for trailing comma being removed from final entry in row
        const EXTRA_CHARS_PER_ROW_TOTAL: usize =
            EXTRA_CHARS_PER_ROW_AT_FRONT + EXTRA_CHARS_PER_ROW_AT_BACK - 1;

        if self.dimension == 0 {
            return String::new();
        }

        let mut highest = T::min();
        let mut lowest = T::max();

        let edge_table_values = self.edges_table.values();

        if edge_table_values.len() == 0 {
            highest = T::zero();
        } else {
            for row_table in edge_table_values {
                for val in row_table.values() {
                    if val.gt(&highest) {
                        highest = *val;
                    }

                    if val.lt(&lowest) {
                        lowest = *val;
                    }
                }
            }
        }

        let highest_integral_count = highest.integral_digit_count();
        let lowest_integral_count = lowest.integral_digit_count();
        let mut entry_size = if highest_integral_count > lowest_integral_count {
            highest_integral_count
        } else {
            lowest_integral_count
        };

        if T::has_decimal() || decimal_digits > 0 {
            entry_size += 1 + decimal_digits;
        }

        // One for the digit in front of the decimal
        let smallest_entry_chars = 1 + if T::has_decimal() || decimal_digits > 0 {
            // One for the decimal, one for each decimal digit
            1 + decimal_digits
        } else {
            0
        };

        let entry_left_padding = entry_size - smallest_entry_chars;
        let chars_per_entry = entry_size + 2;

        let buffer_size = EXTRA_CHARS_PER_ROW_TOTAL * self.dimension as usize
            + chars_per_entry * (self.dimension * self.dimension) as usize
            - 2;

        let mut buffer = MaybeUninit::new(Vec::with_capacity(buffer_size));

        let buffer_ptr = unsafe {
            (*buffer.as_mut_ptr()).set_len((*buffer.as_mut_ptr()).capacity());
            (*buffer.as_mut_ptr()).as_mut_ptr() as *mut u8
        };

        let mut pos = 0;
        for row in 0..self.dimension {
            unsafe {
                ptr::write(buffer_ptr.add(pos), b'[');
                pos += 1;

                ptr::write(buffer_ptr.add(pos), b' ');
                pos += 1;

                for col in 0..self.dimension {
                    for char_pos in 0..entry_size {
                        let c = if char_pos < entry_left_padding {
                            b' '
                        } else if char_pos == entry_left_padding + 1 {
                            b'.'
                        } else {
                            b'0'
                        };

                        ptr::write(buffer_ptr.add(pos), c);
                        pos += 1;
                    }

                    if col != self.dimension - 1 {
                        ptr::write(buffer_ptr.add(pos), b',');
                        pos += 1;
                    }

                    ptr::write(buffer_ptr.add(pos), b' ');
                    pos += 1;
                }

                ptr::write(buffer_ptr.add(pos), b']');
                pos += 1;

                if row != self.dimension - 1 {
                    ptr::write(buffer_ptr.add(pos), b'\r');
                    pos += 1;

                    ptr::write(buffer_ptr.add(pos), b'\n');
                    pos += 1;
                }
            }
        }

        let buffer = unsafe { buffer.assume_init() };

        // Minus one for the removed trailing comma
        let chars_per_row = EXTRA_CHARS_PER_ROW_TOTAL + self.dimension as usize * chars_per_entry;

        for (col, row_table) in self.edges_table.iter() {
            for (row, value) in row_table.iter() {
                pos = *row as usize * chars_per_row
                    + EXTRA_CHARS_PER_ROW_AT_FRONT
                    + chars_per_entry * *col as usize;

                let num = if !T::has_decimal() && decimal_digits > 0 {
                    let width = if lowest.lt(&T::zero()) {
                        highest.integral_digit_count() + 1
                    } else {
                        highest.integral_digit_count()
                    };

                    let mut temp = format!("{number: >width$}.", number = value, width = width,);

                    for _ in 0..decimal_digits {
                        temp.push('0');
                    }

                    temp
                } else {
                    format!(
                        "{number: >width$.decimals$}",
                        number = value,
                        width = entry_size,
                        decimals = decimal_digits
                    )
                };

                let num = num.as_bytes();

                for b in num {
                    unsafe {
                        *buffer_ptr.add(pos) = *b;
                    }
                    pos += 1;
                }
            }
        }

        let buffer = unsafe { String::from(std::str::from_utf8_unchecked(&buffer[..])) };

        buffer
    }
}

impl<T: Debug + Display + Numeric> MatrixRepresentation<T> for CsrSquareMatrix<T> {
    fn dimension(&self) -> u64 {
        self.dimension
    }

    fn entry_count(&self) -> u64 {
        self.entry_count
    }

    fn get_entry(&self, col: u64, row: u64) -> T {
        let row_table = match self.edges_table.get(&col) {
            Some(t) => t,
            None => return T::zero(),
        };

        match row_table.get(&row) {
            Some(e) => *e,
            None => T::zero(),
        }
    }

    fn set_entry(&mut self, entry: T, col: u64, row: u64) {
        if col + 1 > self.dimension {
            self.dimension = col + 1
        }

        if row + 1 > self.dimension {
            self.dimension = row + 1
        }

        if entry == T::zero() {
            return;
        }

        let row_table = self.edges_table.entry(col).or_default();
        let addition = row_table.insert(row, entry);

        if addition.is_none() {
            self.entry_count += 1;
        }
    }

    fn zero_entry(&mut self, col: u64, row: u64) {
        let row_table = match self.edges_table.get_mut(&col) {
            Some(t) => t,
            None => return,
        };

        let removal = row_table.remove(&row);

        if removal.is_some() {
            self.entry_count -= 1;
        }
    }
}

impl<T: Debug + Display + Numeric> ToString for CsrSquareMatrix<T> {
    /// Generates a string representation of a `CsrSquareMatrix`. Each entry in the matrix
    /// string will have 2 digits after the decimal if the entries are of a floating-point
    /// type. If the entries are of an integral type, the entries will have no decimal.
    ///
    /// ```
    /// use graphrox::matrix::{CsrSquareMatrix, MatrixRepresentation};
    ///
    /// let mut matrix = CsrSquareMatrix::new();
    ///
    /// matrix.set_entry(1.3, 0, 0);
    /// matrix.set_entry(1.0, 1, 2);
    /// matrix.set_entry(0.847724, 2, 1);
    /// matrix.set_entry(10.7, 1, 0);
    ///
    /// println!("{}", matrix.to_string());
    ///
    /// /* Output:
    ///
    /// [  1.30, 10.70,  0.00 ]
    /// [  0.00,  0.00,  0.85 ]
    /// [  0.00,  1.00,  0.00 ]
    ///
    /// */
    ///
    /// let mut matrix = CsrSquareMatrix::new();
    ///
    /// matrix.set_entry(1, 0, 0);
    /// matrix.set_entry(7, 1, 2);
    /// matrix.set_entry(-5, 2, 1);
    /// matrix.set_entry(10, 1, 0);
    ///
    /// println!("{}", matrix.to_string());
    ///
    /// /* Output:
    ///
    /// [  1, 10,  0 ]
    /// [  0,  0, -5 ]
    /// [  0,  7,  0 ]
    ///
    /// */
    /// ```
    fn to_string(&self) -> String {
        self.to_string_with_precision(if T::has_decimal() { 2 } else { 0 })
    }
}

impl<'a, T: Debug + Display + Numeric> IntoIterator for &'a CsrSquareMatrix<T> {
    type Item = (T, u64, u64);
    type IntoIter = CsrSquareMatrixIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        CsrSquareMatrixIter {
            matrix: self,
            col_iter: self.edges_table.iter(),
            row_iter: None,
            curr_col: 0,
        }
    }
}

/// Iterator for non-zero entries in a `graphrox::matrix::CsrSquareMatrix`. Iteration is done
/// in arbitrary order.
///
/// ```
/// use graphrox::matrix::{CsrSquareMatrix, MatrixRepresentation};
///
/// let mut matrix = CsrSquareMatrix::new();
///  
/// matrix.set_entry(5.5, 0, 0);
/// matrix.set_entry(-7.8, 1, 2);
///  
/// let matrix_entries = matrix.into_iter().collect::<Vec<_>>();
///  
/// assert_eq!(matrix_entries.len() as u64, matrix.entry_count());
/// assert!(matrix_entries.contains(&(5.5, 0, 0)));
/// assert!(matrix_entries.contains(&(-7.8, 1, 2)));
///
/// for (entry, col, row) in &matrix {
///     println!("Entry {} at ({}, {})", entry, col, row);
/// }
///
/// /* Prints the following in arbitrary order:
///
/// Entry -7.8 at (1, 2)
/// Entry 5.5 at (0, 0)
///
/// */
/// ```
pub struct CsrSquareMatrixIter<'a, T: Debug + Display + Numeric> {
    matrix: &'a CsrSquareMatrix<T>,
    col_iter: HashMapIter<'a, u64, HashMap<u64, T>>,
    row_iter: Option<HashMapIter<'a, u64, T>>,
    curr_col: u64,
}

impl<'a, T: Debug + Display + Numeric> Iterator for CsrSquareMatrixIter<'a, T> {
    type Item = (T, u64, u64);

    fn next(&mut self) -> Option<Self::Item> {
        if self.matrix.dimension() == 0 {
            return None;
        }

        loop {
            if let Some(row_iter) = &mut self.row_iter {
                let row = row_iter.next();
                if let Some((r, e)) = row {
                    return Some((*e, self.curr_col, *r));
                }
            }

            let col_iter = self.col_iter.next();
            match col_iter {
                Some((col, row_set)) => {
                    self.curr_col = *col;
                    self.row_iter = Some(row_set.iter());
                }
                None => return None,
            }

            /* If we are at this point, we have just set a new row_iterator in self. We
             * can therefore loop back and try again.
             *
             * On the off-chance that there is a column with an empty HashMap (which can
             * happen if the last element in the HashMap is removed), we need to go beck
             * to the beginning of the function, hence we loop.
             *
             * The code would be a little cleaner if we recursively called next here,
             * but then a stack overflow would be possible (theoretically, though it
             * would require a LOT of columns to contain empty hash sets sequentially)
             * and Rust doesn't guarantee tail recursion will be optimized into a loop.
             */
        }
    }
}

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

    #[test]
    fn test_new_matrix() {
        let matrix: CsrSquareMatrix<u8> = CsrSquareMatrix::new();

        assert_eq!(matrix.dimension, 0);
        assert_eq!(matrix.entry_count, 0);
        assert_eq!(matrix.edges_table.len(), 0);

        let matrix: CsrSquareMatrix<f32> = CsrSquareMatrix::default();

        assert_eq!(matrix.dimension, 0);
        assert_eq!(matrix.entry_count, 0);
        assert_eq!(matrix.edges_table.len(), 0);
    }

    #[test]
    fn test_get_dimension() {
        let mut matrix = CsrSquareMatrix::new();

        assert_eq!(matrix.dimension(), matrix.dimension);
        assert_eq!(matrix.dimension(), 0);

        matrix.set_entry(2.5, 0, 0);

        assert_eq!(matrix.dimension(), matrix.dimension);
        assert_eq!(matrix.dimension(), 1);

        matrix.set_entry(1.0, 4, 7);
        matrix.set_entry(1.1, 4, 7);

        assert_eq!(matrix.dimension(), matrix.dimension);
        assert_eq!(matrix.dimension(), 8);

        matrix.set_entry(0.0, 100, 1);

        assert_eq!(matrix.dimension(), matrix.dimension);
        assert_eq!(matrix.dimension(), 101);
    }

    #[test]
    fn test_get_entry_count() {
        let mut matrix = CsrSquareMatrix::new();

        assert_eq!(matrix.entry_count(), matrix.entry_count);
        assert_eq!(matrix.entry_count(), 0);

        matrix.set_entry(0, 5, 8);
        matrix.set_entry(0, 0, 0);
        matrix.set_entry(0, 27, 13);

        assert_eq!(matrix.entry_count(), matrix.entry_count);
        assert_eq!(matrix.entry_count(), 0);

        matrix.set_entry(1, 0, 0);

        assert_eq!(matrix.entry_count(), matrix.entry_count);
        assert_eq!(matrix.entry_count(), 1);

        matrix.set_entry(1, 100, 1);
        matrix.set_entry(1, 100, 1);

        assert_eq!(matrix.entry_count(), matrix.entry_count);
        assert_eq!(matrix.entry_count(), 2);

        matrix.set_entry(1, 100, 2);
        matrix.set_entry(1, 1, 99);

        assert_eq!(matrix.entry_count(), matrix.entry_count);
        assert_eq!(matrix.entry_count(), 4);
    }

    #[test]
    fn test_get_entry() {
        let mut matrix = CsrSquareMatrix::new();

        assert_eq!(matrix.get_entry(5, 8), 0.0);
        matrix.set_entry(0.0, 5, 8);
        assert_eq!(matrix.get_entry(5, 8), 0.0);

        matrix.set_entry(1.5, 5, 8);
        assert_eq!(matrix.get_entry(5, 8), 1.5);

        assert_eq!(matrix.get_entry(8, 5), 0.0);
        matrix.set_entry(1.5, 8, 5);
        assert_eq!(matrix.get_entry(8, 5), 1.5);
    }

    #[test]
    fn test_set_entry() {
        let mut matrix = CsrSquareMatrix::new();

        assert_eq!(matrix.get_entry(5, 8), 0);
        assert_eq!(matrix.entry_count, 0);
        assert_eq!(matrix.dimension, 0);
        assert_eq!(matrix.edges_table.len(), 0);
        assert_eq!(matrix.edges_table.get(&5), None);

        matrix.set_entry(0, 5, 8);
        assert_eq!(matrix.get_entry(5, 8), 0);
        assert_eq!(matrix.entry_count, 0);
        assert_eq!(matrix.dimension, 9);
        assert_eq!(matrix.edges_table.len(), 0);
        assert_eq!(matrix.edges_table.get(&5), None);

        matrix.set_entry(7, 5, 8);
        assert_eq!(matrix.get_entry(5, 8), 7);
        assert_eq!(matrix.entry_count, 1);
        assert_eq!(matrix.dimension, 9);
        assert_eq!(matrix.edges_table.len(), 1);
        assert_eq!(matrix.edges_table.get(&5).unwrap().len(), 1);

        matrix.set_entry(2, 5, 9);
        assert_eq!(matrix.get_entry(5, 9), 2);
        assert_eq!(matrix.entry_count, 2);
        assert_eq!(matrix.dimension, 10);
        assert_eq!(matrix.edges_table.len(), 1);
        assert_eq!(matrix.edges_table.get(&5).unwrap().len(), 2);

        matrix.set_entry(3, 5, 9);
        assert_eq!(matrix.get_entry(5, 9), 3);
        assert_eq!(matrix.entry_count, 2);
        assert_eq!(matrix.dimension, 10);
        assert_eq!(matrix.edges_table.len(), 1);
        assert_eq!(matrix.edges_table.get(&5).unwrap().len(), 2);
    }

    #[test]
    fn test_increment_entry() {
        let mut matrix = CsrSquareMatrix::new();

        assert_eq!(matrix.get_entry(5, 8), 0.0);
        assert_eq!(matrix.entry_count, 0);
        assert_eq!(matrix.dimension, 0);
        assert_eq!(matrix.edges_table.len(), 0);
        assert_eq!(matrix.edges_table.get(&5), None);

        matrix.increment_entry(5, 8);
        assert_eq!(matrix.get_entry(5, 8), 1.0);
        assert_eq!(matrix.entry_count, 1);
        assert_eq!(matrix.dimension, 9);
        assert_eq!(matrix.edges_table.len(), 1);
        assert_eq!(matrix.edges_table.get(&5).unwrap().len(), 1);

        matrix.increment_entry(5, 8);
        assert_eq!(matrix.get_entry(5, 8), 2.0);
        assert_eq!(matrix.entry_count, 1);
        assert_eq!(matrix.dimension, 9);
        assert_eq!(matrix.edges_table.len(), 1);
        assert_eq!(matrix.edges_table.get(&5).unwrap().len(), 1);

        matrix.set_entry(78.7, 100, 20);
        matrix.increment_entry(100, 20);
        assert_eq!(matrix.get_entry(100, 20), 79.7);
        assert_eq!(matrix.entry_count, 2);
        assert_eq!(matrix.dimension, 101);
        assert_eq!(matrix.edges_table.len(), 2);
        assert_eq!(matrix.edges_table.get(&100).unwrap().len(), 1);
    }

    #[test]
    fn test_zero_entry() {
        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(9, 5, 8);
        assert_eq!(matrix.get_entry(5, 8), 9);
        assert_eq!(matrix.entry_count, 1);
        assert_eq!(matrix.dimension, 9);
        assert_eq!(matrix.edges_table.len(), 1);
        assert_eq!(matrix.edges_table.get(&5).unwrap().len(), 1);

        matrix.zero_entry(5, 8);
        assert_eq!(matrix.get_entry(5, 8), 0);
        assert_eq!(matrix.entry_count, 0);
        assert_eq!(matrix.dimension, 9);
        assert_eq!(matrix.edges_table.len(), 1);
        assert_eq!(matrix.edges_table.get(&5).unwrap().len(), 0);
    }

    #[test]
    fn test_matrix_to_string() {
        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(1, 0, 0);
        matrix.set_entry(1, 1, 1);
        matrix.set_entry(9, 1, 2);
        matrix.set_entry(1, 2, 1);
        matrix.set_entry(1, 1, 0);

        let expected = "[ 1, 1, 0 ]\r\n[ 0, 1, 1 ]\r\n[ 0, 9, 0 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        matrix.zero_entry(1, 1);
        let expected = "[ 1, 1, 0 ]\r\n[ 0, 0, 1 ]\r\n[ 0, 9, 0 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(1.3, 0, 0);
        matrix.set_entry(2.7, 1, 1);
        matrix.set_entry(1.0, 1, 2);
        matrix.set_entry(0.847324, 2, 1);
        matrix.set_entry(1.7, 1, 0);

        let expected = "[ 1.30, 1.70, 0.00 ]\r\n[ 0.00, 2.70, 0.85 ]\r\n[ 0.00, 1.00, 0.00 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        matrix.zero_entry(1, 1);
        let expected = "[ 1.30, 1.70, 0.00 ]\r\n[ 0.00, 0.00, 0.85 ]\r\n[ 0.00, 1.00, 0.00 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        matrix.set_entry(10.12, 2, 2);
        let expected =
            "[  1.30,  1.70,  0.00 ]\r\n[  0.00,  0.00,  0.85 ]\r\n[  0.00,  1.00, 10.12 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(-100, 1, 1);
        matrix.set_entry(8, 2, 1);
        let expected = "[    0,    0,    0 ]\r\n[    0, -100,    8 ]\r\n[    0,    0,    0 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(10, 0, 0);
        matrix.set_entry(11, 0, 1);
        matrix.set_entry(12, 1, 0);
        matrix.set_entry(13, 1, 1);

        let expected = "[ 10, 12 ]\r\n[ 11, 13 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(-1, 1, 0);

        let expected = "[  0, -1 ]\r\n[  0,  0 ]";
        assert_eq!(expected, matrix.to_string().as_str());

        let matrix: CsrSquareMatrix<f64> = CsrSquareMatrix::new();
        let expected = "";
        assert_eq!(expected, matrix.to_string().as_str());

        let matrix: CsrSquareMatrix<u64> = CsrSquareMatrix::new();
        let expected = "";
        assert_eq!(expected, matrix.to_string().as_str());
    }

    #[test]
    fn test_matrix_to_string_with_precision() {
        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(1, 0, 0);
        matrix.set_entry(1, 1, 1);
        matrix.set_entry(9, 1, 2);
        matrix.set_entry(1, 2, 1);
        matrix.set_entry(1, 1, 0);

        let expected = "[ 1.0, 1.0, 0.0 ]\r\n[ 0.0, 1.0, 1.0 ]\r\n[ 0.0, 9.0, 0.0 ]";
        assert_eq!(expected, matrix.to_string_with_precision(1).as_str());

        let expected =
            "[ 1.000, 1.000, 0.000 ]\r\n[ 0.000, 1.000, 1.000 ]\r\n[ 0.000, 9.000, 0.000 ]";
        assert_eq!(expected, matrix.to_string_with_precision(3).as_str());

        matrix.zero_entry(1, 1);
        let expected = "[ 1, 1, 0 ]\r\n[ 0, 0, 1 ]\r\n[ 0, 9, 0 ]";
        assert_eq!(expected, matrix.to_string_with_precision(0).as_str());

        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(1.3, 0, 0);
        matrix.set_entry(2.7, 1, 1);
        matrix.set_entry(1.0, 1, 2);
        matrix.set_entry(0.847324, 2, 1);
        matrix.set_entry(1.7, 1, 0);

        let expected = "[ 1.30, 1.70, 0.00 ]\r\n[ 0.00, 2.70, 0.85 ]\r\n[ 0.00, 1.00, 0.00 ]";
        assert_eq!(expected, matrix.to_string_with_precision(2).as_str());

        matrix.zero_entry(1, 1);
        let expected =
            "[ 1.300, 1.700, 0.000 ]\r\n[ 0.000, 0.000, 0.847 ]\r\n[ 0.000, 1.000, 0.000 ]";
        assert_eq!(expected, matrix.to_string_with_precision(3).as_str());

        matrix.set_entry(-10.12, 2, 2);
        let expected =
            "[   1.3,   1.7,   0.0 ]\r\n[   0.0,   0.0,   0.8 ]\r\n[   0.0,   1.0, -10.1 ]";
        assert_eq!(expected, matrix.to_string_with_precision(1).as_str());

        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(10, 0, 0);
        matrix.set_entry(11, 0, 1);
        matrix.set_entry(12, 1, 0);
        matrix.set_entry(13, 1, 1);

        let expected = "[ 10, 12 ]\r\n[ 11, 13 ]";
        assert_eq!(expected, matrix.to_string_with_precision(0).as_str());

        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(-1, 1, 0);

        let expected = "[  0, -1 ]\r\n[  0,  0 ]";
        assert_eq!(expected, matrix.to_string_with_precision(0).as_str());

        let matrix: CsrSquareMatrix<f64> = CsrSquareMatrix::new();
        let expected = "";
        assert_eq!(expected, matrix.to_string_with_precision(4).as_str());

        let matrix: CsrSquareMatrix<u64> = CsrSquareMatrix::new();
        let expected = "";
        assert_eq!(expected, matrix.to_string_with_precision(4).as_str());
    }

    #[test]
    fn test_matrix_ref_iterator() {
        let mut matrix = CsrSquareMatrix::new();

        matrix.set_entry(1.2, 0, 0);
        matrix.set_entry(1.5, 1, 1);
        matrix.set_entry(9.8, 1, 2);
        matrix.set_entry(1.1, 2, 1);
        matrix.set_entry(1.1, 1, 0);

        let matrix_entries = &matrix.into_iter().collect::<Vec<_>>();

        assert_eq!(matrix_entries.len() as u64, matrix.entry_count());
        assert!(matrix_entries.contains(&(1.2, 0, 0)));
        assert!(matrix_entries.contains(&(1.5, 1, 1)));
        assert!(matrix_entries.contains(&(9.8, 1, 2)));
        assert!(matrix_entries.contains(&(1.1, 2, 1)));
        assert!(matrix_entries.contains(&(1.1, 1, 0)));

        matrix.zero_entry(1, 1);

        let matrix_entries = &matrix.into_iter().collect::<Vec<_>>();

        assert_eq!(matrix_entries.len() as u64, matrix.entry_count());
        assert!(matrix_entries.contains(&(1.2, 0, 0)));
        assert!(matrix_entries.contains(&(9.8, 1, 2)));
        assert!(matrix_entries.contains(&(1.1, 2, 1)));
        assert!(matrix_entries.contains(&(1.1, 1, 0)));
    }
}