algebra-sparse 0.4.0-beta.1

Efficient sparse linear algebra library built on nalgebra with CSR/CSC formats and block diagonal matrix support
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
// Copyright (C) 2020-2025 algebra-sparse authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use na::{DMatrix, RealField};
use nalgebra::DMatrixView;

use crate::Real;
use crate::csv::{CsVecBuilder, CsVecMut, CsVecRef};
use crate::traits::IntoView;

/// Compressed Sparse Matrix in either CSR or CSC format.
///
/// This is the core sparse matrix structure that can represent either:
/// - CSR (Compressed Sparse Row) format when rows are compressed
/// - CSC (Compressed Sparse Column) format when columns are compressed
///
/// The matrix stores only non-zero elements and their indices, making it
/// memory-efficient for matrices with few non-zero elements.
///
/// # Format
///
/// The matrix uses three internal arrays:
/// - `secondary_indices`: Column indices for CSR or row indices for CSC
/// - `primary_offsets`: Offsets for each row (CSR) or column (CSC)
/// - `values`: Non-zero values stored in row-major (CSR) or column-major (CSC) order
///
/// # Examples
///
/// ```rust
/// use algebra_sparse::{CsMatrix, CsrMatrix};
/// use nalgebra::DMatrix;
///
/// // Create from dense matrix
/// let dense = DMatrix::from_row_slice(2, 3, &[
///     1.0, 0.0, 2.0,
///     0.0, 3.0, 0.0,
/// ]);
/// let sparse = CsrMatrix::from_dense(dense.as_view());
/// ```
#[derive(Default, Clone, Debug)]
pub struct CsMatrix<T> {
    /// The secondary axis indices of the non-zero entries.
    /// For CSR format, these are column indices.
    /// For CSC format, these are row indices.
    pub(crate) secondary_indices: Vec<usize>,
    /// The offsets of each primary axis in the `values` array.
    /// For CSR format, these are row offsets.
    /// For CSC format, these are column offsets.
    pub(crate) primary_offsets: Vec<usize>,
    /// All non-zero values for the matrix.
    pub(crate) values: Vec<T>,
    /// The dimension size of the secondary axis.
    /// For CSR format, this is the number of columns.
    /// For CSC format, this is the number of rows.
    pub(crate) num_secondary: usize,
}

