def __init__(self, name, program): self.program = program self.name = name self.output = [] self.switch = { 1: self.opt1, 2: self.opt2, 3: self.opt3, 4: self.opt4, 5: self.opt5, 6: self.opt6, 7: self.opt7, 8: self.opt8, 9: self.opt9, 99: self.opt99 } self.inputp = 0 self.halt = False self.relative_base = 0 self.memory = {} self.retpt = 0 self.new_position = (0, 0) self.position = (0, 0) self.area = {(0, 0): 'X'} self.graph = Graph() self.graph.add_node((0, 0)) self.oxygen = (0, 0) self.unexplored = set() self.explored = set([(0, 0)]) self.graph.add_node((0, 0)) self.path = []
def make_graph(self): con = pymysql.connect(host='localhost', user='******', password='******', db='drive2', charset='utf8') curs = con.cursor() graph = Graph() sql = "select nodeid from drive2.c1_node" sql2 = "select tonode, length, format(speed,0) from drive2.a3_link, jcm_drive.jcm_a3_link where fromnode = " curs.execute(sql) rows = curs.fetchall() for i in rows: nodeid = list(map(lambda x: x, i)) curs.execute(sql2 + "'" + nodeid[0] + "';") rows = curs.fetchall() if rows is None: continue else: for item in list(rows): cost = item[1] / int(item[2]) graph.add_edge(i[0], item[0], cost) con.close() return graph
def find_conversions(source, target, versions_graph): """ This finds the minimum number of version upgrades required to reach the target version. :param source: source version :param target: target version :param versions_graph: graph to fetch update path from :return: list of conversions in order of execution """ graph = Graph() for source_version, target_version in versions_graph.query( """SELECT ?source_version ?target_version{ ?source_version version:convertsTo ?target_version . }"""): graph.add_edge(str(source_version), str(target_version), {"conversions": 1}) # Find the shortest path res = find_path( graph, str(source), str(target), cost_func=lambda u, v, e, prev_e: e["conversions"], ) # Create and return the conversions conversions = [] print(" -> ".join(res.nodes)) current = source for node in res.nodes: conversions.append((current, node)) current = node return conversions[1:]
def crea_matrice_distanze(dist): initial_matr = np.array(dist) print initial_matr matr = initial_matr.copy() # dict_matr = {(partenza, arrivi): lunghezza for partenza, arrivi in enumerate(dist) for arrivo, lunghezza in # enumerate(arrivi)} graph = Graph() for partenza, arrivi in enumerate(dist): for arrivo, lunghezza in enumerate(arrivi): if lunghezza >= 0: graph.add_edge(partenza, arrivo, {'cost': lunghezza}) cost_func = lambda u, v, e, prev_e: e['cost'] for partenza, arrivi in enumerate(dist): for arrivo in range(len(arrivi)): if partenza == arrivo: matr[partenza, arrivo] = -1 else: try: min_dist = find_path(graph, partenza, arrivo, cost_func=cost_func)[3] matr[partenza, arrivo] = min_dist except Exception as e: matr[partenza, arrivo] = -1 print "matr ditanze\n", matr return matr
def graph3(self): graph = Graph({ 'a': { 'b': 10, 'c': 100, 'd': 1 }, 'b': { 'c': 10 }, 'd': { 'b': 1, 'e': 1 }, 'e': { 'f': 1 }, }) graph.add_node('f', {'c': 1}) graph['f'] = {'c': 1} graph.add_edge('f', 'c', 1) graph.add_edge('g', 'b', 1) nodes = list(graph) nodes.sort() self.assertEqual(nodes, ['a', 'b', 'd', 'e', 'f', 'g']) incoming = graph.get_incoming('c') incoming_nodes = list(incoming.keys()) incoming_nodes.sort() self.assertEqual(incoming_nodes, ['a', 'b', 'f']) return graph
def solve(data): grid = data base = grid for j in range(1, 5): appendix = base + j appendix[appendix > 9] -= 9 grid = np.concatenate((grid, appendix), axis = 0) base = grid for i in range(1, 5): appendix = base + i appendix[appendix > 9] -= 9 grid = np.concatenate((grid, appendix), axis = 1) h, w = np.shape(grid) graph = Graph() for j in range(0, h): for a, b in pairwise(range(0, w)): graph.add_edge(j * h + a, j * h + b, grid[j][b]) graph.add_edge(j * h + b, j * h + a, grid[j][a]) for i in range(0, w): for a, b in pairwise(range(0, h)): graph.add_edge(a * h + i, b * h + i, grid[b][i]) graph.add_edge(b * h + i, a * h + i, grid[a][i]) return find_path(graph, 0, h * w - 1).total_cost
def shortestPathAStar(start_ind, goal_ind): global R # R[0] is the node for the start configuration # R[1] is the node for the goal configuration # each node has edges in the form: self.edges = [] List of tuples (node_id, dist) # loop through our graph and convert it to a nice format for dijkstar graph = Graph() for node in R: for edge in node.edges: graph.add_edge(node.id, edge[0], edge[1]) cfg_array = [] # catch path not found exception try: pathinfo = find_path(graph, start_ind, goal_ind) except: print('Could NOT find a path from start to goal') return cfg_array # get the configurations from each node in this found path for node_id in pathinfo.nodes: cfg_array.append(R[node_id].cfg) return cfg_array
def dist_mat(train_mat, test_mat, k): # construct a weighted graph mat = graph_knn(train_mat, test_mat, k) n = mat.shape[0] graph = Graph() list((graph.add_edge(i, j, {'cost': mat[i, j]}) for i, j in product(range(n), range(n)) if i != j and mat[i, j] != max_dis)) if graph is None: return cost_func = lambda u, v, e, prev_e: e['cost'] mat = np.zeros((n, n)) # the shortest path from node i to node j is the distance between i and j def dis(i): single_short_path = single_source_shortest_paths(graph, i, cost_func=cost_func) for j in range(n): if j != i: mat[i, j] = extract_shortest_path(single_short_path, j) else: mat[i, j] = 0 list((dis(i) for i in range(n))) return mat
def getSortedMapPathData(mapData: dict) -> dict: ''' 获取地图下各节点到目标节点的最短路径数据 Keyword arguments: mapData -- 地图节点数据 ''' graph = Graph() sortedPathData = {} for node in mapData.keys(): for target in mapData[node]: graph.add_edge(node, target, {'cost': mapData[node][target]}) cost_func = lambda u, v, e, prev_e: e['cost'] for node in mapData.keys(): newData = {node: {}} for target in mapData.keys(): if target != node: findPathData = find_path(graph, node, target, cost_func=cost_func) newData[node].update({ target: { "Path": findPathData.nodes[1:], "Time": findPathData.costs } }) sortedPathData.update(newData) return sortedPathData
def get_sorted_map_path_data(map_data: dict) -> dict: """ 获取地图下各节点到目标节点的最短路径数据 Keyword arguments: map_data -- 地图节点数据 """ graph = Graph() sorted_path_data = {} for node in map_data.keys(): for target in map_data[node]: graph.add_edge(node, target, {"cost": map_data[node][target]}) cost_func = lambda u, v, e, prev_e: e["cost"] for node in map_data.keys(): new_data = {node: {}} for target in map_data.keys(): if target != node: find_path_data = find_path(graph, node, target, cost_func=cost_func) new_data[node].update({ target: { "Path": find_path_data.nodes[1:], "Time": find_path_data.costs, } }) sorted_path_data.update(new_data) return sorted_path_data
def findBestPath(self, src, dst): graph = Graph() for node1 in costBetweenNodes.keys(): for node2 in costBetweenNodes[node1].keys(): graph.add_edge(node1, node2, {'cost': costBetweenNodes[node1][node2]}) cost_func = lambda u, v, e, prev_e: e['cost'] return find_path(graph, src, dst, cost_func=cost_func).nodes
def get_sorted_map_path_data( map_data: Dict[str, Dict[str, int]] ) -> Dict[str, Dict[str, game_type.TargetPath]]: """ 获取地图下各节点到目标节点的最短路径数据 Keyword arguments: map_data -- 地图节点数据 当前节点:可通行节点:所需时间 Return arguments: Dict[int,Dict[int,game_type.TargetPath]] -- 最短路径数据 当前节点:目标节点:路径对象 """ graph = Graph() sorted_path_data = {} for node in map_data.keys(): for target in map_data[node]: graph.add_edge(node, target, {"cost": map_data[node][target]}) cost_func = lambda u, v, e, prev_e: e["cost"] for node in map_data.keys(): new_data = {node: {}} for target in map_data.keys(): if target != node: find_path_data = find_path(graph, node, target, cost_func=cost_func) target_path = game_type.TargetPath() target_path.path = find_path_data.nodes[1:] target_path.time = find_path_data.costs new_data[node][target] = target_path sorted_path_data.update(new_data) return sorted_path_data
def dijkstra_planning(self): graph = Graph() temp_nodes = self.nodes[:] temp_nodes.pop(0) k = 0 for i in range(len(self.nodes)): k = k + 1 for j in range(len(temp_nodes)): node_a = self.nodes[i] node_b = temp_nodes[j] if np.linalg.norm(node_a - node_b) != 0: print("add edge:", i, j + k) graph.add_edge(i, j + k, np.linalg.norm(node_a - node_b)) if temp_nodes: temp_nodes.pop(0) print("done") path = find_path(graph, 1, 3) print("path:", path) # if __name__ == "__main__": # test_nodes = [np.array([21, 34]), # np.array([45, 28]), # np.array([76, 14]), # np.array([12, 56]), # np.array([48, 32])] # # motion_planner = Planner(test_nodes) # motion_planner.dynamic_programming()
def solve_graph(): global maze, maze_cost, pacmanpos, world, goal_state graph = Graph() for j in range(0, height): for i in range(0, width): if maze[j][i] != 1: #arriba if (maze[j-1][i] != 1) and (j-1 > 0): xi = str((j,i)) xj = str((j-1,i)) c = maze_cost[j-1][i] graph.add_edge(xi,xj,{'cost':c}) #print(xi+' - '+xj) #abajo if (maze[j+1][i] != 1) and (j+1 < height): xi = str((j,i)) xj = str((j+1,i)) c = maze_cost[j+1][i] graph.add_edge(xi,xj,{'cost':c}) #print(xi+' - '+xj) #derecha if (maze[j][i+1] != 1) and (i+1 < width): xi = str((j,i)) xj = str((j,i+1)) c = maze_cost[j][i+1] graph.add_edge(xi,xj,{'cost':c}) #print(xi+' - '+xj) #izquierda if (maze[j][i-1] != 1) and (i-1 > 0): xi = str((j,i)) xj = str((j,i-1)) c = maze_cost[j][i-1] graph.add_edge(xi,xj,{'cost':c}) #print(xi+' - '+xj) cost_func = lambda u, v, e, prev_e: e['cost'] pacman = worldToGrid(pacmanpos.pacmanPos.x, pacmanpos.pacmanPos.y) start_state = (pacman['y'], pacman['x']) #start_state = (25,14) # goal_state = closest_bonus() # print(goal_state) #goal_state = (25,26) path = find_path(graph, str(start_state), str(goal_state), cost_func=cost_func) # print(path.nodes) if len(path.nodes)>1: next_state = eval(path.nodes[1]) aux = (start_state[0]-next_state[0], start_state[1]-next_state[1]) else: print('yuca') return 4 #print(str(start_state)+' '+str(next_state)) if aux == (1,0): return 0 if aux == (-1,0): return 1 if aux == (0,-1): return 2 if aux == (0,1): return 3
def __close_cycle(node, roundtrip): graph = Graph(undirected=True) __to_dijkstra(node, graph) first_node = roundtrip[0].id last_node = roundtrip[-1].id path_info = find_path(graph, last_node, first_node) return roundtrip + __to_nodes(node, path_info)[1:-2]
def sol_6_b(data_str): orbit_tree = read_orbits(data_str) g = Graph() for planet in orbit_tree: g.add_edge(orbit_tree[planet], planet, 1) g.add_edge(planet, orbit_tree[planet], 1) path = find_path(g, "YOU", orbit_tree["SAN"]) return path.total_cost - 1
def test_find_path_with_annex(self): annex = Graph({1: {2: 1, 3: 0.5}}) result = find_path(self.graph1, 1, 4, annex=annex) nodes, edges, costs, total_cost = result self.assertEqual(nodes, [1, 3, 4]) self.assertEqual(edges, [0.5, 2]) self.assertEqual(costs, [0.5, 2]) self.assertEqual(total_cost, 2.5)
def _get_graph(nets_ids, links): graph = Graph() for link in links: src_connectable_id = link['src_connectable_id'] dst_connectable_id = link['dst_connectable_id'] if src_connectable_id in nets_ids and dst_connectable_id in nets_ids: graph.add_edge(src_connectable_id, dst_connectable_id, 100) return graph
def __init__( self, config: Config, ) -> None: self.config = config self.graph = Graph( ) # Graph of possible movements for dijkstar algorithm lib self.visibility_matrix = self.visibility_matrix() self.move_cost_computer = self.move_cost_computer_class(config)
def dijkstra(d): g = Graph() for i in range(len(d)): for j in range(len(d[i])): dirs = ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)) for x, y in dirs: if 0 <= x < len(d) and 0 <= y < len(d[i]): g.add_edge((i, j), (x, y), d[x][y]) return find_path(g, (0, 0), (len(d) - 1, len(d[0]) - 1)).total_cost
def get_routes(name_num, point1, point2): global_graph = Graph() loc_name = get_loc_name(name_num) global_graph = global_graph.load('./djicstra_graph/{}'.format(loc_name)) graph_route = find_path(global_graph, point1, point2).nodes final_list = list() for elem in graph_route: final_list.append((get_position_name(name_num, elem))) return (final_list)
def graph_search(self): # set up the graph graph = Graph() self.nodes = 0 self.total_cost = 0 # add edges for i in range(len(self.TE)): # pdb.set_trace() edge = self.TE[i] dist = math.sqrt((edge[0][0] - edge[1][0])**2 + (edge[0][1] - edge[1][1])**2) # pdb.set_trace() # find vertex from self.V that matches the edges vertex1 = self.TV.index(edge[0]) vertex2 = self.TV.index(edge[1]) # pdb.set_trace() graph.add_edge(vertex1, vertex2, dist) # pdb.set_trace() temp = find_path(graph, 0, len(self.TV) - 1) self.nodes = temp[0] self.total_cost = temp[3] # now that we have the final path of the robot, we need to extract the ideal robot positions # interpolate all of the vertices to make a series of points that the robot can follow self.robot_positions = [] # iterate over each node in the final path and connect between them for i in range(len(self.nodes) - 1): # take the first and second nodes from_node = self.TV[self.nodes[i]] to_node = self.TV[self.nodes[i + 1]] # take each edge and interpolate a distance equivalent 1/10th of the robot speed per second diff_x = to_node[0] - from_node[0] diff_y = to_node[1] - from_node[1] dist_speed = self.speed * 1 / 10 # m/s * s = m # now find number of points from distance between points and speed dist_covered = math.sqrt(diff_x**2 + diff_y**2) num_points = round(dist_covered / dist_speed) # interpolate using these points x_int = from_node[0] y_int = from_node[1] interpolateds = [x_int, y_int] for i in range(num_points): # append the robot positions self.robot_positions.append(interpolateds) # add the points in by moving the direction amount calculated in x and y x_int = interpolateds[0] + diff_x / num_points y_int = interpolateds[1] + diff_y / num_points interpolateds = [x_int, y_int] # append goal if self.solution_found == 1: self.robot_positions.append(self.qgoal) # self.robot_positions.append(np.linspace(edge[0],edge[1], num = self.speed/50,endpoint=True,retstep=True)) return self.nodes, self.total_cost
def graph_gen( df_edge ): #génère un graph simple des liens entre les tables sans tenir compte des colones graph = Graph() for x in df_edge.index: graph.add_edge(df_edge.loc[x, 'table_FK_id'], df_edge.loc[x, 'tablePK_id'], {'cost': 1}) graph.add_edge(df_edge.loc[x, 'tablePK_id'], df_edge.loc[x, 'table_FK_id'], {'cost': 1}) return graph
def __init__(self, addr, heartbeatTime): """TODO: add your own class fields and initialization code here""" Router.__init__(self, addr) # initialize superclass - don't remove self.heartbeatTime = heartbeatTime self.last_time = 0 self.G = Graph(undirected=True) self.SeqNum = {} self.Neighbours = { } #Dictionary with key as address and cost and seqnum as values self.Curr_Seq = 0
def test_initialise_dijk_grid_with_no_blocks(self): self.grid.width, self.grid.height, self.grid.blocks = 2, 2, [] self.grid.initialise_dijk_grid() test_grid = Graph() for i in range(2): test_grid.add_edge((i, 0), (i, 1), 1) test_grid.add_edge((i, 1), (i, 0), 1) test_grid.add_edge((0, i), (1, i), 1) test_grid.add_edge((1, i), (0, i), 1) self.assertEqual(self.grid.dijk_grid, test_grid)
def graph_gen_col( df_edge ): #fonction créant le graphique à partir du tableau des contraintes relationnel graph = Graph() for x in df_edge.index: graph.add_edge( df_edge.loc[x, 'referenced_table_col'], df_edge.loc[x, 'parent_table_col'], {'cost': 1}) #ajoute le lien entre les 2 tables relié dans un sens graph.add_edge( df_edge.loc[x, 'parent_table_col'], df_edge.loc[x, 'referenced_table_col'], {'cost': 1 }) #ajoute le lien entre les 2 tables relié dans l'autre sens if df_edge.loc[ x, 'referenced_column_id'] == 1: # col id = 1 correspond a une clef primaire a1 = df_edge[( df_edge['table_FK_id'] == df_edge.loc[x, 'table_FK_id'] )]['referenced_column_id'].unique().tolist( ) #crée des liens entre la clef primaire d'une table et toutes les colones ayant une contrainte référentiel avec cette table a2 = df_edge[(df_edge['tablePK_id'] == df_edge.loc[x, 'table_FK_id'] )]['parent_colum_id'].unique().tolist() a = sorted(uniquel(a1 + a2))[1:] if a: for i in a: graph.add_edge( df_edge.loc[x, 'referenced_table_col'], int(df_edge.loc[x, 'table_FK_id'].astype(str) + "0000" + str(i)), {'cost': 1 }) #ajoute les edges avec la lsite crée plus haut graph.add_edge( int(df_edge.loc[x, 'table_FK_id'].astype(str) + "0000" + str(i)), df_edge.loc[x, 'referenced_table_col'], {'cost': 1}) if df_edge.loc[x, 'parent_colum_id'] == 1: b1 = df_edge[(df_edge['tablePK_id'] == df_edge.loc[x, 'tablePK_id'] )]['referenced_column_id'].unique().tolist() b2 = df_edge[(df_edge['table_FK_id'] == df_edge.loc[x, 'tablePK_id'] )]['parent_colum_id'].unique().tolist() b = sorted(uniquel(b1 + b2))[1:] if b: for i in b: graph.add_edge( df_edge.loc[x, 'parent_table_col'], int(df_edge.loc[x, 'tablePK_id'].astype(str) + "0000" + str(i)), {'cost': 1}) graph.add_edge( int(df_edge.loc[x, 'tablePK_id'].astype(str) + "0000" + str(i)), df_edge.loc[x, 'parent_table_col'], {'cost': 1}) return graph
def init(cls): """ set up the router using the already loaded network """ cls.graph = Graph() for edge in Network.routing_edges: cls.graph.add_edge( edge.from_node.getID(), edge.to_node.getID(), { 'length': edge.length, 'maxSpeed': edge.max_speed, 'lanes': len(edge.lanes), 'edgeID': edge.id })
class Dijkstra: graph = Graph() graph.add_edge(1, 2, {'cost': 1}) graph.add_edge(2, 3, {'cost': 2}) def getdijkstra(x, graph, nodeList): cost_func = lambda u, v, e, prev_e: e['cost'] for n in nodeList: if n is not x: print(find_path(graph, x, n, cost_func=cost_func))
def test_initialise_dijk_grid_simple(self): self.grid.width, self.grid.height, self.grid.blocks = 2, 2, [(1, 1)] self.grid.initialise_dijk_grid() test_grid = Graph() for i in range(2): test_grid.add_edge((i, 0), (i, 1), 1) test_grid.add_edge((i, 1), (i, 0), 1) test_grid.add_edge((0, i), (1, i), 1) test_grid.add_edge((1, i), (0, i), 1) test_grid.remove_node((1, 1)) self.assertEqual(self.grid.dijk_grid, test_grid)
def __init__(self, addr, heartbeatTime): """TODO: add your own class fields and initialization code here""" Router.__init__(self, addr) # initialize superclass - don't remove self.heartbeatTime = heartbeatTime self.last_time = 0 # Hints: initialize local state self.link_state = {} #APNA LINK STATE self.link_state_local = {} #BAKI SUB KA LINK STATE self.sequence_number = 0 #SEND KARTAY WAKT SEQ NUM self.check_sequence_number = {} #RECIEVE KARTAY WAKT SEQ NUM self.network_graph = Graph(undirected=True) #GRAPH self.forwarding_table = {} #FRWD TABLE