def prog_21(fname): f = open(fname) n = eval(f.readline().strip()) graphs = {} for i in xrange(n): nodes,num = map(int, f.readline().strip().split()) graph = nx.DiGraph() fe = None for j in xrange(num): e1,e2,w = map(int, f.readline().strip().split()) if j==0: fe = (e1,e2) graph.add_weighted_edges_from([(e1,e2,w)]) graphs[i]={'graph':graph, 'edge':fe} f.close() # print graphs for i in xrange(n): graph = graphs[i]['graph'] fe = graphs[i]['edge'] try: print nx.dijkstra_path_length(graph,fe[0],fe[1])+nx.dijkstra_path_length(graph,fe[1],fe[0]), except: print -1,
def eight_and_nine(graph, source, target, number): if source == target: neighbours = graph.successors(source) for neighbour in neighbours: result = nx.dijkstra_path_length( graph, source=source, target=neighbour) + nx.dijkstra_path_length( graph, source=neighbour, target=target) else: result = nx.dijkstra_path_length(graph, source=source, target=target) return "Output #{}: {}".format(number, result)
def nxShortestPath(nxGraph, nxPos, startPt, endPt, Dijk=0): if Dijk == 0: nxList = nx.shortest_path(nxGraph, source=startPt, target=endPt) score = nx.shortest_path_length(nxGraph, source=startPt, target=endPt) dist = nx.shortest_path_length(nxGraph, source=startPt, target=endPt, weight="distance") elif Dijk == 1: nxList = nx.dijkstra_path(nxGraph, source=startPt, target=endPt, weight="weight") score = nx.dijkstra_path_length(nxGraph, source=startPt, target=endPt, weight="weight") dist = nx.dijkstra_path_length(nxGraph, source=startPt, target=endPt, weight="distance") nxH = nx.subgraph(nxGraph, nxList) return nxList, nxH, score, dist
def test_dijkstra(self): (D, P) = nx.single_source_dijkstra(self.XG, 's') validate_path(self.XG, 's', 'v', 9, P['v']) assert_equal(D['v'], 9) validate_path( self.XG, 's', 'v', 9, nx.single_source_dijkstra_path(self.XG, 's')['v']) assert_equal(dict( nx.single_source_dijkstra_path_length(self.XG, 's'))['v'], 9) validate_path( self.XG, 's', 'v', 9, nx.single_source_dijkstra(self.XG, 's')[1]['v']) validate_path( self.MXG, 's', 'v', 9, nx.single_source_dijkstra_path(self.MXG, 's')['v']) GG = self.XG.to_undirected() # make sure we get lower weight # to_undirected might choose either edge with weight 2 or weight 3 GG['u']['x']['weight'] = 2 (D, P) = nx.single_source_dijkstra(GG, 's') validate_path(GG, 's', 'v', 8, P['v']) assert_equal(D['v'], 8) # uses lower weight of 2 on u<->x edge validate_path(GG, 's', 'v', 8, nx.dijkstra_path(GG, 's', 'v')) assert_equal(nx.dijkstra_path_length(GG, 's', 'v'), 8) validate_path(self.XG2, 1, 3, 4, nx.dijkstra_path(self.XG2, 1, 3)) validate_path(self.XG3, 0, 3, 15, nx.dijkstra_path(self.XG3, 0, 3)) assert_equal(nx.dijkstra_path_length(self.XG3, 0, 3), 15) validate_path(self.XG4, 0, 2, 4, nx.dijkstra_path(self.XG4, 0, 2)) assert_equal(nx.dijkstra_path_length(self.XG4, 0, 2), 4) validate_path(self.MXG4, 0, 2, 4, nx.dijkstra_path(self.MXG4, 0, 2)) validate_path( self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's', 'v')[1]['v']) validate_path( self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's')[1]['v']) validate_path(self.G, 's', 'v', 2, nx.dijkstra_path(self.G, 's', 'v')) assert_equal(nx.dijkstra_path_length(self.G, 's', 'v'), 2) # NetworkXError: node s not reachable from moon assert_raises(nx.NetworkXNoPath, nx.dijkstra_path, self.G, 's', 'moon') assert_raises( nx.NetworkXNoPath, nx.dijkstra_path_length, self.G, 's', 'moon') validate_path(self.cycle, 0, 3, 3, nx.dijkstra_path(self.cycle, 0, 3)) validate_path(self.cycle, 0, 4, 3, nx.dijkstra_path(self.cycle, 0, 4)) assert_equal( nx.single_source_dijkstra(self.cycle, 0, 0), ({0: 0}, {0: [0]}))
def cost_split(G,cur,tremdstlist): csplit=0 tablesplit=[[] for i in xrange(len(tremdstlist))] num=0 for j in tremdstlist: if (cur!=tremdstlist[num]): tablesplit[num]=nx.dijkstra_path(G,cur,tremdstlist[num]) num=num+1 csplit=nx.dijkstra_path_length(G,cur,tremdstlist[0]) #print "CSPLIT added cost from :",cur, "to ",tremdstlist[0],"as ",length[cur][tremdstlist[0]] #*print "tablesplit[0]=",tablesplit[0] for x in xrange(1,num): curpath=tablesplit[x] for y in xrange(len(curpath)): if (y!=len(curpath)-1): if ((curpath[y+1] in tablesplit[0]) !=True): curwt=G.edge[curpath[y]][curpath[y+1]]['weight'] #print "CSPLIT : Adding [",curpath[y],"][",curpath[y+1],"]" csplit=csplit+curwt return csplit
def weighted_concept_path(self, node1, node2): ''' Shortest path between two nodes :param node1: id of node 1 :param node2: id of node 2 :return: shortest path between node1 and node2 ''' spath = 0 if self.all_dist: try: spath = self.all_dist[node1][node2] except: raise exception.GraphException((node1, node2), \ 'No path for this node pair') else: try: spath = nx.dijkstra_path_length(self.G, node1, node2) except: raise exception.GraphException((node1, node2), \ 'No path for this node pair') return spath
def group_cyclefactor_approx( demand_hist, M, transport_graph, cost_label='cost' ) : """ construct and solve the LP relaxation of the IP """ cost, constr, SERVICE = construct_lp_relaxation( demand_hist, M, transport_graph, cost_label=cost_label ) prog = cvxpy.program( cvxpy.minimize( cost ), constr ) res = prog.solve( quiet=DEBUG ) # still need to debug this garbage!!!! wtf is going on here? """ convert to proper format and "round" the solution """ fractional = dict() trips_hist = dict() for (i,j) in demand_hist : target = dict() for edge in itertools.product( M.neighbors_iter(i), M.neighbors_iter(j) ) : temp = SERVICE.get_edge_data( *edge ).get('var').value fractional[ edge ] = temp target[ edge ] = temp demand_update = greedy_chairman_rounding( target ) trips_hist.update( demand_update ) """ construct and solve the resulting cycle factor instance """ service_edges = nx.MultiDiGraph() for (x,y), NUMTRIPS in trips_hist.iteritems() : weight = nx.dijkstra_path_length( transport_graph, x, y, weight=cost_label ) for k in range(NUMTRIPS) : service_edges.add_edge( x,y, cost=weight ) cycles = cyclefactor.cyclefactor( service_edges, transport_graph ) return cycles
def connect_virtually(n, m, c): # create or reference adjacent nodes c_name = '(' + ' '.join(c) + ')' try: nb = [i for i in self.graph[n] if c_name in i.name and not self.graph.successors(i)][0] except IndexError: nb = copy.deepcopy(n) nb.name = n.name + ' ' + c_name try: mb = [i for i in self.graph[m] if c_name in i.name and not self.graph.predecessors(i)][0] except IndexError: mb = copy.deepcopy(m) mb.name = m.name + ' ' + c_name # connect nodes self.graph.add_edge(n, nb, weight=common_intervals[c]) self.graph.add_edge(nb, n, weight=0.0) self.graph.add_edge(m, mb, weight=common_intervals[c]) self.graph.add_edge(mb, m, weight=0.0) tt = nx.dijkstra_path_length(self.graph, n, m) self.graph.add_edge(nb, mb, weight=tt)
def removeNonConnectedUsers(self, graph, dist_threshold): components = nx.connected_components(graph) print "Number of connected components: %s" % len(components) print "Removing non-connected user nodes" remove_nodes = [] for component in components: usernodes = [] userdists = {} for node in component: if type(node) == User: usernodes.append(node) u1idx = 0 ulen = len(usernodes) for u1 in usernodes: u1idx = u1idx + 1 print "%s/%s" % (u1idx, ulen) if not u1.id in userdists: userdists[u1.id] = 1000 for u2 in usernodes: if u1 == u2: continue pathres = nx.dijkstra_path_length(graph,u1,u2) if pathres < userdists[u1.id]: userdists[pathres] = pathres if userdists[u1.id] < dist_threshold: break # condition satisfied for user in usernodes: if userdists[user.id] > dist_threshold: # shortest path to another user is > 5 -> remove print "Removing user %s. Dist value: %s" % (user.id, userdists[user.id]) remove_nodes.append(user) print "Removing %s user nodes" % len(remove_nodes) graph.remove_nodes_from(remove_nodes) del remove_nodes
def test_dijkstra(self): (D,P)= nx.single_source_dijkstra(self.XG,'s') assert_equal(P['v'], ['s', 'x', 'u', 'v']) assert_equal(D['v'],9) assert_equal(nx.single_source_dijkstra_path(self.XG,'s')['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_dijkstra_path_length(self.XG,'s')['v'],9) assert_equal(nx.single_source_dijkstra(self.XG,'s')[1]['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_dijkstra_path(self.MXG,'s')['v'], ['s', 'x', 'u', 'v']) GG=self.XG.to_undirected() # make sure we get lower weight # to_undirected might choose either edge with weight 2 or weight 3 GG['u']['x']['weight']=2 (D,P)= nx.single_source_dijkstra(GG,'s') assert_equal(P['v'] , ['s', 'x', 'u', 'v']) assert_equal(D['v'],8) # uses lower weight of 2 on u<->x edge assert_equal(nx.dijkstra_path(GG,'s','v'), ['s', 'x', 'u', 'v']) assert_equal(nx.dijkstra_path_length(GG,'s','v'),8) assert_equal(nx.dijkstra_path(self.XG2,1,3), [1, 4, 5, 6, 3]) assert_equal(nx.dijkstra_path(self.XG3,0,3), [0, 1, 2, 3]) assert_equal(nx.dijkstra_path_length(self.XG3,0,3),15) assert_equal(nx.dijkstra_path(self.XG4,0,2), [0, 1, 2]) assert_equal(nx.dijkstra_path_length(self.XG4,0,2), 4) assert_equal(nx.dijkstra_path(self.MXG4,0,2), [0, 1, 2]) assert_equal(nx.single_source_dijkstra(self.G,'s','v')[1]['v'], ['s', 'u', 'v']) assert_equal(nx.single_source_dijkstra(self.G,'s')[1]['v'], ['s', 'u', 'v']) assert_equal(nx.dijkstra_path(self.G,'s','v'), ['s', 'u', 'v']) assert_equal(nx.dijkstra_path_length(self.G,'s','v'), 2) # NetworkXError: node s not reachable from moon assert_raises(nx.NetworkXNoPath,nx.dijkstra_path,self.G,'s','moon') assert_raises(nx.NetworkXNoPath,nx.dijkstra_path_length,self.G,'s','moon') assert_equal(nx.dijkstra_path(self.cycle,0,3),[0, 1, 2, 3]) assert_equal(nx.dijkstra_path(self.cycle,0,4), [0, 6, 5, 4]) assert_equal(nx.single_source_dijkstra(self.cycle,0,0),({0:0}, {0:[0]}) )
def sum_dist_former(key_nodes): sum_dist = 0.0 for node in key_nodes: for node_a in key_nodes: dis = float(nx.dijkstra_path_length(G, node_a, node)) sum_dist = sum_dist + dis ave_dist = sum_dist/len(key_nodes) return ave_dist
def demand_enroute_velocity( lengraph, rategraph, length='length', rate='rate' ) : V = 0. for u, v, rate_data in rategraph.edges_iter( data=True ) : curr_rate = rate_data.get( rate, None ) if curr_rate is None : continue dist = nx.dijkstra_path_length( lengraph, u, v, weight=length ) V += curr_rate * dist return V
def nearestPathLen(point1,point2, G): try: return nx.dijkstra_path_length(G, point1, point2) except: print 'Illegal Path:', print point1, print ' ', print point2 return 999999999
def test_dijkstra(self): (D,P)= nx.single_source_dijkstra(self.XG,'s') assert_equal(P['v'], ['s', 'x', 'u', 'v']) assert_equal(D['v'],9) assert_equal(nx.single_source_dijkstra_path(self.XG,'s')['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_dijkstra_path_length(self.XG,'s')['v'],9) assert_equal(nx.single_source_dijkstra(self.XG,'s')[1]['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_dijkstra_path(self.MXG,'s')['v'], ['s', 'x', 'u', 'v']) GG=self.XG.to_undirected() (D,P)= nx.single_source_dijkstra(GG,'s') assert_equal(P['v'] , ['s', 'x', 'u', 'v']) assert_equal(D['v'],8) # uses lower weight of 2 on u<->x edge assert_equal(nx.dijkstra_path(GG,'s','v'), ['s', 'x', 'u', 'v']) assert_equal(nx.dijkstra_path_length(GG,'s','v'),8) assert_equal(nx.dijkstra_path(self.XG2,1,3), [1, 4, 5, 6, 3]) assert_equal(nx.dijkstra_path(self.XG3,0,3), [0, 1, 2, 3]) assert_equal(nx.dijkstra_path_length(self.XG3,0,3),15) assert_equal(nx.dijkstra_path(self.XG4,0,2), [0, 1, 2]) assert_equal(nx.dijkstra_path_length(self.XG4,0,2), 4) assert_equal(nx.dijkstra_path(self.MXG4,0,2), [0, 1, 2]) assert_equal(nx.single_source_dijkstra(self.G,'s','v')[1]['v'], ['s', 'u', 'v']) assert_equal(nx.single_source_dijkstra(self.G,'s')[1]['v'], ['s', 'u', 'v']) assert_equal(nx.dijkstra_path(self.G,'s','v'), ['s', 'u', 'v']) assert_equal(nx.dijkstra_path_length(self.G,'s','v'), 2) # NetworkXError: node s not reachable from moon assert_raises(nx.NetworkXNoPath,nx.dijkstra_path,self.G,'s','moon') assert_raises(nx.NetworkXNoPath,nx.dijkstra_path_length,self.G,'s','moon') assert_equal(nx.dijkstra_path(self.cycle,0,3),[0, 1, 2, 3]) assert_equal(nx.dijkstra_path(self.cycle,0,4), [0, 6, 5, 4]) assert_equal(nx.single_source_dijkstra(self.cycle,0,0),(0, [0]) )
def get_shortest_path_through_gateways(self, source): "return the path lengths to the source ip address to all the gateways" G=nx.DiGraph() G.add_weighted_edges_from([(link.lastHopIP, link.destinationIP, link.tcEdgeCost) for link in self.linklist]) paths_length=dict() for gw in self.gatewaylist: paths_length[gw]=nx.dijkstra_path_length(G, source, gw) return paths_length
def compute_shortest_path(graph, target_node, source_node): ''' Display shortest path result ''' print '\n******* From ' + source_node + ' to ' + target_node + ' *******' path = nx.dijkstra_path(graph,source=source_node,target=target_node) print 'Path:', path path_length = nx.dijkstra_path_length(graph,source=source_node,target=target_node) print 'Path weight: ', path_length display_path_weights(graph, path)
def dij(): with open("rosalind_dij.txt") as f: n, m = map(int, f.readline().strip().split()) lines = f.readlines() edge_list = map(lambda x: map(int, x.strip().split()), lines) # Create the graph G = nx.DiGraph() G.add_nodes_from(range(1,n+1)) G.add_weighted_edges_from(edge_list) for n in G.nodes(): try: print nx.dijkstra_path_length(G, 1, n), except: # node is not reachable print -1, print ""
def StayConnected(N, c): G = nx.complete_graph(1) for i in range(1, N): existingNodes = list(G.nodes()) random.shuffle(existingNodes) optimalToConnect = 0 optimalUtility = float("-inf") for nodeToConnect in existingNodes: G.add_edge(i, nodeToConnect) sumPathLengths = 0 for node in G.nodes(): sumPathLengths -= nx.dijkstra_path_length(G, i, node) if sumPathLengths > optimalUtility: optimalToConnect = nodeToConnect optimalUtility = sumPathLengths G.remove_edge(i, nodeToConnect) G.add_edge(i,nodeToConnect) print optimalUtility existingNodes.remove(nodeToConnect) for nodeToConnect in existingNodes: G.add_edge(i, nodeToConnect) sumPathLengths = 0 for node in G.nodes(): sumPathLengths -= nx.dijkstra_path_length(G, i, node) if sumPathLengths - optimalUtility > c: optimalUtility = sumPathLengths else: G.remove_edge(i, nodeToConnect) return G
def main83(): g = g83(matrix) N = len(matrix) M = len(matrix[0]) print "(%d) Nodes, (%d) Edges" % (len(g.nodes()), len(g.edges())) start = (0,0) end = (N-1, M-1) path_d = nx.dijkstra_path(g, start, end) print len(path_d), nx.dijkstra_path_length(g, start, end) + g.node[start].get('value') for node in path_d: print node, g.node[node].get('value'), g[node]
def test_dijkstra_search_digraph(testgraph): """ Testing dijkstra_search function for undirected graphs. """ a, b = testgraph[2:] s = randint(0, 99) t = randint(0, 99) nx_dijk = nx.dijkstra_path_length(a, s, t) sg_dijk = sg.dijkstra.dijkstra_search(b, s, t, directed = True) assert nx_dijk == sg_dijk[1]
def makecomplete(subset, graph): nodes = subset.nodes() nodesTwo = subset.nodes() result = subset.copy() for node in nodes: for nodeTwo in nodesTwo: if node != nodeTwo: if not subset.has_edge(node, nodeTwo): shortest_path = nx.dijkstra_path_length(graph,node,nodeTwo) result.add_weighted_edges_from([(node,nodeTwo,shortest_path)]) return result
def main(ipr_number, num_clusters): db_dir = os.path.join(os.getcwd(), "db") cur_db = shelve.open(os.path.join(db_dir, ipr_number)) tax_graph = build_tax_graph(cur_db) uniprot_ids = [] info_array = [] for db_domain in cur_db.keys(): if not cur_db[db_domain].get("is_uniref_child", ""): uniprot_ids.append(db_domain) db_item = cur_db[db_domain] cur_cluster_info = [ float(db_item["charge"]), float(db_item["charge_region"]) * 10.0, len(db_item.get("db_refs", [])) * 5.0, calc_domain_distance(db_item) * 100.0, #max(len(db_item.get("string_interactors", [])) - 1, 0), ] info_array.append(cur_cluster_info) info_array = numpy.array(info_array) print 'Num genes', len(info_array), num_clusters cluster_ids, error, nfound = Cluster.kcluster(info_array, nclusters=num_clusters, npass=50)#, method='a', dist='c') #tree = Cluster.treecluster(info_array, method='a', dist='c') #cluster_ids = tree.cut(num_clusters) cluster_dict = collections.defaultdict(lambda: []) for i, cluster_id in enumerate(cluster_ids): cluster_dict[cluster_id].append(uniprot_ids[i]) for index, cluster_group in enumerate(cluster_dict.values()): print '***********', index org_dists = [] for uniprot_id in cluster_group: org = cur_db[uniprot_id]["org_scientific_name"] distance = networkx.dijkstra_path_length(tax_graph, 'Mus musculus', org) org_dists.append((distance, org, uniprot_id)) org_dists.sort() members = [] for d, o, u in org_dists: members.append(dict(organism=o, uniprot_id=get_uniprot_links([u]), alt_names=get_alt_names(cur_db[u]), alt_ids=get_uniprot_links(cur_db[u].get("uniref_children", [])), charge=cur_db[u]["charge"], charge_region="%0.2f" % cur_db[u]["charge_region"], domains=len(cur_db[u].get("db_refs", [])), interactions=get_string_link(u, max(len(cur_db[u].get("string_interactors", [])) - 1, 0)), description=cur_db[u].get("function_descr", " "), c_distance="%0.2f" % calc_domain_distance(cur_db[u]), )) with open("%s-cluster%s.html" % (ipr_number, index), "w") as out_handle: tmpl = Template(cluster_template) out_handle.write(tmpl.render(cluster_members=members))
def process_connection(self, from_point_code, to_point_name, to_point_code, to_point_price): self.points_names[to_point_code] = to_point_name if to_point_price > self.price_limit: return False # break if from_point_code != self.departure_point and to_point_code != self.departure_point: if to_point_code in self.map.nodes(): if nx.dijkstra_path_length(self.map, self.departure_point, from_point_code) + to_point_price >= nx.dijkstra_path_length(self.map, self.departure_point, to_point_code): return True # continue elif nx.dijkstra_path_length(self.map, self.departure_point, from_point_code) + to_point_price > self.price_limit: return True # continue self.map.add_node(to_point_code) self.map.add_edge(from_point_code, to_point_code, label=to_point_price, weight=to_point_price) if to_point_code not in self.visited: self.to_visit.add(to_point_code) return True # continue
def get_etx(self, u_source, u_destination): source, destination = self.__loadG(u_source, u_destination) if source in self.G.nodes() and destination in self.G.nodes(): return nx.dijkstra_path_length(self.G, source, destination) elif source in self.G.nodes(): # find the closest gateway closestgw = None cost = 0 for gw in self.gatewaylist: splen = nx.shortest_path_length(self.G, source, gw) if splen > cost: cost = splen closestgw = gw if closestgw: printout( "Warning: using gateway %s" % (closestgw,)) return nx.dijkstra_path_length(self.G, source, closestgw) else: return 1.0 else: return 1.0
def __init__(self, owner, node_graph, start, end, pos = None): self.owner = owner #print start,end if not nx.has_path(node_graph,start,end): self.valid = False return None #print "----------NEW PATH---------" self.path_list = nx.dijkstra_path(node_graph, source=start, target=end) self.total_length = nx.dijkstra_path_length(node_graph, source=start, target=end) self.current_coords = pos if pos is not None else self.owner.station.loc_to_xyz( start ) self.completed = False self.valid=True
def shortest_path_length(self, from_station_name, to_station_name): ''' Return shortest path length. ''' from_station_g_cd = self._station_name_gcd(from_station_name) to_station_g_cd = self._station_name_gcd(to_station_name) shortest_path_length =\ nx.dijkstra_path_length( self.rail_net, from_station_g_cd, to_station_g_cd) return shortest_path_length
def shortest_path_length_with_locations(self, from_station_location, to_station_location): ''' Return shortest path length with two locations of station. ''' from_station_g_cd = self._station_location_gcd(from_station_location) to_station_g_cd = self._station_location_gcd(to_station_location) shortest_path_length =\ nx.dijkstra_path_length( self.rail_net, from_station_g_cd, to_station_g_cd) return shortest_path_length
def get_path_for_origion_and_destination_pairs(G, pairs, default_value=999): results = [] for orig, dest in pairs: try: result = networkx.dijkstra_path_length(G, str(orig), str(dest)) except: logger.log_warning("failed to find a path from %s to %s; the value is set to %s." \ % (orig, dest, default_value)) result = default_value results.append(result) return results
def nearestNodeToTarget(Graph, targetNode, nodedRoute = []): allResults = [] nearestNode ="" nearestDist = sys.maxint for i,val in enumerate(nodedRoute): if nx.has_path(Graph,val,targetNode): currentDist = nx.dijkstra_path_length(Graph, val, targetNode) allResults.append((val, currentDist)) if currentDist < nearestDist: nearestNode = val nearestDist = currentDist # print str(allResults) return nearestNode, nearestDist
def first_five(graph, path, number): test_list = split_input(path) # print(test_list) result = 0 for element in test_list: # checks if current pair of nodes are neighbors if element[1] not in graph.successors(element[0]): result = 0 else: result += nx.dijkstra_path_length(graph, element[0], element[1]) if result == 0: result = "NO SUCH ROUTE" return "Output #{}: {}".format(number, result)
def top_paths(nodes, graph, weight="weight"): """Find min path through a list of nodes.""" all_paths = [] total_cost = 0 for start, end in zip(nodes[:-1], nodes[1:]): path = nx.dijkstra_path(graph.graph, start, end, weight=weight) cost = nx.dijkstra_path_length(graph.graph, start, end, weight=weight) all_paths.append(path) total_cost += cost if len(all_paths) == 1: return (total_cost, all_paths[0]) else: total_path = [] for path in all_paths[:-1]: total_path += path[:-1] total_path += all_paths[-1] return (total_cost, total_path)
def wienerIndex(g): resPath=0 nodes=nx.nodes(g) if nx.is_directed(g): pairs=iters.permutations(nodes,2) else: pairs=iters.combinations(nodes,2) for i in pairs: try: resPath+=nx.dijkstra_path_length(g,source=i[0],target=i[1] ) except nx.NetworkXNoPath: #print "exception handled" resPath+=0 #print nx.all_pairs_dijkstra_path_length(diG) return resPath
def networkx_method(matrix): n = m = len(matrix) G = nx.DiGraph() for i in range(n): for j in range(m): neighbors = [(i + x, j + y) for x, y in [(-1, 0), (0, -1), (1, 0), (0, 1)] if 0 <= i + x < n and 0 <= j + y < m] for ix, jy in neighbors: G.add_edge((i, j), (ix, jy), weight=matrix[ix][jy]) path_length = nx.dijkstra_path_length(G, source=(0, 0), target=(n - 1, m - 1)) print("Minimum path sum in", n, "by", m, "matrix =", path_length + matrix[0][0])
def geraMelhorCaminho(): g=nx.Graph() _file = open("prouter.dll","r") for lin in _file: ipo = lin.split("|")[0].rstrip() ipd = lin.split("|")[1].rstrip() pso = lin.split("|")[2].rstrip() if pso == "0": g.add_edge(str(ipo),str(ipd),peso=int(pso)) _file.close() for rl in rota_ativa: ipo = rl.split("|")[0].rstrip() ipd = rl.split("|")[1].rstrip() pso = rl.split("|")[2].rstrip() g.add_edge(str(ipo),str(ipd),peso=int(pso)) try: print("Tem Rota? ",nx.has_path(g,"192.168.1.1","192.168.2.1")) _custo = nx.dijkstra_path_length(g,"192.168.1.1","192.168.2.1","peso") addCusto(_custo) melhorCaminho = nx.shortest_path(g,"192.168.1.1","192.168.2.1","peso") except nx.NetworkXException as eee: print(eee) #Remove outras rotas do grafo g.clear() k=0 kmax = len(melhorCaminho)-1 for _remo in melhorCaminho: g.add_edge(melhorCaminho[k],melhorCaminho[k+1]) k+=1 if (k+1 == len(melhorCaminho)): break print(melhorCaminho) pos=nx.spring_layout(g) color_map = [(random(),random(),random()) for i in range(1)] nx.draw_networkx(g,pos,nodelist=["192.168.2.1"],node_size=1000,font_size=6) nx.draw_networkx(g,pos,nodelist=["192.168.1.1"],node_size=1000,font_size=6) nx.draw(g,pos,node_color = color_map,node_size=100,with_labels=False,font_size=6) plt.savefig("./app/static/grafo.png",dpi=150) print("Caminho Gerado") return melhorCaminho
def getShortestPathByEndpoints(self, endpoints): shortest_paths = [] nxgraph = self.graph.nxgraph.copy() position = self.train_info['position'] line_idx = self.train_info['line_idx'] speed = self.train_info['speed'] self.train_point_idx, _ = self.getTrainPosition( line_idx, position, speed) layer1 = self.database.getBuildings() posts = layer1['posts'] stations_neaded_to_dodge = [] neaded_magazine_type = self.goods_type + 1 for post in posts: if (post['type'] == 2 and neaded_magazine_type == 3) or (post['type'] == 3 and neaded_magazine_type == 2): stations_neaded_to_dodge.append(post['point_idx']) stations_count = len(stations_neaded_to_dodge) for edge in self.graph.edges: points = edge.points i = 0 while i < stations_count: station_idx = stations_neaded_to_dodge[i] if points[0] == station_idx or points[1] == station_idx: nxgraph.remove_edge(points[0], points[1]) stations_neaded_to_dodge.remove(station_idx) stations_count -= 1 i -= 1 i += 1 for endpoint in endpoints: path = nx.dijkstra_path(nxgraph, self.train_point_idx, int(endpoint["point_idx"]), "length") path_length = nx.dijkstra_path_length(nxgraph, self.train_point_idx, int(endpoint["point_idx"]), "length") shortest_paths.append([path, path_length]) self.selected_path = None self.selected_path_len = 999999999 for path, path_len in shortest_paths: if self.selected_path_len > path_len: self.selected_path_len = path_len self.selected_path = path
def task_three(): result = "" _description = [] build_array(_description, FILE_DESCRIPTION) build_array(_description, "\n\n") edgesCollection = GRAPH.getEdgesCollection() weightDictionary = GRAPH.getGraphWeights() build_array(_description, "Najkrotsza droga pomiedzy wierzcholkami (w1-w2 droga):\n") graph = nx.Graph() for i in weightDictionary: s = i.split() v1 = s[0] v2 = s[2] weight = weightDictionary.get(i) graph.add_edge(int(v1), int(v2), weight=int(weight)) edges = graph.nodes() newDdgesCollection = [] for i in graph.nodes(): for j in edges: if j > i: text = str(i) + " -- " + str(j) newDdgesCollection.append(text) for i in newDdgesCollection: s = i.split() firstV = s[0] secondV = s[2] build_array(_description, firstV) build_array(_description, "-") build_array(_description, secondV) build_array(_description, " ") build_array(_description, str(nx.dijkstra_path_length(graph, int(firstV), int(secondV)))) build_array(_description, "\n") result = result.join(_description) return result
def find_best_node_and_neighbor(client, spt_nodes, remoted_nodes_first_stage, studentOpinions, studentWeights): best_node = None # We will choose the best node neighbor_node = None # We will remote to this node, first node on way to SPT best_hueristic_seen = float( "-inf") # Keep track of the best hueristic value seen #print(spt_nodes) for node in client.G.nodes: #You only want to remote using vertices outside of SPT if node in spt_nodes or node in remoted_nodes_first_stage: continue #print(node) # Find the shortest path to the SPT and the nodes along the path shortest_path_to_spt = math.inf best_path_nodes_to_spt = list() for spt_node in spt_nodes: distance_to_spt_node = nx.dijkstra_path_length( client.G, node, spt_node) nodes_on_path_to_spt_node = nx.dijkstra_path( client.G, node, spt_node) if (distance_to_spt_node <= shortest_path_to_spt): # Only update the path if it is either shorter or if it is equal and contains more nodes if (distance_to_spt_node < shortest_path_to_spt or len(nodes_on_path_to_spt_node) > len(best_path_nodes_to_spt)): shortest_path_to_spt = distance_to_spt_node best_path_nodes_to_spt = nodes_on_path_to_spt_node # List of nodes on the path #Find the hueristic value for the current node hueristic_for_node = find_hueristic_value(client, node, studentOpinions, studentWeights, best_path_nodes_to_spt) # TO BE CHANGED -- Maybe we can improve this, right now am just only updating the best node if it has at least the same hueristic, not handling ties well if hueristic_for_node >= best_hueristic_seen: best_hueristic_seen = hueristic_for_node best_node = node neighbor_node = best_path_nodes_to_spt[1] #First node on the path # After finding the best node and its neighbor to remote to, return them return best_node, neighbor_node
def add_augmenting_path_to_graph(graph, min_weight_pairs): """ Add the min weight matching edges to the original graph Parameters: graph: NetworkX graph (original graph from trailmap) min_weight_pairs: list[tuples] of node pairs from min weight matching Returns: augmented NetworkX graph """ # We need to make the augmented graph a MultiGraph so we can add parallel edges graph_aug = nx.MultiGraph(graph.copy()) for pair in min_weight_pairs: graph_aug.add_edge( pair[0], pair[1], **{ 'distance': nx.dijkstra_path_length(graph, pair[0], pair[1]), 'trail': 'augmented' }) return graph_aug
def mk_current_neural_state(G, time, pkg, node_addr, *add_data): n = len(G.nodes()) k = node_addr d = pkg.dst neighbors = [] if isinstance(G, nx.DiGraph): for m in G.neighbors(k): if nx.has_path(G, m, d): neighbors.append(m) else: neighbors = G.neighbors(k) add_data_len = sum(map(len, add_data)) dlen = 4 + 2*n + add_data_len + n*n data = np.zeros(dlen) data[0] = d data[1] = k data[2] = time data[3] = pkg.id off = 4 for m in neighbors: data[off + m] = 1 off += n for vec in add_data: vl = len(vec) data[off:off+vl] = vec off += vl for i in range(0, n): for j in range(0, n): if G.has_edge(i, j): data[off + i*n + j] = 1 off += n*n for i in range(off, dlen): data[i] = -INFTY for m in neighbors: try: data[off + m] = -(nx.dijkstra_path_length(G, m, d) + \ G.get_edge_data(k, m)['weight']) except nx.exception.NetworkXNoPath: data[off + m] = -INFTY return data
def cal_obj_mk2(in_solution): #Calculate obj with deviation ratio sol_graph = delivery_network_mk2(in_solution, False) ratio_l = [] for w in warehouses_ID: for site in in_solution: if site != w: try: n_dist = networkx.dijkstra_path_length(sol_graph, (facil_shp[w].x,facil_shp[w].y), (facil_shp[site].x,facil_shp[site].y)) except: print in_solution ss = delivery_network_mk2(in_solution, True, "err_graph") raise networkx.exception.NetworkXNoPath d_ratio = n_dist/ware_dist[w][site] ratio_l.append(d_ratio) avg_ratio = sum(ratio_l)/float(len(ratio_l)) obj_n = cal_obj(in_solution) obj_r = obj_n * 1/avg_ratio return obj_r
def _eva_metrics(self, trajs, batch, graph, metrics): for i, item in enumerate(batch): success = 0 traj = trajs[i] gt_traj = item["route_panoids"] ed = edit_dis(traj, gt_traj) ed = 1 - ed / max(len(traj), len(gt_traj)) target_list = list(nx.all_neighbors(graph, gt_traj[-1])) + [gt_traj[-1]] if traj[-1] in target_list: success = 1 metrics[0] += 1 metrics[2] += ed metrics[1] += nx.dijkstra_path_length(graph, traj[-1], gt_traj[-1]) if self.opts.CLS: metrics[3] += self.cal_cls(graph, traj, gt_traj) if self.opts.DTW: dtw_group = self.cal_dtw(graph, traj, gt_traj, success) for j in range(-3, 0): metrics[j] += dtw_group[j]
def SPANNER(graph, stretch_factor): sorted_edges_of_g = sorted(graph.edges(data=True), key=lambda t: t[2].get('weight', 1)) H = nx.Graph() H.add_nodes_from(graph) for edge in sorted_edges_of_g: edge_weight = graph.get_edge_data(edge[0], edge[1], "weight")['weight'] if nx.has_path(H, edge[0], edge[1]): sh_path_len = nx.dijkstra_path_length(H, edge[0], edge[1], weight='weight') if stretch_factor * edge_weight < sh_path_len: H.add_edge(edge[0], edge[1], weight=edge_weight) else: H.add_edge(edge[0], edge[1], weight=edge_weight) return H
def findPath(self, startPoint, endPoint): dist = euclidean_distances([endPoint], self.gridPoints) self.targetConfigIdx = np.argmin(dist) dist = euclidean_distances([startPoint], self.gridPoints) self.startConfigIdx = np.argmin(dist) self.path = nx.dijkstra_path(self.NX_G, self.targetConfigIdx, self.startConfigIdx) pathLengthTotal = nx.dijkstra_path_length(self.NX_G, self.targetConfigIdx, self.startConfigIdx) pathLengthAll = nx.single_source_dijkstra_path_length( self.NX_G, self.targetConfigIdx) pathCoordinates = [] for i in range(1, len(self.path)): pathCoordinates.append(self.gridPoints[self.path[i]]) return pathLengthTotal, pathCoordinates
def get_subgraph_on_book_locations(gt_library_warehouse, book_locations, source_location): """ Given a list of book locations, this method produces the sub-graph on the navigation grid of these book locations. """ # Ensure the source cell is navigable assert gt_library_warehouse.get_cell(source_location[0], source_location[1]) is NAVIGABLE_CELL, \ "Source must be navigable." # Ensure all the books are on shelves for book_location_r, book_location_c in book_locations: assert gt_library_warehouse.get_cell(book_location_r, book_location_c) is SHELVE_CELL, \ "Book must be on a shelve." G_library = convert_grid_to_graph(gt_library_warehouse.navigation_grid) G_subgraph = nx.MultiDiGraph() G_subgraph.add_node(source_location) G_subgraph.add_nodes_from(book_locations) # Connect each book to each other book for location1, location2 in itertools.combinations(G_subgraph.nodes, 2): if location1 == source_location: cell1_location = location1 else: cell1_location = get_navigable_cell_coordinate_near_book( location1, gt_library_warehouse) if location2 == source_location: cell2_location = location2 else: cell2_location = get_navigable_cell_coordinate_near_book( location2, gt_library_warehouse) # Use Dijkstra's algorithm to determine the distance between adjacent shelves shortest_path_cost = nx.dijkstra_path_length(G_library, cell1_location, cell2_location) G_subgraph.add_edge(location1, location2, weight=shortest_path_cost) G_subgraph.add_edge(location2, location1, weight=shortest_path_cost) return G_subgraph
def AllShortestPaths(g, startpoint): end_point_index = startpoint #for single face islands """Get the end point by getting the index of the point that has the longest shortest path""" initial_length = 0 for i in list(g.nodes): if mu.hasPath(g, startpoint, i): Pathlength = nx.dijkstra_path_length(g, startpoint, i, weight="weight") if Pathlength > initial_length: initial_length = Pathlength end_point_index = i s = i elif Pathlength < initial_length and i != startpoint: end_point_index = s end = end_point_index # Check that start and end are not the same node if startpoint == end: pts = [g.nodes[startpoint]["point"]] indexes = [startpoint] sl = 1 to_be_removed = [startpoint] return [pts, indexes, sl, to_be_removed] else: # Check that a path exist between the two nodes if mu.hasPath(g, startpoint, end): # Calculate shortest path sp = nx.dijkstra_path(g, startpoint, end, weight="weight") # Make polyline through path pts = [g.nodes[i]["point"] for i in sp] #get points indexes indexes = sp sl = len(sp) to_be_removed = sp return [pts, indexes, sl, to_be_removed]
def shortest_path(area): FG = nx.DiGraph() for i in range(len(area)): for j in range(len(area[0])): cur_node = f"{i}-{j}" if i > 0: FG.add_weighted_edges_from([(cur_node, f"{i-1}-{j}", area[i - 1][j])]) if i < len(area) - 1: FG.add_weighted_edges_from([(cur_node, f"{i+1}-{j}", area[i + 1][j])]) if j > 0: FG.add_weighted_edges_from([(cur_node, f"{i}-{j-1}", area[i][j - 1])]) if j < len(area[0]) - 1: FG.add_weighted_edges_from([(cur_node, f"{i}-{j+1}", area[i][j + 1])]) return nx.dijkstra_path_length(FG, "0-0", f"{len(area)-1}-{len(area[0])-1}")
def get_shortest_paths_distances(graph, pairs, edge_weight_name='length'): """ Calculate shortest distance between each pair of nodes in a graph Args: graph (networkx graph) pairs (list[2tuple]): List of length 2 tuples containing node pairs to calculate shortest path between edge_weight_name (str): edge attribute used for distance calculation Returns: dict: mapping each pair in `pairs` to the shortest path using `edge_weight_name` between them. """ distances = {} for pair in pairs: distances[pair] = nx.dijkstra_path_length(graph, pair[0], pair[1], weight=edge_weight_name) return distances
def exe(node_1, node_2, rain, rt_out, sv_out): read_with_GeoPandas(fp) intersects = get_intersections(geoms) graph = make_nodes(intersects, data_frame, rain, node_list) write_nodelist('Examples/nodelist.txt') print('\nShortest Path...\n') for _ in dijkstra_path(graph, node_list[node_1], node_list[node_2]): print(_) print('\nLength from {} to {} is: {}\n'.format( node_1, node_2, dijkstra_path_length(graph, node_list[node_1], node_list[node_2]))) graphic_map(intersects, rt_out, sv_out) graphic_graph(graph, rt_out, sv_out) print('Successfully saved. Have a nice day ;)') if rt_out: show()
def run(): """ generates some files, graphs and store there results in graphs/result""" import os from random import choice from tools import file_to_graph #FIXME change me to use your algorithm # from dijkstra import dijkstra #FIXME change me to use your algorithm import shutil def FAIL(G, v, f): return None #FIXME remove dijkstra = FAIL #FIXME remove file_to_graph = file_to_graph #FIXME so its dijkstra = your algorithm print('number of tests?'), num_tests = input() print('graph size ? '), size = input() test_index = 0 folder = 'graphs' if os.path.exists(folder): shutil.rmtree('graphs/') # note we delete the folder everytime if not os.path.exists(folder): os.makedirs(folder) for x in xrange(num_tests): test_file = 'graphs/graph' + str(test_index) + '.txt' G = random_weighted_graph(size) graph_to_file(G, test_file) start = choice(G.nodes()) finish = choice(G.nodes()) while start == finish: finish = choice(G.nodes()) cost = nx.dijkstra_path_length(G, start, finish) NG = file_to_graph(test_file) if dijkstra(NG, start, finish) != cost: path = nx.dijkstra_path(G, start, finish) visulizer(G, test_index) result = 'Graph{0} failed to find lowest cost {1} with path {2} with start point {3} and finish {4}\n'.\ format(test_index, cost, path, start, finish) else: result = 'Graph{0} passed!\n' with open('graphs/results.txt', 'a') as results: results.write(result) test_index += 1
def network_od_disruption(path_index, path_list, node_path_list, net, edge, edge_fail_dict, edge_fail_dict_big): edge_fail_dict.update({ str(edge): { 'path_index': [], 'old_dist': [], 'new_dist': [], 'incr_fact': [] } }) path_fail_index = [ item for item in range(len(path_list)) if edge in path_list[item] ] if len(path_fail_index) >= 3000 and len(path_fail_index) < 5000: net_copy = net.copy() nodes = [(u, v) for (u, v, d) in net.edges(data='key') if d == edge] for n in nodes: net_copy.remove_edge(n[0], n[1]) for index in path_fail_index: node_path = node_path_list[index] path_length = sum(get_network_edges(net, node_path, 'weight')) if nx.has_path(net_copy, node_path[0], node_path[-1]): new_path_length = nx.dijkstra_path_length(net_copy, source=node_path[0], target=node_path[-1], weight='weight') else: new_path_length = 1e20 path_change = 1.0 * new_path_length / path_length edge_fail_dict[str(edge)]['path_index'].append(path_index[index]) edge_fail_dict[str(edge)]['old_dist'].append(path_length) edge_fail_dict[str(edge)]['new_dist'].append(new_path_length) edge_fail_dict[str(edge)]['incr_fact'].append(path_change) # print ('Done with path %s in edge %s'%(index,edge)) else: edge_fail_dict_big.update({str(edge): len(path_fail_index)}) return (edge_fail_dict, edge_fail_dict_big)
def draw_dij(e_ans): dis, pre = dijk(mp, node_cnt, 0) src = int(e_src.get()) tar = int(e_tar.get()) if src<0 or src>=node_cnt or tar<0 or tar>=node_cnt: e_ans.delete(0, 'end') e_ans.insert(0, "请输入正确的顶点格式") return; print(dis) print(pre) path = nx.dijkstra_path(G, source=src, target=tar) distance = nx.dijkstra_path_length(G, source=src, target=tar) e_ans.delete(0, 'end') e_ans.insert(0, distance) G1 = nx.Graph() for i in range(path.__len__() - 1): G1.add_edge(path[i], path[i + 1], weight=20) i = 0 j = 0 while i < node_cnt: j = 0 while j < node_cnt: if i < j and mp[i, j] != 0 and mp[i, j] != np.inf and not (G1.has_edge(i, j) or G1.has_edge(j, i)): G1.add_edge(i, j, weight=1) j += 1 i += 1 elarge = [(u, v) for (u, v, d) in G1.edges(data=True) if d['weight'] > 1] esmall = [(u, v) for (u, v, d) in G1.edges(data=True) if d['weight'] <= 1] pos = nx.spring_layout(G) # 首先画出节点位置 nx.draw_networkx_nodes(G, pos, node_size=700) # 根据权重,实线为权值大的边,虚线为权值小的边 nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6) nx.draw_networkx_edges(G, pos, edgelist=esmall, width=6, alpha=0.5, edge_color='b', style='dashed') nx.draw(G, pos, font_size=20,with_labels=True, font_family='sans-serif') pylab.show() return
def llf_route(G,origin,destination,nodes_proj): import networkx as nx max_depth = len(nx.dijkstra_path(G,origin,destination,weight = 'length')) #print('Max search depth is '+str(max_depth)) edge_list = list(nx.bfs_predecessors(G, origin, depth_limit=max_depth)) #node_list = list(nx.bfs_tree(G, origin, depth_limit=max_depth)) nt_edges = list(nx.bfs_predecessors(G, origin, depth_limit=1)) #print('Initial edges '+str(nt_edges)) nt_nodes = list(nx.bfs_tree(G, origin, depth_limit=1)) for i in range(len(nt_nodes)-1,len(edge_list)): if edge_list[i][1] in nt_nodes: deflection = abs(bearing(G,edge_list[i][0],edge_list[i][1],nodes_proj) - bearing(G,edge_list[i][1],origin,nodes_proj)) if deflection < 45.0 : nt_nodes.append(edge_list[i][0]) nt_edges.append(edge_list[i]) if destination in nt_nodes: return nx.dijkstra_path(G,origin,destination,weight = 'length') last_leg = 1000000000.0 for j in range(0,len(nt_nodes)): leg = nx.dijkstra_path_length(G,destination,nt_nodes[j],weight = 'length') if leg < last_leg: last_leg = leg route_node = nt_nodes[j] #print('Nodes are '+str(nt_nodes)) #print('Edges are '+str(nt_edges)) #print('Node with least distance from destination is '+str(route_node)) prev_node = route_node route = nx.dijkstra_path(G,destination,route_node,weight = 'length') #print('Last route segment '+str(route)) while prev_node != origin: for i in range(0,len(nt_edges)): if nt_edges[i][0] == prev_node: prev_node = nt_edges[i][1] route.append(prev_node) #print('Updated route '+str(route[::-1])) break return route[::-1] #reversing the route
def chinese_postmap_problem(self, Gin): # print(type(Gin.degree())) odd_nodes = [v for (v, d) in Gin.degree() if d % 2 == 1] # odd_nodes = [v for (v, d) in Gin.degree().items() if d % 2 == 1] # print('Odd nodes ==>') # print(odd_nodes) odd_node_pairs = list(itertools.combinations(odd_nodes, 2)) # print('Odd nodes pairs ==>') print(odd_node_pairs) cost_list = {} for pair in odd_node_pairs: cost_list[pair] = nx.dijkstra_path_length(Gin, pair[0], pair[1], weight='weight') # print('Cost list ==>') print(cost_list) Gc = nx.Graph() for k, v in cost_list.items(): Gc.add_edge(k[0], k[1], **{'distance': v, 'weight': v}) odd_matching_dupes = nx.max_weight_matching(Gc) M = list(pd.unique([tuple(sorted([k, v])) for k, v in odd_matching_dupes.items()])) # print('Matching M ==>') # print(M) Geular = nx.MultiGraph() Geular.add_nodes_from(Gin.nodes(), pos=self.pos) Geular.add_edges_from(Gin.edges()) # print('Add paths ==>') for (m1, m2) in M: path = nx.dijkstra_path(Gin, m1, m2, weight='weight') print(path) nx.add_path(Geular, path) return Geular, odd_nodes, M,
def path(): # 得到坐标 vnode = data[..., 1:3] # 得到点并导入 nodes = list(data[..., 0]) # 节点名映射到 int ,方便计算距离 nodes2int = {} for i in range(len(nodes)): nodes2int[nodes[i]] = i # 导入点 G.add_nodes_from(nodes) # 导入边 edges = [] for l in data: n1 = l[0] for n2 in l[4:]: if n2 is not np.nan: edges.append( [n1, n2, distant(vnode, nodes2int[n1], nodes2int[n2])]) G.add_weighted_edges_from(edges) # 映射坐标 npos = dict(zip(nodes, vnode)) # 获取节点与坐标之间的映射关系,用字典表示 # 计算最短路径 print('dijkstra 方法寻找最短路径:') path = nx.dijkstra_path(G, source='L', target='R3') print('节点 L 到 R3 的路径:', path) print('dijkstra 方法寻找最短距离:') distance = nx.dijkstra_path_length(G, source='L', target='R3') print('节点 L 到 R3 的距离为:', distance) # 画出最短路径 labels = [] for l in data[..., 0]: if l in path: labels.append('★') else: labels.append('·') nlabels = dict(zip(nodes, labels)) # 标志字典,构建节点与标识点之间的关系 nx.draw_networkx_nodes(G, npos, node_size=50, node_color="#6CB6FF") # 绘制节点 nx.draw_networkx_edges(G, npos, edges) # 绘制边 nx.draw_networkx_labels(G, npos, nlabels) # 标签 plt.show()
def getNegDistance(selected): #print "Inside Get NEG distance\n" G_ = nx.read_edgelist(path=readfile, delimiter=",", nodetype=int, create_using=nx.Graph()) G_.remove_nodes_from(selected) totaldistance = 0.0 for node1 in G_.nodes(): for node2 in G_.nodes(): if node2 > node1: if (nx.has_path(G_, node1, node2)): distance = nx.dijkstra_path_length(G_, node1, node2) #print " ".join(map(str, ["Distance between ", node1, " - ", node2, " = ", distance])) totaldistance = totaldistance + (1 / float(distance)) #print " ".join(map(str, ["Total Distance ", totaldistance])) numnodes = len(G_.nodes()) D_f = 1 - ((2 * totaldistance) / (numnodes * (numnodes - 1))) #print "Selected - "+str(selected)+" ++ D_f - "+ str(D_f) return D_f
def depth(self, u): """ Returns the depth of u. If the node u is not from the phylogenetic network, then returns None. EXAMPLE:: >>> network = PhyloNetwork(eNewick="((((LEAF#1))),#1);") >>> network.nodes() ... ['#1', '_4', '_3', '_2', '_1'] >>> map(network.depth, network.nodes()) ... [1, 3, 2, 1, 0] >>> network.depth('non-existing node') ... None """ if not u in self: return None return min( [dijkstra_path_length(self, root, u) for root in self.roots()])
def get_keys(self): G = nx.Graph() d = deque([("", frozenset(self.botcoords))]) G.add_node(("", frozenset(self.botcoords))) G.add_node("FINISHLINE") # Construct graph while len(d) > 0: node = d.popleft() for (newcoords, dist, char) in \ self._find_reachable_keys(node[1], node[0]): newnode = ("".join(sorted(node[0] + char)), frozenset(newcoords)) if newnode not in G: G.add_node(newnode) d.append(newnode) G.add_edge(node, newnode, weight=dist) if newnode[0] == self.allkeys: G.add_edge(newnode, "FINISHLINE", weight=0) print(nx.dijkstra_path_length(G, ("", frozenset(self.botcoords)), "FINISHLINE", "weight"))
def weighted_event_graph(event_graph, metric): """ Adds weights to a graph of 'detection events', by passing each pair of vertices to a single-source Dijkstra algorithm. While this may not be necessary for the highly-symmetric test metrics produced in theoretical studies, there are no guarantees on whether hypotenuse edges are lower in weight than the sum of the weights of the associated perpendicular edges. Also, there may be 'hot spots' (short chains of times/locations where errors are very likely) that justify not taking a straight path from point A to point B. Warning: if you put in a weighted graph, this will overwrite your weights. """ for edge in event_graph.edges(): event_graph[edge[0]][edge[1]]['weight'] = \ nx.dijkstra_path_length(metric, edge[0], edge[1]) return event_graph
def intermediate(city_name, adj_mat, pairs): file_path = city_name + '/cache/' + str(pairs[0]) + '.dat' if (os.path.exists(file_path)): with open(file_path, 'r') as in_file: results = ast.literal_eval(in_file.read()) in_file.close() # else: G = nx.Graph(adj_mat) # results = [] for i, j in pairs: results.append((i, j, nx.dijkstra_path_length(G, i - 1, j - 1))) # with open(file_path, 'w') as out_file: out_file.write(str(results)) out_file.close() # return (results)
def euler83(): grid = [] with open('data/p081_matrix.txt') as f: for line in f: grid.append([int(n) for n in line.strip('\n').split(',')]) n, m = len(grid), len(grid[0]) graph = networkx.DiGraph() for i in range(n): for j in range(m): neighbors = [(i + x, j + y) for x, y in ((-1, 0), (0, -1), (1, 0), (0, 1)) if 0 <= i + x < n and 0 <= j + y < m] for nx, ny in neighbors: graph.add_edge((i, j), (nx, ny), weight=grid[nx][ny]) path_length = networkx.dijkstra_path_length(graph, source=(0, 0), target=(n - 1, m - 1)) print(grid[0][0] + path_length)