impl<T> CsMatrix<T>
where
    T: Real,
{
    /// Create a `CsMatrix` from a dense matrix.
    ///
    /// # Arguments
    /// * `dense_mat` - The dense matrix to convert
    /// * `row_sparse` - If true, creates CSR format; if false, creates CSC format
    /// * `zero_threshold` - Values below this threshold are treated as zero and not stored
    ///
    /// # Examples
    ///
    /// ```rust
    /// use algebra_sparse::CsMatrix;
    /// use nalgebra::DMatrix;
    ///
    /// let dense = DMatrix::from_row_slice(2, 3, &[
    ///     1.0, 0.0, 2.0,
    ///     0.0, 3.0, 0.0,
    /// ]);
    ///
    /// // Create CSR format
    /// let csr = CsMatrix::from_dense(dense.as_view(), true, 1e-10);
    ///
    /// // Create CSC format
    /// let csc = CsMatrix::from_dense(dense.as_view(), false, 1e-10);
    /// ```
    #[inline]
    pub fn from_dense(dense_mat: DMatrixView<T>, row_sparse: bool, zero_threshold: T) -> Self {
        let secondary_size = if row_sparse {
            dense_mat.ncols()
        } else {
            dense_mat.nrows()
        };
        let mut csm = CsMatrix::new(secondary_size);

        if row_sparse {
            for i in 0..dense_mat.nrows() {
                let mut rb = csm.new_lane_builder(zero_threshold);
                let lane = dense_mat.row(i);
                rb.extend_with_nonzeros(lane.iter().copied().enumerate());
            }
        } else {
            for i in 0..dense_mat.ncols() {
                let mut rb = csm.new_lane_builder(zero_threshold);
                let lane = dense_mat.column(i);
                rb.extend_with_nonzeros(lane.iter().copied().enumerate());
            }
        }
        csm
    }

    /// Creates a new empty `CsMatrix` with the given secondary axis size.
    ///
    /// # Arguments
    /// * `secondary_size` - Number of columns for CSR format or rows for CSC format
    ///
    /// # Examples
    ///
    /// ```rust
    /// use algebra_sparse::CsMatrix;
    ///
    /// // Create an empty CSR matrix with 3 columns
    /// let csr: CsMatrix<f64> = CsMatrix::new(3);
    /// ```
    pub fn new(secondary_size: usize) -> Self {
        let primary_offsets = vec![0];
        Self {
            secondary_indices: Vec::new(),
            values: Vec::new(),
            primary_offsets,
            num_secondary: secondary_size,
        }
    }

    /// Creates a new lane (row or column) builder for this matrix.
    ///
    /// Returns a `CsVecBuilder` that can be used to efficiently add non-zero elements
    /// to the next lane of the matrix. When the builder is dropped, the lane is finalized.
    ///
    /// # Arguments
    /// * `zero_threshold` - Values below this threshold are filtered out
    ///
    /// # Examples
    ///
    /// ```rust
    /// use algebra_sparse::CsMatrix;
    ///
    /// let mut matrix = CsMatrix::new(3);
    /// let mut builder = matrix.new_lane_builder(1e-10);
    /// builder.push(0, 1.0);  // Add element at column 0
    /// builder.push(2, 2.0);  // Add element at column 2
    /// ```
    #[inline]
    pub fn new_lane_builder(&mut self, zero_threshold: T) -> CsVecBuilder<T> {
        CsVecBuilder::new(self, zero_threshold)
    }

    /// Resets the matrix to empty state with a new secondary axis size.
    ///
    /// This clears all data and allows reuse of the matrix with different dimensions.
    ///
    /// # Arguments
    /// * `secondary_size` - New secondary axis size
    pub fn reset(&mut self, secondary_size: usize) {
        self.clear();
        self.num_secondary = secondary_size;
    }

    /// Clears all data from the matrix while preserving the secondary axis size.
    ///
    /// This removes all lanes but keeps the matrix ready for reuse with the same dimensions.
    #[inline]
    pub fn clear(&mut self) {
        self.secondary_indices.clear();
        self.values.clear();
        self.primary_offsets.clear();
        self.primary_offsets.push(0);
    }

    /// Returns the number of primary axes (rows for CSR, columns for CSC).
    #[inline]
    pub fn num_primary(&self) -> usize {
        self.primary_offsets.len() - 1
    }

    /// Returns the number of secondary axes (columns for CSR, rows for CSC).
    #[inline]
    pub fn num_secondary(&self) -> usize {
        self.num_secondary
    }

    /// Gets a lane (row for CSR, column for CSC) as an immutable sparse vector.
    ///
    /// # Arguments
    /// * `lane_index` - Index of the lane to retrieve
    ///
    /// # Returns
    /// A `CsVecRef` representing the sparse vector for this lane
    #[inline]
    pub fn get_lane(&self, lane_index: usize) -> CsVecRef<T> {
        let start = self.primary_offsets[lane_index];
        let end = self.primary_offsets[lane_index + 1];
        let col_indices = &self.secondary_indices[start..end];
        let values = &self.values[start..end];
        CsVecRef::from_parts_unchecked(col_indices, values, self.num_secondary)
    }

    /// Gets a lane (row for CSR, column for CSC) as a mutable sparse vector.
    ///
    /// # Arguments
    /// * `lane_index` - Index of the lane to retrieve
    ///
    /// # Returns
    /// A `CsVecMut` allowing modification of the lane's values
    #[inline]
    pub fn get_lane_mut(&mut self, lane_index: usize) -> CsVecMut<T> {
        let start = self.primary_offsets[lane_index];
        let end = self.primary_offsets[lane_index + 1];
        let col_indices = &self.secondary_indices[start..end];
        let values = &mut self.values[start..end];
        CsVecMut {
            col_indices,
            values,
        }
    }

    /// Returns an immutable view of this matrix.
    ///
    /// The view allows efficient read-only access without allocation.
    #[inline]
    pub fn as_view(&self) -> CsMatrixView<T> {
        CsMatrixView {
            secondary_indices: &self.secondary_indices,
            primary_offsets: &self.primary_offsets,
            values: &self.values,
            num_secondary: self.num_secondary,
        }
    }

    /// Returns the density rate of the matrix.
    ///
    /// This is the ratio of non-zero elements to total elements.
    /// A value of 0.1 means 10% of elements are non-zero.
    #[inline]
    pub fn dense_rate(&self) -> f32 {
        self.values.len() as f32 / (self.num_primary() * self.num_secondary()) as f32
    }
}

