sukker 2.0.2

Linear Algebra and Matrices made easy!
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
//!  Module for defining sparse matrices.
//!
//! # What are sparse matrices
//!
//! Generally speaking, matrices with a lot of 0s
//!
//! # How are they represented
//!
//! Since storing large sparse matrices in memory is expensive
//!
//!
//! # What datastructure does sukker use
#![warn(missing_docs)]

mod helper;

use helper::*;

use std::fmt::Display;
use std::{collections::HashMap, error::Error, marker::PhantomData, str::FromStr};

use rayon::prelude::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator};
use serde::{Deserialize, Serialize};

use crate::{Matrix, MatrixElement, MatrixError, Shape};

macro_rules! at {
    ($row:expr, $col:expr, $ncols:expr) => {
        ($row * $ncols + $col) as usize
    };
}

/// SparseMatrixData represents the datatype used to store information
/// about non-zero values in a general matrix.
///
/// The keys are the index to the position in data,
/// while the value is the value to be stored inside the matrix
pub type SparseMatrixData<'a, T> = HashMap<Shape, T>;

#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
/// Represents a sparse matrix and its data
pub struct SparseMatrix<'a, T>
where
    T: MatrixElement,
    <T as FromStr>::Err: Error + 'static,
    Vec<T>: IntoParallelIterator,
    Vec<&'a T>: IntoParallelRefIterator<'a>,
{
    /// Vector containing all data
    data: SparseMatrixData<'a, T>,
    /// Number of rows
    pub nrows: usize,
    /// Number of columns
    pub ncols: usize,
    _lifetime: PhantomData<&'a T>,
}

impl<'a, T> Display for SparseMatrix<'a, T>
where
    T: MatrixElement,
    <T as FromStr>::Err: Error + 'static,
    Vec<T>: IntoParallelIterator,
    Vec<&'a T>: IntoParallelRefIterator<'a>,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for i in 0..self.nrows {
            for j in 0..self.ncols {
                let elem = match self.data.get(&(i, j)) {
                    Some(&val) => val,
                    None => T::zero(),
                };

                write!(f, "{elem} ");
            }
            write!(f, "\n");
        }
        writeln!(f, "\ndtype = {}", std::any::type_name::<T>())
    }
}

impl<'a, T> Default for SparseMatrix<'a, T>
where
    T: MatrixElement,
    <T as FromStr>::Err: Error + 'static,
    Vec<T>: IntoParallelIterator,
    Vec<&'a T>: IntoParallelRefIterator<'a>,
{
    /// Returns a sparse 3x3 identity matrix
    fn default() -> Self {
        Self::eye(3)
    }
}

