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
// CSC Array implementation
//
// This module provides the CSC (Compressed Sparse Column) array format,
// which is efficient for column-wise operations.

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::coo_array::CooArray;
use crate::csr_array::CsrArray;
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)
}

/// CSC Array format
///
/// The CSC (Compressed Sparse Column) format stores a sparse array in three arrays:
/// - data: array of non-zero values
/// - indices: row indices of the non-zero values
/// - indptr: index pointers; for each column, points to the first non-zero element
///
/// # Notes
///
/// - Efficient for column-oriented operations
/// - Fast matrix-vector multiplications for A^T x
/// - Fast column slicing
/// - Slow row slicing
/// - Slow constructing by setting individual elements
///
#[derive(Clone)]
pub struct CscArray<T>
where
    T: SparseElement + Div<Output = T> + 'static,
{
    /// Non-zero values
    data: Array1<T>,
    /// Row indices of non-zero values
    indices: Array1<usize>,
    /// Column pointers (indices into data/indices for the start of each column)
    indptr: Array1<usize>,
    /// Shape of the sparse array
    shape: (usize, usize),
    /// Whether indices are sorted for each column
    has_sorted_indices: bool,
}

impl<T> CscArray<T>
where
    T: SparseElement + Div<Output = T> + Zero + 'static,
{
    /// Creates a new CSC array from raw components
    ///
    /// # Arguments
    /// * `data` - Array of non-zero values
    /// * `indices` - Row indices of non-zero values
    /// * `indptr` - Index pointers for the start of each column
    /// * `shape` - Shape of the sparse array
    ///
    /// # Returns
    /// A new `CscArray`
    ///
    /// # 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.1 + 1 {
            return Err(SparseError::InconsistentData {
                reason: format!(
                    "indptr length ({}) must be one more than the number of columns ({})",
                    indptr.len(),
                    shape.1
                ),
            });
        }

        if let Some(&max_idx) = indices.iter().max() {
            if max_idx >= shape.0 {
                return Err(SparseError::IndexOutOfBounds {
                    index: (max_idx, 0),
                    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 CSC array from triplet format (COO-like)
    ///
    /// # Arguments
    /// * `rows` - Row indices
    /// * `cols` - Column indices
    /// * `data` - Values
    /// * `shape` - Shape of the sparse array
    /// * `sorted` - Whether the triplets are sorted by column
    ///
    /// # Returns
    /// A new `CscArray`
    ///
    /// # Errors
    /// Returns an error if the data is not consistent
    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.1 + 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(|&(_, col_, _)| col_);
        }

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

        // Create indptr
        let mut indptr = Vec::with_capacity(shape.1 + 1);
        indptr.push(0);
        let mut cumsum = 0;
        for &count in &col_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 (row_, _, val) in all_data {
            indices.push(row_);
            values.push(val);
        }

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

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

impl<T> SparseArray<T> for CscArray<T>
where
    T: SparseElement + Div<Output = T> + Float + '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 col in 0..cols {
            let start = self.indptr[col];
            let end = self.indptr[col + 1];

            for i in start..end {
                let row = 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>>> {
        // Convert to COO format
        let nnz = self.nnz();
        let mut row_indices = Vec::with_capacity(nnz);
        let mut col_indices = Vec::with_capacity(nnz);
        let mut values = Vec::with_capacity(nnz);

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

            for idx in start..end {
                row_indices.push(self.indices[idx]);
                col_indices.push(col);
                values.push(self.data[idx]);
            }
        }

        CooArray::from_triplets(&row_indices, &col_indices, &values, self.shape, false)
            .map(|array| Box::new(array) as Box<dyn SparseArray<T>>)
    }

    fn to_csr(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // For efficiency, we'll go via COO format
        self.to_coo()?.to_csr()
    }

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

    fn to_dok(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to DOK format
        // For now, we'll go via COO format
        self.to_coo()?.to_dok()
    }

    fn to_lil(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to LIL format
        // For now, we'll go via COO format
        self.to_coo()?.to_lil()
    }

    fn to_dia(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to DIA format
        // For now, we'll go via COO format
        self.to_coo()?.to_dia()
    }

    fn to_bsr(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // This would convert to BSR format
        // For now, we'll go via COO format
        self.to_coo()?.to_bsr()
    }

    fn add(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // For efficiency, convert to CSR format and then add
        let self_csr = self.to_csr()?;
        self_csr.add(other)
    }

    fn sub(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // For efficiency, convert to CSR format and then subtract
        let self_csr = self.to_csr()?;
        self_csr.sub(other)
    }

    fn mul(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // Element-wise multiplication (Hadamard product)
        // Convert to CSR for efficiency
        let self_csr = self.to_csr()?;
        self_csr.mul(other)
    }

    fn div(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // Element-wise division
        // Convert to CSR for efficiency
        let self_csr = self.to_csr()?;
        self_csr.div(other)
    }

    fn dot(&self, other: &dyn SparseArray<T>) -> SparseResult<Box<dyn SparseArray<T>>> {
        // Matrix multiplication
        // Convert to CSR for efficiency
        let self_csr = self.to_csr()?;
        self_csr.dot(other)
    }

    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 col in 0..n {
            let start = self.indptr[col];
            let end = self.indptr[col + 1];

            let val = other[col];
            if !SparseElement::is_zero(&val) {
                for idx in start..end {
                    let row = self.indices[idx];
                    result[row] = result[row] + self.data[idx] * val;
                }
            }
        }

        Ok(result)
    }

    fn transpose(&self) -> SparseResult<Box<dyn SparseArray<T>>> {
        // CSC transposed is effectively CSR (swap rows/cols)
        CsrArray::new(
            self.data.clone(),
            self.indices.clone(),
            self.indptr.clone(),
            (self.shape.1, self.shape.0), // Swap dimensions
        )
        .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[j];
        let end = self.indptr[j + 1];

        for idx in start..end {
            if self.indices[idx] == i {
                return self.data[idx];
            }

            // If indices are sorted, we can break early
            if self.has_sorted_indices && self.indices[idx] > i {
                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[j];
        let end = self.indptr[j + 1];

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

        // Element not found - insert at end of this column's range
        self.data = array1_insert(&self.data, end, value);
        self.indices = array1_insert(&self.indices, end, i);
        // Increment indptr for all subsequent columns
        for col_ptr in self.indptr.iter_mut().skip(j + 1) {
            *col_ptr += 1;
        }
        // Re-check sorted state for this column
        if self.has_sorted_indices {
            let new_end = self.indptr[j + 1];
            let new_start = self.indptr[j];
            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 (_, cols) = self.shape;

        for col in 0..cols {
            let start = self.indptr[col];
            let end = self.indptr[col + 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 (_, cols) = self.shape;

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

            if start == end {
                continue;
            }

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

            // Sort by row index
            col_data.sort_by_key(|&(row_, _)| row_);

            // Put the sorted data back
            for (i, (row, val)) in col_data.into_iter().enumerate() {
                self.indices[start + i] = row;
                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)
                // For efficiency, convert to CSR and sum
                let self_csr = self.to_csr()?;
                self_csr.sum(Some(0))
            }
            Some(1) => {
                // Sum along columns (result is a column vector)
                let mut result = Vec::with_capacity(self.shape.1);

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

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

                // Convert to COO format for the column vector
                let mut row_indices = Vec::new();
                let mut col_indices = Vec::new();
                let mut values = Vec::new();

                for (col, &val) in result.iter().enumerate() {
                    if !SparseElement::is_zero(&val) {
                        row_indices.push(0);
                        col_indices.push(col);
                        values.push(val);
                    }
                }

                let coo = CooArray::from_triplets(
                    &row_indices,
                    &col_indices,
                    &values,
                    (1, self.shape.1),
                    true,
                )?;

                Ok(SparseSum::SparseArray(Box::new(coo)))
            }
            _ => 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
        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() {
            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 min_val > T::sparse_zero() && self.nnz() < self.shape.0 * self.shape.1 {
            min_val = T::sparse_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 col in 0..self.shape.1 {
            let start = self.indptr[col];
            let end = self.indptr[col + 1];

            for idx in start..end {
                let row = 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);
        }

        // CSC format is efficient for column slicing
        let mut data = Vec::new();
        let mut indices = Vec::new();
        let mut indptr = vec![0];

        for col in start_col..end_col {
            let start = self.indptr[col];
            let end = self.indptr[col + 1];

            for idx in start..end {
                let row = self.indices[idx];
                if row >= start_row && row < end_row {
                    data.push(self.data[idx]);
                    indices.push(row - start_row); // Adjust indices
                }
            }
            indptr.push(data.len());
        }

        CscArray::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 CscArray<T>
where
    T: SparseElement + Div<Output = T> + Float + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "CscArray<{}x{}, nnz={}>",
            self.shape.0,
            self.shape.1,
            self.nnz()
        )
    }
}

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

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

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

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

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

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

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

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

        let csc =
            CscArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");
        let dense = csc.to_array();

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

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

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

        // Check that the conversion preserved values
        let csc_array = csc.to_array();
        let csr_array = csr.to_array();

        for i in 0..shape.0 {
            for j in 0..shape.1 {
                assert_relative_eq!(csc_array[[i, j]], csr_array[[i, j]]);
            }
        }
    }

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

        let csc =
            CscArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");
        let vec = Array1::from_vec(vec![1.0, 2.0, 3.0]);

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

        // Expected:
        // [0,0]*1 + [0,1]*2 + [0,2]*3 = 1*1 + 2*2 + 0*3 = 5
        // [1,0]*1 + [1,1]*2 + [1,2]*3 = 0*1 + 0*2 + 3*3 = 9
        // [2,0]*1 + [2,1]*2 + [2,2]*3 = 4*1 + 0*2 + 5*3 = 19
        assert_eq!(result.len(), 3);
        assert_relative_eq!(result[0], 5.0);
        assert_relative_eq!(result[1], 9.0);
        assert_relative_eq!(result[2], 19.0);
    }

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

        let csc =
            CscArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");
        let transposed = csc.transpose().expect("Operation failed");

        // Check dimensions are swapped
        assert_eq!(transposed.shape(), (3, 3));

        // Check values are correctly transposed
        let dense = transposed.to_array();
        assert_eq!(dense[[0, 0]], 1.0);
        assert_eq!(dense[[0, 2]], 4.0);
        assert_eq!(dense[[1, 0]], 2.0);
        assert_eq!(dense[[2, 1]], 3.0);
        assert_eq!(dense[[2, 2]], 5.0);
    }

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

        let csc =
            CscArray::from_triplets(&rows, &cols, &data, shape, false).expect("Operation failed");
        let (result_rows, result_cols, result_data) = csc.find();

        // Check that the find operation returned all non-zero elements
        assert_eq!(result_rows.len(), 5);
        assert_eq!(result_cols.len(), 5);
        assert_eq!(result_data.len(), 5);

        // Create vectors of tuples to compare
        let mut original: Vec<_> = rows
            .iter()
            .zip(cols.iter())
            .zip(data.iter())
            .map(|((r, c), d)| (*r, *c, *d))
            .collect();

        let mut result: Vec<_> = result_rows
            .iter()
            .zip(result_cols.iter())
            .zip(result_data.iter())
            .map(|((r, c), d)| (*r, *c, *d))
            .collect();

        // Sort the vectors before comparing
        original.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
        result.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));

        assert_eq!(original, result);
    }
}