def solveGreedy(game, over, dir): estimation = manhattanDistance(game, over) max = 0 caminho[AuxFunctions.returnString(game)] = AuxFunctions.returnString(game) distancias = [] # Implementacao de heap em ordem das distancias heapq.heapify(distancias) heapq.heappush(distancias, (estimation, game)) while not len(distancias) == 0: node = heapq.heappop(distancias) repetidos[AuxFunctions.returnString(node[1])] = 1 index = node[1].index(0) for value in dir[index]: # Troca de elementos, acedendo a segunda posicao do tuplo node1 = node[1][:] node1[index + value], node1[index] = node1[index], node1[index + value] node1String = AuxFunctions.returnString(node1) if not caminho.get(node1String): caminho[node1String] = AuxFunctions.returnString(node[1]) dis = manhattanDistance(node1, over) if dis == 0: print "Tiveram em dada altura um maximo de", max, "nos na fila." return node if not repetidos.get(node1String): heapq.heappush(distancias, (dis, node1[:])) if len(distancias) > max: max = len(distancias)
def solveIDFS(game, over, dir): nivel_limite = 0 max = 0 while True: stack = [game] repetidos.clear() dis.clear() dis[game] = 0 while not len(stack) == 0: node = stack.pop(0) if AuxFunctions.isSolution(list(node), list(over)): print "Tiveram em dada altura um maximo de", max, "nos na fila." return nivel_limite index = node.index('0') if dis.get(node) < nivel_limite: for value in dir[index]: nodeTrader = list(node)[:] nodeTrader[index+value], nodeTrader[index] = nodeTrader[index], nodeTrader[index+value] nodeTraderString = AuxFunctions.returnString(nodeTrader) if not caminho.get(nodeTraderString): caminho[nodeTraderString] = node if not dis.get(nodeTraderString) or dis.get(node) + 1 < dis.get(nodeTraderString): dis[nodeTraderString] = dis.get(node) + 1 stack.insert(0, nodeTraderString) print len(stack) if len(stack) > max: max = len(stack) nivel_limite += 1
def manhattanDistance(game, over): gameString = AuxFunctions.returnString(game) overString = AuxFunctions.returnString(over) distancias = {0: 0, 1: 1, 2: 2, 3: 1, 4: 2, 5: 3, 6: 2, 7: 3, 8: 4} soma = 0 for x in range(1, 9): subtracao = gameString.index(str(x)) - overString.index(str(x)) d = math.fabs(subtracao) if subtracao == 1 and (gameString.index(str(x)) == 2 or gameString.index(str(x)) == 5): d = 5 soma += distancias[int(d)] return soma
def calculate_features_for_all_graphs(self): graph_number = 0 # We use this to later save f_vector result in dict for data in self.graphs: graph_number += 1 self.scored_graphs.append( (data[0], AuxFunctions.get_features_for_graph( self.features, data[0], self.sentence_tags[graph_number - 1], self.is_improved), data[1], AuxFunctions.get_features_for_graph( self.features, data[1], self.sentence_tags[graph_number - 1], self.is_improved), graph_number))
def data_inference(self, unlabeled_document_name, output_name, w): sentence_words_pos = dict() sentence_num = 0 with open(unlabeled_document_name, 'r') as f1: with open(output_name, 'w+') as f2: for line in f1: if line == '\n': data_for_full_graph = set() words_tags = dict() for counter in sentence_words_pos: word_tuple = sentence_words_pos[counter] data_for_full_graph.add( (word_tuple[0], word_tuple[1], counter)) words_tags[counter] = sentence_words_pos[counter][ 1] data_for_full_graph.add(('root', 'root', 0)) sentence_words_pos[0] = ('root', 'root', 0) words_tags[0] = 'root' full_unweighted_g = AuxFunctions.make_full_graph( list(data_for_full_graph)) g_features = AuxFunctions.get_features_for_graph( self.features, full_unweighted_g, words_tags, self.is_improved) full_weighted_g = AuxFunctions.get_weighted_graph( full_unweighted_g, g_features, w) g_inference = edmonds.mst(('root', 'root', 0), full_weighted_g) inference_arches = self.get_arches_in_order( g_inference) self.write_lines(inference_arches, f2) sentence_num += 1 print('Done sentence number ' + str(sentence_num)) sentence_words_pos = dict() else: split_line = line.split('\t') # (counter)->(token,pos) sentence_words_pos[int( split_line[0])] = (split_line[1], split_line[3]) f2.close() f1.close()
def get_f_vector(self, g, g_num): f_vector = np.zeros(self.feature_num, dtype=int) features = AuxFunctions.get_features_for_graph( self.features, g, self.sentence_tags[g_num - 1], self.is_improved) for feature_data in features: for feature_i in feature_data[2]: f_vector[feature_i] += 1 return f_vector
def main(): global repetidos repetidos = {} global dis dis = {} dir = [[1, 3], [-1, 1, 3], [-1, 3], [-3, 1, 3], [-3, -1, 1, 3], [-3, -1, 3], [-3, 1], [-3, -1, 1], [-3, -1]] game = [0] * 9 over = [0] * 9 tabGame = AuxFunctions.buildGame(game) repetidos[tabGame] = 0 tabOver = AuxFunctions.buildGame(over) if AuxFunctions.isSolvable(tabGame, tabOver): print solveDFS(game, over, dir) else: print "Nao e resolvivel"
def main(): global repetidos repetidos = {} global dis dis = {} global caminho caminho = {} dir = [[1, 3], [-1, 1, 3], [-1, 3], [-3, 1, 3], [-3, -1, 1, 3], [-3, -1, 3], [-3, 1], [-3, -1, 1], [-3, -1]] game = [0] * 9 over = [0] * 9 tabGame = AuxFunctions.buildGame(game) tabOver = AuxFunctions.buildGame(over) if AuxFunctions.isSolvable(tabGame, tabOver): solveGreedy(game, over, dir) jogadas = AuxFunctions.printCaminho(caminho, tabGame, tabOver) print "Encontrada solucao em", jogadas, "jogadas." else: print "Nao e resolvivel"
def main(): global repetidos repetidos = {} global caminho caminho = {} global dis dis = {} dir = [[1,3], [-1, 1, 3], [-1,3], [-3, 1, 3], [-3, -1, 1, 3], [-3, -1, 3], [-3, 1], [-3, -1, 1], [-3, -1]] game = [0]*9 over = [0]*9 tabGame = AuxFunctions.buildGame(game) caminho[tabGame] = tabGame tabOver = AuxFunctions.buildGame(over) if AuxFunctions.isSolvable(tabGame, tabOver): print solveIDFS(tabGame, tabOver, dir) jogadas = AuxFunctions.printCaminho(caminho, tabGame, tabOver) else: print "Nao e resolvivel"
def solveAStar(game, over, dir): distancias = [] heap.heapify(distancias) max = 0 gameString = AuxFunctions.returnString(game) dis[gameString] = 0 caminho[gameString] = gameString heap.heappush(distancias, (manhattanDistance(game, over), game)) while not len(distancias) == 0: node = heap.heappop(distancias) repetidos[AuxFunctions.returnString(node[1])] = 1 if AuxFunctions.isSolution(node[1], over): print "Tiveram em dada altura um maximo de", max, "nos na fila." return distancia index = node[1].index(0) for value in dir[index]: node1 = node[1][:] node1String = AuxFunctions.returnString(node1) distancia = dis.get(node1String) + 1 distanciaTemp = dis.get(node1String) node1[index+value], node1[index] = node1[index], node1[index+value] node1String = AuxFunctions.returnString(node1) dis[node1String] = distanciaTemp + 1 distancia += manhattanDistance(node1, over) if not caminho.get(node1String): caminho[node1String] = AuxFunctions.returnString(node[1]) if not repetidos.get(node1String): heap.heappush(distancias, (distancia, node1)) if len(distancias) > max: max = len(distancias)
def solveDFS(game, over, dir): tabGame = AuxFunctions.returnString(game) tabTemp = AuxFunctions.returnString(game) stack = [tabGame] max = 0 dis[tabGame] = 0 while not len(stack) == 0: game = list(stack.pop(0)) tabGame = AuxFunctions.returnString(game) # printTable(game) index = game.index("0") if not repetidos.get(tabGame): repetidos[tabGame] = 1 for value in dir[index]: tempGame = game[:] tempGame[index + value], tempGame[index] = tempGame[index], tempGame[index + value] tabTemp = AuxFunctions.returnString(tempGame) stack.insert(0, tabTemp) if max < len(stack): max = len(stack) dis[tabTemp] = dis.get(tabGame) + 1 if AuxFunctions.isSolution(tempGame, over): print "Tiveram em dada altura um maximo de", max, "nos na fila." return dis.get(tabTemp)
def solveBFS(game, over, dir): tabGame = AuxFunctions.returnString(game) queue = [tabGame] dis[tabGame] = 0 max = 0 while not len(queue) == 0: game = list(queue.pop(0)) tabGame = AuxFunctions.returnString(game) index = game.index('0') if not repetidos.get(tabGame): repetidos[tabGame] = 1 for value in dir[index]: tempGame = game[:] tempGame[index+value], tempGame[index] = tempGame[index], tempGame[index+value] tabTemp = AuxFunctions.returnString(tempGame) dis[tabTemp] = dis[tabGame] + 1 queue.append(tabTemp) if len(queue) > max: max = len(queue) if not caminho.get(tabTemp): caminho[tabTemp] = tabGame if AuxFunctions.isSolution(tempGame, over): print "Tiveram em dada altura um maximo de", max, "nos na fila." return dis.get(tabTemp)
def make_graphs(self): counter = 0 for arches_data in self.arches_data_list: # Get (arches tuples, full data) g = dict() arches_tuples = arches_data[0] for arch_tuple in arches_tuples: if (arch_tuple[0][0], arch_tuple[0][1], arch_tuple[1]) in g: g[(arch_tuple[0][0], arch_tuple[0][1], arch_tuple[1])][(arch_tuple[0][2], arch_tuple[0][3], arch_tuple[2])] = 0 else: g[(arch_tuple[0][0], arch_tuple[0][1], arch_tuple[1])] = { (arch_tuple[0][2], arch_tuple[0][3], arch_tuple[2]): 0 } self.graphs.append( (g, AuxFunctions.make_full_graph(arches_data[1])))
def perceptron(self, n): w = np.zeros(self.feature_num, dtype=int) for i in range(0, n): iteration_time = datetime.now() scored_graph_index = list(range(0, len(self.scored_graphs), 1)) shuffled_scored_graph_index = sorted(scored_graph_index, key=lambda k: random.random()) for index in shuffled_scored_graph_index: data = self.scored_graphs[index] weighted_full_graph = AuxFunctions.get_weighted_graph( data[2], data[3], w) g_tag = edmonds.mst(('root', 'root', 0), weighted_full_graph) if True: # For better performance w = w + self.get_saved_f_vector( data[0], data[4]) - self.get_f_vector(g_tag, data[4]) print('Done ' + str(i + 1) + ' iteration at ' + str(datetime.now() - iteration_time)) if self.is_improved: ImprovedFunctions.save_w(w, i + 1) else: BasicFunctions.save_w(w, i + 1)
def Pressure(frames, temp): ''' Function to calculte the pressure for a temperature. Input: np.array with the positions and velocities for each timestep and a double giving the temperature. Output: Double giving the pressure for that temperature. (np.array, double) -> (double) ''' listt = [] for t in range(len(frames)): posvecs = frames[t, 0] listn = [] for i in range(0, C.n): for j in range(0, C.n): #expression from lecture notes to calculate the distance according to the minimal #image convention. distancevec = (posvecs[i] - posvecs[j] + C.L / 2) % C.L - C.L / 2 distance = la.norm(distancevec) if i != j: listn.append(distance * AF.PotentialDeriv(distance)) listt.append(1 / 2 * np.sum(listn)) P = np.mean(listt) #P = (1/(6*C.L**3)) * P #P = (C.n * temp)/(C.L**3) - P P = (1 / (3 * C.n * temp)) * P P = 1 - P return P
#Import default libraries import serial import serial.tools.list_ports import sys from PyQt5.QtWidgets import QApplication, QMainWindow import os #Import custom libraries and classes #from Main_GUI import Timing_GUI from Main_GUI import Ui_MainWindow import AuxFunctions as AF #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Navigate to working directory, creating if necessary AF.nav_to_directory( os.path.join("C:\\Users", os.getlogin(), "Documents", "Swim Manager"), 'Meet_Output.txt') #Ready serial device arduino = AF.open_python_port() #Ensures Arduino is connected & ready before launching GUI #Comment this line to run GUI w/o Arduino Connected. This may cause errors when certain buttons are pressed AF.wait_for_arduino_ready(arduino) #Run GUI app = QApplication(sys.argv) ui = Ui_MainWindow(arduino) #app.quitOnLastWindowClosed = False #app.setQuitOnLastWindowClosed(False) sys.exit(app.exec_())