-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix.py
More file actions
executable file
·644 lines (539 loc) · 19.3 KB
/
Matrix.py
File metadata and controls
executable file
·644 lines (539 loc) · 19.3 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# To install use 'pip install numpy'
import numpy as np
import copy
from math import sqrt
class Matrix:
"""
Matrix library that will store matrix in a CSR (Compressed Sparse Row)
format and provides methods to perform elementary matrix operations with
this matrix in this format. (This format aims to optimise memory usage,
but increases number of computations)
WARNING: In current solution, matrix will ignore 'zero rows' and 'zero
columns' in a matrix.
"""
# Class variables
r = [] # row pointer (points to an index of changing row value)
c = [] # stores the column index of the value(self.v)
v = [] # stores a list of values
isCSR = False # marks the current type of storage is sparse of not
# FOR TESTING while developing ONLY
init_matrix = [] # stores the matrix in array of arrays of ints/floats
r_ = [] # stores the row index of the value(self.v)
def __init__(self, matrix=None):
"""
Constructor: initializes variables, checks the type, converts to
sparse matrix iff the input matrix is not a sparse matrix.
:param matrix: [list] - array of arrays of floats/ints
:return:
"""
if matrix and not isinstance(matrix, Matrix):
if isinstance(matrix, str):
matrix = self.str2list(matrix)
self.clean_up()
self.init_matrix = matrix
if matrix and not self.isCSR:
self.list2csr()
def set(self, r, c, v):
self.r = r
self.c = c
self.v = v
self.isCSR = True
return self
def copy(self):
"""
Copies the object into a new one
:return: [Matrix] a new instance copy of the current object
"""
return copy.deepcopy(self)
def clean_up(self):
"""
Clean Up: initializes lists of sparse storage to empty lists
:return: self [Matrix]
"""
self.r = []
self.c = []
self.v = []
self.isCSR = False
self.r_ = [] # FOR TESTING ONLY
return self
def get_sparse(self):
"""
Get Matrix in sparse form
:return: [list] of following lists:
self.r [list] - row pointer (points to an index of changing row value)
self.c [list] - column indexes of the values(self.v)
self.v [list] - list of plain matrix values
"""
return [self.r, self.c, self.v]
def is_csr(self):
"""
Is Sparse: checks if the current instance of a Matrix class is
already stored in a sparse format
:return: [Boolean] - is in sparse format? True or False
"""
return self.isCSR
def rows(self):
"""
Number of Rows: computes the number of rows in current matrix.
:return: [Int] - number of rows
"""
return len(self.r)-1
def cols(self):
"""
Number of Columns: computes the number of cols in current matrix.
:return: [Int] - number of cols
"""
return max(self.c)+1
def list2csr(self):
"""
List To Sparse: converts the array of arrays of ints/floats to sparse
matrix and stores in needed data structure (list [r, c, v]). NOTE:
make sure self.init_matrix is set before calling this method.
:return: [Matrix] - self object
"""
if not self.init_matrix:
print("!!! Exception: Nothing to convert to sparse matrix, "
"self.init_matrix = []")
if not self.is_csr():
prev_r = -1
for n, row in enumerate(self.init_matrix):
for col, val in enumerate(row):
if val != 0:
if prev_r != n:
prev_r = n
self.r.append(len(self.v))
self.r_.append(n)
self.c.append(col)
self.v.append(val)
self.r.append(len(self.v))
self.isCSR = True
return self
def csr2list(self):
"""
CSR To List: converts current sparse matrix to an array of arrays of
ints/floats
:return: [Matrix] - self object
"""
if self.is_csr():
rows = []
for i in range(0, self.rows()):
row = []
for j in range(0, self.cols()):
row.append(0.0)
rows.append(row)
prev_i = i = 0
for x, val in enumerate(self.v):
if x == self.r[prev_i]:
i = prev_i
if len(self.r) > prev_i+1:
prev_i += 1
j = self.c[x]
rows[i][j] = val
self.clean_up()
self.init_matrix = rows
return self
@staticmethod
def combine_vectors(vectors):
"""
Combines list of vectors and outputs a new matrix
:param vectors: [list] of [Matrix] or [list]
:return: [Matrix]
"""
prev_rows = vectors[0].rows()
new_tuples = []
j = 0
for vector in vectors:
if prev_rows != vector.rows():
print("!!! Exception: Can't combine vectors that are not "
"the same dimension!")
return Matrix()
if vector.cols() != 1:
print("!!! Exception: Can't combine matrices, try passing a "
"vector")
return Matrix()
if isinstance(vector, Matrix):
tuples = vector.csr2tuple()
else:
tuples = Matrix(vector).csr2tuple()
for tup in tuples:
new_tuples.append((tup[0], j, tup[2]))
j += 1
new_tuples = sorted(new_tuples)
r, c, v = Matrix.tuple2csr(new_tuples)
result = Matrix().set(r, c, v)
return result
@staticmethod
def combine(vectors):
"""
Alias method for calling combine_vectors()
:param vectors:
:return:
"""
return Matrix.combine_vectors(vectors)
@staticmethod
def str2list(matrix_str):
"""
Converts a string into a list format which could be converted to Matrix
:param matrix_str: [str]
:return: [list]
"""
matrix = []
matrix_str = matrix_str.replace(" ", "")
rows = matrix_str.split("],")
for row in rows:
row = row.replace("[", "")
row = row.replace("]", "")
row = row.replace("\r", "")
row = row.replace("\n", "")
# converting to floats
values = row.split(",")
for i, v in enumerate(values):
values[i] = float(v)
matrix.append(values)
return matrix
@staticmethod
def list2str(matrix_rows):
"""
Converts a list into a string format
:param matrix_rows:
:return:
"""
text = ""
for row in matrix_rows:
text += str(row) + "\n"
return text
def display(self, text="", returns=False, nl="\n", indent="\t"):
"""
Displays the matrix in whatever format it is
:param text: [string] any text that you want to display before matrix
:param returns: [boolean] Whether to print the matrix or return
:param nl: [string] new line tag. (cold be '\n', ' ', '|' or anything)
:return:
"""
if self.is_csr():
matrix = self.get_sparse_display()
else:
matrix = self.init_matrix
result = ""
if text != "":
result += text + nl
c = 0
for row in matrix:
c += 1
first = "[" if c == 1 else " " # first row has '['
last = " ]" if c == len(matrix) else "," # last row has ' ]'
e = [float("%.2f" % x) if isinstance(x, float) else x for x in row]
result += str("%s%s%s%s" % (indent, first, e, last)) + nl
if not returns:
print(result)
return result
def get_sparse_display(self):
"""
Display the matrix in a sparse format (replacing 0s with '_')
NOTE: comutation happens from a sparse matrix directly.
:param returns:
:return:
"""
rows = []
for i in range(0, self.rows()):
row = []
for j in range(0, self.cols()):
row.append("__")
rows.append(row)
prev_i = i = 0
for x, val in enumerate(self.v):
if x == self.r[prev_i]:
i = prev_i
if len(self.r) > prev_i+1:
prev_i += 1
j = self.c[x]
rows[i][j] = val
return rows
def _type_check(self, matrix):
"""
Converts given matrix in Matrix format.
:param matrix: [str]
[list]
[matrix]
:return:
"""
if isinstance(matrix, str):
matrix = self.str2list(matrix)
if isinstance(matrix, list):
matrix = Matrix(matrix)
matrix.display()
if not isinstance(matrix, Matrix):
print("!!! Exception: Can't convert to a Matrix!")
return matrix
def csr2tuple(self):
current_row = 0
triples_list = []
for j, v in enumerate(self.v):
if j == self.r[current_row + 1]:
current_row += 1
triples_list.append((current_row, self.c[j], v))
return triples_list
@staticmethod
def tuple2csr(list):
new_r = []
new_c = []
new_v = []
prev_r = -1
for triple in list:
if prev_r != triple[0]:
prev_r = triple[0]
new_r.append(len(new_v))
new_c.append(triple[1])
new_v.append(triple[2])
new_r.append(len(new_v))
return new_r, new_c, new_v
def transpose(self, to_self=False):
"""
Takes transpose of a matrix
:param to_self: [Boolean] if this operation should return a new object
:return: [Matrix] - self object
"""
new_tuple = []
for a_tuple in self.csr2tuple():
# Making transpose: (x, y, v) => (y, x, v)
new_tuple.append((a_tuple[1], a_tuple[0], a_tuple[2]))
# Need to sort for 1st element in tuple(x) so we will be able to go
# back to sparse matrix by re-computing self.r (rows list)
result = sorted(new_tuple)
r, c, v = Matrix.tuple2csr(result)
if to_self:
self.r, self.c, self.v = r, c, v
result = self
else:
result = Matrix().set(r, c, v)
return result
def t(self, to_self=False):
return self.transpose(to_self)
def is_symmetric(self):
"""
Checks if the current Matrix object (is CSR format) is symmetric
:return: [bool] True or False
"""
result = False
t = self.t()
if self.r == t.r and self.c == t.c and self.v == t.v and\
self != t: # Making sure we are not comparing the same object
result = True
return result
def qr(self, normalized=True):
"""
Computes the QR Factorization where where Q is an orthogonal matrix
and R is an upper triangular matrix.
NOTE: using external library to compute it since have no time to
implement it.
:param normalized:
:return: [Matrix], [Matrix] Q, R matrices
"""
a = self.copy().csr2list().init_matrix
q, r = np.linalg.qr(a)
if normalized:
q = q / q.max(axis=0)
return Matrix(q.tolist()), Matrix(r.tolist())
def dot(self, vector=None):
"""
Computes the dot product with a vector. Both self and vector should
be 1 column [Matrix].
:param vector: [Matrix] to take the dot product with. If None,
then we duplicate the current [Matrix]
:return: [float] or [int]
"""
if vector is None or vector == self:
vector = self.copy()
if self.cols() > 1:
print("!!! Exception: Can't compute dot product self, dimension "
"is > 1 !")
if vector.cols() > 1:
print("!!! Exception: Can't compute dot product vector, dimension "
"is > 1 !")
if self.rows() != vector.rows():
print("!!! Exception: Can't compute dot product, vectors have "
"different number of rows !")
result = 0
for i in range(0, self.rows()):
result += self.v[i] * vector.v[i]
return result
def length(self):
"""
Computes the length of a current Matrix (NOTE: dot() assumes its a
vector, 1 column).
:return: [float] or [int]
"""
d = self.dot(self.copy())
return sqrt(d)
def norm(self):
"""
Alias function for computing length of a vector
:return: [float] or [int]
"""
return self.length()
def scalar(self, scalar=1.0, to_self=False):
"""
Scalar - multiplies all values of a matrix to a scalar number
:param scalar: [float]
:param to_self: [Boolean] if this operation should return a new object
:return: [Matrix] - self object
"""
if scalar == 0:
print("!!! Exception: Scalar number can't be '0'!")
if to_self:
self.v = [x*scalar for x in self.v]
result = self
else:
matrix = self.copy()
matrix.v = [x*scalar for x in matrix.v]
result = matrix
return result
def scale(self, scalar=1.0, to_self=False):
return self.scalar(scalar, to_self)
def add(self, matrix, to_self=False):
"""
Add
:param matrix:
:param to_self: [Boolean] if this operation should return a new object
:return: [Matrix] - self object
"""
matrix = self._type_check(matrix)
if self.rows() != matrix.rows() or self.cols() != matrix.cols():
print("!!! Exception: Wrong size matrix passed to add!")
a_tuple = self.csr2tuple()
b_tuple = matrix.csr2tuple()
a_new = []
b_new = []
result = []
for a in a_tuple:
a_new.append(a)
for b in b_tuple:
b_new.append(b)
if a[0] == b[0] and a[1] == b[1]:
result.append((b[0], b[1], a[2] + b[2]))
if a in a_new:
a_new.remove(a)
if b in b_new:
b_new.remove(b)
for a in a_new:
result.append((a[0], a[1], a[2]))
for b in b_new:
result.append((b[0], b[1], b[2]))
result = sorted(result)
r, c, v = Matrix.tuple2csr(result)
if to_self:
self.r, self.c, self.v = r, c, v
result = self
else:
result = Matrix().set(r, c, v)
return result
def subtract(self, matrix, to_self=False):
"""
Subtract
:param matrix:
:param to_self: [Boolean] if this operation should return a new object
:return: [Matrix] - self object
"""
matrix = self._type_check(matrix)
if self.rows() != matrix.rows() or self.cols() != matrix.cols():
print("!!! Exception: Wrong size matrix passed to subtract!")
a_tuple = self.csr2tuple()
b_tuple = matrix.csr2tuple()
result = []
for i in range(0, self.rows()):
for j in range(0, self.cols()):
a = [x for x in a_tuple if x[0] == i and x[1] == j]
b = [x for x in b_tuple if x[0] == i and x[1] == j]
if a and b:
a = a[0]
b = b[0]
result.append((i, j, a[2] - b[2]))
a_tuple.remove(a)
b_tuple.remove(b)
for a in a_tuple:
result.append((a[0], a[1], a[2]))
for b in b_tuple:
result.append((b[0], b[1], -b[2]))
result = sorted(result)
r, c, v = Matrix.tuple2csr(result)
if to_self:
self.r, self.c, self.v = r, c, v
result = self
else:
result = Matrix().set(r, c, v)
return result
def sub(self, matrix):
"""
Alias of function
:param matrix:
:return:
"""
return self.subtract(matrix)
def multiply(self, matrix, to_self=False):
"""
Multiply
:param matrix:
:param to_self: [Boolean] if this operation should return a new object
:return: [Matrix] - self object
"""
matrix = self._type_check(matrix)
if self.cols() != matrix.rows():
print("!!! Exception: Wrong size matrix passed to multiply! "
"Should be MxN * NxR")
a_tuple = self.csr2tuple()
b_tuple = matrix.csr2tuple()
result = []
a_rows = {}
b_cols = {}
for i in range(0, self.rows()):
a_rows[i] = {}
for a in a_tuple:
if a[0] == i:
a_rows[i][a[1]] = a[2]
for i in range(0, matrix.rows()):
b_cols[i] = {}
for b in b_tuple:
if b[1] == i:
b_cols[i][b[0]] = b[2]
for row in a_rows:
for col in b_cols:
sum = 0
for i in range(0, max(self.rows(), matrix.rows())):
if i in a_rows[row] and i in b_cols[col]:
a = a_rows[row][i]
b = b_cols[col][i]
sum += a * b
for item in result:
if item[0] == row and item[1] == col:
result.remove(item)
result.append((row, col, sum))
result = sorted(result)
r, c, v = Matrix.tuple2csr(result)
if to_self:
self.r, self.c, self.v = r, c, v
result = self
else:
result = Matrix().set(r, c, v)
return result
def mul(self, matrix):
"""
Alias of function
:param matrix:
:return: [Matrix] - self object
"""
return self.multiply(matrix)
def divide(self, matrix):
"""
Divide
:param matrix:
:return: [Matrix] - self object
"""
print("!!! Exception: Not implemented")
return self
def div(self, matrix):
"""
Alias of function
:param matrix:
:return:
"""
return self.divide(matrix)