def subDeterminedMAG(H, zeta): """Returns a sub-determined MAG, i.e. a MAG with aggregated aspects according to the sub-determination tuple zeta. The tuple zeta has the same number of elements as the number of aspects on the original MAG H, and for each aspect carries a value 1 or 0, so that only the aspects marked with 1 will remain on the resulted MAG. The resulting sub-determined MAG has the edges of the original MAG projected over the reduced aspect structure given by the sub-determination. input: MAG H and sub-determination tuple zeta output: Sub-determined MAG Hz """ E = H[1] Ez = set() asps = list(zeta) + list(zeta) n = len(asps) for e in E: ez = [] for i in range(n): if asps[i] != 0: ez.append(e[i]) if alg.pi_o(ez) != alg.pi_d(ez): Ez.add(tuple(ez)) A = buildAspectListFromEdges(Ez) return A,Ez
def subDeterminedMAG(H, zeta): """Returns a sub-determined MAG, i.e. a MAG with aggregated aspects according to the sub-determination tuple zeta. The tuple zeta has the same number of elements as the number of aspects on the original MAG H, and for each aspect carries a value 1 or 0, so that only the aspects marked with 1 will remain on the resulted MAG. The resulting sub-determined MAG has the edges of the original MAG projected over the reduced aspect structure given by the sub-determination. input: MAG H and sub-determination tuple zeta output: Sub-determined MAG Hz """ E = H[1] Ez = set() asps = list(zeta) + list(zeta) n = len(asps) for e in E: ez = [] for i in range(n): if asps[i] != 0: ez.append(e[i]) if alg.pi_o(ez) != alg.pi_d(ez): Ez.add(tuple(ez)) A = buildAspectListFromEdges(Ez) return A, Ez
def make_model(self): df = self.df0[[ "m5_change", "m10_change", "m15_change", "m20_change", "m60_change", "rolling_mean" ]].astype(float) df['prediction'] = df['m60_change'].shift(-1) df = df.fillna(0) df.loc[df.prediction >= 0, 'prediction'] = 1 df.loc[df.prediction < 0, 'prediction'] = 0 df_len = len(df) end = int(0.7 * df_len) features = df.columns[:-1] x = df[features] y = df.prediction x_train = x[:end] y_train = y[:end] x_test = x[end:] y_test = y[end:] algo.performRFClass(x_train, y_train, x_test, y_test, self.symbol, True)
def testSimpleProcess(): N = 90024247 e = 2706925 p, q = Algorithms.findFactors(N) print str(p) + ":" + str(q) phi = Algorithms.calcEulersTotient(p, q) sub_1, mult_sub_1, sub_2, mult_sub_2 = Setup.calcSecretExponent(e, phi) d = mult_sub_1 if(e == sub_2): d = mult_sub_2 print str(e) + ":" + str(d) encry_result = Message.encryptMessage("i love math", N, e, ref_ch_to_int) print "encry_result: " + str(encry_result) decry_result = Message.decryptMessage(encry_result, N, d, ref_int_to_ch) print "decry_result: " + decry_result encry_result_A = Message.encryptMessage("the answer is a", N, e, ref_ch_to_int) print "encry_result_A: " + str(encry_result_A) sig_A = 84069637 decry_result_A = Message.decryptMessageSig(encry_result_A, N, d, ref_int_to_ch, sig_A, e) print "decry_result_A: " + decry_result_A encry_result_B = Message.encryptMessage("the answer is b", N, e, ref_ch_to_int) print "encry_result_B: " + str(encry_result_B) sig_B = 84066637 decry_result_B = Message.decryptMessageSig(encry_result_B, N, d, ref_int_to_ch, sig_B, e) print "decry_result_B: " + decry_result_B
def main(): os.system("clear") try: print(f'Bienvenido \nEste programa retornara la raiz cudrada de algun numero \n Se puede elegir entre diferentes algoritmos para llevar a cabo la tarea') print('Algoritmos: \n1.-Busqueda Binaria\n2.-Enumeracion exhaustiva\n3.-Aproximacion de soluciones') objetivo = int(input("Escriba el numero del que desea obtener la raiz cuadrada: \n>>")) algoritmo = int(input('Que algoritmo quiere usar? \n>>')) if algoritmo == 2: alg.Enum(objetivo) elif algoritmo == 3: alg.Aprox(objetivo) elif algoritmo >= 4: print("Por favor escoge una opcion de algoritmo valido!") else: alg.Binary(objetivo) repeat = input('Quiere repetir la operacion (Y/n)?') if repeat.upper() == 'Y': main() else: os.system("clear") exit() except ValueError: print(f'Por favor, introduce los valores requeridos!')
def testAvoidBloodVesselsValidPath(self): entriesID = [235,243,244,255,256,262,263,270] targetsID = [1,2,3,4,8,9,10,11] entriesAndTargets = Algorithms.addEntriesAndTargetsInDictFromID(entriesID,targetsID) vessels = slicer.util.getNode("vessels") result = Algorithms.getIncisionsWithValidArea(entriesAndTargets, vessels) self.assertTrue(len(result) > 0) self.delayDisplay('testAvoidBloodVesselsValidPath passed!')
def testAvoidVentriclesInvalidPath(self): entriesID = [4,5,7,11,12,16,17,33] targetsID = [3,4,5,6,7,10,11,12] entriesAndTargets = Algorithms.addEntriesAndTargetsInDictFromID(entriesID,targetsID) ventricles = slicer.util.getNode("ventricles") result = Algorithms.getIncisionsWithValidArea(entriesAndTargets, ventricles) self.assertTrue(len(result) > 0) self.delayDisplay('testAvoidBloodVesselsValidPath passed!')
def testAvoidVentriclesValidPath(self): entriesID = [451,452,453,454,455,456,457,458] targetsID = [161,162,163,164,165,166,167,168] entriesAndTargets = Algorithms.addEntriesAndTargetsInDictFromID(entriesID,targetsID) ventricles = slicer.util.getNode("ventricles") result = Algorithms.getIncisionsWithValidArea(entriesAndTargets, ventricles) self.assertTrue(len(result) > 0) self.delayDisplay('testAvoidBloodVesselsValidPath passed!')
def cvToAdjMatrixRow(v, A_H): """ Returns the matrix line corresponding to a composite vertex :input composite vertex v in its symbolic tuple form, and MAG's Aspect list A_H :output numeric representation of the composite vertex The numeric representation of a composite vertex directly indicates its corresponding row and column on the adjacency matrix """ T_H = alg.CompTuple(A_H) return alg.D(idxV(v, A_H), T_H)
def testAvoidBloodVesselsInvalidPath(self): entriesID = [35,56,70,73,85,94,95,129] targetsID = [25,26,46,47,52,54,55,69] entriesAndTargets = Algorithms.addEntriesAndTargetsInDictFromID(entriesID,targetsID) vessels = slicer.util.getNode("vessels") result = Algorithms.getIncisionsWithValidArea(entriesAndTargets, vessels) self.assertTrue(len(result) > 0) self.delayDisplay('testAvoidBloodVesselsInvalidPath passed!')
def adjMatrixRowToCv(n, A_H): """ Returns the composite vertex corresponding to a matrix line :input numeric representation of the composite vertex n, and MAG's Aspect list A_H :output composite vertex in its symbolic tuple form The numeric representation of a composite vertex directly indicates its corresponding row and column on the adjacency matrix This function is the inverse of cvToAdjMatrixRow """ T_H = alg.CompTuple(A_H) return invIdxV(alg.InvD(n, T_H), A_H)
def testPoorChoice(): N = 181043 e = 5 p, q = Algorithms.findFactors(N) phi = Algorithms.calcEulersTotient(p, q) sub_1, mult_sub_1, sub_2, mult_sub_2 = Setup.calcSecretExponent(e, phi) d = mult_sub_1 if e == sub_2: d = mult_sub_2 encrypts = [77739] # 5430, 133606 decry_result = Message.decryptMessage(encrypts, N, d, ref_int_to_ch) print "decry_result: " + decry_result
def choosePolicy(self): if (self.WhichAlgorithm == 1): self.Policy = AG.UCB() elif (self.WhichAlgorithm == 2): self.Policy = AG.lri() else: self.Policy = AG.lrp() for index in range(self.k): if (self.WhichAlgorithm == 1): self.ProbArr.append(0) else: self.ProbArr.append(1.0/self.k) #For LRI or LRP style choosing
def main(): # Reset out open("out", "w").close() for k in [5, 10, 20]: for vertex_amount_index in range(11, 31): vertex_amount = vertex_amount_index * 50 print(k, vertex_amount) sum_distances = [] sum_time = [] vertices = Generator.generate_fancy_clusters((5000, 5000), k, vertex_amount, 100) for test_index in range(10): print(test_index) sum_distances.append([]) sum_time.append([]) for algo in [Algorithms.k_means, Algorithms.agglomerative_brute, Algorithms.agglomerative_matrix, Algorithms.divisive]: for recalculate in [Algorithms.recalculate_clusters_average, Algorithms.recalculate_clusters_medoid]: start_time = time() colored_array, cluster_array = algo(k, vertices, 100, recalculate) sum_time[test_index].append(time() - start_time) avg = Algorithms.calculate_average_offsets(colored_array[-1], cluster_array[-1]) avg = Algorithms.average_int(avg) sum_distances[test_index].append(avg) with open("out", "a") as file: average_distances = list([Algorithms.average_float(sum_distances, key=lambda x: x[i]) for i in range(len(sum_distances[0]))]) average_time = list([Algorithms.average_float(sum_time, key=lambda x: x[i]) for i in range(len(sum_time[0]))]) print(k, vertex_amount, "||", " ".join([str(x) for x in average_distances]), "|", " ".join([str(x) for x in average_time]), file=file)
def NumeroDiPrimi(s): x = 0 for i in s: if Algorithms.IsPrime(i): x += 1 else: return x
def btn_calc_power_matrix(self): if self.leftMatSize[0] != self.leftMatSize[1]: messagebox.showerror(title=_("Matrix Assistant"), message=_("the matrix must be square!")) return try: n = int(self.powExp.get()) if n == 0 or n == 1 or n < -1: raise Exception() except: messagebox.showerror( title=_("Matrix Assistant"), message=_( "the power exponent must be one of {-1, 2, 3, and bigger}!" )) return Application.clearControls(self.resultMatrix) leftMat = Application.getDataFromEntries(self.leftMatrix, self.leftMatSize) if leftMat: if n == -1: self.btn_calc_inverse_matrix() return else: res = copy.deepcopy(leftMat) for i in range(n - 1): res = Algorithms.multiplyMatrix(res, leftMat) for i in range(self.leftMatSize[0]): for j in range(self.leftMatSize[0]): self.resultMatrix[i * MATRIX_SIZE + j].insert( 0, res[i][j])
def test_refreshP_simulating(self): g = Linking.Graph() for i in range(5): g.add_vertex(i) # 0 1 # \ / \ # 2 3 # / # 4 g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(1, 3) g.add_edge(2, 4) al = Algorithms.algorithms(g.vert_dict) al.generateProbabilityTable() al.setProbabilityTable(0, 'T', 0.1) al.setProbabilityTable(1, 'T', 0.5) al.setProbabilityTable(2, 'TT', 1) al.setProbabilityTable(2, 'TF', 1) al.setProbabilityTable(2, 'FT', 0.5) al.setProbabilityTable(2, 'FF', 0.01) al.setProbabilityTable(3, 'T', 0.8) al.setProbabilityTable(3, 'F', 0.01) al.setProbabilityTable(4, 'T', 0.1) al.setProbabilityTable(4, 'F', 0.01) al.simulateData(10000) obs = {3: 'T', 4: 'T'} self.assertTrue(math.fabs(al.query(obs, 0) - 0.17) <= 0.05) self.assertTrue(math.fabs(al.query(obs, 1) - 1) <= 0.05) self.assertTrue(math.fabs(al.query(obs, 2) - 0.92) <= 0.05) self.assertTrue(math.fabs(al.query(obs, 3) - 1) <= 0.05) self.assertTrue(math.fabs(al.query(obs, 4) - 1) <= 0.05)
def test_setKnownPT(self): g = Linking.Graph() for i in range(5): g.add_vertex(i) # 0 1 # \ / \ # 2 3 # / # 4 g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(1, 3) g.add_edge(2, 4) al = Algorithms.algorithms(g.vert_dict) al.generateProbabilityTable() al.setKnownPT(0, 'T', 0.1) al.setKnownPT(1, 'T', 0.5) al.setKnownPT(2, 'TT', 1) al.setKnownPT(2, 'TF', 1) al.setKnownPT(2, 'FT', 0.5) al.setKnownPT(2, 'FF', 0.01) al.setKnownPT(3, 'T', 0.8) al.setKnownPT(3, 'F', 0.01) al.setKnownPT(4, 'T', 0.1) al.setKnownPT(4, 'F', 0.01) v = g.get_vertex(2).probabilityTable['TT'][0] #node 2 self.assertTrue(v == 1) #expect v =1 v = g.get_vertex(3).probabilityTable['T'][0] #node 3 self.assertTrue(v == 0.8) #expect v = 0.8 v = g.get_vertex(4).probabilityTable['T'][0] #node 4 self.assertTrue(v == 0.1) #expect v = 0.1 v = g.get_vertex(0).probabilityTable['T'][0] #node 0 self.assertTrue(v == 0.1) #expect v = 0.1 v = g.get_vertex(1).probabilityTable['T'][0] #node 1 self.assertTrue(v == 0.5) #expect v = 0.5
def genUV_Textures(key): if self.PE is None: self.PE = Algorithms.People_Extractor( "/shared/bodyMetrics.json") if self.UV is None: self.UV = Algorithms.UV_Extractor() image = db.getData("modanetImages", key) image = white_balance(image) boxes, bodys = db.getData("densepose", key) people, mergedIUVs = self.PE.extract( boxes, bodys, image) data = self.UV.extract( people, mergedIUVs, image, 64 ) # This 64 is prob suppose to be set by algortihm, but oh well db.saveData("UV_Textures", key, data, "ndarray") return data
def dynamic_wotr(str_A=None, str_B=None): if str_A: ED2, ed2, tr2, newA, newB = Algorithms.edit_distance_wotr(str_A, str_B) ED2 = ED2.tolist() arr_A = list(str_A) arr_B = list(str_B) for idx, zz in enumerate(newA): if newA[idx] == '-': newA[idx] = newA[idx] else: newA[idx] = newA[idx].decode('utf-8') for idx, zz in enumerate(newB): if newB[idx] == '-': newB[idx] = newB[idx] else: newB[idx] = newB[idx].decode('utf-8') return render_template("dynamicwithouttraceback.html", EDI=ED2, tr2=tr2, str_A=str_A, str_B=str_B, arr_A=arr_A, arr_B=arr_B, edInt=ed2, newA=newA, newB=newB) else: return render_template("dynamicwithouttraceback.html", str_A=str_A, str_B=str_B)
def testAvoidBloodVesselsInvalidPath(self): bloodVessels = self.getNode(self.VESSEL_NODE_LABEL) entriesAndTargets = {(212.09, 147.385, 76.878): [[158.0, 133.0, 82.0]]} result = Algorithms.getIncisionsWithValidArea(entriesAndTargets, bloodVessels) self.assertTrue(len(result) == 0) self.delayDisplay('testAvoidBloodVesselsInvalidPath passed!')
def _KSVMtrain(X, Y, kernel_dict): m = Y.shape[0] if kernel_dict['type'] == 'RBF': K = Kernel.RBF(m, kernel_dict['gamma']) K.calculate(X) elif kernel_dict['type'] == 'LINEAR': K = Kernel.LINEAR(m) K.calculate(X) elif kernel_dict['type'] == 'POLY': K = Kernel.POLY(m) K.calculate(X) elif kernel_dict['type'] == 'TANH': K = Kernel.TANH(m, kernel_dict['c'], kernel_dict['d']) K.calculate(X) elif kernel_dict['type'] == 'TL1': K = Kernel.TL1(m, kernel_dict['rho']) K.calculate(X) p1, p2 = trans_mat(K.kernelMat) K.kernelMat = np.dot((p1 - p2), K.kernelMat) #根据SVM求出alpha,b ??? svm = Algorithms.SVM(X, Y, kernel_dict) #更新alpha alpha = np.dot((p1 - p2), svm.alphas) b = svm.b return (alpha, b, K)
def __init__(self): self.stemming_on = False self.stop_word_on = False self.summary = False self.use_threshold = False self.max_words_in_summary = 100 self.keep_all = True # by default do not exclude dupe words self.normalize = False self.rval = 0 self.score = 'size' # size | tfidf | stfidf self.update = False self.penalty = False self.total_sentences = 0 self.sentence_dictionary = defaultdict(list) # map of modified sentences to actual sentences (tokenized) self.dictionary = {} # keys are final tokenized output # values are 2-tuple of original sentence and size self.mod_words = () # all unique words of document self.mod_sentences = ((),) self.unique_sent = ((),) self.alg = Alg.Algorithms() self.stemmer = EnglishStemmer() self.doc_size = 0
def test_generatePriorProbability(self): g = Linking.Graph() for i in range(5): g.add_vertex(i) # 0 1 # \ / \ # 2 3 # / # 4 g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(1, 3) g.add_edge(2, 4) al = Algorithms.algorithms(g.vert_dict) al.generateProbabilityTable() al.setKnownPT(0, 'T', 0.1) al.setKnownPT(1, 'T', 0.5) al.setKnownPT(2, 'TT', 1) al.setKnownPT(2, 'TF', 1) al.setKnownPT(2, 'FT', 0.5) al.setKnownPT(2, 'FF', 0.01) al.setKnownPT(3, 'T', 0.8) al.setKnownPT(3, 'F', 0.01) al.setKnownPT(4, 'T', 0.1) al.setKnownPT(4, 'F', 0.01) al.generatePriorProbability() self.assertTrue(g.get_vertex(0).probability == 0.1) self.assertTrue(g.get_vertex(1).probability == 0.5) self.assertTrue(g.get_vertex(2).probability == 0.3295) self.assertTrue(g.get_vertex(3).probability == 0.405) self.assertTrue(g.get_vertex(4).probability == 0.039655)
def test_valueIteration(self): g = Linking.Grid(2, 2) g.grid_dict[0].reward = -4 g.grid_dict[1].utility = 100 g.grid_dict[1].reward = 100 g.grid_dict[2].utility = -100 g.grid_dict[2].reward = -100 g.setObstacle(3) al = Algorithms.algorithms(g.grid_dict) action = {'forward': 0.8, 'left': 0.1, 'right': 0.1} discount = 0.9 expexted = {0: 64.83478199000001, 1: 100, 2: -100, 3: 0} # print(al.valueIteration(discount,action,g)) self.assertDictEqual(al.valueIteration(discount, action, g), expexted) #another test g = Linking.Grid(4, 3) for i in g.grid_dict: if i != 5: g.grid_dict[i].reward = -4 g.grid_dict[3].utility = 100 g.grid_dict[3].reward = 100 g.grid_dict[7].utility = -100 g.grid_dict[7].reward = -100 g.setObstacle(5) al = Algorithms.algorithms(g.grid_dict) action = {'forward': 0.8, 'left': 0.1, 'right': 0.1} discount = 0.9 expexted = { 0: 50.94115412930875, 1: 64.95855729696827, 2: 79.5362031683467, 3: 100, 4: 39.85041277059019, 5: 0, 6: 48.6439148544741, 7: -100, 8: 29.64382885103273, 9: 25.391792612055916, 10: 34.476553020311734, 11: 12.99228937944113 } # print(al.valueIteration(discount,action,g)) self.assertDictEqual(al.valueIteration(discount, action, g), expexted)
def main(self): grid = self.make_grid() # initialize the start and end position start = None end = None # True if we run the main loop run = True while run: self.draw(grid) for event in pygame.event.get(): if run == False: break if event.type == pygame.QUIT: run = False # the left key on the mouse is pressed if pygame.mouse.get_pressed()[0]: pos = pygame.mouse.get_pos() # the mouse position on the screen row, col = self.get_clicked_pos(pos, self.args.rows, self.args.width) spot = grid[row][col] if not start and spot != end: start = spot start.make_start() elif not end and spot != start: end = spot end.make_end() # we already defined the start and end positions elif start and end and spot != start and spot != end: spot.make_barrier() # the right key on the mouse is pressed elif pygame.mouse.get_pressed()[2]: pos = pygame.mouse.get_pos() # the mouse position on the screen row, col = self.get_clicked_pos(pos, self.args.rows, self.args.width) # translate to the right cube spot = grid[row][col] spot.reset() # the two variables that were initialized if spot == start: start = None elif spot == end: end = None # the key is pressed down if event.type == pygame.KEYDOWN: # the key is the space key if event.key == pygame.K_SPACE and start and end: for row in grid: for spot in row: spot.update_neighbors(grid) algorithm = Algorithms.Algorithm(self.win, lambda: self.draw(grid), grid, start, end, self.args.algorithm_name) try: self.run_algorithm(algorithm) except pygame.error: run = False continue # clear the screen if event.key == pygame.K_c: start = None end = None grid = self.make_grid() pygame.quit()
def printAStar(dim, p, q): #print an A* maze pygame.display.set_caption("A* Maze") maze = Algorithms.makeMaze(dim, p) initial = Algorithms.State(0, 0, 0, None) goal = Algorithms.State(dim - 1, dim - 1, 0, None) route = Algorithms.checkAStar(dim, maze, initial, goal)[0] grid = makeMazeArray(maze, dim) for i in range(len(route)): grid[route[i][0]][route[i][1]] = 3 grid[0][0] = 4 grid[dim - 1][dim - 1] = 4 return grid
def btn_determinant(self): self.clearResult() a = self.getVectorA() b = self.getVectorB() c = self.getVectorC() if a and b and c: data = [[a.x, a.y, a.z], [b.x, b.y, b.z], [c.x, c.y, c.z]] self.setScalarResult(Algorithms.calcDet(data))
def decryptMessageSig(m_encrypts, N, d, ref_int_to_ch, sig, e): # Compute m_decrypt = m_encrypt^d mod n conversions = [] for i in xrange(0, len(m_encrypts), 1): m_encrypt = m_encrypts[i] m_decrypt = Algorithms.calcLargeMod(m_encrypt, d, N) conversion = convertIntToMessage(m_decrypt, ref_int_to_ch) conversions.append(conversion) # print "m_encrypt: " + str(m_encrypt) # print "m_decrypt: " + str(m_decrypt) # print "conversion: " + conversion # This part will calculate the original signature to see # if it came from the correct sender. m_orig_hash = Algorithms.calcLargeMod(sig, e, N) # print "m_orig_hash: " + str(m_orig_hash) # print "-----------------------" return " ".join(conversions)
def testGetFilteredHippocampusInvalidTargets(self): hippocampus = self.getNode(self.HIPPOCAMPUS_NODE_LABEL) coordinates = [0, 1, 2] targets = slicer.vtkMRMLMarkupsFiducialNode() targets.AddFiducialFromArray(coordinates) filteredTargets = Algorithms.getValidTargets(targets, hippocampus) self.assertTrue(len(filteredTargets) == 0) self.delayDisplay('testGetFilteredHippocampusInvalidTargets passed!')
def testCountRejectedByHardConstraints(self, entries, targets, hippocampus, bloodVesselsDilate, bloodVessels, cortex, angle, distanceThreshold, total, printOutput): entriesAndTargets = Algorithms.entriesAndTargetsInDict( entries, Algorithms.convertMarkupNodeToPoints(targets)) self.testCountRejectedTrajectoriesForDistanceThreshold( entriesAndTargets, distanceThreshold, total, printOutput) self.testCountRejectedTrajectoriesForBloodVesselsDilate( entriesAndTargets, bloodVesselsDilate, total, printOutput) self.testCountRejectedTrajectoriesForBloodVessels( entriesAndTargets, bloodVessels, total, printOutput) self.testCountRejectedTrajectoriesForAngle(entriesAndTargets, cortex, angle, total, printOutput) self.testCountRejectedTrajectoriesCombiningAllHard( entries, targets, hippocampus, bloodVesselsDilate, bloodVessels, cortex, angle, total, printOutput)
def myArithmeticMean(self, model, variable, data, unit): """ Determine arithmetic mean of signal """ time = data[0] values = data[1] (Tmin, Tmax) = getTimeRange(time) (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax) vMean = Algorithms.arithmeticMean(timeInRange, valuesInRange) tMean = timeInRange[0] + (timeInRange[-1] - timeInRange[0]) / 2 plotSignalAndFeature(variable, time, values, unit, "mean", tMean, vMean, Tmin, Tmax, markFeature=False)
def permMatSign(P): IntRing=Modular.Integer() v=Mat(IntRing,P.n,1) for i in xrange(P.n): v.setElt(i,0,IntRing.make(i)) permVec=P.apply(v) perm=[] for i in xrange(permVec.m): perm.append(permVec.getElt(i,0)) return Algorithms.permSign(perm)
def myRootMeanSquare(self, model, variable, data, unit): """ Determine root mean square of signal """ time = data[0] values = data[1] (Tmin, Tmax) = getTimeRange(time) (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax) vMean = Algorithms.rootMeanSquare(timeInRange, valuesInRange) tMean = timeInRange[0] + (timeInRange[-1] - timeInRange[0]) / 2 plotSignalAndFeature(variable, time, values, unit, "rms", tMean, vMean, Tmin, Tmax, markFeature=False)
def crappyDet(self): sum=self.ring.zero() for perm in itertools.permutations(range(self.n)): product=self.ring.one() i=0 for j in perm: product=self.ring.mul(product,self.getElt(i,j)) i=i+1 if Algorithms.permSign(perm)<0: sum=self.ring.sub(sum,product) else: sum=self.ring.add(sum,product) return sum
def plotFFT(widget): """ Determine fft of signals in selected widget """ print("plotFFT") model = "" for (modelNumber, modelName, variableName), data in widget.getData(): # print "var:", var, "data: ", data minVal = (0, float("inf")) maxVal = (0, float("-inf")) # for time, value in data: # Get data from data array: time = numpy.array(list((x for x, _ in data))) # data[0] values = numpy.array(list((x for _ , x in data))) (Tmin, Tmax, N) = getFFTtimeRange(time) (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax) # Compute fft: A=A(f) import Algorithms (f, A) = Algorithms.fft(timeInRange, valuesInRange, N) # Open new plot tab: import plotWidget window = widget.createNewWindow() container = plotWidget.plotContainer(window) plotWidget = plotWidget.PlotWidget(container) container.setPlotWidget(plotWidget) # Create the plot plotdata = ArrayPlotData(x=f, y=A, border_visible=True, overlay_border=True) plot = Plot(plotdata, title="FFT") # Plot(plotdata, title="FFT") barPlot = plot.plot(("x", "y"), type="bar", bar_width=0.1, color="blue")[0] # scatterPlot = plot.plot(("x", "y"), type="scatter", color="blue")[0] # Attach some tools to the plot plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) # Activate Plot: plotWidget.setPlot(plot) container.setPlotWidget(plotWidget) layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom) layout.addWidget(container) window.setLayout(layout) window.show()
def test_twoblobs(self): array = numpy.zeros([12, 12], "float") for i in range(3, 10): # top edge array[2, i] = 1 for i in range(2, 7): # far left side array[i, 2] = 1 # bottom left side array[7, i] = 1 for i in range(4, 8): # inner left side (left bump) array[i, 6] = 1 # spacer array[4, 7] = 1 for i in range(4, 8): # inner right side (right bump) array[i, 8] = 1 for i in range(7, 10): array[i, 7] = 1 for i in range(7, 10): # bottom right side array[9, i] = 1 for i in range(2, 10): # far right side array[i, 10] = 1 isinside = Algorithms.segment(array) answer = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] for i in range(0, len(answer)): for j in range(0, len(answer[i])): self.assertTrue(isinside[i][j] == answer[i][j])
def myFFT(self, model, variable, data, unit): time = data[0] values = data[1] (Tmin, Tmax, N) = getFFTtimeRange(time) (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax) # Compute fft: A=A(f) (f, A) = Algorithms.fft(timeInRange, valuesInRange, N) # Plot A=A(f) plt.figure() plt.plot(f, A) plt.grid() plt.xlabel("frequency [Hz]") if isinstance(unit, str) and unit != "": plt.ylabel("amplitude [" + unit + "]") else: plt.ylabel("amplitude") plt.show()
def inv(self,x): if (x==0): raise Exception("div by zero") (gcd,a,b)=Algorithms.euclid(x,self.q) return self.make(a)
def plotFFTPlusTHD(widget): """ Determine fft of signals in selected widget and calculate Total harmonic disturbance""" print("plotFFT and Total Harmonic Disturbance") model = "" for (modelNumber, modelName, variableName), data in widget.getData(): # print "var:", var, "data: ", data minVal = (0, float("inf")) maxVal = (0, float("-inf")) # for time, value in data: # Get data from data array: time = numpy.array(list((x for x, _ in data))) # data[0] values = numpy.array(list((x for _ , x in data))) unit = "" (Tmin, Tmax, N) = getFFTtimeRange(time) (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax) # Compute fft: A=A(f) import Algorithms (f, A) = Algorithms.fft(timeInRange, valuesInRange, N) #******* START THD CALCULATION ************* # Estimate fundamental frequency: maxindex = A.argmax() estimation = f[maxindex] def getExFreq(estimation): return estimation """ Inquire im measured fundamental frequency is correct: """ ''' import guidata guidata.qapplication() import guidata.dataset.dataitems as di import guidata.dataset.datatypes as dt class Processing(dt.DataSet): """ Fundamental Frequency """ correctedFreq = di.FloatItem("fundamental frequency [Hz]", default=estimation) param = Processing() okPressed = param.edit() if okPressed: return param.correctedFreq else: # Cancel button pressed return estimation ''' # Ask for a better fundamental frequency exFreq = max(0, min(f.max(), getExFreq(estimation))) # Check if we have at least one harmonic: if exFreq > 0.5 * f.max(): print "THD calculation not possible, extend frequency window to at least 2*fundamental frequency" THD = 999 else: # Get 5% window around fundamental frequency and calculate power: mask = (f > exFreq * 0.975) & (f < exFreq * 1.025) print "Calculating fundamental energy from points: frequency=%s, Amplitude=%s" % (f[mask], A[mask]) P1 = numpy.vdot(A[mask], A[mask]) # squared amplitude PH = 0 # Sum up the Power of all harmonic frequencies in spectrum: noHarmonics = numpy.int(numpy.floor(f.max() / exFreq)) for i in range(noHarmonics - 1): mask = (f > (i + 2) * exFreq * 0.975) & (f < (i + 2) * exFreq * 1.025) PH = PH + (numpy.vdot(A[mask], A[mask])) # squared amplitude THD = PH / P1 * 100 #******* END THD CALCULATION ************* # Open new plot tab: import plotWidget window = widget.createNewWindow() container = plotWidget.plotContainer(window) plotWidget = plotWidget.PlotWidget(container) container.setPlotWidget(plotWidget) # Plot data plotdata = ArrayPlotData(x=f, y=A, border_visible=True, overlay_border=True) plot = Plot(plotdata, title="FFT") # Plot(plotdata, title="FFT") barPlot = plot.plot(("x", "y"), type="bar", bar_width=0.3, color="blue")[0] # Attach some tools to the plot plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) # Activate Plot: plotWidget.setPlot(plot) if THD != 999: thdLabel = DataLabel(component=plotWidget.plot, data_point=(f[A.argmax()], A.max()), label_position="bottom right", padding_bottom=20, marker_color="transparent", marker_size=8, marker="circle", arrow_visible=False, label_format=str('THD = %.4g percent based on %d harmonics of the %.4g Hz frequency' % (THD, noHarmonics, exFreq))) plotWidget.plot.overlays.append(thdLabel) container.setPlotWidget(plotWidget) layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom) layout.addWidget(container) window.setLayout(layout) window.show()