impl<'a, T> IntoView for &'a CsMatrix<T> {
    type View = CsMatrixView<'a, T>;

    fn into_view(self) -> Self::View {
        CsMatrixView {
            secondary_indices: &self.secondary_indices,
            primary_offsets: &self.primary_offsets,
            values: &self.values,
            num_secondary: self.num_secondary,
        }
    }
}

/// An immutable view of a compressed sparse matrix.
///
/// This provides efficient read-only access to sparse matrix data without
/// allocation. Views can be created from both mutable and immutable matrices
/// and are useful for passing matrices to functions without transferring ownership.
///
/// The view has the same format capabilities as `CsMatrix` - it can represent
/// both CSR and CSC formats depending on how it's created.
#[derive(Clone, Copy, Debug)]
pub struct CsMatrixView<'a, T> {
    /// The secondary axis indices of the non-zero entries.
    /// For CSR format, these are column indices.
    /// For CSC format, these are row indices.
    secondary_indices: &'a [usize],
    /// The offsets of each primary axis in the `values` array.
    /// For CSR format, these are row offsets.
    /// For CSC format, these are column offsets.
    primary_offsets: &'a [usize],
    /// All non-zero values for the matrix.
    values: &'a [T],
    /// The dimension size of the secondary axis.
    /// For CSR format, this is the number of columns.
    /// For CSC format, this is the number of rows.
    num_secondary: usize,
}

impl<'a, T> CsMatrixView<'a, T>
where
    T: RealField,
{
    /// Returns the number of primary axes (rows for CSR, columns for CSC).
    #[inline]
    pub fn num_primary(&self) -> usize {
        self.primary_offsets.len() - 1
    }

    /// Returns the number of secondary axes (columns for CSR, rows for CSC).
    #[inline]
    pub fn num_secondary(&self) -> usize {
        self.num_secondary
    }

    /// Gets a lane (row for CSR, column for CSC) as an immutable sparse vector.
    ///
    /// # Arguments
    /// * `lane_index` - Index of the lane to retrieve
    ///
    /// # Returns
    /// A `CsVecRef` representing the sparse vector for this lane
    #[inline]
    pub fn get_lane(self, lane_index: usize) -> CsVecRef<'a, T> {
        let start = self.primary_offsets[lane_index];
        let end = self.primary_offsets[lane_index + 1];
        let col_indices = &self.secondary_indices[start..end];
        let values = &self.values[start..end];
        CsVecRef::from_parts_unchecked(col_indices, values, self.num_secondary)
    }

    /// Returns the density rate of the matrix.
    ///
    /// This is the ratio of non-zero elements to total elements.
    /// A value of 0.1 means 10% of elements are non-zero.
    #[inline]
    pub fn dense_rate(&self) -> f32 {
        self.values.len() as f32 / (self.num_primary() * self.num_secondary()) as f32
    }
}

impl<'a, T> IntoView for CsMatrixView<'a, T> {
    type View = CsMatrixView<'a, T>;

    #[inline]
    fn into_view(self) -> Self::View {
        self
    }
}

/// Compressed Sparse Row (CSR) Matrix.
///
/// CSR format is optimized for row-wise operations and matrix-vector products.
/// It stores non-zero elements row by row, making it efficient for:
/// - Row access and iteration
/// - Sparse matrix-vector multiplication
/// - Row-based computations
///
/// # Format
///
/// The CSR format uses three arrays:
/// - `values`: Non-zero values stored row by row
/// - `col_indices`: Column indices for each non-zero value
/// - `row_offsets`: Starting index in values/col_indices for each row
///
/// # Examples
///
/// ```rust
/// use algebra_sparse::CsrMatrix;
/// use nalgebra::DMatrix;
///
/// // Create from dense matrix
/// let dense = DMatrix::from_row_slice(2, 3, &[
///     1.0, 0.0, 2.0,
///     0.0, 3.0, 0.0,
/// ]);
/// let csr = CsrMatrix::from_dense(dense.as_view());
///
/// // Get row as sparse vector
/// let row = csr.as_view().get_row(0);
/// for (col, val) in row.iter() {
///     println!("({}, {})", col, val);
/// }
/// ```
#[derive(Default, Clone)]
pub struct CsrMatrix<T>(CsMatrix<T>);

