-
Notifications
You must be signed in to change notification settings - Fork 5
/
csr_mat.rs
210 lines (172 loc) · 5.23 KB
/
csr_mat.rs
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
//! Definition of CSR matrices.
use crate::dense::traits::AijIterator;
use crate::dense::types::RlstResult;
use crate::sparse::sparse_mat::SparseMatType;
use crate::dense::traits::Shape;
use crate::dense::types::RlstScalar;
use crate::sparse::sparse_mat::tools::normalize_aij;
use super::csc_mat::CscMatrix;
/// A CSR matrix
#[derive(Clone)]
pub struct CsrMatrix<T: RlstScalar> {
mat_type: SparseMatType,
shape: [usize; 2],
indices: Vec<usize>,
indptr: Vec<usize>,
data: Vec<T>,
}
impl<Item: RlstScalar> CsrMatrix<Item> {
/// Create a new CSR matrix
pub fn new(
shape: [usize; 2],
indices: Vec<usize>,
indptr: Vec<usize>,
data: Vec<Item>,
) -> Self {
Self {
mat_type: SparseMatType::Csr,
shape,
indices,
indptr,
data,
}
}
/// Number of element
pub fn nelems(&self) -> usize {
self.data.len()
}
/// Matrix type
pub fn mat_type(&self) -> &SparseMatType {
&self.mat_type
}
/// Indices of items
pub fn indices(&self) -> &[usize] {
&self.indices
}
/// Indices at which each row starts
pub fn indptr(&self) -> &[usize] {
&self.indptr
}
/// Entries of the matrix
pub fn data(&self) -> &[Item] {
&self.data
}
/// Matrix multiplication
pub fn matmul(&self, alpha: Item, x: &[Item], beta: Item, y: &mut [Item]) {
assert_eq!(self.shape()[0], y.len());
assert_eq!(self.shape()[1], x.len());
for (row, out) in y.iter_mut().enumerate() {
*out = beta * *out
+ alpha * {
let c1 = self.indptr()[row];
let c2 = self.indptr()[1 + row];
let mut acc = Item::zero();
for index in c1..c2 {
let col = self.indices()[index];
acc += self.data()[index] * x[col];
}
acc
}
}
}
/// Convert to CSC matrix
pub fn into_csc(self) -> CscMatrix<Item> {
let mut rows = Vec::<usize>::with_capacity(self.nelems());
let mut cols = Vec::<usize>::with_capacity(self.nelems());
let mut data = Vec::<Item>::with_capacity(self.nelems());
for (row, col, elem) in self.iter_aij() {
rows.push(row);
cols.push(col);
data.push(elem);
}
CscMatrix::from_aij(self.shape(), &rows, &cols, &data).unwrap()
}
/// Create CSR matrix from rows, columns and data
pub fn from_aij(
shape: [usize; 2],
rows: &[usize],
cols: &[usize],
data: &[Item],
) -> RlstResult<Self> {
let (rows, cols, data) = normalize_aij(rows, cols, data, SparseMatType::Csr);
let max_col = cols.iter().max().unwrap();
let max_row = rows.last().unwrap();
assert!(
*max_col < shape[1],
"Maximum column {} must be smaller than `shape.1` {}",
max_col,
shape[1]
);
assert!(
*max_row < shape[0],
"Maximum row {} must be smaller than `shape.0` {}",
max_row,
shape[0]
);
let nelems = data.len();
let mut indptr = Vec::<usize>::with_capacity(1 + shape[0]);
let mut count: usize = 0;
for row in 0..(shape[0]) {
indptr.push(count);
while count < nelems && row == rows[count] {
count += 1;
}
}
indptr.push(count);
Ok(Self::new(shape, cols, indptr, data))
}
}
/// CSR iterator
pub struct CsrAijIterator<'a, Item: RlstScalar> {
mat: &'a CsrMatrix<Item>,
row: usize,
pos: usize,
}
impl<'a, Item: RlstScalar> CsrAijIterator<'a, Item> {
/// Create a new iterator
pub fn new(mat: &'a CsrMatrix<Item>) -> Self {
// We need to move the row pointer to the first row that has at least one element.
let mut row: usize = 0;
while row < mat.shape()[0] && mat.indptr[row] == mat.indptr[1 + row] {
row += 1;
}
Self { mat, row, pos: 0 }
}
}
impl<'a, Item: RlstScalar> std::iter::Iterator for CsrAijIterator<'a, Item> {
type Item = (usize, usize, Item);
fn next(&mut self) -> Option<Self::Item> {
if self.pos == self.mat.data().len() {
return None;
}
let result = Some((
self.row,
*self.mat.indices().get(self.pos).unwrap(),
*self.mat.data().get(self.pos).unwrap(),
));
self.pos += 1;
// The following jumps over all zero rows to the next relevant row
while self.row < self.mat.shape()[0] && self.mat.indptr()[1 + self.row] <= self.pos {
self.row += 1;
}
result
}
fn count(self) -> usize
where
Self: Sized,
{
self.mat.data().len()
}
}
impl<Item: RlstScalar> AijIterator for CsrMatrix<Item> {
type Item = Item;
type Iter<'a> = CsrAijIterator<'a, Item> where Self: 'a;
fn iter_aij(&self) -> Self::Iter<'_> {
CsrAijIterator::new(self)
}
}
impl<Item: RlstScalar> Shape<2> for CsrMatrix<Item> {
fn shape(&self) -> [usize; 2] {
self.shape
}
}