def simplex_step(A, b, c, R_square, show_bases=False): if show_bases: print("basis: ", R_square) R = A.D[0] # Extract the subsystem A_square = Mat((R_square, A.D[1]), {(r,c):A[r,c] for r,c in A.f if r in R_square}) b_square = Vec(R_square, {k:b[k] for k in R_square}) # Compute the current vertex x = solve(A_square, b_square) print("(value: ",c*x,") ",end="") # Compute a possibly feasible dual solution y_square = solve(A_square.transpose(), c) #compute entries with labels in R_square y = Vec(R, y_square.f) #Put in zero for the other entries if min(y.values()) >= -1e-10: return ('OPTIMUM', x) #found optimum! R_leave = {i for i in R if y[i]< -1e-10} #labels at which y is negative r_leave = min(R_leave, key=hash) #choose first label at which y is negative # Compute the direction to move d = Vec(R_square, {r_leave:1}) w = solve(A_square, d) # Compute how far to move Aw = A*w # compute once because we use it many times R_enter = {r for r in R if Aw[r] < -1e-10} if len(R_enter)==0: return ('UNBOUNDED', None) Ax = A*x # compute once because we use it many times delta_dict = {r:(b[r] - Ax[r])/(Aw[r]) for r in R_enter} delta = min(delta_dict.values()) # Compute the new tight constraint r_enter = min({r for r in R_enter if delta_dict[r] == delta}, key=hash)[0] # Update the set representing the basis R_square.discard(r_leave) R_square.add(r_enter) return ('STEP', None)
def dot_prod_mat_mat_mult(A, B): assert A.D[1] == B.D[0] result = Mat((A.D[0], B.D[1]), {}) rows = mat2rowdict(A) cols = mat2coldict(B) for i, row in rows.items(): for j, col in cols.items(): result.f[(i, j)] = row * col return result
def problem7_1(): domain = ({'a','b','c'},{'A','B'}) A = Mat(domain,{('a','A'):8, ('a','B'):1,('b','A'):6, ('b','B'):2,('c','A'):0,('c','B'):6}) print(A) b = Vec(domain[0], {'a': 10, 'b': 8, 'c': 6}) print(b) x = QR_solve(A, b) print(x) print([x]) result = A.transpose()*(b-A*x) print(result.is_almost_zero()) print((b-A*x)*(b-A*x))
def problem8_2(): domain = ({'a','b'},{'A','B'}) A = Mat(domain,{('a','A'):3, ('a','B'):1,('b','A'):4, ('b','B'):1}) print(A) b = Vec(domain[0], {'a': 10, 'b': 13}) print(b) x = QR_solve(A, b) print(x) print([x]) result = A.transpose()*(b-A*x) print(result.is_almost_zero()) print((b-A*x)*(b-A*x))
def dot_prod_mat_mat_mult(A, B): assert A.D[1] == B.D[0] ret_mat = Mat((A.D[0], B.D[1]), {}) a_row = matutil.mat2rowdict(A) b_col = matutil.mat2coldict(B) for key, val in a_row.items(): for key2, val2 in b_col.items(): ret_mat.f[(key, key2)] = val * val2 return ret_mat
def problem6(): domain = ({'a','b','c'},{'A','B'}) A = Mat(domain,{('a','A'):-1, ('a','B'):2,('b','A'):5, ('b','B'):3,('c','A'):1,('c','B'):-2}) print(A) Q, R = QR_factor(A) print(Q) print(R) b = Vec(domain[0], {'a': 1, 'b': -1}) x = QR_solve(A, b) print(x) print([x]) result = A.transpose()*(b-A*x) print(result.is_almost_zero())
def identity(labels = {'x','y','u'}): ''' In case you have never seen this notation for a parameter before, the way it works is that identity() now defaults to having labels equal to {'x','y','u'}. So you should write your procedure as if it were defined 'def identity(labels):'. However, if you want the labels of your identity matrix to be {'x','y','u'}, you can just call identity(). Additionally, if you want {'r','g','b'}, or another set, to be the labels of your matrix, you can call identity({'r','g','b'}). ''' res = Mat((labels,labels), dict()) for k in list(labels): res.f[k,k] = 1 return res
def find_error_matrix(S): """ Input: a matrix S whose columns are error syndromes Output: a matrix whose cth column is the error corresponding to the cth column of S. Example: >>> S = listlist2mat([[0,one,one,one],[0,one,0,0],[0,0,0,one]]) >>> find_error_matrix(S) == Mat(({0, 1, 2, 3, 4, 5, 6}, {0, 1, 2, 3}), {(1, 3): 0, (3, 0): 0, (2, 1): 0, (6, 2): 0, (5, 1): one, (0, 3): 0, (4, 0): 0, (1, 2): 0, (3, 3): 0, (6, 3): 0, (5, 0): 0, (2, 2): 0, (4, 1): 0, (1, 1): 0, (3, 2): one, (0, 0): 0, (6, 0): 0, (2, 3): 0, (4, 2): 0, (1, 0): 0, (5, 3): 0, (0, 1): 0, (6, 1): 0, (3, 1): 0, (2, 0): 0, (4, 3): one, (5, 2): 0, (0, 2): 0}) True """ retMat = Mat((set(range(2**len(S.D[0])-1)),S.D[1]), {}) for x in S.D[1]: pos = 0 for y in S.D[0]: if S.f[y,x] == one: pos += (2 ** (len(S.D[0])-y-1) ) retMat.f[pos-1,x] = one return retMat
from hw7 import QR_solve from mat import coldict2mat from mat import Mat from orthonormalization import aug_orthonormalize from QR import factor from vec import Vec from vecutil import list2vec print('Augmented Orthonormalize') L = [list2vec(v) for v in [[4,3,1,2],[8,9,-5,-5],[10,1,-1,5]]] print(coldict2mat(L)) Qlist, Rlist = aug_orthonormalize(L) print(coldict2mat(Qlist)) print(coldict2mat(Rlist)) print((coldict2mat(Qlist)*coldict2mat(Rlist))) print('QR Solve') A=Mat(({'a','b','c'},{'A','B'}), {('a','A'):-1, ('a','B'):2, ('b','A'):5, ('b','B'):3,('c','A'):1, ('c','B'):-2}) print(A) Q, R = factor(A) print(Q) print(R) b = Vec({'a','b','c'}, {'a':1,'b':-1}) x = QR_solve(A,b) print(x) residual = A.transpose()*(b-A*x) print(residual)
def identity(D): m = Mat((D,D), {(d,d):1 for d in D}) return m.f
x2 = solve(B, b2) #residual r2 = b2 - B * x2 #Is it really a solution? Assign True if yes, False if no. is_good2 = (B * x2 == b2) ## 17: (Problem 4.17.21) Solving 2x2 linear systems and finding matrix inverse solving_systems_x1 = -1 / 5 solving_systems_x2 = 2 / 5 solving_systems_y1 = 4 / 5 solving_systems_y2 = -3 / 5 solving_systems_m = Mat(({0, 1}, {0, 1}), { (0, 0): -1 / 5, (0, 1): 4 / 5, (1, 0): 2 / 5, (1, 1): -3 / 5 }) solving_systems_a = Mat(({0, 1}, {0, 1}), { (0, 0): 3, (0, 1): 4, (1, 0): 2, (1, 1): 1 }) solving_systems_a_times_m = Mat(({0, 1}, {0, 1}), {(0, 0): 1, (1, 1): 1}) solving_systems_m_times_a = Mat(({0, 1}, {0, 1}), {(0, 0): 1, (1, 1): 1}) ## 18: (Problem 4.17.22) Matrix inverse criterion # Please write your solutions as booleans (True or False) are_inverses1 = True
Input: - A: an orthogonal Mat - B: an orthogonal Mat whose column labels are the row labels of A - a: the coordinate representation in terms of rows of A of some vector v Output: - the Vec b such that b is the coordinate representation of v in terms of columns of B Example: >>> A = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): 0, (1, 2): 0, (0, 0): 1, (2, 0): 0, (1, 0): 0, (2, 2): 1, (0, 2): 0, (2, 1): 0, (1, 1): 1}) >>> B = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): 0, (1, 2): 0, (0, 0): 2, (2, 0): 0, (1, 0): 0, (2, 2): 2, (0, 2): 0, (2, 1): 0, (1, 1): 2}) >>> a = Vec({0, 1, 2},{0: 4, 1: 1, 2: 3}) >>> orthogonal_change_of_basis(A, B, a) == Vec({0, 1, 2},{0: 8, 1: 2, 2: 6}) True ''' return a*A*B A = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): 0, (1, 2): 0, (0, 0): 1, (2, 0): 0, (1, 0): 0, (2, 2): 1, (0, 2): 0, (2, 1): 0, (1, 1): 1}) B = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): 0, (1, 2): 0, (0, 0): 2, (2, 0): 0, (1, 0): 0, (2, 2): 2, (0, 2): 0, (2, 1): 0, (1, 1): 2}) a = Vec({0, 1, 2},{0: 4, 1: 1, 2: 3}) ## Problem 5 def orthonormal_projection_orthogonal(W, b): ''' Input: - W: Mat whose rows are orthonormal - b: Vec whose labels are equal to W's column labels Output: - The projection of b orthogonal to W's row space. Example: >>> W = Mat(({0, 1}, {0, 1, 2}), {(0, 1): 0, (1, 2): 0, (0, 0): 1, (1, 0): 0, (0, 2): 0, (1, 1): 1}) >>> b = Vec({0, 1, 2},{0: 3, 1: 1, 2: 4})
def submatrix(M, rows, cols): return Mat((M.D[0]&rows, M.D[1]&cols), {(r,c):val for (r,c),val in M.f.items() if r in rows and c in cols})
# Quiz 4.1.2: Write a nested comprehension whose value is list-of-column-lists representation of # a 3 × 4 matrix whose i, j element is i − j print([[i-j for i in range(3)] for j in range(4)]) # Quiz 4.1.5: Give a Python expression whose value is the coldict representation of the matrix # of Example 4.1.3 (Page 187). D = {'a', 'b'} col_1 = Vec(D, {'a':1, 'b':10}) col_2 = Vec(D, {'a':2, 'b':20}) col_3 = Vec(D, {'a':3, 'b':30}) coldict = {'@':col_1, '#':col_2, '?':col_3} print(coldict) # Quiz 4.1.7: Write an expression for the {'a','b','c'}×{'a','b','c'} identity matrix represented # as an instance of Mat. m = Mat(({'a', 'b', 'c'}, {'a', 'b', 'c'}), {('a', 'a'):1, ('b', 'b'):1, ('c', 'c'):1}) print(m.f) def identity(D): m = Mat((D,D), {(d,d):1 for d in D}) return m.f print(identity({'a', 'b'})) # Quiz 4.1.9: Write a one-line procedure mat2rowdict(A) that, given an instance # of Mat, returns the rowdict representation of the same matrix. Use dictionary # comprehensions. # test def mat2rowdict(A): return {r:Vec(A.D[1],{c:A.f[r,c] for c in A.D[1]}) for r in A.D[0]}
# Part 1 vT_x_1 = [2, 1] Sigma_vT_x_1 = [4, 1] U_Sigma_vT_x_1 = [1, 4, 0] # Part 2 vT_x_2 = [0, 2] Sigma_vT_x_2 = [0, 2] U_Sigma_vT_x_2 = [2, 0, 0] ## 4: (Problem 11.8.4) The SVD of a small simple matrix # A.D = ({'r1','r2'},{'c1','c2'}) # Row and column labels of SA should be {0,1, ...} UA = Mat(({'r1', 'r2'}, {0, 1}), {('r1', 0): 1, ('r2', 1): -1}) SA = Mat(({0, 1}, {0, 1}), {(0, 0): 3, (1, 1): 1}) VA = Mat(({'c1', 'c2'}, {0, 1}), {('c1', 0): 1, ('c2', 1): 1}) # B.D = ({'r1','r2'},{'c1','c2'}) # Row- and column-labels of SB should be {0,1, ...} UB = Mat(({'r1', 'r2'}, {0, 1}), {('r1', 1): 1, ('r2', 0): 1}) SB = Mat(({0, 1}, {0, 1}), {(0, 0): 4, (1, 1): 3}) VB = Mat(({'c1', 'c2'}, {0, 1}), {('c1', 1): 1, ('c2', 0): 1}) # C.D = ({'r1','r2','r3'},{'c1','c2'}) # Row- and column-labels of SC should be {0,1, ...} UC = Mat(({'r1', 'r2', 'r3'}, {0}), {('r1', 0): 1}) SC = Mat(({0}, {0}), {(0, 0): 4}) VC = Mat(({'c1', 'c2'}, {0}), {('c2', 0): 1})
""" 0 1 2 3 4 5 6 ----------------------- 0 | 0 0 0 0 0 0 one 1 | 0 0 0 0 0 one 0 2 | 0 0 0 0 one 0 0 3 | 0 0 one 0 0 0 0 """ ## Task 1 part 2 # Please write your answer as a list. Use one from GF2 and 0 as the elements. encoding_1001 = [0,0,one,one,0,0,one] ## Task 2 # Express your answer as an instance of the Mat class. R = Mat(({0, 1, 2, 3}, {0, 1, 2, 3, 4, 5, 6}), {(1, 2): 0, (3, 2): one, (0, 0): 0, (3, 0): 0, (0, 4): 0, (1, 4): 0, (2, 6): 0, (0, 5): 0, (2, 1): 0, (2, 5): 0, (2, 0): 0, (1, 0): 0, (3, 5): 0, (0, 1): 0, (0, 2): 0, (3, 3): 0, (0, 6): one, (3, 4): 0, (3, 1): 0, (1, 6): 0, (1, 1): 0, (1, 5): one, (3, 6): 0, (2, 2): 0, (1, 3): 0, (2, 3): 0, (0, 3): 0, (2, 4): one}) ## Task 3 # Create an instance of Mat representing the check matrix H. H = Mat(({0, 1, 2}, {0, 1, 2, 3, 4, 5, 6}), {(0, 1): 0, (1, 2): one, (2, 4): one, (0, 0): 0, (2, 6): one, (1, 5): one, (2, 2): one, (1, 1): one, (1, 4): 0, (0, 2): 0, (0, 6): one, (1, 3): 0, (0, 5): one, (2, 1): 0, (2, 5): 0, (0, 4): one, (2, 3): 0, (1, 6): one, (1, 0): 0, (2, 0): one, (0, 3): one}) ## Task 4 part 1 def find_error(e): """ Input: an error syndrome as an instance of Vec Output: the corresponding error vector e Examples: >>> find_error(Vec({0,1,2}, {0:one})) Vec({0, 1, 2, 3, 4, 5, 6},{3: one}) >>> find_error(Vec({0,1,2}, {2:one})) Vec({0, 1, 2, 3, 4, 5, 6},{0: one})
## 7: (Task 5.12.4) Build linear system # Apply make_nine_equations to the list of tuples specifying the pixel coordinates of the # whiteboard corners in the image. Assign the resulting list of nine vectors to veclist: corners = [(358, 36), (329, 597), (592, 157), (580, 483)] veclist = make_nine_equations(corners) # Build a Mat whose rows are the Vecs in veclist L = rowdict2mat(veclist) ## 8: () Solve linear system # Now solve the matrix-vector equation to get a Vec hvec, and turn it into a matrix H. hvec = solve(L, b) H = Mat(({'y1', 'y2', 'y3'}, {'x1', 'x2', 'x3'}), {(a, b): hvec[(a, b)] for a in ['y1', 'y2', 'y3'] for b in ['x1', 'x2', 'x3']}) ## 9: (Task 5.12.7) Y Board Comprehension def mat_move2board(Y): ''' Input: - Y: a Mat each column of which is a {'y1', 'y2', 'y3'}-Vec giving the whiteboard coordinates of a point q. Output: - a Mat each column of which is the corresponding point in the whiteboard plane (the point of intersection with the whiteboard plane of the line through the origin and q). Example:
('y2', 'x3'): -1 }) return [u, v] ## Task 3 y_dom = {'y1', 'y2', 'y3'} x_dom = {'x1', 'x2', 'x3'} domain = {(a, b) for a in y_dom for b in x_dom} l8 = Vec(domain, {('y1', 'x1'): 1}) L = rowdict2mat( make_equations(358, 36, 0, 0) + make_equations(329, 597, 0, 1) + make_equations(592, 157, 1, 0) + make_equations(580, 483, 1, 1) + [l8]) b = Vec(set(range(9)), {8: 1}) h = solve(L, b) H = Mat((y_dom, x_dom), {(a, b): h[a, b] for a in y_dom for b in x_dom}) ## Task 4 def mat_move2board(Y): ''' Input: - Y: Mat instance, each column of which is a 'y1', 'y2', 'y3' vector giving the whiteboard coordinates of a point q. Output: - Mat instance, each column of which is the corresponding point in the whiteboard plane (the point of intersection with the whiteboard plane of the line through the origin and q). ''' Y_cols = list(mat2coldict(Y).values()) for i in range(len(Y_cols)):
__author__ = 'Jamie' from mat import Mat from vec import Vec from GF2 import one # No operations should mutate the input matrices, except setitem. print('For getitem(M,k):') M = Mat(({1,3,5}, {'a'}), {(1,'a'):4, (5,'a'): 2}) print(M[1,'a'] == 4) print(M[3,'a'] == 0) print(M == M) # Make sure your operations work on other fields, like GF(2). M = Mat((set(range(1000)), {'e',' '}), {(500, ' '): one, (255, 'e'): 0}) print(M[500, ' '] == one) print(M[500, 'e'] == 0) print(M[255, 'e'] == 0) print(Mat((set(range(1000)), {'e',' '}), {(500, ' '): one, (255, 'e'): 0}) == M) # True print('For setitem(M,k,val)') M = Mat(({'a','b','c'}, {5}), {('a', 5):3, ('b', 5):7}) M['b', 5] = 9 M['c', 5] = 13 print(M == Mat(({'a','b','c'}, {5}), {('a', 5):3, ('b', 5):9, ('c',5):13})) # True
bcoldict = mat2coldict(B) resultMat = Mat((A.D[0], B.D[1]), {}) for arowlabel, arowvec in arowdict.items(): for bcollabel, bcolvec in bcoldict.items(): resultMat[arowlabel, bcollabel] = arowvec * bcolvec return resultMat ## Problem 18 solving_systems_x1 = -1.0 / 5.0 solving_systems_x2 = 2.0 / 5.0 solving_systems_y1 = 4.0 / 5.0 solving_systems_y2 = -3.0 / 5.0 solving_systems_m = Mat(({0, 1}, {0, 1}), { (0, 0): -0.2, (0, 1): 0.8, (1, 0): 0.4, (1, 1): -0.6 }) solving_systems_a = Mat(({0, 1}, {0, 1}), { (0, 0): 3, (0, 1): 4, (1, 0): 2, (1, 1): 1 }) solving_systems_a_times_m = Mat(({0, 1}, {0, 1}), {(0, 0): 1, (1, 1): 1}) solving_systems_m_times_a = Mat(({0, 1}, {0, 1}), {(0, 0): 1, (1, 1): 1}) ## Problem 19 # Please write your solutions as booleans (True or False) are_inverses1 = True