def main(): count = 0 input = open('dij10.txt', 'r') x = input.read() tamanhoMatriz = 0 #leitura do arquivo da matriz de adjacencia for row, line in enumerate(x.split('\n')): for col, val in enumerate(line.split(' ')): if (count == 0): tamanhoMatriz = int(val) count += 1 break break count = 0 matriz = np.zeros((tamanhoMatriz, tamanhoMatriz)) matrizFinal = np.zeros((tamanhoMatriz, tamanhoMatriz)) for row, line in enumerate(x.split('\n')): for col, val in enumerate(line.split(' ')): if (count == 0): tamanhoMatriz = int(val) count += 1 break else: count += 2 matriz[int(row - 1)][int(col)] = int(val) for i in range(0, tamanhoMatriz): for j in range(i, tamanhoMatriz): if i == j: continue else: matrizFinal[i][j] = matriz[i][j - i - 1] matrizFinal[j][i] = matriz[i][j - i - 1] print('Matriz de adjacencias: \n') print(matrizFinal) g = Graph(tamanhoMatriz) g.graph = matrizFinal g.dijkstra(2) count -= 1
def findPathBetweenTwoStationInSameLayer(id1, id2, layerName): if id1 == id2: return [id1] layer = mapNameToLayer[layerName] graph = mapNameToGraph[layerName] # listFakeId = convertFakeId([id1, id2], layer) g = Graph() route = g.dijkstra(graph, listFakeId[0], listFakeId[1]) return convertToTrustId(route, layer)
def find_shortest_traversal(matrix, node_list): """ Given a matrix and a list of nodes, this function will output the shortest traversal visiting the nodes in that order. :param matrix: The matrix :param node_list: The list of nodes :return: List with path """ path = [node_list[0]] graph = Graph() for i in range(len(node_list[:-1])): path.extend(graph.dijkstra(graph=matrix, src=node_list[i])[node_list[i+1]+1][1:]) return path
def _dijkstra(): node_count = 6 g1 = Dijkstra(node_count) # Node 0: <1,5> <2,1> <3,4> g1.add_into_adj_list(0, Node_Distance(1, 5)) g1.add_into_adj_list(0, Node_Distance(2, 1)) g1.add_into_adj_list(0, Node_Distance(3, 4)) # Node 1: <0,5> <2,3> <4,8> g1.add_into_adj_list(1, Node_Distance(0, 5)) g1.add_into_adj_list(1, Node_Distance(2, 3)) g1.add_into_adj_list(1, Node_Distance(4, 8)) # Node 2: <0,1> <1,3> <3,2> <4,1> g1.add_into_adj_list(2, Node_Distance(0, 1)) g1.add_into_adj_list(2, Node_Distance(1, 3)) g1.add_into_adj_list(2, Node_Distance(3, 2)) g1.add_into_adj_list(2, Node_Distance(4, 1)) # Node 3: <0,4> <2,2> <4,2> <5,1> g1.add_into_adj_list(3, Node_Distance(0, 4)) g1.add_into_adj_list(3, Node_Distance(2, 2)) g1.add_into_adj_list(3, Node_Distance(4, 2)) g1.add_into_adj_list(3, Node_Distance(5, 1)) # Node 4: <1,8> <2,1> <3,2> <5,3> g1.add_into_adj_list(4, Node_Distance(1, 8)) g1.add_into_adj_list(4, Node_Distance(2, 1)) g1.add_into_adj_list(4, Node_Distance(3, 2)) g1.add_into_adj_list(4, Node_Distance(5, 3)) # Node 5: <3,1> <4,3> g1.add_into_adj_list(5, Node_Distance(3, 1)) g1.add_into_adj_list(5, Node_Distance(4, 3)) g1.dijkstra(0,verbose=True) print("\n") g1.dijkstra(5)
def output_path(ad_mat): # Create a graph graph = Graph() visited = [0] # Start at node 0 home_drops = [] path = [0] while len(visited) != len(ad_mat): remaining = [] for node in range(len(ad_mat)): if node not in visited: remaining.append(node) best = remaining[0] for j in remaining[1:]: if graph.dijkstra(ad_mat, visited[-1])[0][j] < graph.dijkstra( ad_mat, visited[-1])[0][best]: best = j path.extend(graph.dijkstra(ad_mat, visited[-1])[best + 1][1:]) visited.append(best) # Route from end node to start node path.extend(graph.dijkstra(ad_mat, visited[-1])[1][1:]) return path
def get_distance_dict(adj_mat): """ Returns a dictionary of the shortest distances from all node to all others in the parameter adjacency matrix. :param adj_mat: A adjacency matrix (mxn array) for the graph to calculate distances from :return: A dictionary with shortest distances from all nodes to all others """ distances = {} graph = Graph() for i in range(len(adj_mat)): distances[i] = {} for i in range(len(adj_mat)): for j in range(len(adj_mat)): distances[i][j] = graph.dijkstra(adj_mat, i)[0][j] return distances
def get_shortest_path(src, dst, link_costs, ROUTER_ID_MAPPING): if src == dst: return 0, int(ROUTER_ID_MAPPING[src]) # Make link_costs symmetrical symm_link_costs = [] for link in link_costs: symm_link_costs.append(link) symm_link_costs.append((link[1], link[0], link[2])) network = Graph(symm_link_costs) try: shortest_path = network.dijkstra(src, dst) except: return 65535, 65535 path_cost = 0 for hop in range(len(shortest_path)-1): path_cost += utils.get_link_cost(shortest_path[hop], shortest_path[hop+1], symm_link_costs) return path_cost, int(ROUTER_ID_MAPPING[shortest_path[1]])
def get_distance_list_fast(self, adj_mat): """ Returns a list of the shortest distances from all node to all others in the parameter adjacency matrix. index corresponds to node, value correponds to distances. :param adj_mat: An adjacency matrix (mxn array) for the graph to calculate distances from :return: A list with shortest distances from all nodes to all others """ distances = [0 for j in range(len(adj_mat))] dijkstras = [0 for j in range(len(adj_mat))] graph = Graph() for i in range(len(adj_mat)): distances[i] = [0 for j in range(len(adj_mat))] dijkstras[i] = graph.dijkstra(adj_mat, i)[0] for i in range(len(adj_mat)): for j in range(len(adj_mat)): distances[i][j] = dijkstras[i][j] return distances
def get_path_dict(adj_mat): """ Returns a dictionary where the key values are node-indexes and the values are a new dict. The keys in this new dict are all nodes in graph. The values for these keys are shortest paths from original node to key node. :param adj_mat: :return: """ paths = {} graph = Graph() for i in range(len(adj_mat)): paths[i] = {} for i in range(len(adj_mat)): for j in range(len(adj_mat)): if i == j: paths[i][j] = [i] else: paths[i][j] = graph.dijkstra(adj_mat, i)[j+1] return paths
def calculate_cluster_distances(ad_mat, indexes): """ Calculate the distances between the given list of indexes in the given adjacency matrix, using dijkstra. :param ad_mat: The adjacency matrix representing the graph :param indexes: The indexes you want to calculate distances for :return: A dict {node: {other_node: distance}} """ distances = {} graph = Graph() # Each node maintains a list with nodes distances to itself for i in indexes: for j in indexes: distances[i] = {j:0} for i in indexes: for j in indexes: try: distances[i][j] = graph.dijkstra(ad_mat, i)[0][j] except: distances[i][j] = 0 return distances
class WarpMaze: def __init__(self, source_file=None): with open(source_file) as f: maze = [list(line.strip('\r\n')) for line in f] self.width = max([len(row) for row in maze]) self.height = len(maze) self.loc_warp = dict() self.warp_loc = defaultdict(set) self.graph = Graph() self.interior = set() self.exterior = set() # Copy the file to the local dict: self.maze = self.copy_to_dict(maze) # Identify all the wormhole tokens: self.parse_warps() # Populate graph: self.build_graph() # Start/finish for the maze: self.source = self.warp_loc['AA'].pop() self.target = self.warp_loc['ZZ'].pop() # Part 2: self.scores = dict() def copy_to_dict(self, list_of_lists): maze_dict = dict() for y, row in enumerate(list_of_lists): for x, ch in enumerate(row): maze_dict[(x, y)] = ch return maze_dict def parse_warps(self): for x in range(self.width): for y in range(self.height): ch_1 = self.maze.get((x, y), ' ') t_x = None t_y = None # If ch_1 is the start of a token identifier may have found a token: if ch_1 in ascii_uppercase: # These are the horizontal tokens: ch_2 = self.maze.get((x + 1, y), ' ') if ch_2 in ascii_uppercase: if self.maze.get((x + 2, y)) == '.': t_x = x + 2 if self.maze.get((x - 1, y)) == '.': t_x = x - 1 self.loc_warp[(t_x, y)] = ch_1 + ch_2 ch_2 = self.maze.get((x - 1, y), ' ') if ch_2 in ascii_uppercase: if self.maze.get((x - 2, y)) == '.': t_x = x - 2 if self.maze.get((x + 1, y)) == '.': t_x = x + 1 self.loc_warp[(t_x, y)] = ch_2 + ch_1 # These are vertical tokens: ch_2 = self.maze.get((x, y + 1), ' ') if ch_2 in ascii_uppercase: if self.maze.get((x, y + 2)) == '.': t_y = y + 2 if self.maze.get((x, y - 1)) == '.': t_y = y - 1 self.loc_warp[(x, t_y)] = ch_1 + ch_2 ch_2 = self.maze.get((x, y - 1), ' ') if ch_2 in ascii_uppercase: if self.maze.get((x, y - 2)) == '.': t_y = y - 2 if self.maze.get((x, y + 1)) == '.': t_y = y + 1 self.loc_warp[(x, t_y)] = ch_2 + ch_1 for loc, warp in self.loc_warp.items(): self.warp_loc[warp].add(loc) x, y = loc if 2 < x < self.width - 3 and 2 < y < self.height - 3: self.interior.add(loc) else: self.exterior.add(loc) def flood_fill(self, warp): def neighbors(x, y): return [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] for loc in self.warp_loc[warp]: boundary = [loc] interior = [] flood_dist = 0 while boundary: flood_dist += 1 b_size = len(boundary) for _ in range(b_size): b = boundary.pop(0) interior.append(b) hood = neighbors(*b) for n_xy in hood: if n_xy in self.loc_warp and n_xy != loc: self.graph.add([loc, n_xy, flood_dist]) interior.append(n_xy) if self.maze.get( n_xy ) == '.' and n_xy not in boundary and n_xy not in interior: boundary.append(n_xy) def build_graph(self): for warp, locs in self.warp_loc.items(): if len(locs) > 1: n1 = locs.pop() n2 = locs.pop() self.graph.add([n1, n2, 1]) locs.add(n1) locs.add(n2) self.flood_fill(warp) def maze_solve(self): dist, path = self.graph.dijkstra(self.source, self.target) named_path = [] for graph_node in path: named_path.append(self.loc_warp[graph_node]) return dist, named_path def min_cost_to_exit(self, state): if state == (*self.target, 0): return 0 if state in self.scores: return self.scores[state]
# coding: utf-8 from dijkstra import Graph example = { 'a': { 'b': 12, 'c': 4 }, 'b': { 'a': 12, 'd': 5, 'e': 3 }, 'c': { 'a': 4, 'd': 2, 'f': 6 }, 'd': { 'b': 5, 'c': 2, 'g': 8 }, 'e': { 'b': 3, 'h': 7 }, 'f': { 'c': 6, 'g': 5 }, 'g': { 'd': 8, 'f': 5, 'h': 3 }, 'h': { 'e': 7, 'g': 3 }, } graph = Graph(example, 'a', 'h') graph.dijkstra() print "Melhor caminho: " + str(graph.shortest_path()) print "Distâncias por vértice: " + str(graph.shortest_path_distance())
}, 3: { 2: 2, 4: 1, 5: 5, 6: 6 }, 4: { 3: 1, 5: 1 }, 5: { 2: 5, 4: 1, 3: 5, 6: 3 }, 6: { 1: 10, 3: 6, 5: 3, 2: 8 }, } graph = Graph(example, 1, 6) graph.dijkstra() print "Melhor caminho: " + str(graph.shortest_path()) print "Distâncias por vértice: " + str(graph.shortest_path_distance())
hop_count_list.append(Hop) power_consumption = Dataframe_cluster_cluster.loc[From_cluster_C, 'Power'] power_consumption = 10**(power_consumption / 10) / 1000 ## power consumption in watt dico[From_cluster_C] = dico.get(From_cluster_C, 0) + power_consumption continue if ((From_cluster_C, To_cluster_D) in Dijk_Dict): #print('From-To combination exists', From_cluster_C, To_cluster_D) Dijk_output = Dijk_Dict[(From_cluster_C, To_cluster_D)] else: # applying Dijkstra algorithm between randomly selected nodes graph = Graph(edgeList) Dijk_output = graph.dijkstra(From_cluster_C, To_cluster_D) if len(Dijk_output) <= 1: continue else: Dijk_Dict[(From_cluster_C, To_cluster_D)] = Dijk_output h = len(Dijk_output) - 1 Hop = h hop_count_list.append(Hop) for ii in range(len(Dijk_output) - 1): U = Dijk_output[ii] power_consumption = Dataframe_cluster_cluster.loc[U, 'Power'] power_consumption = 10**(power_consumption / 10) / 1000 ## power consumption in watt dico[U] = dico.get(U, 0) + power_consumption
command = "curl -s http://192.168.56.1:8080/wm/device/?ipv4=%s" % (start) result = os.popen(command).read() parsedResult1 = json.loads(result) x = parsedResult1['devices'][0]['attachmentPoint'][0]['switch'] x = x[-1] x = int(x) - 1 command = "curl -s http://192.168.56.1:8080/wm/device/?ipv4=%s" % (end) result = os.popen(command).read() parsedResult2 = json.loads(result) y = parsedResult2['devices'][0]['attachmentPoint'][0]['switch'] y = y[-1] y = int(y) - 1 #x: number of src switch #y: number of dst switch path = [] path = g.dijkstra(graph, x, y, z) for i in range(len(path)): path[i] = path[i] + 1 command = "curl -s http://192.168.56.1:8080/wm/topology/links/json" result = os.popen(command).read() parsedResult = json.loads(result) j = 0 srcPort = 0 dstPort = 0 if start == end or len(path) == 1: print "please check your input" sys.exit() for i in range(len(path)):
def __init__(self, x, y): self.x = x self.y = y self.width = 100 self.height = 50 def draw(self): pg.draw.rect(screen, BLACK, (self.x, self.y, self.width, self.height), 0) def checkClick(self, x, y): if x > self.x and x < self.x + self.width: if y > self.y and y < self.y + self.height: clearGrid() class Agent: def __init__(self): self.x = 0 self.y = 0 if __name__ == '__main__': pg.init() makeGrid(grid) g = Graph(1600, grid) print(g.dijkstra(grid[0][0], grid[5][5])) gameLoop()