impl<T> CsrMatrix<T>
where
    T: Real,
{
    /// Creates a CSR matrix from a dense matrix.
    ///
    /// Values below the zero threshold are automatically filtered out.
    /// The zero threshold is obtained from the `Real` trait implementation.
    ///
    /// # Arguments
    /// * `dense_mat` - The dense matrix to convert
    ///
    /// # Examples
    ///
    /// ```rust
    /// use algebra_sparse::CsrMatrix;
    /// use nalgebra::DMatrix;
    ///
    /// let dense = DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 2.0]);
    /// let csr = CsrMatrix::from_dense(dense.as_view());
    /// ```
    #[inline]
    pub fn from_dense(dense_mat: DMatrixView<T>) -> Self {
        Self(CsMatrix::from_dense(dense_mat, true, T::zero_threshold()))
    }

    /// Creates a new empty CSR matrix with the given number of columns.
    ///
    /// # Arguments
    /// * `ncols` - Number of columns in the matrix
    ///
    /// # Examples
    ///
    /// ```rust
    /// use algebra_sparse::CsrMatrix;
    ///
    /// let mut csr: CsrMatrix<f64> = CsrMatrix::new(3);
    /// // Now you can add rows using new_row_builder()
    /// ```
    pub fn new(ncols: usize) -> Self {
        Self(CsMatrix::new(ncols))
    }

    /// Resets the CSR matrix to empty state with the given number of columns.
    ///
    /// This clears all data and allows reuse of the matrix.
    ///
    /// # Arguments
    /// * `ncols` - New number of columns
    pub fn reset(&mut self, ncols: usize) {
        self.0.reset(ncols);
    }

    /// Clears all rows in the CSR matrix while preserving the number of columns.
    ///
    /// This removes all rows but keeps the matrix ready for reuse.
    #[inline]
    pub fn clear(&mut self) {
        self.0.clear();
    }

    /// Creates a new row builder for adding elements to the next row.
    ///
    /// The builder allows efficient construction of sparse rows. When the builder
    /// is dropped, the row is finalized and added to the matrix.
    ///
    /// # Arguments
    /// * `zero_threshold` - Values below this threshold are filtered out
    ///
    /// # Examples
    ///
    /// ```rust
    /// use algebra_sparse::CsrMatrix;
    ///
    /// let mut csr = CsrMatrix::new(3);
    /// let mut builder = csr.new_row_builder(1e-10);
    /// builder.push(0, 1.0);  // Add element at column 0
    /// builder.push(2, 2.0);  // Add element at column 2
    /// // Row is automatically added when builder is dropped
    /// ```
    #[inline]
    pub fn new_row_builder(&mut self, zero_threshold: T) -> CsVecBuilder<T> {
        self.0.new_lane_builder(zero_threshold)
    }

    /// Gets a mutable row as a sparse vector.
    ///
    /// # Arguments
    /// * `row_index` - Index of the row to retrieve
    ///
    /// # Returns
    /// A `CsVecMut` allowing modification of the row's values
    ///
    /// # Note
    /// This only allows modification of existing values, not structural changes.
    #[inline]
    pub fn get_row_mut(&mut self, row_index: usize) -> CsVecMut<T> {
        self.0.get_lane_mut(row_index)
    }

    /// Returns an immutable view of this CSR matrix.
    ///
    /// The view allows efficient read-only access without allocation
    /// and can be used for matrix operations.
    #[inline]
    pub fn as_view(&self) -> CsrMatrixView<T> {
        CsrMatrixView(self.0.as_view())
    }
}

impl<'a, T> IntoView for &'a CsrMatrix<T>
where
    T: Real,
{
    type View = CsrMatrixView<'a, T>;

    fn into_view(self) -> Self::View {
        CsrMatrixView(self.0.as_view())
    }
}

