-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTomMatrix.py
1950 lines (1788 loc) · 80.4 KB
/
TomMatrix.py
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################
##~~Written by Tom Blanchet~~##
#~~~~~Written 2012-2014~~~~~~#
###############################
#import itertools
#import Tkinter
import math
import sys
import random
import time
import mpmath
from TomMatrixEditor import MatrixEditor
#import copy
MULTIPLIERTHRESHHOLD = 350000 ##Yes, actually...
def timer(func, *args, **keywords):
start = time.clock()
retVal = func(*args, **keywords)
stop = time.clock()
return retVal, stop-start
class EigenError(StandardError):
pass
class MatrixError(StandardError):
pass
class matrix:
##Notes:
## Need to Do:
## Tune the mulitplier threshhold
## Efficient algorithms for sparse Matricies
## Make algorithms work with keyvalues
## "exact" Eigenvalues (When possible)
## Make QRDecomposition more efficient
## Make Schur more efficient
"""This is a matrix class that deals with operations and manipulations of
real matrices.
A few ways to make a matrix:
matrix(<number>, rows, cols) makes a diagonal matrix with the number along the diagonal.
E.G.
>>> print matrix(2.5, 3, 5)
[2.5, 0.0, 0.0, 0.0, 0.0]
[0.0, 2.5, 0.0, 0.0, 0.0]
[0.0, 0.0, 2.5, 0.0, 0.0]
matrix(<list>, rows, cols) fills a matrix with the elements from the list.
The list length must be < rows*cols, and will fill by row, then column
E.G.
>>> print matrix([1, 2, 3], 2, 2)
[1, 2]
[3, 0]
>>> matrix([1, 2, 3, 4, 5], 2, 2)
Traceback (most recent call last):
File "<pyshell#189>", line 1, in <module>
matrix([1, 2, 3, 4, 5], 2, 2)
File "C:/Python27/TomMatrix.py", line 67, in __init__
raise BufferError("data must be able to fit in the matrix")
BufferError: data must be able to fit in the matrix
matrix(<dict>, rows, cols) fills the matrix based on keys from a dictionary.
The keys of the dictionary MUST be 2-tuples to denote rows and columns.
The keys may contain strs, ints, or longs. To view str rows or columns,
use matrix.KeyPrint(). If Rows and Cols = 0, this matrix will only
contain the keys that are given in the dictionary. Note that the size
of the matrix does NOT inclue key valued entries.
(Currently, this feature is not fully supported)
matrix(None, rows, cols) is the same as matrix(0, rows, cols)
By default, matrix() makes a 2x2 matrix with all zero entries.
For an instanciated matrix m:
Get or set an entry: m[row, col] or m[index]
Get a submatrix: m[rowStart, colStart: rowStop, colStop]
Get a row: m.getRow(row)
Pop a row: m.popRow(row)
Add a row: m.addRow(row)
Get a column: m.getCol(col)
Pop a column: m.popCol(col)
Add a column: m.addCol(col)
Make a copy of m: m.Copy()
Transpose m: m.transpose() or m.t()
Make a copy of the ranspose of m: m.tCopy() or m.tC()
To Print: m.Print() or print m (the latter for a unicode free print)
m.KeyPrint() prints the matrix and key valued entries.
For 2 matricies m and n:
m+n is the sum of m and n
m*n is the matrix product of m and n
If m is a square matrix (check with m.isSquare()):
m.inv() = m**-1 calculates the inverse of m
n/m = n*(m.inv())
m**k = m*m*m*...*m k times. (k must be an integer)
m.det() is the determinant of m
See below for other operations the matrix can do.
"""
def __init__(self, data=None, rows=2, cols=2, makeMpf = False):
self._numRows = rows
self._numCols = cols
self._printer = printer()
self._keyPrinter = keyValuedPrinter()
self._data = dict()
self.isMpf = False
## if data == None:
## data = 0
## self._data = [0]*rows*cols
if any([type(data)==i for i in [int, float, long, complex, mpmath.mpf]]):
for i in range(min(rows, cols)):
self._data[i, i] = data
## self._data = [data*(i==j) for i in range(rows) for j in range(cols)]
elif type(data) == dict:
self._data = data
self._checkKeys()
elif type(data) == list:
if len(data)>rows*cols:
raise BufferError("data must be able to fit in the matrix")
for i in xrange(len(data)):
if all([not isinstance(data[i], t) for t in [int, float, long, complex, mpmath.mpf]]):
raise TypeError("Entries must be an int, float, long, complex, or mpmath.mpf.")
self._data[i//self._numCols, i%self._numCols] = data[i]
self._printer(self, doPrint = False)
self._keyPrinter(self, doPrint=False)
if makeMpf:
self.makeMpf()
def _checkKeys(self):
for key in self._data.iterkeys():
if type(key)!=tuple and len(key)!=2:
raise MatrixError("Keys must be 2 tuples.")
elif not any(type(key[0])==i for i in (int, long, str)):
raise MatrixError("Keys must only contain ints, longs, or strings.")
elif not any(type(key[1])==i for i in (int, long, str)):
raise MatrixError("Keys must only contain ints, longs, or strings.")
def Print(self):
try:
self._printer()
except UnicodeEncodeError:
return self._printer.getPrintStr()
def KeyPrint(self):
self._keyPrinter()
def __len__(self):
return len(self._data)
def copy(self):
return matrix(self._data.copy(), self.dims()[0], self.dims()[1])
def getNumCols(self):
return self._numCols
def getNumRows(self):
return self._numRows
def __eq__(self, other):
if isinstance(other, matrix):
return all([self._data == other._data,
self._numRows == other._numRows, self._numCols == self._numCols])
else: return False
def __ne__(self, other):
return not self == other
def dims(self):
return self._numRows, self._numCols
def __getitem__(self, key):
if type(key) == int:
try:
return self._data[key//self._numRows, key%self._numRows]
except KeyError:
if key//self._numRows<self._numCols:
return float(0)
else:
raise IndexError("Index out of range")
if type(key) == tuple:
if len(key) == 2:
##Currently, slices do not parse correctly.
##This code corrects that.
if type(key[0]) == slice:
j = (key[0].stop, key[1])##hacky hacky hacky
NewMat = matrix(rows = j[0], cols=j[1])
for row in range(j[0]):
for col in range(j[1]):
NewMat[row, col] = self[row, col]
return NewMat ###Return
elif type(key[1]) == slice and key[1].stop == None:
i = (key[0], key[1].start)##hacky hacky hacky
nrows = self._numRows-i[0]
ncols = self._numCols-i[1]
NewMat = matrix(0, nrows, ncols)
for row in range(nrows):
for col in range(ncols):
NewMat[row, col] = self[i[0]+row, i[1]+col]
return NewMat ###Return
elif self._data.has_key(key):
return self._data[key]
elif (key[0]<self._numRows)&(key[1]<self._numCols)&(key[0]>=0)&(key[1]>=0):
return 0
elif type(key[0])==str or type(key[1])==str:
return 0
else:
raise IndexError("Index out of Range")
if type(key) == slice:
return self[key.start[0], key.start[1]:key.stop[0], key.stop[1]]
if (len(key) == 3) and (type(key[1]) == slice):
i = (key[0], key[1].start)##hacky hacky hacky
j = (key[1].stop, key[2])
if type(i) == tuple:
if type(j) == tuple:
nrows = j[0]-i[0]
ncols = j[1]-i[1]
NewMat = matrix(0, nrows, ncols)
for row in range(nrows):
for col in range(ncols):
NewMat[row, col] = self[i[0]+row, i[1]+col]
return NewMat ###Return
raise TypeError("Key must be in a proper form.")
def __setitem__(self, key, value):
if self.isMpf:
value = mpmath.mpf(value)
## if type(value) != self._mtype:
## raise TypeError("must be the same type as the matrix")
if type(key) == int:
self._data[key//self._numRows, key%self._numRows] = value
return
if type(key) == tuple:
if len(key) == 2:
if (key[0]<self._numRows)&(key[1]<self._numCols)&(key[0]>=0)&(key[1]>=0):
## self._data[self._numCols*key[0] + key[1]] = value
self._data[key[0],key[1]] = value
return
elif type(key[0]) == str and any(type(key[1])==i for i in (str, int, long)):
self._data[key[0], key[1]] = value
return
elif (type(key[1]) == str) and any(type(key[0])==i for i in (str, int, long)):
self._data[key[0], key[1]] = value
return
else:
raise IndexError("list index out of range")
raise TypeError("must be an int or two ints separated by a comma")
def makeMpf(self):
for k in self._data.iterkeys():
self._data[k] = mpmath.mpf(self._data[k])
self.isMpf = True
## def makeFloat(self):
## for k in self._data.iterkeys():
## self._data[k] = float(self._data[k])
## self.isMpf = False
def addCol(self, position, data=None):
"""Adds a new column to the matrix"""
self.t()
self.addRow(position, data)
self.t()
def addRow(self, position, data=None):
"""Adds a new row to the matrix"""
if position<0:
position += self._numRows+1
if data!=None:
if len(data)>self._numCols:
raise BufferError("The data must fit in the matrix")
self._numRows+=1
for col in xrange(self._numCols):
for row in xrange(self._numRows, position-1, -1):
if self._data.has_key((row, col)):
self._data[row+1, col] = self._data.pop((row, col))
if data == None:
return
else:
for i in xrange(len(data)):
self._data[position, i]=data[i]
## if position<0:
## position+=self._numRows+1
## if data == None:
## data = [0]*self._numCols
## if len(data)!=self._numCols:
## raise BufferError("The data must fit in the matrix")
## if position>self._numRows or position<0:
## raise IndexError("Position is out of range")
## dataPos = self._numCols*position
## listA = []
## listB = []
## for i in range(len(self._data)):
## if i<dataPos:
## listA.append(self._data[i])
## else:
## listB.append(self._data[i])
## self._data = listA+data+listB
## self._numRows+=1
def popCol(self, position):
"""Returns and removes the column at the position."""
self.t()
ret = self.popRow(position)
self.t()
return ret
def popRow(self, position):
"""Returns and removes the row at the position."""
if position<0:
position+=self._numRows
if position<0 or position>=self._numRows:
raise IndexError("position out of Range")
ret = []
for col in xrange(self._numCols):
if self._data.has_key((position, col)):
ret.append(self._data.pop((position, col)))
else:
ret.append(0)
for row in xrange(position+1, self._numRows):
if self._data.has_key((row, col)):
self[row-1, col] = self._data.pop((row, col))
self._numRows-=1
return ret
## if position>self._numRows or position<0:
## raise IndexError("Position is out of range")
## dataPos = self._numCols*position
## listA = []
## listB = []
## ret = []
## for i in range(len(self._data)):
## if i<dataPos:
## listA.append(self._data[i])
## elif i>=dataPos+self._numCols:
## listB.append(self._data[i])
## else:
## ret.append(self._data[i])
## self._data = listA+listB
## self._numRows-=1
## return ret
def swapCol(self, pos1, pos2):
"""Swaps the columns at pos1 and pos2."""
self.t()
self.swapRow(pos1, pos2)
self.t()
def swapRow(self, pos1, pos2):
if pos1<0:
pos1+= self._numRows
if pos2<0:
pos2+= self._numRows
if pos1>self._numRows or pos1<0:
raise IndexError("Pos1 is out of range")
if pos2>self._numRows or pos2<0:
raise IndexError("Pos2 is out of range")
row1 = self.getRow(pos1)
row2 = self.getRow(pos2)
for k in range(self._numCols):
self[pos2, k] = row1[k]
self[pos1, k] = row2[k]
def __str__(self):
ret = ""
return ret.join(str(self.getRow(i))+"\n" for i in range(self._numRows))[:-1]
def __call__(self):
return dict(data=self._data, rows=self._numRows, cols=self._numCols, asStr=self.__str__())
def dotProduct(self, other):
"""Takes the Dot Product
This function treats each matrix like a vector."""
if not isinstance(other, matrix):
raise NotImplemented
if (self._numRows != other._numRows)|(self._numCols != other._numCols):
raise MatrixError("must be the same size of matrix")
return sum(self[i]*other[i] for i in range(len(self)))
def iterkeys(self):
return self._data.iterkeys()
def getKeysInRows(self):
ret = dict()
for key in self.iterkeys():
if ret.has_key(key[0]):
ret[key[0]].append(key)
else:
ret[key[0]]=[key]
return ret
def getKeysInCols(self):
ret = dict()
for key in self.iterkeys():
if ret.has_key(key[1]):
ret[key[1]].append(key)
else:
ret[key[1]]=[key]
return ret
def getKeysInRowsAndCols(self):
retRows = dict()
retCols = dict()
for key in self.iterkeys():
if retRows.has_key(key[0]):
retRows[key[0]].append(key)
else:
retRows[key[0]]=[key]
if retCols.has_key(key[1]):
retCols[key[1]].append(key)
else:
retCols[key[1]]=[key]
return retRows, retCols
def has_key(self):
return self._data.has_key
def __add__(self, other):
if not isinstance(other, matrix):
raise NotImplemented
if (self._numRows != other._numRows)|(self._numCols != other._numCols):
raise MatrixError("must be the same size of matrix")
## ret = matrix(rows=max(self._numRows, other._numRows),\
## cols=max(self._numCols, other._numCols))
## for j in range(ret._numCols):
## for i in range(ret._numRows):
## ret[i, j] += self[i, j]
## ret[i, j] += other[i, j]
else:
ret = self.copy()
for key in other._data.iterkeys():
ret[key] += other[key]
return ret
def __sub__(self, other):
if not isinstance(other, matrix):
raise NotImplemented
if (self._numRows != other._numRows)|(self._numCols != other._numCols):
raise MatrixError("must be the same size of matrix")
## ret = matrix(rows=max(self._numRows, other._numRows),\
## cols=max(self._numCols, other._numCols))
## for j in range(ret._numCols):
## for i in range(ret._numRows):
## ret[i, j] += self[i, j]
## ret[i, j] -= other[i, j]
else:
ret = self.copy()
for key in other._data.iterkeys():
ret[key] -= other[key]
return ret
def transpose(self):
"""Transposes the matrix."""
newRows = self._numCols
newCols = self._numRows
new_data = dict()
for key in self._data.iterkeys():
new_data[key[1], key[0]]= self._data[key]
self._numRows = newRows
self._numCols = newCols
self._data = new_data
def tCopy(self):
"""Returns the Transpose of the Matrix"""
ret = self.copy()
ret.t()
return ret
t = transpose ##alias
tC = tCopy
def isSquare(self):
return self._numRows == self._numCols
def makeSquare(self):
dif = self._numRows-self._numCols
if dif>0:
for i in range(dif):
self.addCol(-1)
elif dif<0:
for i in range(-dif):
self.addRow(-1)
def getRow(self, rowNum):
return [self[rowNum, i] for i in range(self._numCols)]
def getCol(self, colNum):
return [self[i, colNum] for i in range(self._numRows)]
def oldMul(self, other):
if any([type(other)==i for i in [int, float, long, complex]]):
return matrix([j*other for j in self._data], self._numRows, self._numCols)
if not isinstance(other, matrix):
raise NotImplemented
if self._numCols != other._numRows:
raise MatrixError(
"in m*n, the number of rows of n must match the number of columns of m")
new_matrix = matrix(rows = self._numRows, cols = other._numCols)
for i in xrange(new_matrix._numRows):
for j in xrange(new_matrix._numCols):
new_matrix[i, j] = sum(self[i, k]*other[k, j] for k in\
xrange(min(self._numCols, other._numRows)))
return new_matrix
def __mul__(self, other):
if any([type(other)==i for i in [int, float, long, complex, mpmath.mpf]]):
return matrix([j*other for j in self], self._numRows, self._numCols)
if not isinstance(other, matrix):
raise NotImplemented
if self._numCols != other._numRows:
raise MatrixError(
"in m*n, the number of rows of n must match the number of columns of m")
mindim = min(self._numRows, self._numCols, other._numRows, other._numCols)
if mindim*(mpmath.mp.prec**self.isMpf)<=MULTIPLIERTHRESHHOLD or mindim<=1:
new_matrix = matrix(rows = self._numRows, cols = other._numCols)
## for j in xrange(new_matrix._numCols):
## for i in xrange(new_matrix._numRows):
## new_matrix[i, j] = fastDot([(self[i, k],other[k, j]) for k in\
## xrange(self._numCols)])
SRows, SCols = self.getKeysInRowsAndCols()
ORows, OCols = other.getKeysInRowsAndCols()
SColsAndORows = SCols.viewkeys()&ORows.viewkeys()
if len(SColsAndORows)!=0:
if self.isMpf and other.isMpf:
for SRow in SRows.iterkeys():
for OCol in OCols.iterkeys():
new_matrix[SRow, OCol] = mpmath.fdot((self[SRow, k], other[k, OCol]) for k in SColsAndORows)
else:
for SRow in SRows.iterkeys():
for OCol in OCols.iterkeys():
new_matrix[SRow, OCol] = fastDot((self[SRow, k], other[k, OCol]) for k in SColsAndORows)
## if iterORows.has_key(keyS[1]):
## for keyO in iterORows[keyS[1]]:
## if toDotDict.has_key((keyS[0], keyO[1])):
## toDotDict[keyS[0], keyO[1]].append((self[keyS],other[keyO]))
## else:
## toDotDict[keyS[0], keyO[1]] = [(self[keyS],other[keyO])]
## if self.isMpf and other.isMpf:
## for key in toDotDict.iterkeys():
## new_matrix[key] = mpmath.fdot(toDotDict[key])
## else:
## for key in toDotDict.iterkeys():
## new_matrix[key] = fastDot(toDotDict[key])
return new_matrix
else: #Strassen
selfC = self.copy()
otherC = other.copy()
selfC.makeSquare()
otherC.makeSquare()
dif = otherC.getNumRows()-selfC.getNumRows()
if dif>0:
for i in range(dif):
selfC.addRow(-1)
selfC.addCol(-1)
elif dif<0:
for i in range(-dif):
otherC.addRow(-1)
otherC.addCol(-1)
if self.getNumRows()%2==1:
selfC.addRow(-1)
selfC.addCol(-1)
otherC.addRow(-1)
otherC.addCol(-1)
A_segs = (selfC._numRows//2, selfC._numCols//2)
B_segs = (otherC._numRows//2, otherC._numCols//2)
A = [[selfC[:A_segs[0], A_segs[1]],selfC[0, A_segs[1]:A_segs[0],selfC._numRows] ],\
[selfC[A_segs[0], 0: selfC._numRows, A_segs[1]], selfC[A_segs[0], A_segs[1]:]]]
B = [[otherC[:B_segs[0], B_segs[1]],otherC[0, B_segs[1]:B_segs[0],otherC._numRows] ],\
[otherC[B_segs[0], 0: otherC._numRows, B_segs[1]], otherC[B_segs[0], B_segs[1]:]]]
M_1 = (A[0][0]+A[1][1])*(B[0][0]+B[1][1])
M_2 = (A[1][0]+A[1][1])*B[0][0]
M_3 = A[0][0]*(B[0][1]-B[1][1])
M_4 = A[1][1]*(B[1][0]-B[0][0])
M_5 = (A[0][0]+A[0][1])*B[1][1]
M_6 = (A[1][0]-A[0][0])*(B[0][0]+B[0][1])
M_7 = (A[0][1]-A[1][1])*(B[1][0]+B[1][1])
blockMat = [[M_1+M_4-M_5+M_7, M_3+M_5],\
[M_2+M_4 , M_1-M_2+M_3+M_6]]
new_matrix = matrix(None, self._numRows, other._numCols)
for i in range(new_matrix._numRows):
for j in range(new_matrix._numCols):
isRow0 = i<blockMat[0][0]._numRows
isCol0 = j<blockMat[0][0]._numCols
new_matrix[i, j] =\
blockMat[not isRow0][not isCol0]\
[i-((not isRow0)*blockMat[0][0]._numRows),\
j-((not isCol0)*blockMat[0][0]._numCols)]
return new_matrix
def __rmul__(self, other):
if any([type(other)==i for i in [int, float, long, complex]]):
return self*other
else:
raise NotImplemented
def HadamardProd(self, other):
"""Returns the Hadamard Product of the matrices"""
if not isinstance(other, matrix):
raise NotImplemented
if self.dims()!=other.dims():
raise MatrixError(
"Matrices must be the same size.")
new_matrix = matrix(None, self._numRows, self._numCols)
for i in range(new_matrix._numRows):
for j in range(new_matrix._numCols):
new_matrix[i, j] = self[i, j]*other[i, j]
return new_matrix
def KroneckerProd(self, other):
"""Returns the Kronecker Product of the matrices"""
rows = self._numRows * other._numRows
cols = self._numCols * other._numCols
outMat = matrix(rows=rows, cols=cols)
for j in range(cols):
for i in range(rows):
outMat[i, j] = self[i/other._numRows, j/other._numCols]*other[i%other._numRows,j%other._numCols]
return outMat
def __div__(self, other):
if isinstance(other, matrix):
return self*other.inv()
elif any([type(other)==i for i in [int, float, long, complex]]):
return matrix([j/other for j in self._data], self._numRows, self._numCols)
else:
raise NotImplemented
def __rdiv__(self, other):
if any([type(other)==i for i in [int, float, long, complex]]):
return other*self.inv()
else:
raise NotImplemented
def __mod__(self, other):
if not ((type(other)==int) or (type(other)==long)):
raise NotImplemented
else:
i = 0
stopCon = len(self._data)
while(i<stopCon):
self._data[i] %= other
i += 1
def __pow__(self, other):
if not self.isSquare():
raise MatrixError(
"must be a square matrix")
k = bin(abs(other))
n = self
ptr = 1
ret = matrix(rows=self._numRows, cols=self._numCols)##Will make the unit matrix
for i in range(self._numRows):
for j in range(self._numCols):
if i==j:
ret[i,j] = 1
while(k[-ptr] != 'b'):
if(n == 1):
return ret #exit
if(k[-ptr] == '1'):
ret = (ret*n)
n = (n*n)
ptr = ptr + 1
if other<0:
return ret.inv()
else:
return ret
def inv(self):
"""Calculates the inverse of the matrix."""
###This is a somewhat novel algortihm.
###It is based on Back Substitution.
if not self.isSquare():
raise MatrixError("The matix must be square to find the inverse.")
Q, R, sign = self.QRDecomposition()
invR = matrix(0, self._numCols, self._numRows)
rowindex = range(self._numRows)
rowindex.reverse()
colindex = range(self._numCols)
colindex.reverse()
for k in colindex: ##for each column
for j in rowindex: #for each row
if j<=k:
if R[j, j] == 0:
raise MatrixError("The matrix is not invertable.")
invR[j, k] = ((j==k)-sum(R[j, i]*invR[i, k] for i in range(j+1, self._numRows)))/float(R[j,j])
return invR*Q.tC()
## def LUPDecomp(self):
## """Returns the LUP Decomposition of the matrix.
##
## A fourth value is returned as well, this is 1
## if there were an even number of row exchanges in P,
## and -1 if not."""
def Img(self, threshhold = 0.1**5):
"""Returns the image of the matrix
The threshhold is for determining at what point a
vector is a zero vector, to account for floating
point errors. A good estimate of the threshhold makes
for faster calculation."""
##This uses RRQR to determine an orthonomal basis for the image
CurA = self.copy()
stayFlag = True
Q = matrix(1, self._numRows, self._numRows)
## qList = []
count = 0
## reduced = False
for j in range(min(self._numCols, self._numRows)):
stayFlag = True
skipFlag = False
while(stayFlag):
if count == CurA._numCols:
Q.t()
retList = []
for i in range(Q._numCols - CurA._numRows):
retList.append(Q.popCol(0))
return retList ###Exit
stayFlag=False
alpha = (sum(CurA[i, 0]**2 for i in range(CurA._numRows))**.5)
u = vector([0]*j+[CurA[i, 0]+(i==0)*alpha for i in range(CurA._numRows)])
magU = sum(uIn**2 for uIn in u)**.5
if magU<=threshhold:
skipFlag = True
if skipFlag == False:
Q.HouseholderRef(u)
CurA.HouseholderRef(u[j:])
skipFlag = False
## v = u/magU
## q = matrix(1, self._numCols, self._numCols)-v.outerProduct(v*2)
## qList.append(q)
## qCut = matrix([q[row, col] for col in range(j, q._numRows) for row in range(j, q._numRows)],
## CurA._numRows, CurA._numRows)
## CurA = qCut*CurA
if abs(CurA[0,0]) < threshhold:
if CurA._numCols == 1:
count += 1
stayFlag = True
continue
PushCol = CurA.popCol(0)
CurA.addCol(-1, PushCol)
count += 1
stayFlag = True
if j < min(self._numCols, self._numRows)-1:
CurA = matrix([CurA[j, i] for j in range(1, CurA._numRows) for i in range(1, CurA._numCols)],
CurA._numRows-1, CurA._numCols-1)
Q.t()
ret = [Q.popCol(0) for i in range(Q._numCols)]
if abs(CurA[0,0]) < threshhold:
ret = ret[:-1]
return ret
## AList = [vector(self.getCol(i)) for i in range(self._numCols)]
## UList = [AList[0]]
## EList = []
## ##If the varience of the entries are above the threshhold,
## ##then we concider the vector to be "non-zero" (varience
## ##assuming the expected value of the vector is 0)
## if (UList[0].norm()/float(self._numRows))**.5>threshhold:
## EList = [AList[0]/AList[0].norm()]
## for a in AList[1:]:
## UList.append(a - sum(e.proj(a) for e in EList))
## if (UList[-1].norm()/float(self._numRows))**.5>threshhold:
## EList.append(UList[-1]/(UList[-1]).norm())
## else:
## UList = UList[:-1]
## return [list(k) for k in EList]
def Ker(self, threshhold = 0.1**5):
"""Returns the kernel of the matrix.
The threshhold is for determining at what point a
vector is a zero vector, to account for floating
point errors. A good estimate of the threshhold makes
for faster calculation."""
##This uses RRQR to determine an orthonomal basis for the kernel
CurA = self.copy()
CurA.t()
stayFlag = True
Q = matrix(1, self._numCols, self._numCols)
if self.isMpf:
Q.makeMpf()
CurA.makeMpf()
## qList = []
count = 0
## reduced = False
for j in range(min(self._numCols, self._numRows)):
stayFlag = True
skipFlag = False
while(stayFlag):
if count == CurA._numCols:
Q.t()
retList = []
for i in range(CurA._numRows):
retList.append(Q.popCol(-1))
return retList ###Exit
stayFlag=False
alpha = (sum(CurA[i, 0]**2 for i in range(CurA._numRows))**.5)
u = vector([0]*j+[CurA[i, 0]+(i==0)*alpha for i in range(CurA._numRows)])
magU = sum(uIn**2 for uIn in u)**.5
if magU<=threshhold:
skipFlag = True
if skipFlag == False:
Q.HouseholderRef(u)
CurA.HouseholderRef(u[j:])
skipFlag = False
## v = u/magU
## q = matrix(1, self._numCols, self._numCols)-v.outerProduct(v*2)
## qList.append(q)
## qCut = matrix([q[row, col] for col in range(j, q._numRows) for row in range(j, q._numRows)],
## CurA._numRows, CurA._numRows)
## CurA = qCut*CurA
if abs(CurA[0,0]) < threshhold:
if CurA._numCols == 1:
count += 1
stayFlag = True
continue
PushCol = CurA.popCol(0)
CurA.addCol(-1, PushCol)
count += 1
stayFlag = True
if j < min(self._numCols, self._numRows)-1:
CurA = matrix([CurA[j, i] for j in range(1, CurA._numRows) for i in range(1, CurA._numCols)],
CurA._numRows-1, CurA._numCols-1)
Q.t()
retList = []
if abs(CurA[0,0]) < threshhold:
retList.append(Q.popCol(-1))
for i in range(CurA._numRows-1):
retList.append(Q.popCol(-1))
return retList ###Exit
## ###this approximates, designed for non-rational form matricies.
## ###Finding an orthonormal basis that spans the rows of the matrix.
## ###Using the Gram-Schmidt process
## AList = [vector(self.getRow(i)) for i in range(self._numRows)]
## UList = [AList[0]]
## EList = []
## ##If the varience of the entries are above the threshhold,
## ##then we concider the vector to be "non-zero" (varience
## ##assuming the expected value of the vector is 0)
## if (UList[0].norm()/float(self._numCols))**.5>threshhold:
## EList = [AList[0]/AList[0].norm()]
## for a in AList[1:]:
## UList.append(a - sum(e.proj(a) for e in EList))
## if (UList[-1].norm()/float(self._numCols))**.5>threshhold:
## EList.append(UList[-1]/(UList[-1]).norm())
## else:
## UList = UList[:-1]
## IdMatrix = matrix(1000, self._numCols, self._numCols)
## IList = [vector(IdMatrix.getCol(i)) for i in range(self._numCols)]
## ##AList contains the space that is orthogonal to the rows of the matrix
## AList = [i - sum(e.proj(i) for e in EList) for i in IList]
## UList = [AList[0]]
## EList = []
## if (UList[0].norm()/float(self._numCols))**.5>threshhold:
## EList = [AList[0]/AList[0].norm()]
## for a in AList[1:]:
## UList.append(a - sum(e.proj(a) for e in EList))
## if (UList[-1].norm()/float(self._numCols))**.5>threshhold:
## EList.append(UList[-1]/(UList[-1]).norm())
## else:
## UList = UList[:-1]
#### rmVal = []
#### for ai in range(len(AList)):
#### if AList[ai].norm()>threshhold:
#### AList[ai] = AList[ai]/AList[ai].norm()
#### else:
#### rmVal.append(AList[ai])
#### for val in rmVal:
#### AList.remove(val)
#
# return [list(k) for k in EList]
def trace(self):
"""Returns the trace of the matrix."""
return sum(self[i, i] for i in range(min(self._numRows, self._numCols)))
def det(self):
"""Finds the determinant."""
if not self.isSquare():
raise MatrixError("The matix must be square to find the determinant.")
if self._numRows == 1:
return self[0,0]
QRdecomp = self.QRDecomposition()
return QRdecomp[2]*product(*[QRdecomp[1][i,i] for i in range(self._numRows)])
def rank(self, threshhold = .1**5):
"""Finds the rank of the matrix."""
CurA = self.copy()
stayFlag = True
count = 0
for j in range(min(self._numCols, self._numRows)):
stayFlag = True
skipFlag = False
while(stayFlag):
if count == CurA._numCols:
return j ####Here is the exit for small ranks!
stayFlag=False
alpha = (sum(CurA[i, 0]**2 for i in range(CurA._numRows))**.5)
u = vector([0]*j+[CurA[i, 0]+(i==0)*alpha for i in range(CurA._numRows)])
magU = sum(uIn**2 for uIn in u)**.5
if magU<=threshhold:
skipFlag = True
if skipFlag == False:
CurA.HouseholderRef(u[j:])
skipFlag = True
## v = u/magU
## q = matrix(1, self._numRows, self._numRows)-v.outerProduct(v*2)
## qCut = matrix([q[row, col] for col in range(j, q._numRows) for row in range(j, q._numRows)],
## CurA._numRows, CurA._numRows)
## CurA = qCut*CurA
if abs(CurA[0,0]) < threshhold:
if CurA._numCols == 1:
stayFlag = True
count += 1
continue
PushCol = CurA.popCol(0)
CurA.addCol(-1, PushCol)
count += 1
stayFlag = True
if j < min(self._numCols, self._numRows)-1:
CurA = matrix([CurA[j, i] for j in range(1, CurA._numRows) for i in range(1, CurA._numCols)],
CurA._numRows-1, CurA._numCols-1)
if abs(CurA[0,0]) < threshhold:
return min(self._numCols, self._numRows)-1
return min(self._numCols, self._numRows)
def nullity(self):
"""Returns the nullity of the matrix"""
return self._numCols - self.rank()
def REF(self, threshhold = .1**5):
"""Returns a row echelon form of the matrix"""
selfC = self.copy()
pivotRow = 0
pivotCol = 0
while(pivotRow<self._numRows and pivotCol<self._numCols):
if abs(selfC[pivotRow,pivotCol])<threshhold:
##can I swap?
swapped = False
for row in range(pivotRow+1, min(self._numCols, self._numRows)):
if selfC[row, pivotCol]>=threshhold:
selfC.swapRow(pivotRow, row)
swapped=True
break
##If I can't, move to the next column
if not swapped:
pivotCol += 1
if pivotCol>=self._numRows:
break
for col in range(pivotCol+1, self._numCols):
selfC[pivotRow, col] = selfC[pivotRow, col]/float(selfC[pivotRow, pivotCol])
selfC[pivotRow, pivotCol] = 1.0
for row in range(pivotRow+1, self._numRows):
for col in range(pivotCol+1, self._numCols):
selfC[row, col] = selfC[row, col]-(selfC[pivotRow, col]*selfC[row, pivotCol])
selfC[row, pivotCol] = 0.0
pivotRow+=1
pivotCol+=1
return selfC
def RREF(self, threshhold = .1**5):
"""Returns the reduced row echelon form of the matrix."""
mat = self.REF(threshhold)
pivotRow = 0
pivotCol = 0
while(pivotRow<mat._numRows and pivotCol<mat._numCols):
while(mat[pivotRow, pivotCol] != 1.0):
pivotCol += 1
if pivotCol>=mat._numCols:
return mat ##Exit
for row in range(pivotRow):
for col in range(pivotCol+1, mat._numCols):
mat[row, col] = mat[row, col] - mat[pivotRow, col]*mat[row, pivotCol]
mat[row, pivotCol] = 0.0
pivotRow += 1
return mat
def Eigen(self, itr = 100, confidence= 0.1**10, threshhold = 0.1**10, kerThreshhold = 0.1**10):
"""Finds the eigendecomposition (eigenvalues, eigenvectors) of the matrix.
iterMax is the max iterations of the Schur decomposition algorithm, while the confidence is
the confidence of zeros below the diagonal of the Schur form of the matrix.
The threshhold is the threshhold for determining at what point two eigenvectors/eigenvalues