-
Notifications
You must be signed in to change notification settings - Fork 8
/
sparsevec.go
192 lines (164 loc) · 4.78 KB
/
sparsevec.go
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
package pgvector
import (
"database/sql"
"database/sql/driver"
"encoding/binary"
"fmt"
"math"
"slices"
"strconv"
"strings"
)
// SparseVector is a wrapper to implement sql.Scanner and driver.Valuer.
type SparseVector struct {
dim int32
indices []int32
values []float32
}
// NewSparseVector creates a new SparseVector from a slice of float32.
func NewSparseVector(vec []float32) SparseVector {
dim := int32(len(vec))
indices := make([]int32, 0)
values := make([]float32, 0)
for i := 0; i < len(vec); i++ {
if vec[i] != 0 {
indices = append(indices, int32(i))
values = append(values, vec[i])
}
}
return SparseVector{dim: dim, indices: indices, values: values}
}
// NewSparseVectorFromMap creates a new SparseVector from a map of non-zero elements.
func NewSparseVectorFromMap(elements map[int32]float32, dim int32) SparseVector {
indices := make([]int32, 0, len(elements))
values := make([]float32, 0, len(elements))
for k, v := range elements {
if v != 0 {
indices = append(indices, k)
}
}
slices.Sort(indices)
for _, k := range indices {
values = append(values, elements[k])
}
return SparseVector{dim: dim, indices: indices, values: values}
}
// Dimensions returns the number of dimensions.
func (v SparseVector) Dimensions() int32 {
return v.dim
}
// Indices returns the non-zero indices.
func (v SparseVector) Indices() []int32 {
return v.indices
}
// Values returns the non-zero values.
func (v SparseVector) Values() []float32 {
return v.values
}
// Slice returns a slice of float32.
func (v SparseVector) Slice() []float32 {
vec := make([]float32, v.dim)
for i := 0; i < len(v.indices); i++ {
vec[v.indices[i]] = v.values[i]
}
return vec
}
// String returns a string representation of the sparse vector.
func (v SparseVector) String() string {
buf := make([]byte, 0, 13+27*len(v.indices))
buf = append(buf, '{')
for i := 0; i < len(v.indices); i++ {
if i > 0 {
buf = append(buf, ',')
}
buf = strconv.AppendInt(buf, int64(v.indices[i])+1, 10)
buf = append(buf, ':')
buf = strconv.AppendFloat(buf, float64(v.values[i]), 'f', -1, 32)
}
buf = append(buf, '}')
buf = append(buf, '/')
buf = strconv.AppendInt(buf, int64(v.dim), 10)
return string(buf)
}
// Parse parses a string representation of a sparse vector.
func (v *SparseVector) Parse(s string) error {
sp := strings.SplitN(s, "/", 2)
dim, err := strconv.ParseInt(sp[1], 10, 32)
if err != nil {
return err
}
elements := strings.Split(sp[0][1:len(sp[0])-1], ",")
v.dim = int32(dim)
v.indices = make([]int32, 0, len(elements))
v.values = make([]float32, 0, len(elements))
for i := 0; i < len(elements); i++ {
ep := strings.SplitN(elements[i], ":", 2)
n, err := strconv.ParseInt(ep[0], 10, 32)
if err != nil {
return err
}
v.indices = append(v.indices, int32(n-1))
n2, err := strconv.ParseFloat(ep[1], 32)
if err != nil {
return err
}
v.values = append(v.values, float32(n2))
}
return nil
}
// EncodeBinary encodes a binary representation of the sparse vector.
func (v SparseVector) EncodeBinary(buf []byte) (newBuf []byte, err error) {
nnz := len(v.indices)
buf = slices.Grow(buf, 12+8*nnz)
buf = binary.BigEndian.AppendUint32(buf, uint32(v.dim))
buf = binary.BigEndian.AppendUint32(buf, uint32(nnz))
buf = binary.BigEndian.AppendUint32(buf, 0)
for _, v := range v.indices {
buf = binary.BigEndian.AppendUint32(buf, uint32(v))
}
for _, v := range v.values {
buf = binary.BigEndian.AppendUint32(buf, math.Float32bits(v))
}
return buf, nil
}
// DecodeBinary decodes a binary representation of a sparse vector.
func (v *SparseVector) DecodeBinary(buf []byte) error {
dim := binary.BigEndian.Uint32(buf[0:4])
nnz := int(binary.BigEndian.Uint32(buf[4:8]))
unused := binary.BigEndian.Uint32(buf[8:12])
if unused != 0 {
return fmt.Errorf("expected unused to be 0")
}
v.dim = int32(dim)
v.indices = make([]int32, 0, nnz)
v.values = make([]float32, 0, nnz)
offset := 12
for i := 0; i < nnz; i++ {
v.indices = append(v.indices, int32(binary.BigEndian.Uint32(buf[offset:offset+4])))
offset += 4
}
for i := 0; i < nnz; i++ {
v.values = append(v.values, math.Float32frombits(binary.BigEndian.Uint32(buf[offset:offset+4])))
offset += 4
}
return nil
}
// statically assert that SparseVector implements sql.Scanner.
var _ sql.Scanner = (*SparseVector)(nil)
// Scan implements the sql.Scanner interface.
func (v *SparseVector) Scan(src interface{}) (err error) {
switch src := src.(type) {
case []byte:
return v.Parse(string(src))
case string:
return v.Parse(src)
default:
return fmt.Errorf("unsupported data type: %T", src)
}
}
// statically assert that SparseVector implements driver.Valuer.
var _ driver.Valuer = (*SparseVector)(nil)
// Value implements the driver.Valuer interface.
func (v SparseVector) Value() (driver.Value, error) {
return v.String(), nil
}