Skip to main content

lib_jsl_linalg/sparse/
formats.rs

1//! Sparse matrix storage: coordinate (COO) for assembly, compressed sparse rows (CSR) and
2//! columns (CSC) for computation, as in `scipy.sparse`.
3
4use crate::error::{LinalgError, Result};
5use ndarray::Array2;
6
7/// A matrix being assembled from `(row, column, value)` triplets; duplicates are summed when
8/// converting (SciPy's `coo_array`).
9#[derive(Clone, Debug, Default)]
10pub struct CooMatrix {
11    pub nrows: usize,
12    pub ncols: usize,
13    pub rows: Vec<usize>,
14    pub cols: Vec<usize>,
15    pub values: Vec<f64>,
16}
17
18impl CooMatrix {
19    pub fn new(nrows: usize, ncols: usize) -> Self {
20        CooMatrix { nrows, ncols, ..Default::default() }
21    }
22
23    /// Adds `value` at `(row, col)` (accumulating with any earlier entry there).
24    pub fn push(&mut self, row: usize, col: usize, value: f64) {
25        self.rows.push(row);
26        self.cols.push(col);
27        self.values.push(value);
28    }
29
30    pub fn to_csr(&self) -> Result<CsrMatrix> {
31        CsrMatrix::from_triplets(self.nrows, self.ncols, &self.rows, &self.cols, &self.values)
32    }
33}
34
35/// Compressed sparse rows: the entries of row `i` are `indices[indptr[i]..indptr[i+1]]` (columns,
36/// increasing) and the matching `data` (SciPy's `csr_array`).
37#[derive(Clone, Debug, PartialEq)]
38pub struct CsrMatrix {
39    pub nrows: usize,
40    pub ncols: usize,
41    pub indptr: Vec<usize>,
42    pub indices: Vec<usize>,
43    pub data: Vec<f64>,
44}
45
46/// Compressed sparse columns: the transpose layout of [`CsrMatrix`] (SciPy's `csc_array`).
47#[derive(Clone, Debug, PartialEq)]
48pub struct CscMatrix {
49    pub nrows: usize,
50    pub ncols: usize,
51    pub indptr: Vec<usize>,
52    pub indices: Vec<usize>,
53    pub data: Vec<f64>,
54}
55
56// ANCHOR: from_triplets
57impl CsrMatrix {
58    /// Builds a CSR matrix from triplets, summing duplicates and sorting the column indices of
59    /// each row: a counting sort by row, then by column within each row.
60    pub fn from_triplets(nrows: usize, ncols: usize, rows: &[usize], cols: &[usize], values: &[f64]) -> Result<Self> {
61        if rows.len() != cols.len() || rows.len() != values.len() {
62            return Err(LinalgError::Shape("triplet arrays of different lengths".into()));
63        }
64        if rows.iter().any(|&r| r >= nrows) || cols.iter().any(|&c| c >= ncols) {
65            return Err(LinalgError::Shape("an index lies outside the matrix".into()));
66        }
67        let mut count = vec![0usize; nrows + 1];
68        for &r in rows {
69            count[r + 1] += 1;
70        }
71        for i in 0..nrows {
72            count[i + 1] += count[i];
73        }
74        let mut next = count.clone();
75        let mut cols_sorted = vec![0usize; rows.len()];
76        let mut vals_sorted = vec![0.0; rows.len()];
77        for k in 0..rows.len() {
78            let p = next[rows[k]];
79            cols_sorted[p] = cols[k];
80            vals_sorted[p] = values[k];
81            next[rows[k]] += 1;
82        }
83        let mut indptr = vec![0usize; nrows + 1];
84        let mut indices = Vec::with_capacity(rows.len());
85        let mut data = Vec::with_capacity(rows.len());
86        for i in 0..nrows {
87            let mut entries: Vec<(usize, f64)> = (count[i]..count[i + 1]).map(|p| (cols_sorted[p], vals_sorted[p])).collect();
88            entries.sort_by_key(|e| e.0);
89            for (c, v) in entries {
90                if indices.len() > indptr[i] && *indices.last().expect("non-empty") == c {
91                    *data.last_mut().expect("non-empty") += v;
92                } else {
93                    indices.push(c);
94                    data.push(v);
95                }
96            }
97            indptr[i + 1] = indices.len();
98        }
99        Ok(CsrMatrix { nrows, ncols, indptr, indices, data })
100    }
101    // ANCHOR_END: from_triplets
102
103    /// The entries of `a` larger than `tol` in magnitude.
104    pub fn from_dense(a: &Array2<f64>, tol: f64) -> Self {
105        let (m, n) = a.dim();
106        let mut indptr = vec![0];
107        let (mut indices, mut data) = (Vec::new(), Vec::new());
108        for i in 0..m {
109            for j in 0..n {
110                if a[(i, j)].abs() > tol {
111                    indices.push(j);
112                    data.push(a[(i, j)]);
113                }
114            }
115            indptr.push(indices.len());
116        }
117        CsrMatrix { nrows: m, ncols: n, indptr, indices, data }
118    }
119
120    /// The `n × n` identity.
121    pub fn identity(n: usize) -> Self {
122        CsrMatrix { nrows: n, ncols: n, indptr: (0..=n).collect(), indices: (0..n).collect(), data: vec![1.0; n] }
123    }
124
125    /// A matrix with the given diagonals (SciPy's `diags`): `diagonals[k]` holds the values of the
126    /// diagonal at `offsets[k]` (0 main, positive above), starting from its first element.
127    pub fn diags(diagonals: &[Vec<f64>], offsets: &[isize], nrows: usize, ncols: usize) -> Result<Self> {
128        let mut coo = CooMatrix::new(nrows, ncols);
129        for (d, &off) in diagonals.iter().zip(offsets) {
130            let (r0, c0) = if off >= 0 { (0usize, off as usize) } else { ((-off) as usize, 0usize) };
131            for (t, &v) in d.iter().enumerate() {
132                let (r, c) = (r0 + t, c0 + t);
133                if r < nrows && c < ncols {
134                    coo.push(r, c, v);
135                }
136            }
137        }
138        coo.to_csr()
139    }
140
141    pub fn nnz(&self) -> usize {
142        self.data.len()
143    }
144
145    pub fn to_dense(&self) -> Array2<f64> {
146        let mut a = Array2::zeros((self.nrows, self.ncols));
147        for i in 0..self.nrows {
148            for p in self.indptr[i]..self.indptr[i + 1] {
149                a[(i, self.indices[p])] += self.data[p];
150            }
151        }
152        a
153    }
154
155    /// The entry at `(i, j)` (zero if not stored).
156    pub fn get(&self, i: usize, j: usize) -> f64 {
157        let row = &self.indices[self.indptr[i]..self.indptr[i + 1]];
158        row.binary_search(&j).map_or(0.0, |p| self.data[self.indptr[i] + p])
159    }
160
161    /// `A x`.
162    pub fn matvec(&self, x: &[f64]) -> Vec<f64> {
163        (0..self.nrows).map(|i| (self.indptr[i]..self.indptr[i + 1]).map(|p| self.data[p] * x[self.indices[p]]).sum()).collect()
164    }
165
166    /// `Aᵀ x`.
167    pub fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
168        let mut y = vec![0.0; self.ncols];
169        for i in 0..self.nrows {
170            for p in self.indptr[i]..self.indptr[i + 1] {
171                y[self.indices[p]] += self.data[p] * x[i];
172            }
173        }
174        y
175    }
176
177    /// The transpose, again in CSR form.
178    pub fn transpose(&self) -> CsrMatrix {
179        let c = self.to_csc();
180        CsrMatrix { nrows: self.ncols, ncols: self.nrows, indptr: c.indptr, indices: c.indices, data: c.data }
181    }
182
183    /// The same matrix in CSC form.
184    pub fn to_csc(&self) -> CscMatrix {
185        let mut count = vec![0usize; self.ncols + 1];
186        for &j in &self.indices {
187            count[j + 1] += 1;
188        }
189        for j in 0..self.ncols {
190            count[j + 1] += count[j];
191        }
192        let mut next = count.clone();
193        let mut indices = vec![0usize; self.nnz()];
194        let mut data = vec![0.0; self.nnz()];
195        for i in 0..self.nrows {
196            for p in self.indptr[i]..self.indptr[i + 1] {
197                let j = self.indices[p];
198                indices[next[j]] = i;
199                data[next[j]] = self.data[p];
200                next[j] += 1;
201            }
202        }
203        CscMatrix { nrows: self.nrows, ncols: self.ncols, indptr: count, indices, data }
204    }
205
206    /// `A B` by Gustavson's row-by-row algorithm.
207    pub fn matmul(&self, b: &CsrMatrix) -> Result<CsrMatrix> {
208        if self.ncols != b.nrows {
209            return Err(LinalgError::Shape(format!("{} × {} times {} × {}", self.nrows, self.ncols, b.nrows, b.ncols)));
210        }
211        let mut acc = vec![0.0; b.ncols];
212        let mut marker = vec![usize::MAX; b.ncols];
213        let mut indptr = vec![0];
214        let (mut indices, mut data) = (Vec::new(), Vec::new());
215        for i in 0..self.nrows {
216            let mut cols = Vec::new();
217            for p in self.indptr[i]..self.indptr[i + 1] {
218                let (k, a) = (self.indices[p], self.data[p]);
219                for q in b.indptr[k]..b.indptr[k + 1] {
220                    let j = b.indices[q];
221                    if marker[j] != i {
222                        marker[j] = i;
223                        acc[j] = 0.0;
224                        cols.push(j);
225                    }
226                    acc[j] += a * b.data[q];
227                }
228            }
229            cols.sort_unstable();
230            for j in cols {
231                indices.push(j);
232                data.push(acc[j]);
233            }
234            indptr.push(indices.len());
235        }
236        Ok(CsrMatrix { nrows: self.nrows, ncols: b.ncols, indptr, indices, data })
237    }
238
239    /// `α A + β B`.
240    pub fn add(&self, alpha: f64, b: &CsrMatrix, beta: f64) -> Result<CsrMatrix> {
241        if (self.nrows, self.ncols) != (b.nrows, b.ncols) {
242            return Err(LinalgError::Shape("matrices of different shapes".into()));
243        }
244        let mut coo = CooMatrix::new(self.nrows, self.ncols);
245        for (m, s) in [(self, alpha), (b, beta)] {
246            for i in 0..m.nrows {
247                for p in m.indptr[i]..m.indptr[i + 1] {
248                    coo.push(i, m.indices[p], s * m.data[p]);
249                }
250            }
251        }
252        coo.to_csr()
253    }
254
255    /// The main diagonal.
256    pub fn diagonal(&self) -> Vec<f64> {
257        (0..self.nrows.min(self.ncols)).map(|i| self.get(i, i)).collect()
258    }
259}
260
261impl CscMatrix {
262    pub fn nnz(&self) -> usize {
263        self.data.len()
264    }
265
266    /// `A x`.
267    pub fn matvec(&self, x: &[f64]) -> Vec<f64> {
268        let mut y = vec![0.0; self.nrows];
269        for j in 0..self.ncols {
270            for p in self.indptr[j]..self.indptr[j + 1] {
271                y[self.indices[p]] += self.data[p] * x[j];
272            }
273        }
274        y
275    }
276
277    pub fn to_csr(&self) -> CsrMatrix {
278        let t = CsrMatrix { nrows: self.ncols, ncols: self.nrows, indptr: self.indptr.clone(), indices: self.indices.clone(), data: self.data.clone() };
279        t.transpose()
280    }
281}