impl<'a, T> SparseMatrix<'a, T>
where
    T: MatrixElement,
    <T as FromStr>::Err: Error + 'static,
    Vec<T>: IntoParallelIterator,
    Vec<&'a T>: IntoParallelRefIterator<'a>,
{
    /// Constructs a new sparse matrix based on a shape
    ///
    /// All elements are set to 0 initially
    ///
    /// Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<f32>::new(3,3);
    ///
    /// assert_eq!(sparse.ncols, 3);
    /// assert_eq!(sparse.nrows, 3);
    /// ```
    pub fn new(rows: usize, cols: usize) -> Self {
        Self {
            data: HashMap::new(),
            nrows: rows,
            ncols: cols,
            _lifetime: PhantomData::default(),
        }
    }

    /// Constructs a new sparse matrix based on a hashmap
    /// containing the indices where value is not 0
    ///
    /// This function does not check whether or not the
    /// indices are valid and according to shape. Use `reshape`
    /// to fix this issue.
    ///
    /// Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use sukker::{SparseMatrix, SparseMatrixData};
    ///
    /// let mut indexes: SparseMatrixData<f64> = HashMap::new();
    ///
    /// indexes.insert((0,0), 2.0);
    /// indexes.insert((0,3), 4.0);
    /// indexes.insert((4,5), 6.0);
    /// indexes.insert((2,7), 8.0);
    ///
    /// let sparse = SparseMatrix::<f64>::init(indexes, (3,3));
    ///
    /// assert_eq!(sparse.shape(), (3,3));
    /// assert_eq!(sparse.get(4,5), None);
    /// assert_eq!(sparse.get(0,1), Some(0.0));
    /// ```
    pub fn init(data: SparseMatrixData<'a, T>, shape: Shape) -> Self {
        Self {
            data,
            nrows: shape.0,
            ncols: shape.1,
            _lifetime: PhantomData::default(),
        }
    }

    /// Returns a sparse eye matrix
    ///
    /// Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(3);
    ///
    /// assert_eq!(sparse.ncols, 3);
    /// assert_eq!(sparse.nrows, 3);
    /// ```
    pub fn eye(size: usize) -> Self {
        let data: SparseMatrixData<'a, T> = (0..size)
            .into_par_iter()
            .map(|i| ((i, i), T::one()))
            .collect();

        Self::init(data, (size, size))
    }

    /// Same as eye
    ///
    /// Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<f64>::identity(3);
    ///
    /// assert_eq!(sparse.ncols, 3);
    /// assert_eq!(sparse.nrows, 3);
    /// ```
    pub fn identity(size: usize) -> Self {
        Self::eye(size)
    }

    /// Reshapes a sparse matrix
    ///
    /// Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse = SparseMatrix::<f64>::identity(3);
    ///
    /// sparse.reshape(5,5);
    ///
    /// assert_eq!(sparse.ncols, 5);
    /// assert_eq!(sparse.nrows, 5);
    /// ```
    pub fn reshape(&mut self, nrows: usize, ncols: usize) {
        self.nrows = nrows;
        self.ncols = ncols;
    }

    /// Creates a sparse matrix from a already existent
    /// dense one.
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::{SparseMatrix, Matrix};
    ///
    /// let dense = Matrix::<i32>::eye(4);
    ///
    /// let sparse = SparseMatrix::from_dense(dense);
    ///
    /// assert_eq!(sparse.get(0,0), Some(1));
    /// assert_eq!(sparse.get(1,0), Some(0));
    /// assert_eq!(sparse.shape(), (4,4));
    /// ```
    pub fn from_dense(matrix: Matrix<'a, T>) -> Self {
        let mut data: SparseMatrixData<'a, T> = HashMap::new();

        for i in 0..matrix.nrows {
            for j in 0..matrix.ncols {
                let val = matrix.get(i, j).unwrap();
                if val != T::zero() {
                    data.insert((i, j), val);
                }
            }
        }

        Self::init(data, matrix.shape())
    }

    /// Gets an element from the sparse matrix.
    ///
    /// Returns None if index is out of bounds.
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(3);
    ///
    /// assert_eq!(sparse.get(0,0), Some(1));
    /// assert_eq!(sparse.get(1,0), Some(0));
    /// assert_eq!(sparse.get(4,0), None);
    /// ```
    pub fn get(&self, i: usize, j: usize) -> Option<T> {
        let idx = at!(i, j, self.ncols);

        if idx >= self.size() {
            eprintln!("Error, index out of bounds. Not setting value");
            return None;
        }

        match self.data.get(&(i, j)) {
            None => Some(T::zero()),
            val => val.copied(),
        }
    }

    /// Same as `get`, but will panic if indexes are out of bounds
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(3);
    ///
    /// assert_eq!(sparse.at(0,0), 1);
    /// assert_eq!(sparse.at(1,0), 0);
    /// ```
    pub fn at(&self, i: usize, j: usize) -> T {
        match self.data.get(&(i, j)) {
            None => T::zero(),
            Some(val) => val.clone(),
        }
    }

    /// Sets an element
    ///
    /// Mutates or inserts a value based on indeces given
    pub fn set(&mut self, idx: Shape, value: T) {
        let i = at!(idx.0, idx.1, self.ncols);

        if i >= self.size() {
            eprintln!("Error, index out of bounds. Not setting value");
            return;
        }

        self.data
            .entry(idx)
            .and_modify(|val| *val = value)
            .or_insert(value);
    }

    /// Prints out the sparse matrix data
    ///
    /// Only prints out the hashmap with a set amount of decimals
    pub fn print(&self, decimals: usize) {
        self.data
            .iter()
            .for_each(|((i, j), val)| println!("{i} {j}: {:.decimals$}", val));
    }

    /// Gets the size of the sparse matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(4);
    ///
    /// assert_eq!(sparse.size(), 16);
    #[inline(always)]
    pub fn size(&self) -> usize {
        self.ncols * self.nrows
    }

    /// Get's amount of 0s in the matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(4);
    ///
    /// assert_eq!(sparse.get_zero_count(), 12);
    #[inline(always)]
    pub fn get_zero_count(&self) -> usize {
        self.size() - self.data.len()
    }

    /// Calcualtes sparcity for the given matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(4);
    ///
    /// assert_eq!(sparse.sparcity(), 0.75);
    /// ```
    #[inline(always)]
    pub fn sparcity(&self) -> f64 {
        1.0 - self.data.par_iter().count() as f64 / self.size() as f64
    }

    /// Shape of the matrix outputted as a tuple
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(3);
    ///
    /// assert_eq!(sparse.shape(), (3,3));
    /// ```
    pub fn shape(&self) -> Shape {
        (self.nrows, self.ncols)
    }

    /// Transpose the matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse = SparseMatrix::<i32>::new(4,4);
    ///
    /// sparse.set((2,0), 1);
    /// sparse.set((3,0), 2);
    /// sparse.set((0,1), 3);
    /// sparse.set((0,2), 4);
    ///
    /// sparse.transpose();
    ///
    /// assert_eq!(sparse.at(0,2), 1);
    /// assert_eq!(sparse.at(0,3), 2);
    /// assert_eq!(sparse.at(1,0), 3);
    /// assert_eq!(sparse.at(2,0), 4);
    ///
    /// // Old value is now gone
    /// assert_eq!(sparse.get(3,0), Some(0));
    /// ```
    pub fn transpose(&mut self) {
        let mut new_data: SparseMatrixData<T> = HashMap::new();

        for (&(i, j), &val) in self.data.iter() {
            new_data.insert((j, i), val);
        }

        self.data = new_data;

        swap(&mut self.nrows, &mut self.ncols);
    }

    /// Shorthand for `transpose`
    pub fn t(&mut self) {
        self.transpose();
    }

    /// Tranpose the matrix into a new copy
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut mat = SparseMatrix::<i32>::new(4,4);
    ///
    /// mat.set((2,0), 1);
    /// mat.set((3,0), 2);
    /// mat.set((0,1), 3);
    /// mat.set((0,2), 4);
    ///
    /// let sparse = mat.transpose_new();
    ///
    /// assert_eq!(sparse.at(0,2), 1);
    /// assert_eq!(sparse.at(0,3), 2);
    /// assert_eq!(sparse.at(1,0), 3);
    /// assert_eq!(sparse.at(2,0), 4);
    ///
    /// assert_eq!(sparse.get(3,0), Some(0));
    /// ```
    pub fn transpose_new(&self) -> Self {
        let mut res = self.clone();
        res.transpose();
        res
    }
}

