scirs2-sparse 0.4.2

Sparse matrix module for SciRS2 (scirs2-sparse)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
// CSR Array implementation
//
// This module provides the CSR (Compressed Sparse Row) array format,
// which is efficient for row-wise operations and is one of the most common formats.

use scirs2_core::ndarray::{Array1, Array2, ArrayView1};
use scirs2_core::numeric::{Float, SparseElement, Zero};
use std::fmt::{self, Debug};
use std::ops::{Add, Div, Mul, Sub};

use crate::error::{SparseError, SparseResult};
use crate::sparray::{SparseArray, SparseSum};

/// Insert a value into an `Array1` at position `idx`, shifting subsequent
/// elements to the right.  ndarray's `Array1` does not provide an insert
/// method, so we convert to `Vec`, insert, and convert back.
fn array1_insert<T: Clone + Default>(arr: &Array1<T>, idx: usize, value: T) -> Array1<T> {
    let mut v = arr.to_vec();
    v.insert(idx, value);
    Array1::from_vec(v)
}

/// CSR Array format - Compressed Sparse Row matrix representation
///
/// The CSR (Compressed Sparse Row) format is one of the most popular sparse matrix formats,
/// storing a sparse array using three arrays:
/// - `data`: array of non-zero values in row-major order
/// - `indices`: column indices of the non-zero values
/// - `indptr`: row pointers; `indptr[i]` is the index into `data`/`indices` where row `i` starts
///
/// The CSR format is particularly efficient for:
/// - ✅ Matrix-vector multiplications (`A * x`)
/// - ✅ Matrix-matrix multiplications with other sparse matrices
/// - ✅ Row-wise operations and row slicing
/// - ✅ Iterating over non-zero elements row by row
/// - ✅ Adding and subtracting sparse matrices
///
/// But less efficient for:
/// - ❌ Column-wise operations and column slicing
/// - ❌ Inserting or modifying individual elements after construction
/// - ❌ Operations that require column access patterns
///
/// # Memory Layout
///
/// For a matrix with `m` rows, `n` columns, and `nnz` non-zero elements:
/// - `data`: length `nnz` - stores the actual non-zero values
/// - `indices`: length `nnz` - stores column indices for each non-zero value
/// - `indptr`: length `m+1` - stores cumulative count of non-zeros per row
///
/// # Examples
///
/// ## Basic Construction and Access
/// ```
/// use scirs2_sparse::csr_array::CsrArray;
/// use scirs2_sparse::SparseArray;
///
/// // Create a 3x3 matrix:
/// // [1.0, 0.0, 2.0]
/// // [0.0, 3.0, 0.0]
/// // [4.0, 0.0, 5.0]
/// let rows = vec![0, 0, 1, 2, 2];
/// let cols = vec![0, 2, 1, 0, 2];
/// let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
/// let matrix = CsrArray::from_triplets(&rows, &cols, &data, (3, 3), false).expect("Operation failed");
///
/// // Access elements
/// assert_eq!(matrix.get(0, 0), 1.0);
/// assert_eq!(matrix.get(0, 1), 0.0);  // Zero element
/// assert_eq!(matrix.get(1, 1), 3.0);
///
/// // Get matrix properties
/// assert_eq!(matrix.shape(), (3, 3));
/// assert_eq!(matrix.nnz(), 5);
/// ```
///
/// ## Matrix Operations
/// ```
/// use scirs2_sparse::csr_array::CsrArray;
/// use scirs2_sparse::SparseArray;
/// use scirs2_core::ndarray::Array1;
///
/// let rows = vec![0, 1, 2];
/// let cols = vec![0, 1, 2];
/// let data = vec![2.0, 3.0, 4.0];
/// let matrix = CsrArray::from_triplets(&rows, &cols, &data, (3, 3), false).expect("Operation failed");
///
/// // Matrix-vector multiplication
/// let x = Array1::from_vec(vec![1.0, 2.0, 3.0]);
/// let y = matrix.dot_vector(&x.view()).expect("Operation failed");
/// assert_eq!(y[0], 2.0);  // 2.0 * 1.0
/// assert_eq!(y[1], 6.0);  // 3.0 * 2.0
/// assert_eq!(y[2], 12.0); // 4.0 * 3.0
/// ```
///
/// ## Format Conversion
/// ```
/// use scirs2_sparse::csr_array::CsrArray;
/// use scirs2_sparse::SparseArray;
///
/// let rows = vec![0, 1];
/// let cols = vec![0, 1];
/// let data = vec![1.0, 2.0];
/// let csr = CsrArray::from_triplets(&rows, &cols, &data, (2, 2), false).expect("Operation failed");
///
/// // Convert to dense array
/// let dense = csr.to_array();
/// assert_eq!(dense[[0, 0]], 1.0);
/// assert_eq!(dense[[1, 1]], 2.0);
///
/// // Convert to other sparse formats
/// let coo = csr.to_coo();
/// let csc = csr.to_csc();
/// ```
#[derive(Clone)]
pub struct CsrArray<T>
where
    T: SparseElement + Div<Output = T> + 'static,
{
    /// Non-zero values
    data: Array1<T>,
    /// Column indices of non-zero values
    indices: Array1<usize>,
    /// Row pointers (indices into data/indices for the start of each row)
    indptr: Array1<usize>,
    /// Shape of the sparse array
    shape: (usize, usize),
    /// Whether indices are sorted for each row
    has_sorted_indices: bool,
}