/// An immutable view of a CSR matrix.
///
/// This provides efficient read-only access to CSR matrix data without allocation.
/// Views are commonly used for matrix operations and can be easily created from
/// both mutable and immutable CSR matrices.
///
/// # Examples
///
/// ```rust
/// use algebra_sparse::{CsrMatrix, CsrMatrixViewMethods};
/// use nalgebra::DMatrix;
///
/// let dense = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
/// let csr = CsrMatrix::from_dense(dense.as_view());
/// let view = csr.as_view();
///
/// println!("Number of rows: {}", view.nrows());
/// println!("Number of columns: {}", view.ncols());
/// ```
#[derive(Clone, Copy, Debug)]
pub struct CsrMatrixView<'a, T>(CsMatrixView<'a, T>);

impl<'a, T> CsrMatrixView<'a, T> {
    /// Creates a `CsrMatrixView` from raw parts without checking validity.
    ///
    /// # Safety
    /// This function does not validate that the provided parts form a valid CSR matrix.
    /// Invalid parts may cause undefined behavior when accessing the matrix.
    ///
    /// # Arguments
    /// * `row_offsets` - Row offset array (length = nrows + 1)
    /// * `col_indices` - Column index array for non-zero elements
    /// * `values` - Non-zero values array
    /// * `ncol` - Number of columns
    #[inline]
    pub fn from_parts_unchecked(
        row_offsets: &'a [usize],
        col_indices: &'a [usize],
        values: &'a [T],
        ncol: usize,
    ) -> Self {
        Self(CsMatrixView {
            secondary_indices: col_indices,
            primary_offsets: row_offsets,
            values,
            num_secondary: ncol,
        })
    }
}

impl<'a, T> CsrMatrixView<'a, T>
where
    T: Real,
{
    /// Returns the density rate of the matrix.
    ///
    /// This is the ratio of non-zero elements to total elements.
    /// A value of 0.1 means 10% of elements are non-zero.
    #[inline]
    pub fn dense_rate(&self) -> f32 {
        self.0.dense_rate()
    }

    /// Transposes the CSR matrix view to a CSC matrix view.
    ///
    /// This is a zero-cost operation that only changes the interpretation of the data.
    /// No data is copied or moved.
    ///
    /// # Returns
    /// A CSC view of the same matrix data
    #[inline]
    pub fn transpose(&self) -> CscMatrixView<'a, T> {
        CscMatrixView(self.0)
    }

    /// Returns the shape of the matrix as (nrows, ncols).
    #[inline]
    pub fn shape(&self) -> (usize, usize) {
        (self.nrows(), self.ncols())
    }

    /// Returns the number of rows in the matrix.
    #[inline]
    pub fn nrows(&self) -> usize {
        self.0.num_primary()
    }

    /// Returns the number of columns in the matrix.
    #[inline]
    pub fn ncols(&self) -> usize {
        self.0.num_secondary()
    }

    /// Gets a row as a sparse vector.
    ///
    /// # Arguments
    /// * `row_index` - Index of the row to retrieve
    ///
    /// # Returns
    /// A `CsVecRef` representing the sparse vector for this row
    #[inline]
    pub fn get_row(self, row_index: usize) -> CsVecRef<'a, T> {
        self.0.get_lane(row_index)
    }
}

impl<'a, T> IntoView for CsrMatrixView<'a, T> {
    type View = CsrMatrixView<'a, T>;

    #[inline]
    fn into_view(self) -> Self::View {
        self
    }
}

impl<'b, T> IntoView for &CsrMatrixView<'b, T>
where
    T: Copy,
{
    type View = CsrMatrixView<'b, T>;

    #[inline]
    fn into_view(self) -> Self::View {
        *self
    }
}