/// Operations on sparse matrices
impl<'a, T> SparseMatrix<'a, T>
where
    T: MatrixElement,
    <T as FromStr>::Err: Error + 'static,
    Vec<T>: IntoParallelIterator,
    Vec<&'a T>: IntoParallelRefIterator<'a>,
{
    /// Adds two sparse matrices together
    /// and return a new one
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// let res = sparse1.add(&sparse2).unwrap();
    ///
    /// assert_eq!(res.shape(), (3,3));
    /// assert_eq!(res.get(0,0).unwrap(), 2);
    /// ```
    pub fn add(&self, other: &Self) -> Result<Self, MatrixError> {
        Self::sparse_helper(&self, other, Operation::ADD)
    }

    /// Subtracts two sparse matrices
    /// and return a new one
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// let res = sparse1.sub(&sparse2).unwrap();
    ///
    /// assert_eq!(res.shape(), (3,3));
    /// assert_eq!(res.get(0,0).unwrap(), 2);
    /// ```
    pub fn sub(&self, other: &Self) -> Result<Self, MatrixError> {
        Self::sparse_helper(&self, other, Operation::SUB)
    }
    /// Multiplies two sparse matrices together
    /// and return a new one
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// let res = sparse1.mul(&sparse2).unwrap();
    ///
    /// assert_eq!(res.shape(), (3,3));
    /// assert_eq!(res.get(0,0).unwrap(), 2);
    /// ```
    pub fn mul(&self, other: &Self) -> Result<Self, MatrixError> {
        Self::sparse_helper(&self, other, Operation::MUL)
    }
    /// Divides two sparse matrices
    /// and return a new one
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// let res = sparse1.div(&sparse2).unwrap();
    ///
    /// assert_eq!(res.shape(), (3,3));
    /// assert_eq!(res.get(0,0).unwrap(), 2);
    /// ```
    pub fn div(&self, other: &Self) -> Result<Self, MatrixError> {
        Self::sparse_helper(&self, other, Operation::DIV)
    }

    // =============================================================
    //
    //    Matrix operations modifying the lhs
    //
    // =============================================================

    /// Adds rhs matrix on to lhs matrix.
    /// All elements from rhs gets inserted into lhs
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// sparse1.add_self(&sparse2);
    ///
    /// assert_eq!(sparse1.shape(), (3,3));
    /// assert_eq!(sparse1.get(0,0).unwrap(), 2);
    /// ```
    pub fn add_self(&mut self, other: &Self) {
        Self::sparse_helper_self(self, other, Operation::ADD);
    }

    /// Subs rhs matrix on to lhs matrix.
    /// All elements from rhs gets inserted into lhs
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// sparse1.sub_self(&sparse2);
    ///
    /// assert_eq!(sparse1.shape(), (3,3));
    /// assert_eq!(sparse1.get(0,0).unwrap(), 0);
    /// ```
    pub fn sub_self(&mut self, other: &Self) {
        Self::sparse_helper_self(self, other, Operation::SUB);
    }

    /// Multiplies  rhs matrix on to lhs matrix.
    /// All elements from rhs gets inserted into lhs
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// sparse1.mul_self(&sparse2);
    ///
    /// assert_eq!(sparse1.shape(), (3,3));
    /// assert_eq!(sparse1.get(0,0).unwrap(), 1);
    /// ```
    pub fn mul_self(&mut self, other: &Self) {
        Self::sparse_helper_self(self, other, Operation::MUL);
    }

    /// Divides rhs matrix on to lhs matrix.
    /// All elements from rhs gets inserted into lhs
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse1 = SparseMatrix::<i32>::eye(3);
    /// let sparse2 = SparseMatrix::<i32>::eye(3);
    ///
    /// sparse1.div_self(&sparse2);
    ///
    /// assert_eq!(sparse1.shape(), (3,3));
    /// assert_eq!(sparse1.get(0,0).unwrap(), 1);
    /// ```
    pub fn div_self(&mut self, other: &Self) {
        Self::sparse_helper_self(self, other, Operation::DIV);
    }

    // =============================================================
    //
    //    Matrix operations  with a value
    //
    // =============================================================

    /// Adds value to all non zero values in the matrix
    /// and return a new matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<f32>::eye(3);
    /// let val: f32 = 4.5;
    ///
    /// let res = sparse.add_val(val);
    ///
    /// assert_eq!(res.get(0,0).unwrap(), 5.5);
    /// ```
    pub fn add_val(&self, value: T) -> Self {
        Self::sparse_helper_val(self, value, Operation::ADD)
    }

    /// Subs value to all non zero values in the matrix
    /// and return a new matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<f32>::eye(3);
    /// let val: f32 = 4.5;
    ///
    /// let res = sparse.sub_val(val);
    ///
    /// assert_eq!(res.get(0,0).unwrap(), -3.5);
    /// ```
    pub fn sub_val(&self, value: T) -> Self {
        Self::sparse_helper_val(self, value, Operation::SUB)
    }

    /// Multiplies value to all non zero values in the matrix
    /// and return a new matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<f32>::eye(3);
    /// let val: f32 = 4.5;
    ///
    /// let res = sparse.mul_val(val);
    ///
    /// assert_eq!(res.get(0,0).unwrap(), 4.5);
    /// ```
    pub fn mul_val(&self, value: T) -> Self {
        Self::sparse_helper_val(self, value, Operation::MUL)
    }

    /// Divides value to all non zero values in the matrix
    /// and return a new matrix.
    ///
    /// Will panic if you choose to divide by zero
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<f32>::eye(3);
    /// let val: f32 = 4.0;
    ///
    /// let res = sparse.div_val(val);
    ///
    /// assert_eq!(res.get(0,0).unwrap(), 0.25);
    /// ```
    pub fn div_val(&self, value: T) -> Self {
        Self::sparse_helper_val(self, value, Operation::DIV)
    }

    // =============================================================
    //
    //    Matrix operations modyfing lhs  with a value
    //
    // =============================================================

    /// Adds value to all non zero elements in matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse = SparseMatrix::<f64>::eye(3);
    /// let val = 10.0;
    ///
    /// sparse.add_val_self(val);
    ///
    /// assert_eq!(sparse.get(0,0).unwrap(), 11.0);
    /// ```
    pub fn add_val_self(&mut self, value: T) {
        Self::sparse_helper_self_val(self, value, Operation::ADD)
    }

    /// Subtracts value to all non zero elements in matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse = SparseMatrix::<f64>::eye(3);
    /// let val = 10.0;
    ///
    /// sparse.sub_val_self(val);
    ///
    /// assert_eq!(sparse.get(0,0).unwrap(), -9.0);
    /// ```
    pub fn sub_val_self(&mut self, value: T) {
        Self::sparse_helper_self_val(self, value, Operation::SUB)
    }

    /// Multiplies value to all non zero elements in matrix
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse = SparseMatrix::<f64>::eye(3);
    /// let val = 10.0;
    ///
    /// sparse.mul_val_self(val);
    ///
    /// assert_eq!(sparse.get(0,0).unwrap(), 10.0);
    /// ```
    pub fn mul_val_self(&mut self, value: T) {
        Self::sparse_helper_self_val(self, value, Operation::MUL)
    }

    /// Divides all non zero elemnts in matrix by value in-place
    ///
    /// Will panic if you choose to divide by zero
    ///
    /// Examples:
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let mut sparse = SparseMatrix::<f64>::eye(3);
    /// let val = 10.0;
    ///
    /// sparse.div_val_self(val);
    ///
    /// assert_eq!(sparse.get(0,0).unwrap(), 0.1);
    /// ```
    pub fn div_val_self(&mut self, value: T) {
        Self::sparse_helper_self_val(self, value, Operation::DIV)
    }

    /// Sparse matrix multiplication
    //sparse_/
    /// Coming soon
    fn matmul_sparse(&self, other: &Self) -> Self {
        unimplemented!()
    }
}