impl<T> CsrArray<T>
where
    T: SparseElement + Div<Output = T> + Zero + 'static,
{
    /// Creates a new CSR array from raw components
    ///
    /// # Arguments
    /// * `data` - Array of non-zero values
    /// * `indices` - Column indices of non-zero values
    /// * `indptr` - Index pointers for the start of each row
    /// * `shape` - Shape of the sparse array
    ///
    /// # Returns
    /// A new `CsrArray`
    ///
    /// # Errors
    /// Returns an error if the data is not consistent
    pub fn new(
        data: Array1<T>,
        indices: Array1<usize>,
        indptr: Array1<usize>,
        shape: (usize, usize),
    ) -> SparseResult<Self> {
        // Validation
        if data.len() != indices.len() {
            return Err(SparseError::InconsistentData {
                reason: "data and indices must have the same length".to_string(),
            });
        }

        if indptr.len() != shape.0 + 1 {
            return Err(SparseError::InconsistentData {
                reason: format!(
                    "indptr length ({}) must be one more than the number of rows ({})",
                    indptr.len(),
                    shape.0
                ),
            });
        }

        if let Some(&max_idx) = indices.iter().max() {
            if max_idx >= shape.1 {
                return Err(SparseError::IndexOutOfBounds {
                    index: (0, max_idx),
                    shape,
                });
            }
        }

        if let Some((&last, &first)) = indptr.iter().next_back().zip(indptr.iter().next()) {
            if first != 0 {
                return Err(SparseError::InconsistentData {
                    reason: "first element of indptr must be 0".to_string(),
                });
            }

            if last != data.len() {
                return Err(SparseError::InconsistentData {
                    reason: format!(
                        "last element of indptr ({}) must equal data length ({})",
                        last,
                        data.len()
                    ),
                });
            }
        }

        let has_sorted_indices = Self::check_sorted_indices(&indices, &indptr);

        Ok(Self {
            data,
            indices,
            indptr,
            shape,
            has_sorted_indices,
        })
    }

    /// Create a CSR array from triplet format (COO-like)
    ///
    /// This function creates a CSR (Compressed Sparse Row) array from coordinate triplets.
    /// The triplets represent non-zero elements as (row, column, value) tuples.
    ///
    /// # Arguments
    /// * `rows` - Row indices of non-zero elements
    /// * `cols` - Column indices of non-zero elements  
    /// * `data` - Values of non-zero elements
    /// * `shape` - Shape of the sparse array (nrows, ncols)
    /// * `sorted` - Whether the triplets are already sorted by (row, col). If false, sorting will be performed.
    ///
    /// # Returns
    /// A new `CsrArray` containing the sparse matrix
    ///
    /// # Errors
    /// Returns an error if:
    /// - `rows`, `cols`, and `data` have different lengths
    /// - Any index is out of bounds for the given shape
    /// - The resulting data structure is inconsistent
    ///
    /// # Examples
    ///
    /// Create a simple 3x3 sparse matrix:
    /// ```
    /// use scirs2_sparse::csr_array::CsrArray;
    /// use scirs2_sparse::SparseArray;
    ///
    /// // Create a 3x3 matrix with the following structure:
    /// // [1.0, 0.0, 2.0]
    /// // [0.0, 3.0, 0.0]
    /// // [4.0, 0.0, 5.0]
    /// let rows = vec![0, 0, 1, 2, 2];
    /// let cols = vec![0, 2, 1, 0, 2];
    /// let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    /// let shape = (3, 3);
    ///
    /// let matrix = CsrArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");
    /// assert_eq!(matrix.get(0, 0), 1.0);
    /// assert_eq!(matrix.get(0, 1), 0.0);
    /// assert_eq!(matrix.get(1, 1), 3.0);
    /// ```
    ///
    /// Create an empty sparse matrix:
    /// ```
    /// use scirs2_sparse::csr_array::CsrArray;
    /// use scirs2_sparse::SparseArray;
    ///
    /// let rows: Vec<usize> = vec![];
    /// let cols: Vec<usize> = vec![];
    /// let data: Vec<f64> = vec![];
    /// let shape = (5, 5);
    ///
    /// let matrix = CsrArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");
    /// assert_eq!(matrix.nnz(), 0);
    /// assert_eq!(matrix.shape(), (5, 5));
    /// ```
    ///
    /// Handle duplicate entries (they will be preserved):
    /// ```
    /// use scirs2_sparse::csr_array::CsrArray;
    /// use scirs2_sparse::SparseArray;
    ///
    /// // Multiple entries at the same position
    /// let rows = vec![0, 0];
    /// let cols = vec![0, 0];
    /// let data = vec![1.0, 2.0];
    /// let shape = (2, 2);
    ///
    /// let matrix = CsrArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");
    /// // Note: CSR format preserves duplicates; use sum_duplicates() to combine them
    /// assert_eq!(matrix.nnz(), 2);
    /// ```
    pub fn from_triplets(
        rows: &[usize],
        cols: &[usize],
        data: &[T],
        shape: (usize, usize),
        sorted: bool,
    ) -> SparseResult<Self> {
        if rows.len() != cols.len() || rows.len() != data.len() {
            return Err(SparseError::InconsistentData {
                reason: "rows, cols, and data must have the same length".to_string(),
            });
        }

        if rows.is_empty() {
            // Empty matrix
            let indptr = Array1::zeros(shape.0 + 1);
            return Self::new(Array1::zeros(0), Array1::zeros(0), indptr, shape);
        }

        let nnz = rows.len();
        let mut all_data: Vec<(usize, usize, T)> = Vec::with_capacity(nnz);

        for i in 0..nnz {
            if rows[i] >= shape.0 || cols[i] >= shape.1 {
                return Err(SparseError::IndexOutOfBounds {
                    index: (rows[i], cols[i]),
                    shape,
                });
            }
            all_data.push((rows[i], cols[i], data[i]));
        }

        if !sorted {
            all_data.sort_by_key(|&(row, col_, _)| (row, col_));
        }

        // Count elements per row
        let mut row_counts = vec![0; shape.0];
        for &(row_, _, _) in &all_data {
            row_counts[row_] += 1;
        }

        // Create indptr
        let mut indptr = Vec::with_capacity(shape.0 + 1);
        indptr.push(0);
        let mut cumsum = 0;
        for &count in &row_counts {
            cumsum += count;
            indptr.push(cumsum);
        }

        // Create indices and data arrays
        let mut indices = Vec::with_capacity(nnz);
        let mut values = Vec::with_capacity(nnz);

        for (_, col, val) in all_data {
            indices.push(col);
            values.push(val);
        }

        Self::new(
            Array1::from_vec(values),
            Array1::from_vec(indices),
            Array1::from_vec(indptr),
            shape,
        )
    }

    /// Checks if column indices are sorted for each row
    fn check_sorted_indices(indices: &Array1<usize>, indptr: &Array1<usize>) -> bool {
        for row in 0..indptr.len() - 1 {
            let start = indptr[row];
            let end = indptr[row + 1];

            for i in start..end.saturating_sub(1) {
                if i + 1 < indices.len() && indices[i] > indices[i + 1] {
                    return false;
                }
            }
        }
        true
    }

    /// Get the raw data array
    pub fn get_data(&self) -> &Array1<T> {
        &self.data
    }

    /// Get the raw indices array
    pub fn get_indices(&self) -> &Array1<usize> {
        &self.indices
    }

    /// Get the raw indptr array
    pub fn get_indptr(&self) -> &Array1<usize> {
        &self.indptr
    }

    /// Get the number of rows
    pub fn nrows(&self) -> usize {
        self.shape.0
    }

    /// Get the number of columns  
    pub fn ncols(&self) -> usize {
        self.shape.1
    }

    /// Get the shape (rows, cols)
    pub fn shape(&self) -> (usize, usize) {
        self.shape
    }
}

