-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmatrix.py
More file actions
290 lines (222 loc) · 7.57 KB
/
cmatrix.py
File metadata and controls
290 lines (222 loc) · 7.57 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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""Compressed matrix.
Hierarchical matrix implementation.
Code for ab initio quantum chemistry based on a compressed representation of key data structures. Developed by researchers at the Institute for Advanced Copmutational Science (IACS) at Stony Brook University (SBU). Currently a work in progress.
"""
import numpy as np
import scipy.sparse.linalg as lg
from random import randrange
import string
import random
class CMatrix():
"""CMAtrix class that represents a matrix or a block"""
def __init__(self, mat):
"""
CMAtrix constructor.
Args:
mat (ndarray) : Matrix to compess.
"""
# Store the number of rows and columns
self.nr = mat.shape[0]
self.nc = mat.shape[1]
# Randomly choose matrix (or block) type
# 0 - dense
# 1 - decomposed
# 2 - hierarchical
self.type = randrange(3)
# Ranks
k_svd = 6
k_dense = 2 * k_svd
# Make small blocks dense
if min(self.nr, self.nc) <= k_dense:
self.type = 0
# Store the block as is if it is a dense type block
if self.type == 0:
self.mat = mat
# Or decompose it using any technique
# Used SVD, because it was the easiest to implement
elif self.type == 1:
u, s, vt = lg.svds(mat, k = k_svd) # SVD rank is 6 by default
self.u = u
self.s = s
self.vt = vt
# Or break it into sub-blocks
else:
i = self.nr // 2
j = self.nc // 2
self.b11 = CMatrix(mat[:i,:j])
self.b12 = CMatrix(mat[:i,j:])
self.b21 = CMatrix(mat[i:,:j])
self.b22 = CMatrix(mat[i:,j:])
def dot(self,x):
"""
Matrix-vector multiplication.
Args:
x (ndarray) : Initial vector.
Returns:
y (ndarray) : Resulting vector.
"""
# Check if matrix and vector sizes mismatch
if self.nc != len(x):
print('Matrix-vector size mismatch')
sys.exit(1)
# Dense multiplication
if self.type == 0:
y = self.mat.dot(x)
# Or multiplication using SVD decomposition
elif self.type == 1:
sigma = np.diagflat(self.s) # Form a diagonal matrix from vector S
y = self.u.dot(sigma.dot(self.vt.dot(x)))
# Or delegate to sub-blocks and combine pieces
else:
j = self.nc // 2
y1 = self.b11.dot(x[:j]) + self.b12.dot(x[j:])
y2 = self.b21.dot(x[:j]) + self.b22.dot(x[j:])
y = np.concatenate([y1,y2])
return y
def bstr(self):
"""
Computes a character representation of the matrix.
- Dense block is shown with a letter
- Decomposed block is shown with a digit
Different sub-blocks use different letters and digits
so that the overall structure can be easily seen.
Returns:
s (ndarray) : 2D array of characters, where one character is one element.
"""
# Return a block filled with the same random letter if dense
if self.type == 0:
char = random.choice(string.ascii_letters)
s = np.full((self.nr, self.nc), char)
# Or return a block filled with the same random digit if decomposed
elif self.type == 1:
digit = random.choice(string.digits)
s = np.full((self.nr, self.nc), digit)
# Or delegate to sub-blocks and combine pieces
else:
s1 = np.concatenate((self.b11.bstr(), self.b12.bstr()), axis=1)
s2 = np.concatenate((self.b21.bstr(), self.b22.bstr()), axis=1)
s = np.concatenate((s1, s2), axis=0)
return s
def __str__(self):
"""
Returns a string representation of the matrix.
Useful for debugging.
"""
s = ' - Dense block is shown with a letter\n'
s += ' - Decomposed block is shown with a digit\n\n'
for i in self.bstr():
s += ''.join(j for j in i)
s += '\n'
return s
def memory(self):
"""
Computes the size of memory used.
Returns:
k (int) : The number of doubles stored.
"""
# Return the number of elements if dense
if self.type == 0:
k = self.nr * self.nc
# Or the number of doubles in SVD decomposition
elif self.type == 1:
k = self.u.shape[0] * self.u.shape[1]
k += self.s.shape[0]
k += self.vt.shape[0] * self.vt.shape[1]
# Or sum over sub-blocks
else:
k1 = self.b11.memory() + self.b12.memory()
k2 = self.b21.memory() + self.b22.memory()
k = k1 + k2
return k
def error(self,mat):
"""
Computes matrix error.
Generates a number of random vectors, multiplies by the matrix
and computes the residual norms. The error is relative and is defined as
a ratio of the residual norm and the norm of the exact solution.
The final error is averaged over all random vectors.
Args:
mat (ndarray) : The initial full matrix that is approximated.
Returns:
e (double): Error.
"""
count = 100
e = 0
for i in range(count):
x = np.random.rand(n)
yd = mat.dot(x)
yc = self.dot(x)
dt = yd - yc
e += np.linalg.norm(dt) / np.linalg.norm(yd)
e /= count
return e
if __name__ == "__main__":
# Matrix size
n = 40
# Generate a random symmetric matrix
mat = np.random.rand(n,n)
mat = (mat + mat.T) / 2
print('Given matrix:')
print(mat)
print()
# Generate a random vector
print('Given vector:')
x = np.random.rand(n)
print(x)
print()
# Dense matrix vector multiplication
print('Matrix vector product [Dense]:')
y = mat.dot(x)
print(y)
print()
# Generate a compressed matrix that approximates the given matrix
print('CMatrix:')
cmat = CMatrix(mat)
print(cmat)
print()
# Compressed matrix vector multiplication
print('Matrix vector product [CMatrix]:')
y = cmat.dot(x)
print(y)
print()
# Format strings for printing
fs = '{0:10s} {1:10d} {2:10.5f}'
fd = '{0:10d} {1:10d} {2:10.5f}'
# Print the information about both matrices
print(' Name Memory RelError')
kd = n * n
kc = cmat.memory()
ed = 0
ec = cmat.error(mat)
print(fs.format('Dense', kd, ed))
print(fs.format('CMatrix', kc, ec))
print()
print()
# Another example
# Generate many compressed representations of the same matrix
# Pick the one with twice smaller memory and the smallest error
print('==================================')
print('===== Searching for the best =====')
print('======= Twice smaller size =======')
print('==================================')
print('')
# Print header for the table
print(' Name Memory RelError')
# Generate and find the best
best_ec = float("inf")
for i in range(100):
cmat = CMatrix(mat)
kc = cmat.memory()
ec = cmat.error(mat)
print(fd.format(i, kc, ec))
if kc < kd / 2 and ec < best_ec:
best_cmat = cmat
best_kc = kc
best_ec = ec
best_i = i
# Print the best matrix
print('Best:')
print(fd.format(best_i, best_kc, best_ec))
print()
print('Best CMatrix:')
print(best_cmat)