-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathsparsevec.rs
More file actions
154 lines (134 loc) · 4.68 KB
/
sparsevec.rs
File metadata and controls
154 lines (134 loc) · 4.68 KB
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
#[cfg(feature = "diesel")]
use crate::diesel_ext::sparsevec::SparseVectorType;
#[cfg(feature = "diesel")]
use diesel::{deserialize::FromSqlRow, expression::AsExpression};
/// A sparse vector.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "diesel", derive(FromSqlRow, AsExpression))]
#[cfg_attr(feature = "diesel", diesel(sql_type = SparseVectorType))]
pub struct SparseVector {
pub(crate) dim: i32,
pub(crate) indices: Vec<i32>,
pub(crate) values: Vec<f32>,
}
impl SparseVector {
/// Creates a sparse vector from a dense vector.
pub fn from_dense(vec: &[f32]) -> SparseVector {
let dim: i32 = vec.len().try_into().unwrap();
let mut indices = Vec::new();
let mut values = Vec::new();
for (i, v) in vec.iter().enumerate() {
if *v != 0.0 {
indices.push(i.try_into().unwrap());
values.push(*v);
}
}
SparseVector {
dim,
indices,
values,
}
}
/// Creates a sparse vector from a map of non-zero elements.
pub fn from_map<'a, I: IntoIterator<Item = (&'a i32, &'a f32)>>(
map: I,
dim: i32,
) -> SparseVector {
let mut elements: Vec<(&i32, &f32)> = map.into_iter().filter(|v| *v.1 != 0.0).collect();
elements.sort_by_key(|v| *v.0);
let indices: Vec<i32> = elements.iter().map(|v| *v.0).collect();
let values: Vec<f32> = elements.iter().map(|v| *v.1).collect();
SparseVector {
dim,
indices,
values,
}
}
/// Returns the number of dimensions.
pub fn dimensions(&self) -> i32 {
self.dim
}
/// Returns the non-zero indices.
pub fn indices(&self) -> &[i32] {
&self.indices
}
/// Returns the non-zero values.
pub fn values(&self) -> &[f32] {
&self.values
}
/// Returns the sparse vector as a `Vec<f32>`.
pub fn to_vec(&self) -> Vec<f32> {
let mut vec = vec![0.0; self.dim.try_into().unwrap()];
for (i, v) in self.indices.iter().zip(&self.values) {
vec[usize::try_from(*i).unwrap()] = *v;
}
vec
}
#[cfg(any(feature = "postgres", feature = "sqlx", feature = "diesel"))]
pub(crate) fn from_sql(
buf: &[u8],
) -> Result<SparseVector, Box<dyn std::error::Error + Sync + Send>> {
let dim = i32::from_be_bytes(buf[0..4].try_into()?);
let nnz = i32::from_be_bytes(buf[4..8].try_into()?).try_into()?;
let unused = i32::from_be_bytes(buf[8..12].try_into()?);
if unused != 0 {
return Err("expected unused to be 0".into());
}
let mut indices = Vec::with_capacity(nnz);
for i in 0..nnz {
let s = 12 + 4 * i;
indices.push(i32::from_be_bytes(buf[s..s + 4].try_into()?));
}
let mut values = Vec::with_capacity(nnz);
for i in 0..nnz {
let s = 12 + 4 * nnz + 4 * i;
values.push(f32::from_be_bytes(buf[s..s + 4].try_into()?));
}
Ok(SparseVector {
dim,
indices,
values,
})
}
}
#[cfg(test)]
mod tests {
use crate::SparseVector;
use std::collections::{BTreeMap, HashMap};
#[test]
fn test_from_dense() {
let vec = SparseVector::from_dense(&[1.0, 0.0, 2.0, 0.0, 3.0, 0.0]);
assert_eq!(vec![1.0, 0.0, 2.0, 0.0, 3.0, 0.0], vec.to_vec());
assert_eq!(6, vec.dimensions());
assert_eq!(&[0, 2, 4], vec.indices());
assert_eq!(&[1.0, 2.0, 3.0], vec.values());
}
#[test]
fn test_from_hash_map() {
let map = HashMap::from([(0, 1.0), (2, 2.0), (4, 3.0)]);
let vec = SparseVector::from_map(&map, 6);
assert_eq!(vec![1.0, 0.0, 2.0, 0.0, 3.0, 0.0], vec.to_vec());
assert_eq!(6, vec.dimensions());
assert_eq!(&[0, 2, 4], vec.indices());
assert_eq!(&[1.0, 2.0, 3.0], vec.values());
}
#[test]
fn test_from_btree_map() {
let map = BTreeMap::from([(0, 1.0), (2, 2.0), (4, 3.0)]);
let vec = SparseVector::from_map(&map, 6);
assert_eq!(vec![1.0, 0.0, 2.0, 0.0, 3.0, 0.0], vec.to_vec());
assert_eq!(6, vec.dimensions());
assert_eq!(&[0, 2, 4], vec.indices());
assert_eq!(&[1.0, 2.0, 3.0], vec.values());
}
#[test]
fn test_from_vec_map() {
let vec = vec![(0, 1.0), (2, 2.0), (4, 3.0)];
let map = vec.iter().map(|v| (&v.0, &v.1));
let vec = SparseVector::from_map(map, 6);
assert_eq!(vec![1.0, 0.0, 2.0, 0.0, 3.0, 0.0], vec.to_vec());
assert_eq!(6, vec.dimensions());
assert_eq!(&[0, 2, 4], vec.indices());
assert_eq!(&[1.0, 2.0, 3.0], vec.values());
}
}