def test_rotatematrix(self): s = 6 original = Matrix.RandomMatrix(s) rotated = copy.deepcopy(original) rotated.rotate() for i in range(math.ceil(s / 2)): for j in range(math.ceil(s / 2)): self.assertEqual(rotated.a[i][j], original.a[j][s - 1 - i]) self.assertEqual(rotated.a[j][s - 1 - i], original.a[s - 1 - i][s - 1 - j]) self.assertEqual(rotated.a[s - 1 - i][s - 1 - j], original.a[s - 1 - j][i]) self.assertEqual(rotated.a[s - 1 - j][i], original.a[i][j]) s = 999 original = Matrix.RandomMatrix(s) rotated = copy.deepcopy(original) rotated.rotate() for i in range(math.ceil(s / 2)): for j in range(math.ceil(s / 2)): self.assertEqual(rotated.a[i][j], original.a[j][s - 1 - i]) self.assertEqual(rotated.a[j][s - 1 - i], original.a[s - 1 - i][s - 1 - j]) self.assertEqual(rotated.a[s - 1 - i][s - 1 - j], original.a[s - 1 - j][i]) self.assertEqual(rotated.a[s - 1 - j][i], original.a[i][j])
def Jacobi(matrix, target, iteration=5): """ iterate throught the jacobi method to solve the system """ Id = Identity(len(matrix.matrix)) #exctract the Diagonal from the matrix Diag = [] for i in range(len(matrix.matrix)): line = [] for j in range(len(matrix.matrix)): if i == j: line.append(matrix.matrix[i][j]) else: line.append(R(0)) Diag.append(line) Diag = Matrix.Matrix(Diag) inv_diag = Diag.reverse_diag() X_k = [] for i in range(len(matrix.matrix)): X_k.append([0]) X_k = Matrix.Matrix(X_k) for i in range(iteration): print(i) X_k = ((Id - inv_diag * matrix) * X_k) + (inv_diag * target) # (I - D^-1 * A) * X_k + D^-1 * Y #erreur potentielle de calcul, ou systeme insolvable. print(X_k) return (X_k)
def testGraficar(self): #Se crea una matriz de 0 m1 = m.empty(9, 9) #Se llenan las posiciones de la matriz con las probabilidades de por donde se puede ir el electron m1.fix(1, 0, com.Complex(1 / math.sqrt(2), 0)) m1.fix(2, 0, com.Complex(1 / math.sqrt(2), 0)) #Se llena la matriz con las probabilidades de a que punto de impacto llegara el electron m1.fix(4, 1, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(5, 1, com.Complex((-math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(6, 1, com.Complex((math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(6, 2, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(7, 2, com.Complex((-math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(8, 2, com.Complex((math.sqrt(6) / 6), (-math.sqrt(6) / 6))) #Se llena la matriz asuminedo que una vez ha llegado el electron se quedara en el punto de impacto m1.fix(4, 4, com.Complex(1, 0)) m1.fix(5, 5, com.Complex(1, 0)) m1.fix(6, 6, com.Complex(1, 0)) m1.fix(7, 7, com.Complex(1, 0)) m1.fix(8, 8, com.Complex(1, 0)) #Se genera el vector inicial v = m.crear(9, 1, [1, 0, 0, 0, 0, 0, 0, 0, 0]) #Se realizan 2 clicks a la matriz m4 = m.multiplicar(m1, 2) #Se multiplica el vector inicial por la matriz v4 = m4.multiply(v) #Se hallan las probabilidades de que el electron se encuentre en X punto prob = v4.prob() #Se imprime el resultado m.printVector(prob) self.assertTrue(True)
def testRendijaCuantica(self): m1 = m.empty(11, 11) m1.fix(1, 0, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(2, 0, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(3, 0, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(4, 1, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(5, 1, com.Complex((-math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(6, 1, com.Complex((math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(6, 2, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(7, 2, com.Complex((-math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(8, 2, com.Complex((math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(8, 3, com.Complex((-math.sqrt(6) / 6), (math.sqrt(6) / 6))) m1.fix(9, 3, com.Complex((-math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(10, 3, com.Complex((-math.sqrt(6) / 6), (-math.sqrt(6) / 6))) m1.fix(4, 4, com.Complex(1, 0)) m1.fix(5, 5, com.Complex(1, 0)) m1.fix(6, 6, com.Complex(1, 0)) m1.fix(7, 7, com.Complex(1, 0)) m1.fix(8, 8, com.Complex(1, 0)) m1.fix(9, 9, com.Complex(1, 0)) m1.fix(10, 10, com.Complex(1, 0)) v = m.crear(11, 1, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) m4 = m.multiplicar(m1, 4) v4 = m4.multiply(v) v4 = v4.round(4) r = m.crearR( 11, 1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, -0.3333], [0.3333, 0], [0, 0], [0.3333, 0], [0, 0], [0.3333, 0], [0.3333, 0]]) self.assertTrue(r.equals(v4))
def Quadratic_Generate_Hyperbola(np,t=3.0): dt=2.0*t/(1.0*(np-1)) a=self.Quadratic_Axis() ps=Mesh() t=-t for n in range( self.NPoints ): p=Vector([ a[0]*sqrt(1+t**2.0), a[1]*t, ]) ps.append( self.C+p ) t+=dt S=[] if (self.Lambdas[0]>0.0): S=Matrix([ [ -1.0, 0.0 ], [ 0.0, 1.0 ], ]) elif (self.Lambdas[1]>0.0): S=Matrix([ [ 1.0, 0.0 ], [ 0.0,-1.0 ], ]) pss=self.Map_Points(ps,A) assymptote1=Mesh("Assimptote1",[ ps[0], ps1[ len(ps1)-1 ] ]) assymptote2=Mesh("Assimptote2",[ ps1[0],ps[ len(ps) -1 ] ]) return [ ps,pss,assymptote1,assymptote2 ]
def main(): f11 = F1RosenbrockBananaFunction() f12 = F1RosenbrockBananaFunction() f21 = F2() f22 = F2() elements1 = np.array([[-1.9, 2]]) tocka11 = Matrix(1, 2, elements1) tocka12 = Matrix.copy_matrix(tocka11) elements2 = np.array([[0.1, 0.3]]) tocka21 = Matrix(1, 2, elements2) tocka22 = Matrix.copy_matrix(tocka21) #double[] donjeGranice = new double [] {-100,-100}; donjeGranice = [-100, -100] gornjeGranice = [100, 100] impOgr1 = InequalityImplicitConstraint1() impOgr2 = InequalityImplicitConstraint2() implicitnaOgranicenja = [impOgr1, impOgr2] box_algorithm = BoxAlgorithm(f11, donjeGranice, gornjeGranice, implicitnaOgranicenja, EPSILON, ALPHA, PRINT) box_algorithm2 = BoxAlgorithm(f21, donjeGranice, gornjeGranice, implicitnaOgranicenja, EPSILON, ALPHA, PRINT) rjesenjePoBoxu1, logger1 = box_algorithm.run(tocka11) #rjesenjePoBoxu2 = BoxAlgorithm.run(f21,tocka21,donjeGranice.clone(),gornjeGranice.clone(),implicitnaOgranicenja,EPSILON,ALPHA,PRINT) rjesenjePoBoxu2, logger2 = box_algorithm2.run(tocka21) print "\n\n" print "Rjesenje po Boxu za f1: " Matrix.printMatrix(rjesenjePoBoxu1) print "Rjesenje po Boxu za f2: " Matrix.printMatrix(rjesenjePoBoxu2)
def getPositionOnScreen(self, translation, rotation, center): #change function name '''returns the point on the screen based on the translation and rotation of the viewer from the origin''' self.vector.setValue(self.x - translation[0] - center[0], 0, 0) self.vector.setValue(self.y - translation[1], 1, 0) self.vector.setValue(self.z - translation[2] - center[1], 2, 0) mat = Matrix.multiply(Matrix.createRotationMatrix(-rotation[1], 0), Matrix.createRotationMatrix(-rotation[0], 2)) self.vector = Matrix.multiply(mat, self.vector) if self.vector.getValue(1, 0) < 0: return [-1, -1] else: #self.vector.setValue(getRelativeLength(self.vector.getValue(2,0) - center[1], getHypotenuse(self.vector.getValue(1,0), self.vector.getValue(0,0) - center[0]), OPTICAL_DISTANCE) + center[1], 2, 0) self.vector.setValue( getRelativeLength(self.vector.getValue( 2, 0), self.vector.getValue(1, 0), OPTICAL_DISTANCE) + center[1], 2, 0) self.vector.setValue( getRelativeLength(self.vector.getValue( 0, 0), self.vector.getValue(1, 0), OPTICAL_DISTANCE) + center[0], 0, 0) return [ int(self.vector.getValue(0, 0)), int(self.vector.getValue(2, 0)) ]
def RunGameOfLife( self ): self.CanvasRandMap.delete('all') self.BitMatrix = [] self.Matrix = Matrix(LineTotalSize, CollumnTotalSize, self.BitMatrix) self.Rules = ApplyRules( self.BitMatrix ) self.Draw = DrawMatrix( self.BitMatrix, self.CanvasRandMap ) self.NumGenerations = 0 self.DefineInitialMatrix() while( True ): self.Draw.DrawMatrixFunction() self.LabelNumber["text"] = self.NumGenerations self.LabelNumber.pack( side = BOTTOM ) self.RandMap.after( 50 ) self.RandMap.update() self.LabelNumber.after( 50 ) self.LabelNumber.update() self.NumGenerations += 1 self.BitMatrix = self.Rules.ApplyRulesFunction() self.CanvasRandMap.delete('all')
def centers_and_points(v, maximum_points=10000): m = v.full_matrix() lev = min(v.surface_levels) import _volume ijk = _volume.high_indices(m, lev) ijk_mean = ijk.mean(axis=0) # Test at most maximum_points in correlation calculation to make it faster. if not maximum_points is None and len(ijk) > maximum_points: from numpy.random import randint r = randint(len(ijk), size=maximum_points) ijk = ijk[r, :] from numpy import float32 xyz = ijk.astype(float32) d = v.data import Matrix as M M.transform_points(xyz, d.ijk_to_xyz_transform) w = v.interpolated_values(xyz) icenter = [round(i) for i in ijk_mean] center = d.ijk_to_xyz(icenter) centers = [center] for offset in (0, -1): icenter = [(n - 1) / 2 if n % 2 else (n / 2) + offset for n in d.size] center = d.ijk_to_xyz(icenter) if not center in centers: centers.append(center) return centers, xyz, w
def setTurretRotation (self, t_): t = t_ if abs (t) > self.turretrotspeed: t = self.turretrotspeed * t / abs (t) self.turretTheta += t m = Matrix.translate (-self.pos.x (), -self.pos.y (), 0) * Matrix.rotate (0, -t, 0) * Matrix.translate (self.pos.x (), self.pos.y (), 0) self.turret.transform (m)
def __DisplayGraph(self, type, weight, covariance): A = [i + (j * 0.1) for i in range(-2, 2) for j in range(10)] B = [] Up = [] Down = [] for i in A: num = 0.0 for j in range(len(weight)): num += (weight[j] * (i**j)) B.append(num) X = [[i**j for j in range(self.basis)]] if type == 0: variance = covariance else: variance = ((1 / self.a) + Matrix.multiply( Matrix.multiply(X, Matrix.getMatrixInverse(covariance)), Matrix.transpose(X))[0][0])**(1 / 2) Up.append(num + variance) Down.append(num - variance) mp.axis([-2, 2, -20, 25]) mp.xticks([i for i in range(-2, 3, 1)]) mp.yticks([i for i in range(-20, 21, 10)]) if type == 1: mp.plot(self.X[:10], self.Y[:10], 'bo') elif type == 2: mp.plot(self.X[:50], self.Y[:50], 'bo') elif type == 3: mp.plot(self.X, self.Y, 'bo') mp.plot(A, B, 'k') mp.plot(A, Up, 'r', antialiased=True) mp.plot(A, Down, 'r', antialiased=True) mp.show()
def rotateCoordinates(self, pos, axisOfRotation, origin, theta): xRotMatrix = Matrix([ [1, 0, 0], [0, cos(radians(theta)), -sin(radians(theta))], [0, sin(radians(theta)), cos(radians(theta))] ]) yRotMatrix = Matrix([ [cos(radians(theta)), 0, sin(radians(theta))], [0, 1, 0], [-sin(radians(theta)), 0, cos(radians(theta))] ]) zRotMatrix = Matrix([ [cos(radians(theta)), -sin(radians(theta)), 0], [sin(radians(theta)), cos(radians(theta)), 0], [0, 0, 1] ]) # 1) Find direction vector from origin to pos directionVector = VectorUtils.getDirectionVector(origin, pos) #print "directionVector: " + str(directionVector) # 2) Perform a rotation of direction vector theta degrees about origin in respect to axisOfRotation # Logic is {axisOfRotation}RotMatrix * columnVector of direction vector switcher = { X_INDEX: xRotMatrix, Y_INDEX: yRotMatrix, Z_INDEX: zRotMatrix } rotationMatrix = switcher[axisOfRotation] columnVector = Vector(directionVector).transpose() #print "rotationMatrix:\n" + str(rotationMatrix) + "\n" + "columnVector:\n" + str(columnVector) newDirectionVector = rotationMatrix * columnVector #print "newDirectionVector: \n" + str(newDirectionVector) # 3) Add the the result from 2 to origin return VectorUtils.addVectors(origin, newDirectionVector.transpose()._contents[0]) #TODO: Change this and use vector / matrix methods
def calc_cte(l_pipes, l_nodes, l_reservoir, eq='D-W'): n_p = len(l_pipes) n_n = len(l_nodes) n_r = len(l_reservoir) n_t = n_n + n_r a_t = zeros(n_t, n_p) l_t = l_reservoir + l_nodes co_m = 2 equation = eq.lower() if equation == 'd-w': co_m = 2 elif equation == 'c-m': co_m = 2 elif equation == 'h-w': co_m = 1.85 for i in range(n_p): a_t[i][l_t.index(l_pipes[i].n_i)] = -1 a_t[i][l_t.index(l_pipes[i].n_f)] = 1 n_c_d = [i + n_r for i in range(n_n) if l_nodes[i].cond] a_12 = a_t.get_col(n_c_d) n_c_c = [i for i in range(n_r) if l_reservoir[i].cond] a_10 = a_t.get_col(n_c_c) a_21 = a_12.T n_d = diagonal(co_m, n_p) ide = diagonal(1, n_p) h_o = Matrix([[i.level] for i in l_reservoir]) q_d = Matrix([[i.demand] for i in l_nodes]) q_o = Matrix([[i.flow] for i in l_pipes]) return equation, co_m, a_21, n_d, a_12, a_10, h_o, q_d, q_o, {'n_p': n_p, 'n_n': n_n, 'n_r': n_r, 'n_t': n_t, 'a_t': a_t, 'a_12': a_12, 'a_21': a_21, 'a_10': a_10, 'n_d': n_d, 'ide': ide}
def myrecv(s): #receive size first size = '' while len(size) < SIZE_SPEC: text = s.recv(SIZE_SPEC - len(size)).decode() if not text: print('disconnected') return ('') size += text size = int(size) #now receive message msg = '' while len(msg) < size: text = s.recv(size - len(msg)).decode() if text == b'': print('disconnected') break msg += text receive_recover = Matrix.matrix_string2matrix_list(msg) #display the wrong message to audience print('Receiving corrupted matrix:', str(receive_recover)) print('Receiving corrupted message:', Matrix.matrix2alnum(receive_recover)) print() corrected = Matrix.error_correction(receive_recover) msg = Matrix.matrix2alnum(corrected) #msg is now a string for sure! print('Corrected message:', msg) return (msg)
def mainGame(self): if not self.jobs.interface.jobs.board.update_required and not hasattr( self.jobs, "window-game_over"): ## XXX: GAME OVER board = self.jobs.interface.jobs.board Log.log("Game over, displaying game state") matrix = [[(x, y) in board.blocks for x in xrange(board.blocks_width)] for y in xrange(board.blocks_height)] Matrix.put(matrix, f="_") if ((len(self.highscores) < HIGHSCORES or any(board.score > score["score"] for score in self.highscores)) and not Shared.options.get("uber_tetromino") and not Shared.options.get("flip_tetromino")): self.addJob("name_inputbox", Jobs.InputBox(self, "New Highscore!\nName: ")) self.running = self.getName else: self.addJob( "window-game_over", Jobs.Notification(self, "window-game_over", "Game Over")) self.addJob( "endtimer", Jobs.TimedExecution(self, self.quitGame, seconds=3, anykey=True))
def testReadCSV(self): '''Tests if a matrix can be properly initialised from a csv file''' #Test can read csv files produce by the class itself string = self.matrix.csvRepresentation() file = open('temp', 'w') file.write(string) file.close() matrix = Matrix.matrixFromCSVFile('temp') self.assertEqual(matrix, self.matrix) os.remove('temp') #Test initialisation for a csv file not in the same format #as the one created by the Matrix class file = open('temp', 'w') file.write(testCSVString) file.close() matrix = Matrix.matrixFromCSVFile('temp') self.assertEqual(matrix, self.matrix) #Test it works when told not to read header file = open('temp', 'w') file.write(testCSVString2) file.close() matrix = Matrix.matrixFromCSVFile(filename='temp', readHeaders=False) matrix.setColumnHeaders(["Header1", "Header2"]) self.assertEqual(matrix, self.matrix) #Clean up os.remove('temp')
def show_axis(tf, color, os): import Matrix axis, axis_point, angle, axis_shift = Matrix.axis_center_angle_shift(tf) if angle < 0.1: raise CommandError, 'Rotation angle is near zero (%g degrees)' % angle have_box, box = os.bbox() if not have_box: # TODO: Chimera does not provide bounding box of full model. raise CommandError, 'First model must be visible to show axis' axis_center = Matrix.project_to_axis(box.center().data(), axis, axis_point) axis_length = max((box.urb - box.llf).data()) hl = 0.5 * axis_length ap1 = map(lambda a, b: a - hl * b, axis_center, axis) ap2 = map(lambda a, b: a + hl * b, axis_center, axis) from VolumePath import Marker_Set, Link from VolumePath.markerset import chimera_color m = Marker_Set('rotation axis') mm = m.marker_model() mm.openState.xform = os.xform if color: mm.color = chimera_color(color) radius = 0.025 * axis_length m1 = m.place_marker(ap1, None, radius) m2 = m.place_marker(ap2, None, radius) Link(m1, m2, None, radius)
def StartStdOne(self): self.CanvasReadyMap.delete('all') self.BitMatrix = [] self.Matrix = Matrix(LineTotalSize, CollumnTotalSize, self.BitMatrix) self.Rules = ApplyRules(self.BitMatrix) self.Draw = DrawMatrix(self.BitMatrix, self.CanvasReadyMap) self.NumGenerations = 0 self.DefineStandardOne() while (True): self.Draw.DrawMatrixFunction() self.LabelNumber["text"] = self.NumGenerations self.LabelNumber.pack(side=BOTTOM) self.ReadyMap.after(0) self.ReadyMap.update() self.LabelNumber.after(0) self.LabelNumber.update() self.NumGenerations += 1 self.BitMatrix = self.Rules.ApplyRulesFunction() self.CanvasReadyMap.delete('all')
def transform_ellipsoid(axes, center, xform): import Matrix as m tf = m.xform_matrix(xform) axes = m.apply_matrix_without_translation(tf, axes) center = m.apply_matrix(tf, center) return axes, center
def optimize_helix_paramters(v, xyz, w, axis, rise, angle, center): m = v.full_matrix() xyz_to_ijk_transform = v.data.xyz_to_ijk_transform max_steps = 2000 ijk_step_size_min, ijk_step_size_max = 0.01, 0.5 optimize_translation = optimize_rotation = True metric = 'correlation' import Symmetry as S htf = S.helical_symmetry_matrix(rise, angle, axis, center) import Matrix as M tf = M.multiply_matrices(xyz_to_ijk_transform, htf) import FitMap as F move_tf, stats = F.locate_maximum(xyz, w, m, tf, max_steps, ijk_step_size_min, ijk_step_size_max, optimize_translation, optimize_rotation, metric) ohtf = M.multiply_matrices(htf, move_tf) oaxis, ocenter, oangle, orise = M.axis_center_angle_shift(ohtf) if M.inner_product(axis, oaxis) < 0: orise = -orise oangle = -oangle corr = stats['correlation'] return orise, oangle, corr
def testMatrixAdjoint(self): m1 = matrix.Matrix([[ complex.ComplexNumber(6, -3), complex.ComplexNumber(2, 12), complex.ComplexNumber(0, -19) ], [ complex.ComplexNumber(0, 0), complex.ComplexNumber(5, 2.1), complex.ComplexNumber(17, 0) ], [ complex.ComplexNumber(1, 0), complex.ComplexNumber(2, 5), complex.ComplexNumber(3, -4.5) ]]) mTest = m1.adjoint() mSol = matrix.Matrix([[ complex.ComplexNumber(6, 3), complex.ComplexNumber(0, 0), complex.ComplexNumber(1, 0) ], [ complex.ComplexNumber(2, -12), complex.ComplexNumber(5, -2.1), complex.ComplexNumber(2, -5) ], [ complex.ComplexNumber(0, 19), complex.ComplexNumber(17, 0), complex.ComplexNumber(3, 4.5) ]]) self.assertTrue(mTest.equals(mSol))
def rotation_axis(operation, model1, model2, showAxis = True, showSlabs = False, color = None): os1 = set([m.openState for m in model1]) os2 = set([m.openState for m in model2]) if len(os1) != 1: raise CommandError, 'First model spec names %d models, require 1' % len(os1) if len(os2) != 1: raise CommandError, 'Second model spec names %d models, require 1' % len(os2) os1 = os1.pop() os2 = os2.pop() xf = os1.xform.inverse() xf.multiply(os2.xform) import Matrix tf = Matrix.xform_matrix(xf) message = ('Position of %s (%s) relative to %s (%s) coordinates:\n' % (model2[0].name, model2[0].oslIdent(), model1[0].name, model1[0].oslIdent())) message += Matrix.transformation_description(tf) from chimera import replyobj replyobj.info(message) from chimera import MaterialColor if isinstance(color, MaterialColor): color = color.rgba() elif not color is None: raise CommandError, 'Unknown color "%s"' % str(color) if showAxis: show_axis(tf, color, os1) if showSlabs: show_slabs(xf, color, os1)
def show_axis(tf, color, os): import Matrix axis, axis_point, angle, axis_shift = Matrix.axis_center_angle_shift(tf) if angle < 0.1: raise CommandError, 'Rotation angle is near zero (%g degrees)' % angle have_box, box = os.bbox() if not have_box: # TODO: Chimera does not provide bounding box of full model. raise CommandError, 'First model must be visible to show axis' axis_center = Matrix.project_to_axis(box.center().data(), axis, axis_point) axis_length = max((box.urb - box.llf).data()) hl = 0.5*axis_length ap1 = map(lambda a,b: a-hl*b, axis_center, axis) ap2 = map(lambda a,b: a+hl*b, axis_center, axis) from VolumePath import Marker_Set, Link from VolumePath.markerset import chimera_color m = Marker_Set('rotation axis') mm = m.marker_model() mm.openState.xform = os.xform if color: mm.color = chimera_color(color) radius = 0.025 * axis_length m1 = m.place_marker(ap1, None, radius) m2 = m.place_marker(ap2, None, radius) Link(m1, m2, None, radius)
def testRendijaProbabilistica(self): m1 = m.empty(11, 11) m1.fix(1, 0, com.Complex(1 / 3, 0)) m1.fix(2, 0, com.Complex(1 / 3, 0)) m1.fix(3, 0, com.Complex(1 / 3, 0)) m1.fix(4, 1, com.Complex(1 / 3, 0)) m1.fix(5, 1, com.Complex(1 / 3, 0)) m1.fix(6, 1, com.Complex(1 / 3, 0)) m1.fix(6, 2, com.Complex(1 / 3, 0)) m1.fix(7, 2, com.Complex(1 / 3, 0)) m1.fix(8, 2, com.Complex(1 / 3, 0)) m1.fix(8, 3, com.Complex(1 / 3, 0)) m1.fix(9, 3, com.Complex(1 / 3, 0)) m1.fix(10, 3, com.Complex(1 / 3, 0)) m1.fix(4, 4, com.Complex(1, 0)) m1.fix(5, 5, com.Complex(1, 0)) m1.fix(6, 6, com.Complex(1, 0)) m1.fix(7, 7, com.Complex(1, 0)) m1.fix(8, 8, com.Complex(1, 0)) m1.fix(9, 9, com.Complex(1, 0)) m1.fix(10, 10, com.Complex(1, 0)) v = m.crear(11, 1, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) m4 = m.multiplicar(m1, 4) v4 = m4.multiply(v) v4 = v4.round(4) r = m.crear(11, 1, [ 0, 0, 0, 0, 0.1111, 0.1111, 0.2222, 0.1111, 0.2222, 0.1111, 0.1111 ]) self.assertTrue(r.equals(v4))
def amp(ket1, ket2): temp = Complex.Complex(0, 0) ket2 = Matrix.adjoint(ket2) r = Matrix.matrixProduct(ket2, ket1) for i in range(len(r)): temp = Complex.Complex.add(temp, r[i][0]) return temp
def train(self): """Trains the classifiers. """ for i in range(0, 10): A = Matrix.readMatrix("dados_mnist/train_dig%d.txt"%i, self.ntrainings) Wi, _ = Matrix.NMF(A, self.n, self.ntrainings, self.p) self.W.append(Wi)
def rotate(self, rotation): '''rotates the plane by the specified angle, where rotation is a list of rotations [Z,X,Y]''' R1 = Matrix.createRotationMatrix(rotation[0], 2) R2 = Matrix.multiply(Matrix.createRotationMatrix(rotation[1], 0), R1) R3 = Matrix.multiply(Matrix.createRotationMatrix(rotation[2], 1), R2) for i in range(0, len(self.points)): self.points[i].applyMatrix(R3)
def linePlaneIntersectionNumeric(p1, p2, p3, p4, p5): if not useNumeric: return linePlaneIntersection(p1, p2, p3, p4, p5) if useNumpy: top = [[1., 1., 1., 1.], [p1[0], p2[0], p3[0], p4[0]], [p1[1], p2[1], p3[1], p4[1]], [p1[2], p2[2], p3[2], p4[2]]] topDet = numpy.linalg.det(top) bottom = [[1., 1., 1., 0.], [p1[0], p2[0], p3[0], p5[0] - p4[0]], [p1[1], p2[1], p3[1], p5[1] - p4[1]], [p1[2], p2[2], p3[2], p5[2] - p4[2]]] botDet = numpy.linalg.det(bottom) else: # actually use numeric top = Matrix.Matrix([[1., 1., 1., 1.], [p1[0], p2[0], p3[0], p4[0]], [p1[1], p2[1], p3[1], p4[1]], [p1[2], p2[2], p3[2], p4[2]]]) topDet = LinearAlgebra.determinant(top) bottom = Matrix.Matrix([[1., 1., 1., 0.], [p1[0], p2[0], p3[0], p5[0] - p4[0]], [p1[1], p2[1], p3[1], p5[1] - p4[1]], [p1[2], p2[2], p3[2], p5[2] - p4[2]]]) botDet = LinearAlgebra.determinant(bottom) if topDet == 0.0 or botDet == 0.0: return False t = -topDet / botDet x = p4[0] + (p5[0] - p4[0]) * t y = p4[1] + (p5[1] - p4[1]) * t z = p4[2] + (p5[2] - p4[2]) * t return [x, y, z]
def testQuantum1(self): H = m.Matrix([[com.Complex(1, 0), com.Complex(1, 0)], [com.Complex(1, 0), com.Complex(-1, 0)]]) X = m.Matrix([[com.Complex(0, 0), com.Complex(1, 0)], [com.Complex(1, 0), com.Complex(0, 0)]]) H = H.multiplyS((1 / (math.sqrt(2)))) HX = H.productoTensor(X) HH = H.productoTensor(H) v = m.Matrix([[ com.Complex(1, 0), com.Complex(0, 0), com.Complex(0, 0), com.Complex(0, 0) ]]) r = v.multiply(HX) r2 = r.multiply(HH) res = m.Matrix([[ com.Complex(0.707, 0), com.Complex(-0.707, 0), com.Complex(0, 0), com.Complex(0, 0) ]]) r2 = r2.round(3) self.assertTrue(res.equals(r2))
def read_graph(file_path="data/amazon_m_0.edgelist"): matrices = [] a_tuples = [] d_tuples = [] l = 0 prev_i = 0 with open(file_path, "r", encoding="utf8") as file: for line in file: l += 1 if l > 2: row = line.split("\n")[0].split(" ")[:2] i = int(row[0]) j = int(row[1]) v = random.choice([-1, 1]) if prev_i < i: v_ = [item[2] for item in a_tuples if item[0] == prev_i] d_tuples.append((prev_i, prev_i, sum(v_))) prev_i = i a_tuples.append((i, j, v)) v_ = sum([item[2] for item in a_tuples if item[0] == i]) d_tuples.append((i, i, v_)) r, c, v = Matrix.tuple2csr(a_tuples) a = Matrix().set(r, c, v) r, c, v = Matrix.tuple2csr(d_tuples) d = Matrix().set(r, c, v) matrices.append(d.sub(a)) return matrices
def testMatrixTranspose(self): m1 = matrix.Matrix([[ complex.ComplexNumber(6, -3), complex.ComplexNumber(2, 12), complex.ComplexNumber(0, -19) ], [ complex.ComplexNumber(0, 0), complex.ComplexNumber(5, 2.1), complex.ComplexNumber(17, 0) ], [ complex.ComplexNumber(1, 0), complex.ComplexNumber(2, 5), complex.ComplexNumber(3, -4.5) ]]) mTest = m1.transpose() mSol = matrix.Matrix([[ complex.ComplexNumber(6, -3), complex.ComplexNumber(0, 0), complex.ComplexNumber(1, 0) ], [ complex.ComplexNumber(2, 12), complex.ComplexNumber(5, 2.1), complex.ComplexNumber(2, 5) ], [ complex.ComplexNumber(0, -19), complex.ComplexNumber(17, 0), complex.ComplexNumber(3, -4.5) ]]) self.assertTrue(mTest.equals(mSol))
def testShouldGetTheInnerProductoOfTwoMatrices(self): m1 = matrix.Matrix([[complex.ComplexNumber(1, 0), complex.ComplexNumber(1, 0)], [complex.ComplexNumber(-1, 0), complex.ComplexNumber(1, 0)]]) m2 = matrix.Matrix([[complex.ComplexNumber(2, 0), complex.ComplexNumber(1, 0)], [complex.ComplexNumber(1, 0), complex.ComplexNumber(3, 0)]]) mTest = m1.innerProduct(m2) mSol = 5 self.assertEqual(mSol,mTest.partReal)
def expectedValue(obs, ket): # Verificar que ket sea un vector columna bra = Matrix.matrixProduct(obs, ket) bra = Matrix.adjoint(bra) r = 0 for i in range(len(obs)): r += Complex.Complex.add(bra[0][i], ket[i][0]).real return r
def testMultiplicacionVectores(self): v1 = m.Matrix([[com.Complex(1, 1)], [com.Complex(1, 5)]]) v2 = m.Matrix([[com.Complex(2, 2)], [com.Complex(2, 3)]]) c = com.Complex(-13, 17) s = v1.multiply(v2) print(c.printS()) s.print() self.assertTrue(c.equals(c, s))
def compute(self): a = self.get_input("Array") try: mat = sparse.csc_matrix(a.get_array()) out_mat = Matrix() out_mat.set_matrix(mat) self.set_output("Output Matrix", out_mat) except: raise ModuleError("Could not convert input array to matrix")
def set_outputs(self, results): try: out = Matrix() out.set_matrix(sparse.csc_matrix(results[0])) self.setResult("Matrix Output", out) except: pass out_ar = NDArray() out_ar.set_array(numpy.array(results[0])) self.setResult("Array Output", out_ar)
def graph_event_cb(event, v1=v1, axis=axis, center=center, cur_angle = [0]): if not event.button is None: angle = event.xdata if angle is None: angle = 0 # Click outside graph bounds import Matrix tf = Matrix.rotation_transform(axis, angle-cur_angle[0], center) xf = Matrix.chimera_xform(tf) v1.openState.localXform(xf) cur_angle[0] = angle ax.cur_position.set_xdata((angle,angle)) ax.figure.canvas.draw()
def show_cumulative_transform(self, m): from chimera import Xform mxf = getattr(m, 'applied_xform', Xform()) import Matrix tf = Matrix.xform_matrix(mxf) angles = Matrix.euler_angles(tf) shift = mxf.getTranslation().data() text = ('Cumulative:\n' + ' Euler angles %.5g %.5g %.5g\n' % angles + ' Shift: %.5g %.5g %.5g' % shift) self.cumulative['text'] = text
def print_axes(axes, d2, elen, name, xform = None): if xform: import Matrix as m axes = m.apply_matrix_without_translation(m.xform_matrix(xform), axes) from math import sqrt paxes = ['\tv%d = %6.3f %6.3f %6.3f %s = %6.3f r%d = %6.3f' % (a+1, axes[a][0], axes[a][1], axes[a][2], ('a','b','c')[a], elen[a], a+1, sqrt(d2[a])) for a in range(3)] from chimera.replyobj import info info('Inertia axes for %s\n%s\n' % (name, '\n'.join(paxes))) from Accelerators.standard_accelerators import show_reply_log show_reply_log()
def AddParseResults(self, tokenList, POSList, conTree, depTokenPos, depGraph): try: self.parseResult = Matrix.matrix(tokenList) self.parseResult.add_row(self.__alignTokensToOrigSent(tokenList)) self.parseResult.add_row(POSList) except: print >> sys.stderr, "token" raise # conTree -> nltk.tree.ParentedTree # parseResut[CON] row contains treepositions of the leaves try: self.conTree = conTree self.parseResult.add_row(conTree.treepositions('leaves')) except: print >> sys.stderr, "con" raise # depGraph -> pygraph.classes.digraph # parseResult[DEP] row contains identifiers of the leaves try: self.depGraph = depGraph self.parseResult.add_row(self.__GenerateConMatchingDep(depTokenPos)) except: print >> sys.stderr, "dep" raise
def texture_surface_piece(p, t, txf, border_color, offset = 0): p.textureId = t.texture_id() p.useTextureTransparency = ('a' in t.color_mode) p.textureModulationColor = t.modulation_rgba() p.textureBorderColor = border_color va = offset_vertices(p, offset) s2tc = t.texture_matrix() p2s = p.model.openState.xform p2s.premultiply(txf.inverse()) import Matrix p2tc = Matrix.multiply_matrices(s2tc, Matrix.xform_matrix(p2s)) import _contour _contour.affine_transform_vertices(va, p2tc) p.textureCoordinates = va p.using_surface_coloring = True
def save(self, name): xlow = min(x for x, y in self.jobs.board.blocks) xhigh = max(x for x, y in self.jobs.board.blocks) ylow = min(y for x, y in self.jobs.board.blocks) yhigh = max(y for x, y in self.jobs.board.blocks) matrix = [ [(x, y) in self.jobs.board.blocks for x in xrange(xlow, xhigh+1)] for y in xrange(ylow, yhigh+1) ] Log.log("Created new tetromino, displaying below") Matrix.put(matrix) Save.saveTetromino(self.color, name, matrix) Shared.tetrominos = Load.loadTetrominos() return True
def __init__(self): self.numRows = 18 self.numColumns = 63 self.locMatrix = Matrix(self.numColumns,self.numRows) self.componentList = [] self.rails= [0 , 2.5 , 2.5 , 5] #voltage rails. bottom to top. y = 17 16 1 0 self.initializeLocations() #assigns Location objects to each coordinate self.nodeCreation() #assigns functional Nodes to proper Locations self.detailLocations() #sets power rails and display flags
def read_rotation(self, f): axis = self.read_vector(f, 'rotation_axis', None) angle = self.read_float(f, 'rotation_angle', None) if axis is None or angle is None: return ((1,0,0),(0,1,0),(0,0,1)) import Matrix r = Matrix.rotation_from_axis_angle(axis, angle) return r
def fit_map_in_map(map1, map2, initial_map1_transform = None, map1_threshold = None, ijk_step_size_min = 0.01, # Grid index units ijk_step_size_max = 1.5, # Grid index units max_steps = 10000, optimize_translation = True, optimize_rotation = True): # Files have to have file suffix indicating volume format. if initial_map1_transform: xf = Matrix.chimera_xform(initial_map1_transform) map1.surface_model().openState.globalXform(xf) use_threshold = (map1_threshold != None) points, point_weights = map_points_and_weights(map1, use_threshold) if len(points) == 0: if use_threshold: print 'No grid points above map threshold.' else: print 'Map has no non-zero values.' return move_tf, stats = motion_to_maximum(points, point_weights, map2, max_steps, ijk_step_size_min, ijk_step_size_max, optimize_translation, optimize_rotation) if initial_map1_transform: move_tf = Matrix.multiply_matrices(move_tf, initial_map1_transform) header = ('\nFit map %s in map %s using %d points\n' % (map1.name, map2.name, stats['points']) + ' correlation = %.4g, overlap = %.4g\n' % (stats['correlation'], stats['overlap']) + ' steps = %d, shift = %.3g, angle = %.3g degrees\n' % (stats['steps'], stats['shift'], stats['angle'])) print header #tfs = Matrix.transformation_description(move_tf) #print tfs xf = Matrix.chimera_xform(move_tf) map1.surface_model().openState.globalXform(xf)
def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME+'/music/'+self.party['map']['music']+'.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME+"/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME+"/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME+"/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME+"/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME+"/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask , 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start()
def testArchiving(self): '''Tests that archiving a matrix and then reading it back produces the same matrix''' filename = 'temp' self.matrix.writeToFile('temp') newMatrix = Matrix.matrixFromFile(filename) os.remove(filename) self.assertEqual(newMatrix, self.matrix)
def xform_changed_cb(self, trigName, myData, trigData): if 'transformation change' in trigData.reasons: xf = self.relative_xform() if xf: import Matrix if (self.last_relative_xform is None or Matrix.xforms_differ(xf, self.last_relative_xform)): self.last_relative_xform = xf self.update_metric_cb()
def write_grid_as_netcdf(grid_data, outpath, options = {}, progress = None): from Scientific.IO import NetCDF f = NetCDF.NetCDFFile(outpath, 'w') if progress: progress.close_on_cancel(f) # createDimension() cannot handle long integer size values xsize, ysize, zsize = map(int, grid_data.size) f.createDimension('x', xsize) f.createDimension('y', ysize) f.createDimension('z', zsize) f.xyz_origin = grid_data.origin f.xyz_step = grid_data.step if grid_data.cell_angles != (90,90,90): f.cell_angles = grid_data.cell_angles if grid_data.rotation != ((1,0,0),(0,1,0),(0,0,1)): import Matrix axis, angle = Matrix.rotation_axis_angle(grid_data.rotation) f.rotation_axis = axis f.rotation_angle = angle name = 'data' typecode = grid_data.value_type.char v = f.createVariable(name, typecode, ('z','y','x')) v.rgba = grid_data.rgba v.component_number = 1 save_unsigned_typecode(v, typecode) sarrays = subsample_arrays(grid_data, name, f) for k in range(zsize): if progress: progress.plane(k) values = grid_data.matrix((0,0,k), (xsize,ysize,1)) v[k,:,:] = values.view(v.typecode())[0,:,:] for cell_size, ssv in sarrays: kstep = cell_size[2] if k % kstep == 0: ssd = grid_data.available_subsamplings[cell_size] xs,ys,zs = ssd.size ssk = k/kstep if ssk < zs: values = ssd.matrix((0,0,ssk), (xs,ys,1)) ssv[ssk,:,:] = values.view(ssv.typecode())[0,:,:] # Subsample arrays may have an extra plane. for cell_size, ssv in sarrays: ssd = grid_data.available_subsamplings[cell_size] xs,ys,zs = ssd.size for ssk in range(zsize/cell_size[2], zs): values = ssd.matrix((0,0,ssk), (xs,ys,1)) ssv[ssk,:,:] = values.view(ssv.typecode())[0,:,:] f.close()
def mainGame(self): if not self.jobs.interface.jobs.board.update_required and not hasattr(self.jobs, "window-game_over"): ## XXX: GAME OVER board = self.jobs.interface.jobs.board Log.log("Game over, displaying game state") matrix = [ [(x, y) in board.blocks for x in xrange(board.blocks_width)] for y in xrange(board.blocks_height) ] Matrix.put(matrix, f="_") if ((len(self.highscores) < HIGHSCORES or any(board.score > score["score"] for score in self.highscores)) and not Shared.options.get("uber_tetromino") and not Shared.options.get("flip_tetromino") ): self.addJob("name_inputbox", Jobs.InputBox(self, "New Highscore!\nName: ")) self.running = self.getName else: self.addJob("window-game_over", Jobs.Notification(self, "window-game_over", "Game Over")) self.addJob("endtimer", Jobs.TimedExecution(self, self.quitGame, seconds=3, anykey=True))
def find_rotation(self, group): va = group._v_attrs if 'rotation_axis' in va and 'rotation_angle' in va: axis = va.rotation_axis angle = va.rotation_angle import Matrix r = Matrix.rotation_from_axis_angle(axis, angle) else: r = ((1,0,0),(0,1,0),(0,0,1)) return r
def __init__(self, path): import profec_format eg = profec_format.PROFEC_Potential(path) self.energy_grid = eg import Matrix r = Matrix.orthogonalize(eg.rotation) Grid_Data.__init__(self, eg.grid_size, origin = eg.origin, step = eg.step, rotation = r, path = path, file_type = 'profec')
def Schet(self): col = int(self.ui.lineEdit.text()) a = Matrix.matrix(col,col) for i in range(col): for j in range(col): a.set_value(i,j,self.ui.tableWidget.item(i,j).text()) if a.determinant() : b = a.Gauss_Jordan_inverse() for i in range(col): for j in range(col): self.ui.tableWidget_2.setItem(i,j,QtGui.QTableWidgetItem(str(b[i][j])))
def setUpPlayer (self, pos, clrBase = None, clrTurret = None): if self.side == 'player': self.maze.addPlayer (self) self.pos = pos self.vel = 0 self.cooldownTimer = 0 self.viewTheta = math.pi / 8 self.base = Graphics.cube (clrBase) self.base.transform (Matrix.scale (7.5, 7.5, 3.75)) self.base.translate (self.pos.x (), self.pos.y(), 10) self.turretp1 = Graphics.icosahedron (clrTurret) self.turretp1.transform (Matrix.scale (5, 5, 5)) self.turretp2 = Graphics.cube (clrTurret) self.turretp2.transform (Matrix.scale (1, 7.5, 1)) self.turretp2.translate (0, 3.5, 0) self.turret = self.turretp1.union (self.turretp2) self.turret.translate (self.pos.x (), self.pos.y(), 0) self.theta = 0 self.turretTheta = 0 self.changeAngle (math.pi / 4) self.alive = True
def main(argv=None): """ :param argv: the command line args :return: nothing """ if argv is None: argv = sys.argv n = 11 m = 10 down_txt = """1 3 4 4 3 1 4 3 1 4 3 4 2 4 3 3 2 4 4 2 2 2 2 1 4 2 0 2 4 0 1 1 2 2 1 0 2 3 1 4 0 0 4 3 0 4 2 3 4 3 3 4 1 3 3 4 0 3 4 3 0 4 4 3 2 3 4 1 4 2 1 0 4 2 0 2 1 4 0 0 3 1 3 4 3 0 2 1 1 3 2 1 3 3 3 2 0 3 2 0 4 0 2 3 1 1 2 4 4 4 0 4 4 4 3 4 1 2 3 0 4""" right_txt = """1 4 4 1 0 2 0 3 0 3 0 2 4 1 2 0 1 2 3 2 4 0 0 1 4 0 1 0 3 0 0 4 2 3 4 1 2 2 0 4 4 4 3 4 0 4 1 2 4 2 0 2 2 1 3 1 0 4 2 3 3 2 3 4 2 2 3 2 2 3 1 0 4 2 1 3 4 4 0 0 3 4 1 3 1 2 3 3 3 2 4 0 4 3 0 4 2 4 0 0 4 4 2 4 1 4 2 2 2 4 1 2 1 0 0 3 1 4 1 1""" down = Matrix.create_matrix(down_txt) right = Matrix.create_matrix(right_txt) print(get_longest_path(m,n,down,right))
def render(text, font, spaces=1, padding=False): """ Using a bitmap font represented as a 2d matrix, and some text represented as an ASCII string a new matrix is returned. This matrix contains the rendered blocktext. >>> Log.LOGLEVEL = 0 >>> Matrix.put(render("TEST", Load.loadBlockFont("standard")) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |#|#|#|_|#|#|#|_|#|#|#|_|#|#|#| |_|#|_|_|#|_|_|_|#|_|_|_|_|#|_| |_|#|_|_|#|#|#|_|_|#|_|_|_|#|_| |_|#|_|_|#|_|_|_|_|_|#|_|_|#|_| |_|#|_|_|#|#|#|_|#|#|#|_|_|#|_| """ Log.debug("Rendering blocktext {}".format(repr(text))) rows = len(getChar("invalid", font)) matrix = [[] for _ in xrange(rows)] if spaces: spacer = [[False for _ in xrange(spaces)] for _ in xrange(rows)] last = len(text); i = 0 if padding: Matrix.append(matrix, spacer) for char in text: i += 1 letter_matrix = getChar(char, font) Matrix.append(matrix, letter_matrix) if spaces and (i != last or padding): Matrix.append(matrix, spacer) return matrix
def __init__(self, **kwargs): super(MainMenu, self).__init__( "MainMenu", onHeaderClick=lambda: Webbrowser.open(PROJECT_SITE), header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, isroot=True, xcenter=True, soundtrack=Path.join(Load.MUSICDIR, "jazz_cat_infinite_loop_cut.ogg"), sound_enabled=SOUND_ENABLED, **kwargs) self.title_blocks = BlockText.render(TITLE_TEXT, font=Load.loadBlockFont("standard")) blockwidth = (self.width) // len(self.title_blocks[0]) Log.debug("title_board.blockwidth = {}".format(blockwidth)) self.addJob("title_board", Jobs.Board( self, y=SPACER, height=len(self.title_blocks), width=len(self.title_blocks[0]), blockwidth=blockwidth, bgcolor=self.bgcolor, queue=100, draw_grid=False, draw_border=False, ) ) self.jobs.title_board.x = (self.width // 2) - (self.jobs.title_board.width // 2) for x, y in Matrix.matrixToSet(self.title_blocks): self.jobs.title_board.blocks[(x, y)] = (0xaa,0xaa,0xaa) self.options_pos[1] = self.jobs.title_board.y + self.jobs.title_board.height + SPACER*2 self.menu = Factory.textBoxes([ ("Single Player", lambda: self.call(TetrisGame.TetrisGame, caption="Loltris")), ("Two Player", lambda: self.call(TwoPlayerTetrisGame.TwoPlayerTetris, caption="Loltris - Two Player")), ("LAN Play", lambda: self.call(LANTetrisGame.LANMenu, caption="Loltris - LAN play")), ("Options", lambda: self.call(OptionsMenu, caption="Loltris - Options")), ("Creative", lambda: self.call(MakeTetromino.MakeTetromino, caption="Loltris - Creator")), ("Scores", lambda: self.call(HighscoreExplorer.HighscoreList, caption="Loltris - Highscores")), ("Credits", lambda: self.call(Credits.Credits, caption="Loltris - Credits")), ("Homepage", lambda: Webbrowser.open(PROJECT_SITE)), ("SandBox", lambda: self.call(SandBox.SandBox, caption="Loltris - SandBox")), ("Exit", self.quit), ], self, font=MENU_OPTION_FONT, fill=MENU_3DBORDER_BACKGROUND, xcenter=True, colors={ "background":self.colorscheme["background"], "font":self.colorscheme["option"], }, ) self.setupObjects() #self.loadHighscores() ## XXX: Temporary bugfix, scroll_filler is drawn on every frame while the board is not. del self.jobs.scroll_filler
def callback(): output_file = open("host.txt", "w") color = ["Blue","Green","Orange","Red"][var.get()] difficulty = ["easy", "average", "hard"][diff.get()] new_host = Matrix.host(color, difficulty) output_file.write(str(new_host.color) +" " + str(new_host.security_value) + " - ") output_file.write(str(new_host.subsystems["Access"]) + "/" + str(new_host.subsystems["Control"]) + "/") output_file.write(str(new_host.subsystems["Index"]) + "/" + str(new_host.subsystems["Files"]) + "/") output_file.write(str(new_host.subsystems["Slave"]) + "\n\n\n") for line in new_host.sheaf: output_file.write(line + "\n") output_file.write('\n\nPaydata Points\n') for point in new_host.paydata: output_file.write("> " + str(point[0]) + " Mp -- " + str(point[1]) + "\n")