def test_multigraph(self): assert_equal(nx.bellman_ford_path(self.MXG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.MXG, 's', 'v'), 9) assert_equal(nx.single_source_bellman_ford_path(self.MXG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_bellman_ford_path_length(self.MXG, 's')['v'], 9) D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v') assert_equal(D, 9) assert_equal(P, ['s', 'x', 'u', 'v']) P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, 's') assert_equal(P['v'], ['u']) assert_equal(D['v'], 9) P, D = nx.goldberg_radzik(self.MXG, 's') assert_equal(P['v'], 'u') assert_equal(D['v'], 9) assert_equal(nx.bellman_ford_path(self.MXG4, 0, 2), [0, 1, 2]) assert_equal(nx.bellman_ford_path_length(self.MXG4, 0, 2), 4) assert_equal(nx.single_source_bellman_ford_path(self.MXG4, 0)[2], [0, 1, 2]) assert_equal(nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2], 4) D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2) assert_equal(D, 4) assert_equal(P, [0, 1, 2]) P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0) assert_equal(P[2], [1]) assert_equal(D[2], 4) P, D = nx.goldberg_radzik(self.MXG4, 0) assert_equal(P[2], 1) assert_equal(D[2], 4)
def test_others(self): assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9) assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal(dict(nx.single_source_bellman_ford_path_length(self.XG, 's'))['v'], 9) D, P = nx.single_source_bellman_ford(self.XG, 's', target='v') assert_equal(D['v'], 9) assert_equal(P['v'], ['s', 'x', 'u', 'v']) (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's') assert_equal(P['v'], ['u']) assert_equal(D['v'], 9) (P, D) = nx.goldberg_radzik(self.XG, 's') assert_equal(P['v'], 'u') assert_equal(D['v'], 9) G = nx.path_graph(4) assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)), {0: 0, 1: 1, 2: 2, 3: 3}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0, 1: 1, 2: 2, 3: 3}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [None], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})) assert_equal(nx.goldberg_radzik(G, 0), ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3})) assert_equal(nx.single_source_bellman_ford_path(G, 3), {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]}) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 3)), {0: 3, 1: 2, 2: 1, 3: 0}) assert_equal(nx.single_source_bellman_ford(G, 3), ({0: 3, 1: 2, 2: 1, 3: 0}, {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 3), ({0: [1], 1: [2], 2: [3], 3: [None]}, {0: 3, 1: 2, 2: 1, 3: 0})) assert_equal(nx.goldberg_radzik(G, 3), ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0})) G = nx.grid_2d_graph(2, 2) dist, path = nx.single_source_bellman_ford(G, (0, 0)) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) assert_equal(sorted(path.items()), [((0, 0), [(0, 0)]), ((0, 1), [(0, 0), (0, 1)]), ((1, 0), [(0, 0), (1, 0)]), ((1, 1), [(0, 0), (0, 1), (1, 1)])]) pred, dist = nx.bellman_ford_predecessor_and_distance(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), [None]), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) pred, dist = nx.goldberg_radzik(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)), ((1, 0), (0, 0)), ((1, 1), (0, 1))]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
def test_negative_weight(self): G = nx.DiGraph() G.add_nodes_from('abcd') G.add_edge('a','d', weight = 0) G.add_edge('a','b', weight = 1) G.add_edge('b','c', weight = -3) G.add_edge('c','d', weight = 1) assert_equal(nx.bellman_ford_path(G, 'a', 'd'), ['a', 'b', 'c', 'd']) assert_equal(nx.bellman_ford_path_length(G, 'a', 'd'), -1)
def test_others(self): assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9) assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_bellman_ford_path_length(self.XG, 's')['v'], 9) D, P = nx.single_source_bellman_ford(self.XG, 's', target='v') assert_equal(D, 9) assert_equal(P, ['s', 'x', 'u', 'v']) (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's') assert_equal(P['v'], ['u']) assert_equal(D['v'], 9) (P, D) = nx.goldberg_radzik(self.XG, 's') assert_equal(P['v'], 'u') assert_equal(D['v'], 9)
def shortest_path_length(G, source=None, target=None, weight=None, method='dijkstra'): """Compute shortest path lengths in the graph. Parameters ---------- G : NetworkX graph source : node, optional Starting node for path. If not specified, compute shortest path lengths using all nodes as source nodes. target : node, optional Ending node for path. If not specified, compute shortest path lengths using all nodes as target nodes. weight : None or string, optional (default = None) If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. method : string, optional (default = 'dijkstra') The algorithm to use to compute the path length. Supported options: 'dijkstra', 'bellman-ford'. Other inputs produce a ValueError. If `weight` is None, unweighted graph methods are used, and this suggestion is ignored. Returns ------- length: int or iterator If the source and target are both specified, return the length of the shortest path from the source to the target. If only the source is specified, return a dict keyed by target to the shortest path length from the source to that target. If only the target is specified, return a dict keyed by source to the shortest path length from that source to the target. If neither the source nor target are specified, return an iterator over (source, dictionary) where dictionary is keyed by target to shortest path length from source to that target. Raises ------ NodeNotFound If `source` is not in `G`. NetworkXNoPath If no path exists between source and target. ValueError If `method` is not among the supported options. Examples -------- >>> G = nx.path_graph(5) >>> nx.shortest_path_length(G, source=0, target=4) 4 >>> p = nx.shortest_path_length(G, source=0) # target not specified >>> p[4] 4 >>> p = nx.shortest_path_length(G, target=4) # source not specified >>> p[0] 4 >>> p = dict(nx.shortest_path_length(G)) # source,target not specified >>> p[0][4] 4 Notes ----- The length of the path is always 1 less than the number of nodes involved in the path since the length measures the number of edges followed. For digraphs this returns the shortest directed path length. To find path lengths in the reverse direction use G.reverse(copy=False) first to flip the edge orientation. See Also -------- all_pairs_shortest_path_length() all_pairs_dijkstra_path_length() all_pairs_bellman_ford_path_length() single_source_shortest_path_length() single_source_dijkstra_path_length() single_source_bellman_ford_path_length() """ if method not in ('dijkstra', 'bellman-ford'): # so we don't need to check in each branch later raise ValueError('method not supported: {}'.format(method)) method = 'unweighted' if weight is None else method if source is None: if target is None: # Find paths between all pairs. if method == 'unweighted': paths = nx.all_pairs_shortest_path_length(G) elif method == 'dijkstra': paths = nx.all_pairs_dijkstra_path_length(G, weight=weight) else: # method == 'bellman-ford': paths = nx.all_pairs_bellman_ford_path_length(G, weight=weight) else: # Find paths from all nodes co-accessible to the target. with nx.utils.reversed(G): if method == 'unweighted': # We need to exhaust the iterator as Graph needs # to be reversed. path_length = nx.single_source_shortest_path_length paths = path_length(G, target) elif method == 'dijkstra': path_length = nx.single_source_dijkstra_path_length paths = path_length(G, target, weight=weight) else: # method == 'bellman-ford': path_length = nx.single_source_bellman_ford_path_length paths = path_length(G, target, weight=weight) else: if target is None: # Find paths to all nodes accessible from the source. if method == 'unweighted': paths = nx.single_source_shortest_path_length(G, source) elif method == 'dijkstra': path_length = nx.single_source_dijkstra_path_length paths = path_length(G, source, weight=weight) else: # method == 'bellman-ford': path_length = nx.single_source_bellman_ford_path_length paths = path_length(G, source, weight=weight) else: # Find shortest source-target path. if method == 'unweighted': p = nx.bidirectional_shortest_path(G, source, target) paths = len(p) - 1 elif method == 'dijkstra': paths = nx.dijkstra_path_length(G, source, target, weight) else: # method == 'bellman-ford': paths = nx.bellman_ford_path_length(G, source, target, weight) return paths
def solve(list_of_locations, list_of_homes, starting_car_location, adjacency_matrix, params=[]): """ Write your algorithm here. Input: list_of_locations: A list of locations such that node i of the graph corresponds to name at index i of the list list_of_homes: A list of homes starting_car_location: The name of the starting location for the car adjacency_matrix: The adjacency matrix from the input file Output: A list of locations representing the car path A dictionary mapping drop-off location to a list of homes of TAs that got off at that particular location NOTE: both outputs should be in terms of indices not the names of the locations themselves """ orig_name_to_num = {} orig_num_to_name = {} for i in range(len(list_of_locations)): orig_name_to_num[list_of_locations[i]] = i orig_num_to_name[i] = list_of_locations[i] name_to_num = {} name_to_num[starting_car_location] = 0 num_to_name = {} num_to_name[0] = starting_car_location counter = 1 for location in list_of_locations: if (location != starting_car_location): name_to_num[location] = counter num_to_name[counter] = location counter += 1 locs = {} locs[0] = 0 counter2 = 1 for home in list_of_homes: if home != starting_car_location: locs[name_to_num[home]] = counter2 counter2 += 1 edgeList = [] # print(list_of_locations, " list of locations ") # print(adjacency_matrix) for i in range(len(list_of_locations)): for j in range(len(list_of_locations)): matWeight = adjacency_matrix[i][j] if matWeight == 'x': matWeight = 0 else: matWeight = float(matWeight) if matWeight != 0: C = orig_num_to_name[i] start = name_to_num[C] D = orig_num_to_name[j] end = name_to_num[D] edgeList.append((start, end, matWeight)) # print( orig_name_to_num, " orig_name_to_num") # print( orig_num_to_name, " orig_num_to_name") # print( name_to_num, " name_to_num") # print( num_to_name, " num_to_name") G = nx.MultiGraph() G.add_nodes_from(list(num_to_name.keys())) G.add_weighted_edges_from(edgeList) dfs_order, droploc, leafloc = to_solve_k(G, locs) # print("__________ DONE WITH ALG__________") if (dfs_order[-1] != dfs_order[0]): dfs_order.append(dfs_order[0]) for leaf in leafloc: dr = leafloc[leaf] if dr not in dfs_order: min_dist = sys.maxsize vert = 0 for drop in dfs_order: dis = nx.bellman_ford_path_length(G, drop, leaf) if (dis < min_dist): vert = drop min_dist = dis leafloc[leaf] = vert if vert not in droploc: droploc[vert] = [leaf] else: droploc[vert].append(leaf) drive_path = [] for v in dfs_order: char = num_to_name[v] # taking our v and turning it into a char p = orig_name_to_num[ char] # taking the char and returning the true adj matrix index drive_path.append(p) # print("__________test__________") # print(drive_path) homes = set(locs.keys()) homes.remove(0) # while (len(list(homes & set(leafloc.keys())))== len(list(homes))): for loc in locs: if loc != 0 and loc not in leafloc: vert = 0 min_dist = sys.maxsize for drop in dfs_order: dis = nx.bellman_ford_path_length(G, drop, leaf) if (dis < min_dist): min_dist = dis vert = drop leafloc[loc] = vert droploc[vert].append(loc) drop_locations = {} for drop in droploc: locations = [] char = num_to_name[drop] # taking our v and turning it into a char p = orig_name_to_num[ char] # taking the char and returning the true adj matrix index for col in droploc[drop]: charr = num_to_name[col] # taking our v and turning it into a char pp = orig_name_to_num[ charr] # taking the char and returning the true adj matrix index locations.append(pp) drop_locations[p] = locations # print(drop_locations) # print("__________SOLVED__________") return drive_path, drop_locations
print("A* runtime: " + str(end - start) + " seconds") createKML(path, nodes, "AStar") path_length = nx.astar_path_length(G, source, target) if USE_TIME: print("A* path time: " + str(path_length) + " seconds") else: print("A* path distance: " + str(path_length) + " miles") # explored = astar_explored(G, source, target) # print("A* explored: " + explored) print("") start = time.time() path = bellman_ford(G, source, target) end = time.time() print("Bellman Ford shortest path: " + path) print("Bellman Ford runtime: " + str(end - start) + " seconds") createKML(path, nodes, "BellmanFord") path_length = nx.bellman_ford_path_length(G, source, target) if USE_TIME: print("Bellman Ford path time: " + str(path_length) + " seconds") else: print("Bellman Ford path distance: " + str(path_length) + " miles") # explored = bellman_ford_explored(G, source, target) # print("Bellman Ford explored: " + explored) print("") start = time.time() path = floyd_warshall(G, source, target) end = time.time() print("Floyd Warshall shortest path: " + path) print("Floyd Warshall runtime: " + str(end - start) + " seconds") createKML(path, nodes, "FloydWarshall") _, distance = nx.floyd_warshall_predecessor_and_distance(G)
def test_others(self): assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9) assert_equal( nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal( dict(nx.single_source_bellman_ford_path_length(self.XG, 's'))['v'], 9) D, P = nx.single_source_bellman_ford(self.XG, 's', target='v') assert_equal(D['v'], 9) assert_equal(P['v'], ['s', 'x', 'u', 'v']) (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's') assert_equal(P['v'], ['u']) assert_equal(D['v'], 9) (P, D) = nx.goldberg_radzik(self.XG, 's') assert_equal(P['v'], 'u') assert_equal(D['v'], 9) G = nx.path_graph(4) assert_equal(nx.single_source_bellman_ford_path(G, 0), { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3] }) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)), { 0: 0, 1: 1, 2: 2, 3: 3 }) assert_equal(nx.single_source_bellman_ford(G, 0), ({ 0: 0, 1: 1, 2: 2, 3: 3 }, { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3] })) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({ 0: [None], 1: [0], 2: [1], 3: [2] }, { 0: 0, 1: 1, 2: 2, 3: 3 })) assert_equal(nx.goldberg_radzik(G, 0), ({ 0: None, 1: 0, 2: 1, 3: 2 }, { 0: 0, 1: 1, 2: 2, 3: 3 })) assert_equal(nx.single_source_bellman_ford_path(G, 3), { 0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3] }) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 3)), { 0: 3, 1: 2, 2: 1, 3: 0 }) assert_equal(nx.single_source_bellman_ford(G, 3), ({ 0: 3, 1: 2, 2: 1, 3: 0 }, { 0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3] })) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 3), ({ 0: [1], 1: [2], 2: [3], 3: [None] }, { 0: 3, 1: 2, 2: 1, 3: 0 })) assert_equal(nx.goldberg_radzik(G, 3), ({ 0: 1, 1: 2, 2: 3, 3: None }, { 0: 3, 1: 2, 2: 1, 3: 0 })) G = nx.grid_2d_graph(2, 2) dist, path = nx.single_source_bellman_ford(G, (0, 0)) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) assert_equal(sorted(path.items()), [((0, 0), [(0, 0)]), ((0, 1), [(0, 0), (0, 1)]), ((1, 0), [(0, 0), (1, 0)]), ((1, 1), [(0, 0), (0, 1), (1, 1)])]) pred, dist = nx.bellman_ford_predecessor_and_distance(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), [None]), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) pred, dist = nx.goldberg_radzik(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)), ((1, 0), (0, 0)), ((1, 1), (0, 1))]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
def on_button_clicked(b): alert = QMessageBox() if radiobutton1.isChecked()==True: file1="Input10.txt" alert.setText('1!') if radiobutton2.isChecked()==True: file1="Input20.txt" alert.setText('2!') if radiobutton3.isChecked()==True: file1="Input30.txt" alert.setText('3!') if radiobutton4.isChecked()==True: file1="Input40.txt" alert.setText('4!') if radiobutton5.isChecked()==True: file1="Input50.txt" alert.setText('5!') if radiobutton6.isChecked()==True: file1="Input60.txt" alert.setText('6!') if radiobutton7.isChecked()==True: file1="Input70.txt" alert.setText('7!') if radiobutton8.isChecked()==True: file1="Input80.txt" alert.setText('8!') if radiobutton9.isChecked()==True: file1="Input90.txt" alert.setText('9!') if radiobutton10.isChecked()==True: file1="Input100.txt" alert.setText('10!') alert.exec_() vertices=[] vertex=[] edges=[] b=[] G = nx.MultiDiGraph(); f= open(file1,'r') print(f.readline()) print(f.readline()) num= int(f.readline()) j=0 print(f.readline()) for j in range(0,num): vertices.append(f.readline().split()) vertex.append(vertices[j][0]) print(f.readline()) for j in range(0,num): edges.append(f.readline().split()) b.append(edges[j].pop(0)) for i in range(0,num): for j in range(0,num): # print(b[0]) ij= j *4; ij2= ij + 2; if ij < len(edges[i]): a = edges[i][ij] cost = float(edges[i][ij2]) if G.has_edge(b[i],a) : prev_Cost = G.get_edge_data(b[i],a) if prev_Cost[0]['weight'] >cost: G.remove_edge(b[i],a) G.add_edge(b[i],a,weight= cost) else: G.add_edge(b[i],a,weight= cost) #displaying original graph pos = nx.spring_layout(G) nx.draw(G,with_labels=True,node_color='skyblue', node_size=220, width=1, edge_cmap=plt.cm.OrRd,arrowstyle='->',arrowsize=20,font_size=10,pos=nx.random_layout(G, seed=13)) plt.show() if algo1.isChecked()==True: #prims print("Algo1"); G=G.to_undirected() pos = nx.spring_layout(G) T=nx.MultiGraph() V = len(G.nodes()) # V denotes the number of vertices in G dist = [] # dist[i] will hold the minimum weight edge value of node i to be included in MST parent = [None] * V # parent[i] will hold the vertex connected to i, in the MST edge mstSet = [] # mstSet[i] will hold true if vertex i is included in the MST for i in range(V): dist.append(sys.maxsize) mstSet.append(False) n=0 dist.append(0) parent.append(-1) # starting vertex is itself the root, and hence has no paren for count in range(V - 1): # print(count) u = minDistance(dist, mstSet, V) # print(u) # pick the minimum distance vertex from the set of vertices mstSet[u] = True for v in range(V): a=str(u) b=str(v) if G.has_edge(a, b): # print("I am Here") d='weight' c=G[a][b] # print(c[0]['weight']) e=c[0]['weight'] if mstSet[v] == False and e< dist[v]: dist[v] = e # print(dist[v]) parent[v] = u for X in range(V): if parent[X] != -1: # ignore the parent of the starting node if (str(parent[X]),str(X)) in G.edges(): T.add_edge( parent[X], X, weight=dist[X]) nx.draw(T,with_labels=True,node_color='skyblue', node_size=220, width=1, edge_cmap=plt.cm.OrRd,arrowstyle='->',arrowsize=20,font_size=10,pos=nx.random_layout(T, seed=20)) alert_m="Cost is "+str(T.size(weight='weight')/10000000) alert.setText(alert_m) alert.exec_() plt.show() if algo2.isChecked()==True: #kruskal print("Algo1"); G=G.to_undirected() T= (nx.minimum_spanning_tree(G)) print(sorted(T.edges(data=True))) pos = nx.spring_layout(T) alert_m="Cost is "+str(T.size(weight='weight')/10000000) alert.setText(alert_m) alert.exec_() nx.draw(T,with_labels=True,node_color='skyblue', node_size=220, width=1, edge_cmap=plt.cm.OrRd, arrowstyle='->',arrowsize=20, font_size=10, font_weight="bold", pos=nx.random_layout(G, seed=13)) plt.show() if algo3.isChecked()==True: #Dijiskra # print("Algo1"); if nx.has_path(G,str('1'),str('5')): TCost = nx.dijkstra_path_length(G, '1', '5', 'weight') else: TCost = float('inf'); alert_m="Cost of Directed to node 5 is " + str(TCost /10000000) G=G.to_undirected() if nx.has_path(G,str('1'),str('5')): TCost = nx.dijkstra_path_length(G, '1', '5', 'weight') else: TCost = float('inf'); alert_m= alert_m + "\nCost of Undirected to node 5 is " + str(TCost /10000000) alert.setText(alert_m) alert.exec_() #............................... if algo4.isChecked()==True: #Bellman Ford # print("Algo1"); # T=nx.bellman_ford_path(G,'1','5',weight='weight') alert_m="Cost of Directed: " if nx.has_path(G,str(1) , '5'): TCost= nx.bellman_ford_path_length(G,str(1),'5',weight='weight') else: TCost=float('inf'); alert_m=alert_m + str(TCost/10000000) +"\n" G=G.to_undirected() alert_m=alert_m +"Cost of Undirected: " if nx.has_path(G,str(1) , '5'): TCost= nx.bellman_ford_path_length(G,str(1),'5',weight='weight') else: TCost=0 alert_m=alert_m + str(TCost/10000000) +"\n" alert.setText(alert_m) alert.exec_() if algo5.isChecked()==True: #Floyd Warshal # print("Algo1"); path_lengths=nx.floyd_warshall(G) alert_m="" Cost_t=0; for i in range(1,num): for j in range(1,num): if path_lengths[str(i)][str(j)] != float('inf'): Cost_t = Cost_t + path_lengths[str(i)][str(j)] TCost=path_lengths['1']['5'] alert_m="Cost is : "+str(Cost_t/10000000)+ "+" + str(TCost/10000000) alert.setText(alert_m) alert.exec_() if algo6.isChecked()==True: #Clustering Coefficient print("Algo1"); G=G.to_undirected() G=nx.Graph(G) coef=nx.average_clustering(G) alert_m="Coefficient is " + str(coef) alert.setText(alert_m) alert.exec_() f.close() pos = nx.spring_layout(G)
def main(argv): parser = argparse.ArgumentParser() parser.add_argument("gfa_file", help="assembly graph in gfa format") parser.add_argument("kmer_length", help="kmer length assumed overlap") parser.add_argument("cov_file", help="coverages") parser.add_argument("out_stub", help="output_stub") args = parser.parse_args() #import ipdb; ipdb.set_trace() unitigGraph = UnitigGraph.loadGraphFromGfaFile(args.gfa_file, int(args.kmer_length), args.cov_file) components = sorted(nx.connected_components( unitigGraph.undirectedUnitigGraph), key=len, reverse=True) #probably haves separate components but no matter c = 0 for component in components: unitigSubGraph = unitigGraph.createUndirectedGraphSubset(component) if nx.is_directed_acyclic_graph( unitigSubGraph.directedUnitigBiGraph) is True: dGraph = unitigSubGraph.directedUnitigBiGraph top_sort = list(nx.topological_sort(dGraph)) lenSort = len(top_sort) maxPred = {} maxWeightNode = {} for node in top_sort: maxWeight = 0. maxPred[node] = None noded = node[:-1] for predecessor in dGraph.predecessors(node): weight = maxWeightNode[predecessor] if weight > maxWeight: maxWeight = weight maxPred[node] = predecessor if unitigSubGraph.directedUnitigBiGraph.out_degree(node) == 0: lengthPlus = unitigSubGraph.lengths[noded] else: lengthPlus = unitigSubGraph.lengths[ noded] - unitigSubGraph.overlapLength myWeight = np.sum(unitigSubGraph.covMap[noded]) * lengthPlus maxWeightNode[node] = maxWeight + myWeight bestNode = None maxNodeWeight = 0. for node in top_sort: if maxWeightNode[node] > maxNodeWeight: maxNodeWeight = maxWeightNode[node] bestNode = node minPath = [] while bestNode is not None: minPath.append(bestNode) bestNode = maxPred[bestNode] minPath.reverse() for node in minPath: print(node[:-1]) #print("Dummy") else: (source_list, sink_list) = unitigSubGraph.selectSourceSinks(0.75) mindist = 0 minpair = None for source in source_list: sourced = convertNodeToName(source) for sink in sink_list: sinkd = convertNodeToName(sink) dist = nx.bellman_ford_path_length( unitigSubGraph.directedUnitigBiGraph, sourced, sinkd, weight='covweight') if dist < mindist: min = mindist minpair = (sourced, sinkd) minPath = nx.bellman_ford_path( unitigSubGraph.directedUnitigBiGraph, minpair[0], minpair[1], weight='covweight') for noded in minPath: print(noded[:-1]) maxSeq = unitigSubGraph.getUnitigWalk(minPath) with open(args.out_stub + ".fa", "w") as fastaFile: fastaFile.write(">" + args.out_stub + "\n") fastaFile.write(maxSeq + "\n") covPath = unitigSubGraph.computePathCoverage(minPath) with open(args.out_stub + ".csv", "w") as covFile: cList = covPath.tolist() cString = ",".join([str(x) for x in cList]) covFile.write(cString + "\n") #components_d = sorted(nx.connected_components(unitigSubGraph.directedUnitigBiGraph), key = len, reverse=True) c = c + 1
# add position atribute from (x,y) coordinates for n, p in data: G.nodes[n]['pos'] = (p['x'], p['y']) #print(G.nodes(data=True)) #print(G.edges(data=True)) pos = nx.get_node_attributes(G, 'pos') # create plot fig, ax1 = plt.subplots() nx.draw_networkx_nodes(G, pos, node_color="r", node_size=50, ax=ax1) nx.draw_networkx_edges(G, pos, edge_color="b", width=2.0, alpha=0.75, ax=ax1) ax1.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True) #nx.draw(G,pos) plt.gca().invert_yaxis() # plot labes ax1.set_title('random path') ax1.set_xlabel('x') ax1.set_ylabel('y') # overlay map img = plt.imread("map.jpg") ax1.imshow(img) plt.show() # print out the shortest path using Bellman Ford print(nx.bellman_ford_path(G, 'c1_1', 'c4_3', weight='distance')) # print the distance of the path print(nx.bellman_ford_path_length(G, 'c1_1', 'c4_3', weight='distance'))
import networkx as nx import matplotlib.pyplot as plt #infile = "rosalind_sample.txt" infile = "rosalind_bf.txt" with open(infile, "r") as f: lines = [line.strip() for line in f.readlines()] n_node, n_edge = map(int, lines[0].split()) # Read as Directed Graph G = nx.parse_edgelist(lines[1:], nodetype=int, data=(('weight', int), ), delimiter=" ", create_using=nx.DiGraph) # # See the actual tree nx.draw(G, with_labels=True) plt.show() for i in range(1, n_node + 1): try: print(nx.bellman_ford_path_length(G, 1, i), end=" ") except: print("x", end=" ")