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
use vector::BasicReadableVector;
use vector::BasicWriteableVector;
use vector::SparseVector;
pub struct SparseCS {
element: Vec<f32>,
col_ind: Vec<usize>,
size: usize
}
impl SparseCS {
pub fn new(col: usize) -> SparseCS {
let v = SparseCS{element: vec![], col_ind:vec![0], size: col};
return v;
}
pub fn set_size(&mut self, new_size: usize) {
if self.size < new_size {
self.size = new_size;
return;
}
let index = self.col_ind.iter().position(|&idx| idx >= new_size).unwrap();
self.col_ind.truncate(index);
self.element.truncate(index);
}
}
impl BasicReadableVector for SparseCS {
fn get_size(&self) -> usize {
return self.size;
}
fn get_element(&self, i: usize)-> f32 {
if i >= self.get_size() {
panic!("assignment out of bounds");
}
if self.nnz() == 0 {
return 0.0
}
let index = match self.col_ind.binary_search(&i) {
Err(_) => return 0.0,
Ok(index) => index,
};
let idx = self.col_ind[index];
return self.element[idx];
}
}
impl BasicWriteableVector for SparseCS {
fn set_element(&mut self, i: usize, value: f32) {
if i >= self.get_size() {
panic!("assignment out of bounds");
}
if i >= self.element.len() {
self.element.push(value);
self.col_ind.push(i);
return;
}
let index = match self.col_ind.binary_search(&i) {
Err(_) => panic!(),
Ok(index) => index,
};
self.col_ind.insert(index, i);
self.element.insert(index, value);
}
fn set_zero(&mut self) {
self.element = vec![];
self.col_ind = vec![0];
}
}
impl SparseVector for SparseCS {
fn nnz(&self) -> usize {
return self.element.len();
}
}