/// Predicates for sparse matrices
impl<'a, T> SparseMatrix<'a, T>
where
    T: MatrixElement,
    <T as FromStr>::Err: Error + 'static,
    Vec<T>: IntoParallelIterator,
    Vec<&'a T>: IntoParallelRefIterator<'a>,
{
    /// Returns whether or not predicate holds for all values
    ///
    /// # Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(3);
    ///
    /// assert_eq!(sparse.shape(), (3,3));
    /// assert_eq!(sparse.all(|(idx, val)| val >= 0), true);
    /// ```
    pub fn all<F>(&self, pred: F) -> bool
    where
        F: Fn((Shape, T)) -> bool + Sync + Send,
    {
        self.data.clone().into_par_iter().all(pred)
    }

    /// Returns whether or not predicate holds for any
    ///
    /// # Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(3);
    ///
    /// assert_eq!(sparse.shape(), (3,3));
    /// assert_eq!(sparse.any(|(_, val)| val == 1), true);
    /// ```
    pub fn any<F>(&self, pred: F) -> bool
    where
        F: Fn((Shape, T)) -> bool + Sync + Send,
    {
        self.data.clone().into_par_iter().any(pred)
    }

    /// Counts all occurances where predicate holds
    ///
    /// # Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<i32>::eye(3);
    ///
    /// assert_eq!(sparse.count_where(|(_, &val)| val == 1), 3);
    /// ```
    pub fn count_where<F>(&'a self, pred: F) -> usize
    where
        F: Fn((&Shape, &T)) -> bool + Sync,
    {
        self.data.par_iter().filter(|&e| pred(e)).count()
    }

    /// Sums all occurances where predicate holds
    ///
    /// # Examples
    ///
    /// ```
    /// use sukker::SparseMatrix;
    ///
    /// let sparse = SparseMatrix::<f32>::eye(3);
    ///
    /// assert_eq!(sparse.sum_where(|(&(i, j), &val)| val == 1.0 && i > 0), 2.0);
    /// ```
    pub fn sum_where<F>(&self, pred: F) -> T
    where
        F: Fn((&Shape, &T)) -> bool + Sync,
    {
        let mut res = T::zero();
        for (idx, elem) in self.data.iter() {
            if pred((idx, elem)) {
                res += elem
            }
        }

        res
    }

    /// Sets all elements where predicate holds true.
    /// The new value is to be set inside the predicate as well
    ///
    /// # Examples
    ///
    /// ```
    /// ```
    pub fn set_where<F>(&mut self, mut pred: F)
    where
        F: FnMut((&Shape, &mut T)) + Sync + Send,
    {
        self.data.iter_mut().for_each(|e| pred(e));
    }

    fn find<F>(&self, pred: F) -> Option<Shape>
    where
        F: Fn(&T) -> bool + Sync,
    {
        unimplemented!()
    }

    /// Finds all indeces where predicates holds if possible
    ///
    /// # Examples
    ///
    /// ```
    /// ```
    fn find_all<F>(&self, pred: F) -> Option<Vec<Shape>>
    where
        F: Fn(&T) -> bool + Sync,
    {
        unimplemented!()
    }
}