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
//! Dictionary of Keys (DOK) matrix format
//!
//! This module provides the DOK matrix format implementation, which is
//! efficient for incremental matrix construction.
use crate::error::{SparseError, SparseResult};
use scirs2_core::numeric::{SparseElement, Zero};
use std::collections::HashMap;
/// Dictionary of Keys (DOK) matrix
///
/// A sparse matrix format that stores elements in a dictionary (hash map),
/// making it efficient for incremental construction.
pub struct DokMatrix<T> {
/// Number of rows
rows: usize,
/// Number of columns
cols: usize,
/// Dictionary of (row, col) -> value
data: HashMap<(usize, usize), T>,
}
impl<T> DokMatrix<T>
where
T: Clone + Copy + Zero + std::cmp::PartialEq + SparseElement,
{
/// Create a new DOK matrix
///
/// # Arguments
///
/// * `shape` - Tuple containing the matrix dimensions (rows, cols)
///
/// # Returns
///
/// * A new empty DOK matrix
///
/// # Examples
///
/// ```
/// use scirs2_sparse::dok::DokMatrix;
///
/// // Create a 3x3 sparse matrix
/// let mut matrix = DokMatrix::<f64>::new((3, 3));
///
/// // Set some values
/// matrix.set(0, 0, 1.0);
/// matrix.set(0, 2, 2.0);
/// matrix.set(1, 2, 3.0);
/// matrix.set(2, 0, 4.0);
/// matrix.set(2, 1, 5.0);
/// ```
pub fn new(shape: (usize, usize)) -> Self {
let (rows, cols) = shape;
DokMatrix {
rows,
cols,
data: HashMap::new(),
}
}
/// Set a value in the matrix
///
/// # Arguments
///
/// * `row` - Row index
/// * `col` - Column index
/// * `value` - Value to set
///
/// # Returns
///
/// * Ok(()) if successful, Error otherwise
pub fn set(&mut self, row: usize, col: usize, value: T) -> SparseResult<()> {
if row >= self.rows || col >= self.cols {
return Err(SparseError::ValueError(
"Row or column index out of bounds".to_string(),
));
}
if value == T::sparse_zero() {
// Remove zero entries
self.data.remove(&(row, col));
} else {
// Set non-zero value
self.data.insert((row, col), value);
}
Ok(())
}
/// Get a value from the matrix
///
/// # Arguments
///
/// * `row` - Row index
/// * `col` - Column index
///
/// # Returns
///
/// * Value at the specified position, or zero if not set
pub fn get(&self, row: usize, col: usize) -> T {
if row >= self.rows || col >= self.cols {
return T::sparse_zero();
}
*self.data.get(&(row, col)).unwrap_or(&T::sparse_zero())
}
/// Get the number of rows in the matrix
pub fn rows(&self) -> usize {
self.rows
}
/// Get the number of columns in the matrix
pub fn cols(&self) -> usize {
self.cols
}
/// Get the shape (dimensions) of the matrix
pub fn shape(&self) -> (usize, usize) {
(self.rows, self.cols)
}
/// Get the number of non-zero elements in the matrix
pub fn nnz(&self) -> usize {
self.data.len()
}
/// Convert to dense matrix (as `Vec<Vec<T>>`)
pub fn to_dense(&self) -> Vec<Vec<T>>
where
T: Zero + Copy + SparseElement,
{
let mut result = vec![vec![T::sparse_zero(); self.cols]; self.rows];
for (&(row, col), &value) in &self.data {
result[row][col] = value;
}
result
}
/// Convert to COO representation
///
/// # Returns
///
/// * Tuple of (data, row_indices, col_indices)
pub fn to_coo(&self) -> (Vec<T>, Vec<usize>, Vec<usize>) {
let nnz = self.nnz();
let mut data = Vec::with_capacity(nnz);
let mut row_indices = Vec::with_capacity(nnz);
let mut col_indices = Vec::with_capacity(nnz);
// Sort by row, then column for deterministic output
let mut entries: Vec<_> = self.data.iter().collect();
entries.sort_by_key(|(&(row, col), _)| (row, col));
for (&(row, col), &value) in entries {
data.push(value);
row_indices.push(row);
col_indices.push(col);
}
(data, row_indices, col_indices)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dok_create_and_access() {
// Create a 3x3 sparse matrix
let mut matrix = DokMatrix::<f64>::new((3, 3));
// Set some values
matrix.set(0, 0, 1.0).expect("Operation failed");
matrix.set(0, 2, 2.0).expect("Operation failed");
matrix.set(1, 2, 3.0).expect("Operation failed");
matrix.set(2, 0, 4.0).expect("Operation failed");
matrix.set(2, 1, 5.0).expect("Operation failed");
assert_eq!(matrix.nnz(), 5);
// Access values
assert_eq!(matrix.get(0, 0), 1.0);
assert_eq!(matrix.get(0, 1), 0.0); // Zero entry
assert_eq!(matrix.get(0, 2), 2.0);
assert_eq!(matrix.get(1, 2), 3.0);
assert_eq!(matrix.get(2, 0), 4.0);
assert_eq!(matrix.get(2, 1), 5.0);
// Set a value to zero should remove it
matrix.set(0, 0, 0.0).expect("Operation failed");
assert_eq!(matrix.nnz(), 4);
assert_eq!(matrix.get(0, 0), 0.0);
// Out of bounds access should return zero
assert_eq!(matrix.get(3, 0), 0.0);
assert_eq!(matrix.get(0, 3), 0.0);
}
#[test]
fn test_dok_to_dense() {
// Create a 3x3 sparse matrix
let mut matrix = DokMatrix::<f64>::new((3, 3));
// Set some values
matrix.set(0, 0, 1.0).expect("Operation failed");
matrix.set(0, 2, 2.0).expect("Operation failed");
matrix.set(1, 2, 3.0).expect("Operation failed");
matrix.set(2, 0, 4.0).expect("Operation failed");
matrix.set(2, 1, 5.0).expect("Operation failed");
let dense = matrix.to_dense();
let expected = vec![
vec![1.0, 0.0, 2.0],
vec![0.0, 0.0, 3.0],
vec![4.0, 5.0, 0.0],
];
assert_eq!(dense, expected);
}
#[test]
fn test_dok_to_coo() {
// Create a 3x3 sparse matrix
let mut matrix = DokMatrix::<f64>::new((3, 3));
// Set some values
matrix.set(0, 0, 1.0).expect("Operation failed");
matrix.set(0, 2, 2.0).expect("Operation failed");
matrix.set(1, 2, 3.0).expect("Operation failed");
matrix.set(2, 0, 4.0).expect("Operation failed");
matrix.set(2, 1, 5.0).expect("Operation failed");
let (data, row_indices, col_indices) = matrix.to_coo();
// Check that all entries are present
assert_eq!(data.len(), 5);
assert_eq!(row_indices.len(), 5);
assert_eq!(col_indices.len(), 5);
// Check the content (sorted by row, then column)
let expected_data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let expected_rows = vec![0, 0, 1, 2, 2];
let expected_cols = vec![0, 2, 2, 0, 1];
assert_eq!(data, expected_data);
assert_eq!(row_indices, expected_rows);
assert_eq!(col_indices, expected_cols);
}
}