/// Trait providing methods for CSR matrix view operations.
///
/// This trait extends types that can be converted to CSR views with convenient
/// methods for matrix operations and introspection.
pub trait CsrMatrixViewMethods<'a, T> {
    /// Returns the number of rows in the matrix.
    fn nrows(self) -> usize;

    /// Returns the number of columns in the matrix.
    fn ncols(self) -> usize;

    /// Gets a row as a sparse vector.
    ///
    /// # Arguments
    /// * `row_index` - Index of the row to retrieve
    ///
    /// # Returns
    /// A `CsVecRef` representing the sparse vector for this row
    fn get_row(self, row_index: usize) -> CsVecRef<'a, T>;

    /// Converts to a dense matrix.
    ///
    /// This allocates a new dense matrix and copies all non-zero elements.
    ///
    /// # Returns
    /// A dense `DMatrix` containing the same data
    fn to_dense(self) -> DMatrix<T>
    where
        Self: Sized + Copy,
        T: Real,
    {
        let mut m = DMatrix::zeros(self.nrows(), self.ncols());
        for i in 0..self.nrows() {
            let row = self.get_row(i);
            for (col, value) in row.iter() {
                unsafe {
                    *m.get_unchecked_mut((i, col)) = value;
                }
            }
        }
        m
    }
}

impl<'a, T, V> CsrMatrixViewMethods<'a, V> for &'a T
where
    V: Real,
    &'a T: IntoView<View = CsrMatrixView<'a, V>>,
{
    /// Get the number of rows.
    #[inline]
    fn nrows(self) -> usize {
        CsrMatrixView::nrows(&self.into_view())
    }

    /// Get the number of columns.
    #[inline]
    fn ncols(self) -> usize {
        CsrMatrixView::ncols(&self.into_view())
    }

    /// Get a row as a sparse vector.
    #[inline]
    fn get_row(self, row_index: usize) -> CsVecRef<'a, V> {
        self.into_view().get_row(row_index)
    }
}

/// Compressed Sparse Column (CSC) Matrix View.
///
/// CSC format is optimized for column-wise operations and is the transpose
/// of CSR format. It stores non-zero elements column by column, making it
/// efficient for:
/// - Column access and iteration
/// - Column-based computations
/// - Matrix operations that benefit from column-wise access
///
/// This is a view type that provides efficient read-only access to matrix data
/// without allocation.
///
/// # Examples
///
/// ```rust
/// use algebra_sparse::CsrMatrix;
/// use nalgebra::DMatrix;
///
/// let dense = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
/// let csr = CsrMatrix::from_dense(dense.as_view());
/// let csc = csr.as_view().transpose();
///
/// // Access columns
/// for col_idx in 0..csc.ncols() {
///     let col = csc.get_col(col_idx);
///     for (row, val) in col.iter() {
///         println!("({}, {})", row, val);
///     }
/// }
/// ```
#[derive(Clone, Copy)]
pub struct CscMatrixView<'a, T>(CsMatrixView<'a, T>);

impl<'a, T> CscMatrixView<'a, T>
where
    T: Real,
{
    /// Returns the number of rows in the matrix.
    #[inline]
    pub fn nrows(&self) -> usize {
        self.0.num_secondary()
    }

    /// Returns the number of columns in the matrix.
    #[inline]
    pub fn ncols(&self) -> usize {
        self.0.num_primary()
    }

    /// Gets a column as a sparse vector.
    ///
    /// # Arguments
    /// * `col_index` - Index of the column to retrieve
    ///
    /// # Returns
    /// A `CsVecRef` representing the sparse vector for this column
    #[inline]
    pub fn get_col(&self, col_index: usize) -> CsVecRef<'a, T> {
        self.0.get_lane(col_index)
    }

    /// Transposes to a `CsrMatrixView`.
    ///
    /// This is a zero-cost operation that only changes the interpretation of the data.
    /// No data is copied or moved.
    ///
    /// # Returns
    /// A CSR view of the same matrix data
    #[inline]
    pub fn transpose(&self) -> CsrMatrixView<'a, T> {
        CsrMatrixView(self.0)
    }

    /// Converts to a dense matrix.
    ///
    /// This allocates a new dense matrix and copies all non-zero elements.
    ///
    /// # Returns
    /// A dense `DMatrix` containing the same data
    pub fn to_dense(&self) -> DMatrix<T> {
        let mut dense = DMatrix::zeros(self.nrows(), self.ncols());
        for col in 0..self.ncols() {
            let col_vec = self.get_col(col);
            for (row, value) in col_vec.iter() {
                dense[(row, col)] = value;
            }
        }
        dense
    }
}