def dot_product_vec_mat_mult(v, M): assert v.D == M.D[0] result = Vec(M.D[1], {r: 0 for r in M.D[1]}) cols = mat2coldict(M) for k in M.D[1]: result.f[k] = v * cols[k] return result
def matrix_matrix_mul(A, B): """ Returns the result of the matrix-matrix multiplication, A*B. >>> A = Mat(({0,1,2}, {0,1,2}), {(1,1):4, (0,0):0, (1,2):1, (1,0):5, (0,1):3, (0,2):2}) >>> B = Mat(({0,1,2}, {0,1,2}), {(1,0):5, (2,1):3, (1,1):2, (2,0):0, (0,0):1, (0,1):4}) >>> A*B == Mat(({0,1,2}, {0,1,2}), {(0,0):15, (0,1):12, (1,0):25, (1,1):31}) True >>> C = Mat(({0,1,2}, {'a','b'}), {(0,'a'):4, (0,'b'):-3, (1,'a'):1, (2,'a'):1, (2,'b'):-2}) >>> D = Mat(({'a','b'}, {'x','y'}), {('a','x'):3, ('a','y'):-2, ('b','x'):4, ('b','y'):-1}) >>> C*D == Mat(({0,1,2}, {'x','y'}), {(0,'y'):-5, (1,'x'):3, (1,'y'):-2, (2,'x'):-5}) True >>> M = Mat(({0, 1}, {'a', 'c', 'b'}), {}) >>> N = Mat(({'a', 'c', 'b'}, {(1, 1), (2, 2)}), {}) >>> M*N == Mat(({0,1}, {(1,1), (2,2)}), {}) True >>> E = Mat(({'a','b'},{'A','B'}), {('a','A'):1,('a','B'):2,('b','A'):3,('b','B'):4}) >>> F = Mat(({'A','B'},{'c','d'}),{('A','d'):5}) >>> E*F == Mat(({'a', 'b'}, {'d', 'c'}), {('b', 'd'): 15, ('a', 'd'): 5}) True >>> F.transpose()*E.transpose() == Mat(({'d', 'c'}, {'a', 'b'}), {('d', 'b'): 15, ('d', 'a'): 5}) True """ M = Mat((A.D[0],B.D[1]),{}) v = Vec(B.D[0],{}) #each column of matrix B is a Rx1 vector for col in B.D[1]: v.f = {} #init the function of the vector for row in B.D[0]: if (row,col) in B.f: v.f[row] = B.f[row,col] M.f.update({(r,col):v for r,v in matrix_vector_mul(A, v).f.items() if v != 0}) return M
def draw_gl( self ): n = self.n r = self.r vt = Vec( 1,2,3 ).norm() if vt == n: vt = Vec( 3,2,1 ).norm() v1 = vt.vcross( n ) v2 = v1.vcross( n ) v1,v2,v3,v4 = r + v1+v2, r + v1-v2, r + v2-v1, r -v1-v2 glBegin( GL_LINES ) glVertex3f( *v1 ) glVertex3f( *v4 ) glVertex3f( *v2 ) glVertex3f( *v3 ) glVertex3f( *v1 ) glVertex3f( *v2 ) glVertex3f( *v1 ) glVertex3f( *v3 ) glVertex3f( *v3 ) glVertex3f( *v4 ) glVertex3f( *v2 ) glVertex3f( *v4 ) glEnd( )
def __init__(self): self.cells = {} self.leaderboard_names = [] self.leaderboard_groups = [] self.top_left = Vec(0, 0) self.bottom_right = Vec(0, 0) self.reset()
def vector_matrix_mul(v, M): """ returns the product of vector v and matrix M Consider using brackets notation v[...] in your procedure to access entries of the input vector. This avoids some sparsity bugs. >>> v1 = Vec({1, 2, 3}, {1: 1, 2: 8}) >>> M1 = Mat(({1, 2, 3}, {'a', 'b', 'c'}), {(1, 'b'): 2, (2, 'a'):-1, (3, 'a'): 1, (3, 'c'): 7}) >>> v1*M1 == Vec({'a', 'b', 'c'},{'a': -8, 'b': 2, 'c': 0}) True >>> v1 == Vec({1, 2, 3}, {1: 1, 2: 8}) True >>> M1 == Mat(({1, 2, 3}, {'a', 'b', 'c'}), {(1, 'b'): 2, (2, 'a'):-1, (3, 'a'): 1, (3, 'c'): 7}) True >>> v2 = Vec({'a','b'}, {}) >>> M2 = Mat(({'a','b'}, {0, 2, 4, 6, 7}), {}) >>> v2*M2 == Vec({0, 2, 4, 6, 7},{}) True >>> v3 = Vec({'a','b'},{'a':1,'b':1}) >>> M3 = Mat(({'a', 'b'}, {0, 1}), {('a', 1): 1, ('b', 1): 1, ('a', 0): 1, ('b', 0): 1}) >>> v3*M3 == Vec({0, 1},{0: 2, 1: 2}) True """ assert M.D[0] == v.D result = Vec( M.D[1], {}) for key in M.f : if result.f.get( key[1] ) == None : resultf = 0 else : resultf = result.f.get( key[1] ) if v.f.get(key[0]) == None : vf = 0 else : vf = v.f.get(key[0]) result.f[key[1]] = resultf + vf * M.f[key] return result
def matrix_vector_mul(M, v): """ Returns the product of matrix M and vector v. Consider using brackets notation v[...] in your procedure to access entries of the input vector. This avoids some sparsity bugs. >>> N1 = Mat(({1, 3, 5, 7}, {'a', 'b'}), {(1, 'a'): -1, (1, 'b'): 2, (3, 'a'): 1, (3, 'b'):4, (7, 'a'): 3, (5, 'b'):-1}) >>> u1 = Vec({'a', 'b'}, {'a': 1, 'b': 2}) >>> N1*u1 == Vec({1, 3, 5, 7},{1: 3, 3: 9, 5: -2, 7: 3}) True >>> N1 == Mat(({1, 3, 5, 7}, {'a', 'b'}), {(1, 'a'): -1, (1, 'b'): 2, (3, 'a'): 1, (3, 'b'):4, (7, 'a'): 3, (5, 'b'):-1}) True >>> u1 == Vec({'a', 'b'}, {'a': 1, 'b': 2}) True >>> N2 = Mat(({('a', 'b'), ('c', 'd')}, {1, 2, 3, 5, 8}), {}) >>> u2 = Vec({1, 2, 3, 5, 8}, {}) >>> N2*u2 == Vec({('a', 'b'), ('c', 'd')},{}) True >>> M3 = Mat(({0,1},{'a','b'}),{(0,'a'):1, (0,'b'):1, (1,'a'):1, (1,'b'):1}) >>> v3 = Vec({'a','b'},{'a':1,'b':1}) >>> M3*v3 == Vec({0, 1},{0: 2, 1: 2}) True """ assert M.D[1] == v.D result = Vec( M.D[0], {}) for key in M.f : if result.f.get( key[0] ) == None : resultf = 0 else : resultf = result.f.get( key[0] ) if v.f.get(key[1]) == None : vf = 0 else : vf = v.f.get(key[1]) result.f[key[0]] = resultf + vf * M.f[key] return result
def dot_product_mat_vec_mult(M, v): assert M.D[1] == v.D result = Vec(M.D[0], {c: 0 for c in M.D[0]}) rows = mat2rowdict(M) for k in M.D[0]: result.f[k] = rows[k] * v return result
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 vector_matrix_mul(v, M): "Returns the product of vector v and matrix M" assert M.D[0] == v.D new_vec = Vec(M.D[1], {i: 0 for i in M.D[1]}) for i in new_vec.f: for j in M.D[1]: new_vec.f[i] = new_vec.f[i] + v.f.get(j, 0)*M.f.get((j, i), 0) return new_vec
def matrix_vector_mul(M, v): "Returns the product of matrix M and vector v" assert M.D[1] == v.D new_vec = Vec(M.D[0], {i: 0 for i in M.D[0]}) for i in new_vec.f: for j in M.D[1]: new_vec.f[i] = new_vec.f[i] + v.f.get(j, 0)*M.f.get((i, j), 0) return new_vec
def dot_product_mat_vec_mult(M, v): assert(M.D[1] == v.D) new_v = Vec(M.D[0], {}) row_dict = matutil.mat2rowdict(M) for key, val in row_dict.items(): new_v.f[key] = val * v return new_v
def matrix_vector_mul(M, v): "Returns the product of matrix M and vector v" assert M.D[1] == v.D resultVec = Vec(M.D[0],dict()) for k in M.f.keys(): if k[0] in resultVec.f: resultVec.f[k[0]] = resultVec.f[k[0]] + M[k[0],k[1]]*v[k[1]] else: resultVec.f[k[0]] = M[k[0],k[1]] * v[k[1]] return resultVec pass
def dot_product_vec_mat_mult(v, M): assert(v.D == M.D[0]) new_v = Vec(M.D[1], {}) col_dict = matutil.mat2coldict(M) for key, val in col_dict.items(): new_v.f[key] = v * val return new_v
def extract_col(M, column): ''' Takes a matrix, M and a col key from that matrix and returns a vector representing that col. ''' assert column in M.D[1] v = Vec(M.D[0], {}) for row in M.D[0]: key = (row, column) if key in M.f: v.f[row] = M.f[key] return v
def extract_row(M, row): """ Takes a matrix, M and a row key from that matrix and returns a vector representing that row. """ assert row in M.D[0] v = Vec(M.D[1], {}) for column in M.D[1]: key = (row, column) if key in M.f: v.f[column] = M.f[key] return v
def vector_matrix_mul(v, M): "Returns the product of vector v and matrix M" assert M.D[0] == v.D ret_v = Vec(M.D[1], {}) for d in ret_v.D: ret_v.f[d] = 0 for (k1, k2), val in M.f.items(): ret_v.f[k2] += val * v[k1] return ret_v
def matrix_vector_mul(M, v): "Returns the product of matrix M and vector v" assert M.D[1] == v.D ret_v = Vec(M.D[0], {}) for d in ret_v.D: ret_v.f[d] = 0 for (k1, k2), val in M.f.items(): ret_v.f[k1] += val * v[k2] return ret_v
def vec_sum(veclist, D): ''' >>> D = {'a','b','c'} >>> v1 = Vec(D, {'a': 1}) >>> v2 = Vec(D, {'a': 0, 'b': 1}) >>> v3 = Vec(D, { 'b': 2}) >>> v4 = Vec(D, {'a': 10, 'b': 10}) >>> vec_sum([v1, v2, v3, v4], D) == Vec(D, {'b': 13, 'a': 11}) True ''' sumvec = Vec(D, {}) for k in D: sumvec.f[k] = sum(getitem(g,k) for g in veclist) return sumvec
def find_matrix_inverse(A): ''' input: An invertible matrix, A, over GF(2) output: Inverse of A >>> M = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (1, 2): 0, (0, 0): 0, (2, 0): 0, (1, 0): one, (2, 2): one, (0, 2): 0, (2, 1): 0, (1, 1): 0}) >>> find_matrix_inverse(M) == Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (2, 0): 0, (0, 0): 0, (2, 2): one, (1, 0): one, (1, 2): 0, (1, 1): 0, (2, 1): 0, (0, 2): 0}) True ''' b_vecs = list() id_vec = Vec(A.D[1], { }) for c in A.D[1]: id_vec.f = { c:one } b_vecs.append(solve(A, id_vec)) return coldict2mat(b_vecs)
def make_Vec(primeset, factors): ''' Input: - primeset: a set of primes - factors: a list of factors [(p_1,a_1), ..., (p_n, a_n)] with p_i in primeset Output: - a vector v over GF(2) with domain primeset such that v[p_i] = int2GF2(a_i) for all i Example: >>> make_Vec({2,3,11}, [(2,3), (3,2)]) == Vec({2,3,11},{2:one}) True ''' return_vec = Vec(primeset,{}) for each in factors: return_vec.f[each[0]] = int2GF2(each[1]) return return_vec
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}) >>> find_error(Vec({0,1,2}, {1:one, 2:one})) Vec({0, 1, 2, 3, 4, 5, 6},{2: one}) """ result = Vec({0,1,2,3,4,5,6},{}) cols = mat2coldict(H) for k,v in cols.items(): if e==v: result.f[k] = one return result
def extract_col(M, column): ''' Takes a matrix, M and a col key from that matrix and returns a vector representing that col. ''' list_rc_M = [(r,c) for r in M.D[0] for c in M.D[1] ] for (d1,d2) in list_rc_M: if not ((d1,d2) in M.f): M.f[d1,d2]=0 else: pass #assert column in M.D[1] v = Vec(M.D[0], {}) for row in M.D[0]: key = (row, column) if key in M.f: v.f[row] = M.f[key] return v
def find_triangular_matrix_inverse(A): ''' input: An upper triangular Mat, A, with nonzero diagonal elements output: Inverse of A >>> A = listlist2mat([[1, .5, .2, 4],[0, 1, .3, .9],[0,0,1,.1],[0,0,0,1]]) >>> find_triangular_matrix_inverse(A) == Mat(({0, 1, 2, 3}, {0, 1, 2, 3}), {(0, 1): -0.5, (1, 2): -0.3, (3, 2): 0.0, (0, 0): 1.0, (3, 3): 1.0, (3, 0): 0.0, (3, 1): 0.0, (2, 1): 0.0, (0, 2): -0.05000000000000002, (2, 0): 0.0, (1, 3): -0.87, (2, 3): -0.1, (2, 2): 1.0, (1, 0): 0.0, (0, 3): -3.545, (1, 1): 1.0}) True ''' b = Vec(A.D[1], {}) rowList = [ mat2rowdict(A)[i] for i in A.D[1] ] colList = list() for i in A.D[1]: b.f = { i:1 } colList.append(triangular_solve_n(rowList, b)) return coldict2mat(colList) # A = listlist2mat([[1, .5, .2, 4],[0, 1, .3, .9],[0,0,1,.1],[0,0,0,1]]) # print(A) # print(mat2rowdict(A)) # print(find_triangular_matrix_inverse(A)) # print(A*find_triangular_matrix_inverse(A)) # print(find_triangular_matrix_inverse(A) == Mat(({0, 1, 2, 3}, {0, 1, 2, 3}), {(0, 1): -0.5, (1, 2): -0.3, (3, 2): 0.0, (0, 0): 1.0, (3, 3): 1.0, (3, 0): 0.0, (3, 1): 0.0, (2, 1): 0.0, (0, 2): -0.05000000000000002, (2, 0): 0.0, (1, 3): -0.87, (2, 3): -0.1, (2, 2): 1.0, (1, 0): 0.0, (0, 3): -3.545, (1, 1): 1.0}))
class Cell(object): def __init__(self, *args, **kwargs): self.pos = Vec() self.update(*args, **kwargs) def update(self, cid=-1, x=0, y=0, size=0, name='', color=(1, 0, 1), is_virus=False, is_agitated=False, skin_url=''): self.cid = cid self.pos.set(x, y) self.size = size self.mass = size ** 2 / 100.0 self.name = getattr(self, 'name', name) or name self.color2 = color self.color = tuple(map(lambda rgb: rgb / 255.0, color)) self.is_virus = is_virus self.is_agitated = is_agitated self.skin_url = skin_url @property def is_food(self): return self.size < 20 and not self.name @property def is_ejected_mass(self): return self.size in (37, 38) and not self.name def same_player(self, other): """ Compares name and color. Returns True if both are owned by the same player. """ return self.name == other.name \ and self.color == other.color def __lt__(self, other): if self.mass != other.mass: return self.mass < other.mass return self.cid < other.cid
def vector_matrix_mul(v, M): """ returns the product of (1xn) vector v and matrix M >>> v1 = Vec({1, 2, 3}, {1: 1, 2: 8}) >>> M1 = Mat(({1, 2, 3}, {'a', 'b', 'c'}), {(1, 'b'): 2, (2, 'a'):-1, (3, 'a'): 1, (3, 'c'): 7}) >>> v1*M1 == Vec({'a', 'b', 'c'},{'a': -8, 'b': 2, 'c': 0}) True >>> v1 == Vec({1, 2, 3}, {1: 1, 2: 8}) True >>> M1 == Mat(({1, 2, 3}, {'a', 'b', 'c'}), {(1, 'b'): 2, (2, 'a'):-1, (3, 'a'): 1, (3, 'c'): 7}) True >>> v2 = Vec({'a','b'}, {}) >>> M2 = Mat(({'a','b'}, {0, 2, 4, 6, 7}), {}) >>> v2*M2 == Vec({0, 2, 4, 6, 7},{}) True """ assert M.D[0] == v.D nv = Vec(M.D[1],{}) # column labels are now domain if len(v.f) == 0: # if function is empty, retutn empty function in vector return nv listv = [0]*len(v.D) # create a list a long a vector filled with zeros vcsd = list(v.D) # create a list of vector coumn domain lmr = list(M.D[0]) # create a list of matrix rows nc = len(M.D[0])# number of rows for i in range(len(v.D)): vcn = vcsd[i] if vcn in v.f: listv[i] = v.f[vcn] #actal f(x) FOR X, remember speed hack init with 0, dont have to set 0 for mcn in M.D[1]: listim = [0]*nc for i in range(nc): mrn = lmr[i] if (mrn,mcn) in M.f: listim[i] = M.f[mrn,mcn] #actal f(x) FOR X nv.f[mcn] = sum(a*b for a,b in zip(listim,listv)) return nv
def matrix_vector_mul(M, v): """ Returns the product of matrix M and (nx1) vector v. >>> N1 = Mat(({1, 3, 5, 7}, {'a', 'b'}), {(1, 'a'): -1, (1, 'b'): 2, (3, 'a'): 1, (3, 'b'):4, (7, 'a'): 3, (5, 'b'):-1}) >>> u1 = Vec({'a', 'b'}, {'a': 1, 'b': 2}) >>> N1*u1 == Vec({1, 3, 5, 7},{1: 3, 3: 9, 5: -2, 7: 3}) True >>> N1 == Mat(({1, 3, 5, 7}, {'a', 'b'}), {(1, 'a'): -1, (1, 'b'): 2, (3, 'a'): 1, (3, 'b'):4, (7, 'a'): 3, (5, 'b'):-1}) True >>> u1 == Vec({'a', 'b'}, {'a': 1, 'b': 2}) True >>> N2 = Mat(({('a', 'b'), ('c', 'd')}, {1, 2, 3, 5, 8}), {}) >>> u2 = Vec({1, 2, 3, 5, 8}, {}) >>> N2*u2 == Vec({('a', 'b'), ('c', 'd')},{}) True """ assert M.D[1] == v.D nv = Vec(M.D[0],{}) # row labels are now domain if len(v.f) == 0: # if function is empty, retutn empty function in vector return nv listv = [0]*len(v.D) # create a list a long a vector filles with zeros vrs = v.D.copy() lmc = list(M.D[1]) nc = len(M.D[1]) for i in range(len(v.D)): vrn = vrs.pop() if vrn in v.f: listv[i] = v.f[vrn] #actal f(x) FOR X for mrn in M.D[0]: listim = [0]*nc for i in range(nc): mcn = lmc[i] if (mrn,mcn) in M.f: listim[i] = M.f[mrn,mcn] #actal f(x) FOR X nv.f[mrn] = sum(a*b for a,b in zip(listim,listv)) return nv
class World(object): cell_class = Cell def __init__(self): self.cells = {} self.leaderboard_names = [] self.leaderboard_groups = [] self.top_left = Vec(0, 0) self.bottom_right = Vec(0, 0) self.reset() def reset(self): """ Clears the `cells` and leaderboards, and sets all corners to `0,0`. """ self.cells.clear() del self.leaderboard_names[:] del self.leaderboard_groups[:] self.top_left.set(0, 0) self.bottom_right.set(0, 0) def create_cell(self, cid): """ Creates a new cell in the world. Override to use a custom cell class. """ self.cells[cid] = self.cell_class() @property def center(self): return Vec(self.size.x/2,self.size.y/2) @property def size(self): return self.top_left.abs() + self.bottom_right.abs() def __eq__(self, other): """Compares two worlds by comparing their leaderboards.""" for ls, lo in zip(self.leaderboard_names, other.leaderboard_names): if ls != lo: return False for ls, lo in zip(self.leaderboard_groups, other.leaderboard_groups): if ls != lo: return False if self.top_left != other.top_left: return False if self.bottom_right != other.bottom_right: return False return True
def adjust(v,multipliers): return Vec(v.D,{i: v.f[i]*multipliers[i] if i in v.f else 0 for i in v.D})
def test_sub(self): vec = Vec(10, 0) / Vec(5, 1) self.assertEqual(vec, Vec(2, 0))
def list2vec(L): return Vec(set(range(len(L))), {i: L[i] for i in range(len(L)) if L[i] != 0})
def test_sub(self): vec = Vec(10, 0) - Vec(5, 0) self.assertEqual(vec, Vec(5, 0))
from bitutil import noise from GF2 import one ## Task 1 part 1 """ Create an instance of Mat representing the generator matrix G. You can use the procedure listlist2mat in the matutil module (be sure to import first). Since we are working over GF (2), you should use the value one from the GF2 module to represent 1""" G = listlist2mat([[one, 0, one, one], [one, one, 0, one], [0, 0, 0, one], [one, one, one, 0], [0, 0, one, 0], [0, one, 0, 0], [one, 0, 0, 0]]) #print(G) ## Task 1 part 2 # Please write your answer as a list. Use one from GF2 and 0 as the elements. encoding_1001 = G * Vec({0, 1, 2, 3}, {0: one, 3: one}) #print(encoding_1001) ## Task 2 # Express your answer as an instance of the Mat class. #R = listlist2mat( [[1.0/8,1.0/8,-1.0/4,1.0/8,-1.0/4,-1.0/4,5.0/8],[-1.0/4,1.0/4,0,1.0/4,0,1.0/2,-1.0/4],[1.0/4,-1.0/4,0,1.0/4,1.0/2,0,-1.0/4],[1.0/4,1.0/4,1.0/2,-1.0/4,0,0,-1.0/4]]) R = listlist2mat([[0.125, 0.125, -0.25, 0.125, -0.25, -0.25, 0.625], [-0.25, 0.25, 0, 0.25, 0, 0.5, -0.25], [0.25, -0.25, 0, 0.25, 0.5, 0, -0.25], [0.25, 0.25, 0.5, -0.25, 0, 0, -0.25]]) #print(R*G) ## Task 3 # Create an instance of Mat representing the check matrix H. H = None
}) v = Vec( D, { ('y2', 'x1'): -x1, ('y2', 'x2'): -x2, ('y2', 'x3'): -1, ('y3', 'x1'): w2 * x1, ('y3', 'x2'): w2 * x2, ('y3', 'x3'): w2 }) return [u, v] ## 4: () Scaling row # This is the vector defining the scaling equation w = Vec(D, {('y1', 'x1'): 1}) ## 5: () Right-hand side # Now construct the Vec b that serves as the right-hand side for the matrix-vector equation L*hvec=b # This is the {0, ..., 8}-Vec whose entries are all zero except for a 1 in position 8 b = Vec({i for i in range(9)}, {8: 1}) ## 6: () Rows of constraint matrix def make_nine_equations(corners): ''' input: a list of four tuples: [(i0,j0),(i1,j1),(i2,j2),(i3,j3)] where i0,j0 are the pixel coordinates of the top-left corner, i1,j1 are the pixel coordinates of the bottom-left corner, i2,j2 are the pixel coordinates of the top-right corner,
These procedures use the list-of-lists-of-integers representation of grayscale images. This is the representation used by the image module. """ def import_faces(path=''): "call import_faces() to obtain a list of images of faces" faces = {} for i in range(1, 21): name = path + ('faces/img%02d.png' % i) print('Reading '+name) faces[i-1] = image.file2image(name) return faces def import_unclassified(path=''): "call import_faces() to obtain a list of images of things including faces" unclassified = {} for i in range(1, 12): name = path + ('unclassified/img%02d.png' % i) print('Reading '+name) unclassified[i-1] = image.file2image(name) return unclassified # Test data M_d = ({0,1,2},{0,1}) M_f = {(0,0):1/sqrt(2) , (1,0):1/sqrt(2) , (0,1):1/sqrt(3), (1,1):-1/sqrt(3), (2,1):1/sqrt(3)} test_M = Mat(M_d, M_f) x_d = {0,1,2} x_f = {0:10,1:20,2:30} test_x = Vec(x_d, x_f)
('y1', 'x1') ('y1', 'x2') ('y1', 'x3') ('y2', 'x1') ('y2', 'x2') ('y2', 'x3') ('y3', 'x1') ('y3', 'x2') ('y3', 'x3') --------------------------------------------------------------------------------------------------------------------- 0 0 0 -18 -23 -1 18 23 1 Again, the negations of these vectors form an equally valid solution. ''' u = Vec(D, {('y1', 'x1'):(-x1), ('y1', 'x2'):(-x2), ('y1', 'x3'):(-1), ('y3', 'x1'):(w1*x1), ('y3', 'x2'):(w1*x2), ('y3', 'x3'):w1}) v = Vec(D, {('y2', 'x1'):(-x1), ('y2', 'x2'):(-x2), ('y2', 'x3'):(-1), ('y3', 'x1'):(w2*x1), ('y3', 'x2'):(w2*x2), ('y3', 'x3'):w2}) return [u, v] ## 4: () Scaling row # This is the vector defining the scaling equation w = Vec(D, {('y1', 'x1'):1}) ## 5: () Right-hand side # Now construct the Vec b that serves as the right-hand side for the matrix-vector equation L*hvec=b # This is the {0, ..., 8}-Vec whose entries are all zero except for a 1 in position 8 b = Vec({0, 1, 2, 3, 4, 5, 6, 7, 8}, {8:1}) ## 6: () Rows of constraint matrix def make_nine_equations(corners): ''' input: a list of four tuples: [(i0,j0),(i1,j1),(i2,j2),(i3,j3)]
## 3: (Problem 12.14.3) Finding the eigenvalue associated with an eigenvector # Part a p3_part_a_eigenvalue1 = -1 p3_part_a_eigenvalue2 = 5 # Part b p3_part_b_eigenvalue1 = 2 p3_part_b_eigenvalue2 = 5 ## 4: (Problem 12.14.11) Markov chains and eigenvectors # a Mat D = {'S', 'R', 'F', 'W'} transition_matrix = coldict2mat({ 'S': Vec(D, { 'S': 0.5, 'W': 0.3, 'R': 0.2 }), 'W': Vec(D, { 'S': 0.1, 'W': 0.1, 'F': 0.8 }), 'R': Vec(D, { 'S': 0.2, 'F': 0.2, 'R': 0.6 }), 'F': Vec(D, { 'W': 0.6, 'F': 0.4
your_answer_c_AB = [[6,0,0,0],[6,0,0,0],[8,0,0,0],[5,0,0,0]] your_answer_c_BA = [[4,2,1,-1],[4,2,1,-1],[0,0,0,0],[0,0,0,0]] your_answer_d_AB = [[0,3,0,4],[0,4,0,1],[0,4,0,4],[0,-6,0,-1]] your_answer_d_BA = [[0,11,0,-2],[0,0,0,0],[0,0,0,0],[1,5,-2,3]] your_answer_e_AB = [[0,3,0,8],[0,-9,0,2],[0,0,0,8],[0,15,0,-2]] your_answer_e_BA = [[-2,12,4,-10],[0,0,0,0],[0,0,0,0],[-3,-15,6,-9]] your_answer_f_AB = [[-4,4,2,-3],[-1,10,-4,9],[-4,8,8,0],[1,12,4,-15]] your_answer_f_BA = [[-4,-2,-1,1],[2,10,-4,6],[8,8,8,0],[-3,18,6,-15]] ## Problem 10 column_row_vector_multiplication1 = Vec({0, 1}, {0:13,1:20}) column_row_vector_multiplication2 = Vec({0, 1, 2}, {0:24,1:11,2:4}) column_row_vector_multiplication3 = Vec({0, 1, 2, 3}, {0:4,1:8,2:11,3:3}) column_row_vector_multiplication4 = Vec({0,1}, {0:30,1:16}) column_row_vector_multiplication5 = Vec({0, 1, 2}, {0:-3,1:1,2:9}) ## Problem 11 def lin_comb_mat_vec_mult(M, v): assert(M.D[1] == v.D) from matutil import mat2coldict
#task 1 def move2board(y_vec): """function that maps the location of a point in the whiteboard plane not on the whiteboard to a point on the white board such that the line from the origin through the y_vec will intersect the whiteboard at the output point input must be a 'y1','y2','y3' vector. would have liked a more general function but I guess there's no situation where this applies where the labels aren't defined.""" #return Vec(y_vec.D, {y_vec.D[0]:y_vec.D[0]/y_vec.D[2],y_vec.D[1]:y_vec.D[1]/y_vec.D[2], y_vec.D[2]:1}) y3 = y_vec assert y_vec.D == {'y1', 'y2', 'y3'} return Vec(y_vec.D, {k: v / y_vec.f['y3'] for k, v in y_vec.f.items()}) v = Vec({'y1', 'y2', 'y3'}, {'y1': 5, 'y2': 3, 'y3': 0.5}) print(move2board(v)) #task 2 D = {(y, x) for y in ['y3', 'y2', 'y1'] for x in ['x1', 'x2', 'x3']} def make_equations(w1, w2, x1, x2): """this prodedure returns the vectors that if multiplied by the unknown values in H would produce 0, hence giving us opportunity to solve for the values of H. Could use solver to do it but that so far has not been part of the lab. This procedure is in service of converting from the camera basis to the whiteboard basis.""" u = Vec( D, { ('y3', 'x1'): w1 * x1, ('y3', 'x2'): w1 * x2, ('y3', 'x3'): w1,
Examples: >>> find_error(Vec({0,1,2}, {0:one})) == Vec({0, 1, 2, 3, 4, 5, 6},{3: one}) True >>> find_error(Vec({0,1,2}, {2:one})) == Vec({0, 1, 2, 3, 4, 5, 6},{0: one}) True >>> find_error(Vec({0,1,2}, {1:one, 2:one})) == Vec({0, 1, 2, 3, 4, 5, 6},{2: one}) True >>> find_error(Vec({0,1,2}, {})) == Vec({0,1,2,3,4,5,6}, {}) True """ col_dict = mat2coldict(H) return Vec(H.D[1], {err: one for err in col_dict if col_dict[err] == syndrome}) ## Task 6 # Use the Vec class for your answers. non_codeword = Vec({0,1,2,3,4,5,6}, {0: one, 1:0, 2:one, 3:one, 4:0, 5:one, 6:one}) error_vector = find_error(H * non_codeword) code_word = error_vector + non_codeword original = R * code_word # R * code_word ## Task 7 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 """
def test_mul(self): vec = Vec(10, 0) * Vec(5, 0) self.assertEqual(vec, Vec(50, 0))
## Problem 6 # Write your solution for this problem in orthonormalization.py. ## Problem 7 # Write your solution for this problem in orthonormalization.py. ## Problem 8 # Please give each solution as a Vec least_squares_A1 = listlist2mat([[8, 1], [6, 2], [0, 6]]) least_squares_Q1 = listlist2mat([[.8, -0.099], [.6, 0.132], [0, 0.986]]) least_squares_R1 = listlist2mat([[10, 2], [0, 6.08]]) least_squares_b1 = list2vec([10, 8, 6]) x_hat_1 = Vec({0, 1}, {0: 1.0832236842105263, 1: 0.9838815789473685}) least_squares_A2 = listlist2mat([[3, 1], [4, 1], [5, 1]]) least_squares_Q2 = listlist2mat([[.424, .808], [.566, .115], [.707, -.577]]) least_squares_R2 = listlist2mat([[7.07, 1.7], [0, .346]]) least_squares_b2 = list2vec([10, 13, 15]) x_hat_2 = Vec({0, 1}, {0: 2.501098838207519, 1: 2.658959537572254}) ## Problem 9 def QR_solve(A, b): ''' Input: - A: a Mat - b: a Vec
def dot_product_mat_vec_mult(M, v): assert(M.D[1] == v.D) dot_prod = Vec(M.D[0],{}) for (key,value) in mat2rowdict(M).items(): dot_prod.f[key] = value*v return dot_prod
def make_equations(x1, x2, w1, w2): ''' Input: - x1, x2: pixel coordinates of a point q in the image plane - w1, w2: w1=y1/y3 and w=y2/y3 where y1,y2,y3 are the whiteboard coordinates of q. Output: - List [u,v] of D-vectors that define linear equations u*h = 0 and v*h = 0 For example, suppose we have an image of the whiteboard in which the top-left whiteboard corner appears at pixel coordinates 9, 18 the bottom-left whiteboard corner appears at pixel coordinates 8,25 the top-right whiteboard corner appears at pixel coordinates 20,20 the bottom-right whiteboard corner appears at pixel coordinates 18,23 Let q be the point in the image plane with pixel coordinates x=8,y=25, i.e. camera coordinates (8,25,1). Let y1,y2,y3 be the whiteboard coordinates of the same point. The line that goes through the origin and p intersects the whiteboard at a point p. That point p is the bottom-left corner of the whiteboard, so its whiteboard coordinates are 1,0,1. Therefore (y1/y3,y2/y3,y3/y3) = (1,0,1). We define w1=y1/y3 and w2=y2/y3, so w1 = 1 and w2 = 0. Given this input-output pair, let's find two linear equations u*h=0 and v*h=0 constraining the unknown vector h whose entries are the entries of the matrix H. >>> for v in make_equations(8,25,1,0): print(v) <BLANKLINE> ('y1', 'x1') ('y1', 'x2') ('y1', 'x3') ('y2', 'x1') ('y2', 'x2') ('y2', 'x3') ('y3', 'x1') ('y3', 'x2') ('y3', 'x3') --------------------------------------------------------------------------------------------------------------------- -8 -25 -1 0 0 0 8 25 1 <BLANKLINE> ('y1', 'x1') ('y1', 'x2') ('y1', 'x3') ('y2', 'x1') ('y2', 'x2') ('y2', 'x3') ('y3', 'x1') ('y3', 'x2') ('y3', 'x3') --------------------------------------------------------------------------------------------------------------------- 0 0 0 -8 -25 -1 0 0 0 Note that the negations of these vectors form an equally valid solution. Similarly, consider the point q in the image plane with pixel coordinates 18, 23. Let y1,y2,y3 be the whiteboard coordinates of p. The corresponding point p in the whiteboard plane is the bottom-right corner, and the whiteboard coordinates of p are 1,1,1, so (y1/y3,y2/y3,y3/y3)=(1,1,1). We define w1=y1/y3 and w2=y2/y3, so w1=1 and w2=1. We obtain the vectors u and v defining equations u*h=0 and v*h=0 as follows: >>> for v in make_equations(18,23,1,1): print(v) <BLANKLINE> ('y1', 'x1') ('y1', 'x2') ('y1', 'x3') ('y2', 'x1') ('y2', 'x2') ('y2', 'x3') ('y3', 'x1') ('y3', 'x2') ('y3', 'x3') --------------------------------------------------------------------------------------------------------------------- -18 -23 -1 0 0 0 18 23 1 <BLANKLINE> ('y1', 'x1') ('y1', 'x2') ('y1', 'x3') ('y2', 'x1') ('y2', 'x2') ('y2', 'x3') ('y3', 'x1') ('y3', 'x2') ('y3', 'x3') --------------------------------------------------------------------------------------------------------------------- 0 0 0 -18 -23 -1 18 23 1 Again, the negations of these vectors form an equally valid solution. ''' u = Vec( D, { ('y1', 'x1'): -x1, ('y1', 'x2'): -x2, ('y1', 'x3'): -1, ('y3', 'x1'): w1 * x1, ('y3', 'x2'): w1 * x2, ('y3', 'x3'): w1 }) v = Vec( D, { ('y2', 'x1'): -x1, ('y2', 'x2'): -x2, ('y2', 'x3'): -1, ('y3', 'x1'): w2 * x1, ('y3', 'x2'): w2 * x2, ('y3', 'x3'): w2 }) return [u, v]
def test_mul_scalar(self): self.assertEqual(Vec(5, 5) * 5, Vec(25, 25))
def adjust(v,mul): return Vec(v.D,{i:mul[i]*v[i] for i in v.D})
def dot_product_vec_mat_mult(v, M): assert(v.D == M.D[0]) from matutil import mat2coldict matcolumn = mat2coldict(M) return Vec(M.D[1], {i:(matcolumn[i]*v) for i in matcolumn.keys()} )
def on_button_down(self, mouse_pos): self.vel_placing = self.pos_placing - self.camera.screen_to_world( Vec.from_tuple(mouse_pos))
def dot_product_mat_vec_mult(M, v): assert(M.D[1] == v.D) from matutil import mat2rowdict matrow = mat2rowdict(M) return Vec(M.D[0], {i:(matrow[i]*v) for i in matrow.keys()} )
def test_sub(self): self.assertEqual(Vec(10, 5).square(), Vec(100, 25))
def zero_vec(D): return Vec(D, {})
from orthogonalization import orthogonalize from orthogonalization import aug_orthogonalize from triangular import triangular_solve ## 1: (Problem 1) Generators for orthogonal complement U_vecs_1 = [list2vec([0, 0, 3, 2])] W_vecs_1 = [ list2vec(v) for v in [[1, 2, -3, -1], [1, 2, 0, 1], [3, 1, 0, -1], [-1, -2, 3, 1]] ] # Give a list of Vecs ortho_compl_generators_1 = [ Vec({0, 1, 2, 3}, { 0: 1.0, 1: 2.0, 2: -0.4615384615384617, 3: 0.6923076923076923 }), Vec({0, 1, 2, 3}, { 0: 2.2432432432432434, 1: -0.5135135135135134, 2: 0.810810810810811, 3: -1.2162162162162162 }) ] U_vecs_2 = [list2vec([3, 0, 1])] W_vecs_2 = [list2vec(v) for v in [[1, 0, 0], [1, 0, 1]]] # Give a list of Vecs ortho_compl_generators_2 = [
def edit_existing_body(self, body): #If a body is already being edited, switch to editing the new body instead if self.editing_body: self.finish_editing_body() if self.infolabels: self.remove_planet_info_labels() self.editing_body = True self.mouse_objects_stack.append( slider.Slider("Radius", body.radius, 1, 1 * 10**10, body.radius.var, Vec(10, 160), 200, 10, 10, interpolation_type=1)) self.mouse_objects_stack.append( slider.Slider("Mass", body.mass, 1, 1 * 10**36, body.mass.var, Vec(10, 240), 200, 10, 10, interpolation_type=1)) self.mouse_objects_stack.append( slider.Slider("Red", body.colour[0], 0, 255, body.colour[0].var, Vec(10, 320), 200, 10, 10)) self.mouse_objects_stack.append( slider.Slider("Green", body.colour[1], 0, 255, body.colour[1].var, Vec(10, 400), 200, 10, 10)) self.mouse_objects_stack.append( slider.Slider("Blue", body.colour[2], 0, 255, body.colour[2].var, Vec(10, 480), 200, 10, 10)) self.mouse_objects_stack.append( button.Button( "Delete", Vec(10, 560), 100, 30, lambda body=body: self.delete_body_during_editing(body), self.renderer.font_medium)) self.mouse_objects_stack.append( button.Button("Done", Vec(130, 560), 100, 30, self.finish_editing_body, self.renderer.font_medium)) self.infolabels.append( infolabel.InfoLabel("Velocity (m/s)", body.vel_magnitude, Vec(640, 50))) self.infolabels.append( infolabel.InfoLabel("Accel (m/s^2)", body.accel_magnitude, Vec(640, 100)))
def on_button_click(self, mouse_pos): self.pos_placing = self.camera.screen_to_world( Vec.from_tuple(mouse_pos)) self.body_pos.x = self.pos_placing.x self.body_pos.y = self.pos_placing.y
def generate_solar_system(self): self.finish_editing_body() self.remove_planet_info_labels() self.camera.stop_tracking() #Save a backup of the old solar system just in case they clicked it by accident self.save_bodies(filename="..\\save_states\\backup.stt") #Remove the current bodies self.bodies = [] #Reset the bodies drop down list and mouse objects stack #Remove all buttons from the drop down list and the mouse object stack #I start at 1: because i don't want to remove the 'None' button for mouse_object in self.mouse_objects_stack: if isinstance(mouse_object, dropdownmenu.DropDownMenu ) and mouse_object.name == "Bodies": for button in mouse_object.buttons[1:]: self.mouse_objects_stack.remove(button) mouse_object.buttons.remove(button) #Create a constellation name constellation = random.choice(naming.constellations) #Create a star name using the Bayer Designation star_name = random.choice(naming.greek_letters) + " " + constellation num_bodies = random.randint(3, 10) body_names = [] #Create distinct planet names for each of the planets by the naming convention '[number] [constellation] [letter]' while len(body_names) < num_bodies: body_name = "%d %s %s" % (random.randint( 1, 100), constellation, random.choice(string.ascii_letters)) #Make sure if we have already generated this name, then generate a new one if body_name not in body_names: body_names.append(body_name) #Stars generally range from cyan to yellow, so I found that keeping green at a fixed value and keeping red and green to add to make 255 worked well to generate star colours star_red = random.randint(0, 255) #Add the star to the game star = body.Body(star_name, random.randint(1 * 10**8, 5 * 10**9), random.randint(1 * 10**27, 1 * 10**32), Vec(0, 0), Vec(0, 0), (star_red, 255, 255 - star_red), emits_light=True) self.add_body_to_game(star) #Generate all of the bodies for body_num in range(num_bodies): body_mass = random.randint(1 * 10**22, 1 * 10**26) body_distance_from_sun = star.radius.var + random.randint( 1 * 10**9, 1 * 10**12) """ To calculate the velocity to keep the planet in orbit around the sun: G = universal gravitational constant M = mass of sun m = mass of body r = distance of body away from sun v = velocity of planet Centripetal force = GMm/r^2 Centripetal force = mv^2/r GMm/r^2 = mv^2/r GM/r^2 = v^2/r GM/r = v^2 sqrt(GM/r) = v """ angle = random.uniform(0, 2 * math.pi) body_velocity = math.sqrt(self.G * star.mass.var / body_distance_from_sun) self.add_body_to_game( body.Body( body_names[body_num], random.randint(1 * 10**6, 1 * 10**8), body_mass, Vec( math.cos(angle) * body_distance_from_sun, math.sin(angle) * body_distance_from_sun), Vec( math.sin(angle) * body_velocity, -math.cos(angle) * body_velocity), (random.randint(0, 255), random.randint( 0, 255), random.randint(0, 255))))
def __init__(self, *args, **kwargs): self.pos = Vec() self.update(*args, **kwargs)
def add_gui(self): #Quick function to format the time in the speed multiplier def format_time(x): if x > 31557600: return str(round(x / 31557600, 3)) + " years/s" if x > 2592000: return str(round(x / 2592000, 3)) + " months/s" if x > 604800: return str(round(x / 604800, 3)) + " weeks/s" if x > 86400: return str(round(x / 86400, 3)) + " days/s" if x > 3600: return str(round(x / 3600, 3)) + " hours/s" if x > 60: return str(round(x / 60, 3)) + " minutes/s" return str(round(x, 3)) + " seconds/s" # Add the GUI objects self.mouse_objects_stack.append( slider.Slider("Speed multiplier", self.dt, 1, 50000000, self.dt.var, Vec(410, 10), 200, 10, 10, var_formatter=format_time, interpolation_type=1)) self.scale = scale.Scale(Vec(630, 10), 150, 10, 1 / (self.camera.zoom)) self.mouse_objects_stack.append( dropdownmenu.DropDownMenu("File", Vec(0, 0), 100, 30)) self.mouse_objects_stack[-1].add_button("Save", self.save_bodies, self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack[-2].add_button("Load", self.load_bodies, self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack[-3].add_button("Random", self.generate_solar_system, self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack.append( dropdownmenu.DropDownMenu("Options", Vec(297, 0), 100, 30)) self.mouse_objects_stack[-1].add_button( "Tracers", lambda: self.change_flags(flags_file.RENDER_TRACERS), self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack[-2].add_button( "Labels", lambda: self.change_flags(flags_file.RENDER_PLANET_LABELS), self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack[-3].add_button( "Shadows", lambda: self.change_flags(flags_file.SHADOWS), self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack[-4].add_button( "Unrealistic", lambda: self.change_flags(flags_file.REALISTIC), self.renderer.font_medium, self.mouse_objects_stack, toggled_name="Realistic") self.mouse_objects_stack[-5].add_button( "Pause", lambda: self.change_flags(flags_file.PAUSED), self.renderer.font_medium, self.mouse_objects_stack, toggled_name="Unpause") self.mouse_objects_stack[-6].add_button( "Fullscreen", lambda: self.renderer.toggle_fullscreen(self), self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack[-7].add_button("Quit", pygame.quit, self.renderer.font_medium, self.mouse_objects_stack) self.mouse_objects_stack.append( button.Button("Add body", Vec(99, 0), 100, 30, self.start_creating_new_body, self.renderer.font_medium)) self.mouse_objects_stack.append( dropdownmenu.DropDownMenu("Bodies", Vec(198, 0), 100, 30)) self.mouse_objects_stack[-1].add_button( "None", lambda: [ self.camera.stop_tracking(), self.finish_editing_body(), self.remove_planet_info_labels() ], self.renderer.font_medium, self.mouse_objects_stack) for body in self.bodies: self.mouse_objects_stack[-1].add_button( body.name, lambda body=body: [self.camera.track_body(body), self.edit_existing_body(body)], self.renderer.font_medium, self.mouse_objects_stack)
def dot_product_mat_vec_mult(M, v): assert(M.D[1] == v.D) from matutil import mat2rowdict rows = mat2rowdict(M) return Vec(M.D[0], {row:rowVec*v for row,rowVec in rows.items()})
def test_distance(self): self.assertEqual(Vec(0, 4).distance(Vec(0, 0)), 4) self.assertEqual(Vec(3, 0).distance(Vec(0, 0)), 3) self.assertEqual(Vec(3, 4).distance(Vec(0, 0)), 5)
def dot_product_vec_mat_mult(v, M): assert(v.D == M.D[0]) from matutil import mat2coldict cols = mat2coldict(M) return Vec(M.D[1], {col:v*colVec for col,colVec in cols.items()})
clusters = {} # Count the number of iterations until convergence iterations = 0 # Will be used to determine if the algorithm is complete convergence = False # Initialize the means to random points in the general range of our dataset means = [Vec(randrange(minX, maxX), randrange(minY, maxY)) for x in range(k)] while convergence is False: iterations += 1 clusters = {i : [] for i in range(0,k)} for v in data: cluster = -1 distance = float('inf') for i in range(len(means)): d = Vec.distance(v, means[i]) if d < distance: distance = d cluster = i clusters[cluster].append(v) # Create a list to store the new means new_means = [] for key in clusters: # Sum the vectors in each cluster summed = Vec.zero() cluster = clusters[key] for v in cluster: summed += v # Find the mean of all the vectors in each cluster