impl<T> SparseArray<T> for CsrArray<T>
where
    T: SparseElement + Div<Output = T> + PartialOrd + Zero + 'static,
{
    fn shape(&self) -> (usize, usize) {
        self.shape
    }

    fn nnz(&self) -> usize {
        self.data.len()
    }

    fn dtype(&self) -> &str {
        "float" // Placeholder, ideally we would return the actual type
    }

    fn to_array(&self) -> Array2<T> {
        let (rows, cols) = self.shape;
        let mut result = Array2::zeros((rows, cols));

        for row in 0..rows {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            for i in start..end {
                let col = self.indices[i];
                result[[row, col]] = self.data[i];
            }
        }

        result
    }

    fn toarray(&self) -> Array2<T> {
        self.to_array()
    }

    fn to_coo(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to COO format
        // For now we just return self
        Ok(Box::new(self.clone()))
    }

    fn to_csr(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        Ok(Box::new(self.clone()))
    }

    fn to_csc(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to CSC format
        // For now we just return self
        Ok(Box::new(self.clone()))
    }

    fn to_dok(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to DOK format
        // For now we just return self
        Ok(Box::new(self.clone()))
    }

    fn to_lil(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to LIL format
        // For now we just return self
        Ok(Box::new(self.clone()))
    }

    fn to_dia(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to DIA format
        // For now we just return self
        Ok(Box::new(self.clone()))
    }

    fn to_bsr(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to BSR format
        // For now we just return self
        Ok(Box::new(self.clone()))
    }

    fn add(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        if self.shape() != other.shape() {
            return Err(SparseError::DimensionMismatch {
                expected: self.shape().0,
                found: other.shape().0,
            });
        }

        // Fast path: if `other` is also a CsrArray with sorted indices,
        // perform a sorted row merge in O(nnz(A) + nnz(B)) time.
        if let Some(other_csr) = other.as_any().downcast_ref::<CsrArray<T>>() {
            if self.has_sorted_indices && other_csr.has_sorted_indices {
                let (nrows, _) = self.shape();
                let mut data = Vec::new();
                let mut indices = Vec::new();
                let mut indptr = vec![0usize];

                for row in 0..nrows {
                    let a_start = self.indptr[row];
                    let a_end = self.indptr[row + 1];
                    let b_start = other_csr.indptr[row];
                    let b_end = other_csr.indptr[row + 1];

                    let a_cols = &self.indices.as_slice().unwrap_or(&[])[a_start..a_end];
                    let a_data = &self.data.as_slice().unwrap_or(&[])[a_start..a_end];
                    let b_cols = &other_csr.indices.as_slice().unwrap_or(&[])[b_start..b_end];
                    let b_data = &other_csr.data.as_slice().unwrap_or(&[])[b_start..b_end];

                    let mut ai = 0;
                    let mut bi = 0;
                    while ai < a_cols.len() && bi < b_cols.len() {
                        if a_cols[ai] < b_cols[bi] {
                            let val = a_data[ai];
                            if val != T::sparse_zero() {
                                data.push(val);
                                indices.push(a_cols[ai]);
                            }
                            ai += 1;
                        } else if a_cols[ai] > b_cols[bi] {
                            let val = b_data[bi];
                            if val != T::sparse_zero() {
                                data.push(val);
                                indices.push(b_cols[bi]);
                            }
                            bi += 1;
                        } else {
                            let val = a_data[ai] + b_data[bi];
                            if val != T::sparse_zero() {
                                data.push(val);
                                indices.push(a_cols[ai]);
                            }
                            ai += 1;
                            bi += 1;
                        }
                    }
                    while ai < a_cols.len() {
                        let val = a_data[ai];
                        if val != T::sparse_zero() {
                            data.push(val);
                            indices.push(a_cols[ai]);
                        }
                        ai += 1;
                    }
                    while bi < b_cols.len() {
                        let val = b_data[bi];
                        if val != T::sparse_zero() {
                            data.push(val);
                            indices.push(b_cols[bi]);
                        }
                        bi += 1;
                    }
                    indptr.push(data.len());
                }

                return CsrArray::new(
                    Array1::from_vec(data),
                    Array1::from_vec(indices),
                    Array1::from_vec(indptr),
                    self.shape(),
                )
                .map(|array| Box::new(array) as Box<dyn SparseArray<T>>);
            }
        }

        // Fallback: dense conversion
        let self_array = self.to_array();
        let other_array = other.to_array();
        let result = &self_array + &other_array;

        let (rows, cols) = self.shape();
        let mut data = Vec::new();
        let mut indices = Vec::new();
        let mut indptr = vec![0];

        for row in 0..rows {
            for col in 0..cols {
                let val = result[[row, col]];
                if val != T::sparse_zero() {
                    data.push(val);
                    indices.push(col);
                }
            }
            indptr.push(data.len());
        }

        CsrArray::new(
            Array1::from_vec(data),
            Array1::from_vec(indices),
            Array1::from_vec(indptr),
            self.shape(),
        )
        .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn sub(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // Similar to add, this is a placeholder
        let self_array = self.to_array();
        let other_array = other.to_array();

        if self.shape() != other.shape() {
            return Err(SparseError::DimensionMismatch {
                expected: self.shape().0,
                found: other.shape().0,
            });
        }

        let result = &self_array - &other_array;

        // Convert back to CSR
        let (rows, cols) = self.shape();
        let mut data = Vec::new();
        let mut indices = Vec::new();
        let mut indptr = vec![0];

        for row in 0..rows {
            for col in 0..cols {
                let val = result[[row, col]];
                if val != T::sparse_zero() {
                    data.push(val);
                    indices.push(col);
                }
            }
            indptr.push(data.len());
        }

        CsrArray::new(
            Array1::from_vec(data),
            Array1::from_vec(indices),
            Array1::from_vec(indptr),
            self.shape(),
        )
        .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn mul(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This is element-wise multiplication (Hadamard product)
        // In the sparse array API, * is element-wise, not matrix multiplication
        let self_array = self.to_array();
        let other_array = other.to_array();

        if self.shape() != other.shape() {
            return Err(SparseError::DimensionMismatch {
                expected: self.shape().0,
                found: other.shape().0,
            });
        }

        let result = &self_array * &other_array;

        // Convert back to CSR
        let (rows, cols) = self.shape();
        let mut data = Vec::new();
        let mut indices = Vec::new();
        let mut indptr = vec![0];

        for row in 0..rows {
            for col in 0..cols {
                let val = result[[row, col]];
                if val != T::sparse_zero() {
                    data.push(val);
                    indices.push(col);
                }
            }
            indptr.push(data.len());
        }

        CsrArray::new(
            Array1::from_vec(data),
            Array1::from_vec(indices),
            Array1::from_vec(indptr),
            self.shape(),
        )
        .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn div(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // Element-wise division
        let self_array = self.to_array();
        let other_array = other.to_array();

        if self.shape() != other.shape() {
            return Err(SparseError::DimensionMismatch {
                expected: self.shape().0,
                found: other.shape().0,
            });
        }

        let result = &self_array / &other_array;

        // Convert back to CSR
        let (rows, cols) = self.shape();
        let mut data = Vec::new();
        let mut indices = Vec::new();
        let mut indptr = vec![0];

        for row in 0..rows {
            for col in 0..cols {
                let val = result[[row, col]];
                if val != T::sparse_zero() {
                    data.push(val);
                    indices.push(col);
                }
            }
            indptr.push(data.len());
        }

        CsrArray::new(
            Array1::from_vec(data),
            Array1::from_vec(indices),
            Array1::from_vec(indptr),
            self.shape(),
        )
        .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn dot(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        let (m, n) = self.shape();
        let (p, q) = other.shape();

        if n != p {
            return Err(SparseError::DimensionMismatch {
                expected: n,
                found: p,
            });
        }

        // Fast path: if `other` is also a CsrArray, use scatter-gather
        // row-by-row multiplication in O(nnz(A) * avg_nnz_per_row(B)) time.
        if let Some(other_csr) = other.as_any().downcast_ref::<CsrArray<T>>() {
            let mut data = Vec::new();
            let mut col_indices = Vec::new();
            let mut indptr = vec![0usize];

            let mut workspace = vec![T::sparse_zero(); q];
            let mut marker = vec![false; q];

            for i in 0..m {
                let a_start = self.indptr[i];
                let a_end = self.indptr[i + 1];
                let mut touched: Vec<usize> = Vec::new();

                for a_idx in a_start..a_end {
                    let k = self.indices[a_idx];
                    let a_ik = self.data[a_idx];
                    if a_ik == T::sparse_zero() {
                        continue;
                    }
                    let b_start = other_csr.indptr[k];
                    let b_end = other_csr.indptr[k + 1];
                    for b_idx in b_start..b_end {
                        let j = other_csr.indices[b_idx];
                        workspace[j] = workspace[j] + a_ik * other_csr.data[b_idx];
                        if !marker[j] {
                            marker[j] = true;
                            touched.push(j);
                        }
                    }
                }

                touched.sort_unstable();
                for &j in &touched {
                    let val = workspace[j];
                    if val != T::sparse_zero() {
                        data.push(val);
                        col_indices.push(j);
                    }
                    workspace[j] = T::sparse_zero();
                    marker[j] = false;
                }
                indptr.push(data.len());
            }

            return CsrArray::new(
                Array1::from_vec(data),
                Array1::from_vec(col_indices),
                Array1::from_vec(indptr),
                (m, q),
            )
            .map(|array| Box::new(array) as Box<dyn SparseArray<T>>);
        }

        // Fallback: use dense `other` matrix
        let other_array = other.to_array();
        let mut data = Vec::new();
        let mut col_indices = Vec::new();
        let mut indptr = vec![0];

        for row in 0..m {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            for j in 0..q {
                let mut sum = T::sparse_zero();
                for idx in start..end {
                    let col = self.indices[idx];
                    sum = sum + self.data[idx] * other_array[[col, j]];
                }
                if sum != T::sparse_zero() {
                    data.push(sum);
                    col_indices.push(j);
                }
            }
            indptr.push(data.len());
        }

        CsrArray::new(
            Array1::from_vec(data),
            Array1::from_vec(col_indices),
            Array1::from_vec(indptr),
            (m, q),
        )
        .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn dot_vector(&self, other: &ArrayView1<T>) -> SparseResult<Array1<T>> {
        let (m, n) = self.shape();
        if n != other.len() {
            return Err(SparseError::DimensionMismatch {
                expected: n,
                found: other.len(),
            });
        }

        let mut result = Array1::zeros(m);

        for row in 0..m {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            let mut sum = T::sparse_zero();
            for idx in start..end {
                let col = self.indices[idx];
                sum = sum + self.data[idx] * other[col];
            }
            result[row] = sum;
        }

        Ok(result)
    }

    fn transpose(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // Transpose is non-trivial for CSR format
        // A full implementation would convert to CSC format or implement
        // an efficient algorithm
        let (rows, cols) = self.shape();
        let mut row_indices = Vec::with_capacity(self.nnz());
        let mut col_indices = Vec::with_capacity(self.nnz());
        let mut values = Vec::with_capacity(self.nnz());

        for row in 0..rows {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            for idx in start..end {
                let col = self.indices[idx];
                row_indices.push(col); // Note: rows and cols are swapped for transposition
                col_indices.push(row);
                values.push(self.data[idx]);
            }
        }

        // We need to create CSR from this "COO" representation
        CsrArray::from_triplets(
            &row_indices,
            &col_indices,
            &values,
            (cols, rows), // Swapped dimensions
            false,
        )
        .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn copy(&self) -> Box<dyn SparseArray<T>> {
        Box::new(self.clone())
    }

    fn get(&self, i: usize, j: usize) -> T {
        if i >= self.shape.0 || j >= self.shape.1 {
            return T::sparse_zero();
        }

        let start = self.indptr[i];
        let end = self.indptr[i + 1];

        for idx in start..end {
            if self.indices[idx] == j {
                return self.data[idx];
            }
            // If indices are sorted, we can break early
            if self.has_sorted_indices && self.indices[idx] > j {
                break;
            }
        }

        T::sparse_zero()
    }

    fn set(&mut self, i: usize, j: usize, value: T) -> SparseResult<()> {
        if i >= self.shape.0 || j >= self.shape.1 {
            return Err(SparseError::IndexOutOfBounds {
                index: (i, j),
                shape: self.shape,
            });
        }

        let start = self.indptr[i];
        let end = self.indptr[i + 1];

        // Try to find existing element
        for idx in start..end {
            if self.indices[idx] == j {
                self.data[idx] = value;
                return Ok(());
            }
            if self.has_sorted_indices && self.indices[idx] > j {
                // Insert at position `idx` to maintain sorted order
                self.data = array1_insert(&self.data, idx, value);
                self.indices = array1_insert(&self.indices, idx, j);
                // Increment indptr for all subsequent rows
                for row_ptr in self.indptr.iter_mut().skip(i + 1) {
                    *row_ptr += 1;
                }
                return Ok(());
            }
        }

        // Element not found - insert at end of this row's range
        self.data = array1_insert(&self.data, end, value);
        self.indices = array1_insert(&self.indices, end, j);
        // Increment indptr for all subsequent rows
        for row_ptr in self.indptr.iter_mut().skip(i + 1) {
            *row_ptr += 1;
        }
        // If we inserted at the end, indices may no longer be sorted
        // (only if there are elements after this row that come before j).
        // Re-check sorted state for this row.
        if self.has_sorted_indices {
            let new_end = self.indptr[i + 1];
            let new_start = self.indptr[i];
            for k in new_start..new_end.saturating_sub(1) {
                if self.indices[k] > self.indices[k + 1] {
                    self.has_sorted_indices = false;
                    break;
                }
            }
        }
        Ok(())
    }

    fn eliminate_zeros(&mut self) {
        // Find all non-zero entries
        let mut new_data = Vec::new();
        let mut new_indices = Vec::new();
        let mut new_indptr = vec![0];

        let (rows, _) = self.shape();

        for row in 0..rows {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            for idx in start..end {
                if !SparseElement::is_zero(&self.data[idx]) {
                    new_data.push(self.data[idx]);
                    new_indices.push(self.indices[idx]);
                }
            }
            new_indptr.push(new_data.len());
        }

        // Replace data with filtered data
        self.data = Array1::from_vec(new_data);
        self.indices = Array1::from_vec(new_indices);
        self.indptr = Array1::from_vec(new_indptr);
    }

    fn sort_indices(&mut self) {
        if self.has_sorted_indices {
            return;
        }

        let (rows, _) = self.shape();

        for row in 0..rows {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            if start == end {
                continue;
            }

            // Extract the non-zero elements for this row
            let mut row_data = Vec::with_capacity(end - start);
            for idx in start..end {
                row_data.push((self.indices[idx], self.data[idx]));
            }

            // Sort by column index
            row_data.sort_by_key(|&(col_, _)| col_);

            // Put the sorted data back
            for (i, (col, val)) in row_data.into_iter().enumerate() {
                self.indices[start + i] = col;
                self.data[start + i] = val;
            }
        }

        self.has_sorted_indices = true;
    }

    fn sorted_indices(&self) -> Box<dyn SparseArray<T>> {
        if self.has_sorted_indices {
            return Box::new(self.clone());
        }

        let mut sorted = self.clone();
        sorted.sort_indices();
        Box::new(sorted)
    }

    fn has_sorted_indices(&self) -> bool {
        self.has_sorted_indices
    }

    fn sum(&self, axis: Option<usize>) -> SparseResult<SparseSum<T>> {
        match axis {
            None => {
                // Sum all elements
                let mut sum = T::sparse_zero();
                for &val in self.data.iter() {
                    sum = sum + val;
                }
                Ok(SparseSum::Scalar(sum))
            }
            Some(0) => {
                // Sum along rows (result is a row vector)
                let (_, cols) = self.shape();
                let mut result = vec![T::sparse_zero(); cols];

                for row in 0..self.shape.0 {
                    let start = self.indptr[row];
                    let end = self.indptr[row + 1];

                    for idx in start..end {
                        let col = self.indices[idx];
                        result[col] = result[col] + self.data[idx];
                    }
                }

                // Convert to CSR format
                let mut data = Vec::new();
                let mut indices = Vec::new();
                let mut indptr = vec![0];

                for (col, &val) in result.iter().enumerate() {
                    if val != T::sparse_zero() {
                        data.push(val);
                        indices.push(col);
                    }
                }
                indptr.push(data.len());

                let result_array = CsrArray::new(
                    Array1::from_vec(data),
                    Array1::from_vec(indices),
                    Array1::from_vec(indptr),
                    (1, cols),
                )?;

                Ok(SparseSum::SparseArray(Box::new(result_array)))
            }
            Some(1) => {
                // Sum along columns (result is a column vector)
                let mut result = Vec::with_capacity(self.shape.0);

                for row in 0..self.shape.0 {
                    let start = self.indptr[row];
                    let end = self.indptr[row + 1];

                    let mut row_sum = T::sparse_zero();
                    for idx in start..end {
                        row_sum = row_sum + self.data[idx];
                    }
                    result.push(row_sum);
                }

                // Convert to CSR format
                let mut data = Vec::new();
                let mut indices = Vec::new();
                let mut indptr = vec![0];

                for &val in result.iter() {
                    if val != T::sparse_zero() {
                        data.push(val);
                        indices.push(0);
                        indptr.push(data.len());
                    } else {
                        indptr.push(data.len());
                    }
                }

                let result_array = CsrArray::new(
                    Array1::from_vec(data),
                    Array1::from_vec(indices),
                    Array1::from_vec(indptr),
                    (self.shape.0, 1),
                )?;

                Ok(SparseSum::SparseArray(Box::new(result_array)))
            }
            _ => Err(SparseError::InvalidAxis),
        }
    }

    fn max(&self) -> T {
        if self.data.is_empty() {
            // Empty sparse matrix - all elements are implicitly zero
            return T::sparse_zero();
        }

        let mut max_val = self.data[0];
        for &val in self.data.iter().skip(1) {
            if val > max_val {
                max_val = val;
            }
        }

        // Check if max_val is less than zero, as zeros aren't explicitly stored
        // If the matrix has implicit zeros and max_val < 0, then max is 0
        let zero = T::sparse_zero();
        if max_val < zero && self.nnz() < self.shape.0 * self.shape.1 {
            max_val = zero;
        }

        max_val
    }

    fn min(&self) -> T {
        if self.data.is_empty() {
            // Empty sparse matrix - all elements are implicitly zero
            return T::sparse_zero();
        }

        let mut min_val = self.data[0];
        for &val in self.data.iter().skip(1) {
            if val < min_val {
                min_val = val;
            }
        }

        // Check if min_val is greater than zero, as zeros aren't explicitly stored
        // If the matrix has implicit zeros and min_val > 0, then min is 0
        let zero = T::sparse_zero();
        if min_val > zero && self.nnz() < self.shape.0 * self.shape.1 {
            min_val = zero;
        }

        min_val
    }

    fn find(&self) -> (Array1<usize>, Array1<usize>, Array1<T>) {
        let nnz = self.nnz();
        let mut rows = Vec::with_capacity(nnz);
        let mut cols = Vec::with_capacity(nnz);
        let mut values = Vec::with_capacity(nnz);

        for row in 0..self.shape.0 {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            for idx in start..end {
                let col = self.indices[idx];
                rows.push(row);
                cols.push(col);
                values.push(self.data[idx]);
            }
        }

        (
            Array1::from_vec(rows),
            Array1::from_vec(cols),
            Array1::from_vec(values),
        )
    }

    fn slice(
        &self,
        row_range: (usize, usize),
        col_range: (usize, usize),
    ) -> SparseResult<Box<dyn SparseArray<T>>> {
        let (start_row, end_row) = row_range;
        let (start_col, end_col) = col_range;

        if start_row >= self.shape.0
            || end_row > self.shape.0
            || start_col >= self.shape.1
            || end_col > self.shape.1
        {
            return Err(SparseError::InvalidSliceRange);
        }

        if start_row >= end_row || start_col >= end_col {
            return Err(SparseError::InvalidSliceRange);
        }

        let mut data = Vec::new();
        let mut indices = Vec::new();
        let mut indptr = vec![0];

        for row in start_row..end_row {
            let start = self.indptr[row];
            let end = self.indptr[row + 1];

            for idx in start..end {
                let col = self.indices[idx];
                if col >= start_col && col < end_col {
                    data.push(self.data[idx]);
                    indices.push(col - start_col);
                }
            }
            indptr.push(data.len());
        }

        CsrArray::new(
            Array1::from_vec(data),
            Array1::from_vec(indices),
            Array1::from_vec(indptr),
            (end_row - start_row, end_col - start_col),
        )
        .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn get_indptr(&self) -> Option<&Array1<usize>> {
        Some(&self.indptr)
    }

    fn indptr(&self) -> Option<&Array1<usize>> {
        Some(&self.indptr)
    }
}

impl<T> fmt::Debug for CsrArray<T>
where
    T: SparseElement + Div<Output = T> + PartialOrd + Zero + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "CsrArray<{}x{}, nnz={}>",
            self.shape.0,
            self.shape.1,
            self.nnz()
        )
    }
}

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

    #[test]
    fn test_csr_array_construction() {
        let data = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let indices = Array1::from_vec(vec![0, 2, 1, 0, 2]);
        let indptr = Array1::from_vec(vec![0, 2, 3, 5]);
        let shape = (3, 3);

        let csr = CsrArray::new(data, indices, indptr, shape).expect("Operation failed");

        assert_eq!(csr.shape(), (3, 3));
        assert_eq!(csr.nnz(), 5);
        assert_eq!(csr.get(0, 0), 1.0);
        assert_eq!(csr.get(0, 2), 2.0);
        assert_eq!(csr.get(1, 1), 3.0);
        assert_eq!(csr.get(2, 0), 4.0);
        assert_eq!(csr.get(2, 2), 5.0);
        assert_eq!(csr.get(0, 1), 0.0);
    }

    #[test]
    fn test_csr_from_triplets() {
        let rows = vec![0, 0, 1, 2, 2];
        let cols = vec![0, 2, 1, 0, 2];
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let shape = (3, 3);

        let csr =
            CsrArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");

        assert_eq!(csr.shape(), (3, 3));
        assert_eq!(csr.nnz(), 5);
        assert_eq!(csr.get(0, 0), 1.0);
        assert_eq!(csr.get(0, 2), 2.0);
        assert_eq!(csr.get(1, 1), 3.0);
        assert_eq!(csr.get(2, 0), 4.0);
        assert_eq!(csr.get(2, 2), 5.0);
        assert_eq!(csr.get(0, 1), 0.0);
    }

    #[test]
    fn test_csr_array_to_array() {
        let data = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let indices = Array1::from_vec(vec![0, 2, 1, 0, 2]);
        let indptr = Array1::from_vec(vec![0, 2, 3, 5]);
        let shape = (3, 3);

        let csr = CsrArray::new(data, indices, indptr, shape).expect("Operation failed");
        let dense = csr.to_array();

        assert_eq!(dense.shape(), &[3, 3]);
        assert_eq!(dense[[0, 0]], 1.0);
        assert_eq!(dense[[0, 1]], 0.0);
        assert_eq!(dense[[0, 2]], 2.0);
        assert_eq!(dense[[1, 0]], 0.0);
        assert_eq!(dense[[1, 1]], 3.0);
        assert_eq!(dense[[1, 2]], 0.0);
        assert_eq!(dense[[2, 0]], 4.0);
        assert_eq!(dense[[2, 1]], 0.0);
        assert_eq!(dense[[2, 2]], 5.0);
    }

    #[test]
    fn test_csr_array_dot_vector() {
        let data = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let indices = Array1::from_vec(vec![0, 2, 1, 0, 2]);
        let indptr = Array1::from_vec(vec![0, 2, 3, 5]);
        let shape = (3, 3);

        let csr = CsrArray::new(data, indices, indptr, shape).expect("Operation failed");
        let vec = Array1::from_vec(vec![1.0, 2.0, 3.0]);

        let result = csr.dot_vector(&vec.view()).expect("Operation failed");

        // Expected: [1*1 + 0*2 + 2*3, 0*1 + 3*2 + 0*3, 4*1 + 0*2 + 5*3] = [7, 6, 19]
        assert_eq!(result.len(), 3);
        assert_relative_eq!(result[0], 7.0);
        assert_relative_eq!(result[1], 6.0);
        assert_relative_eq!(result[2], 19.0);
    }

    #[test]
    fn test_csr_array_sum() {
        let data = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let indices = Array1::from_vec(vec![0, 2, 1, 0, 2]);
        let indptr = Array1::from_vec(vec![0, 2, 3, 5]);
        let shape = (3, 3);

        let csr = CsrArray::new(data, indices, indptr, shape).expect("Operation failed");

        // Sum all elements
        if let SparseSum::Scalar(sum) = csr.sum(None).expect("Operation failed") {
            assert_relative_eq!(sum, 15.0);
        } else {
            panic!("Expected scalar sum");
        }

        // Sum along rows
        if let SparseSum::SparseArray(row_sum) = csr.sum(Some(0)).expect("Operation failed") {
            let row_sum_array = row_sum.to_array();
            assert_eq!(row_sum_array.shape(), &[1, 3]);
            assert_relative_eq!(row_sum_array[[0, 0]], 5.0);
            assert_relative_eq!(row_sum_array[[0, 1]], 3.0);
            assert_relative_eq!(row_sum_array[[0, 2]], 7.0);
        } else {
            panic!("Expected sparse array sum");
        }

        // Sum along columns
        if let SparseSum::SparseArray(col_sum) = csr.sum(Some(1)).expect("Operation failed") {
            let col_sum_array = col_sum.to_array();
            assert_eq!(col_sum_array.shape(), &[3, 1]);
            assert_relative_eq!(col_sum_array[[0, 0]], 3.0);
            assert_relative_eq!(col_sum_array[[1, 0]], 3.0);
            assert_relative_eq!(col_sum_array[[2, 0]], 9.0);
        } else {
            panic!("Expected sparse array sum");
        }
    }
}