Example #1
0
    def test_weight_function(self):
        """Tests that a callable weight is interpreted as a weight
        function instead of an edge attribute.

        """
        # Create a triangle in which the edge from node 0 to node 2 has
        # a large weight and the other two edges have a small weight.
        G = nx.complete_graph(3)
        G.adj[0][2]['weight'] = 10
        G.adj[0][1]['weight'] = 1
        G.adj[1][2]['weight'] = 1
        # The weight function will take the multiplicative inverse of
        # the weights on the edges. This way, weights that were large
        # before now become small and vice versa.

        def weight(u, v, d): return 1 / d['weight']
        # The shortest path from 0 to 2 using the actual weights on the
        # edges should be [0, 1, 2].
        distance, path = nx.single_source_dijkstra(G, 0, 2)
        assert_equal(distance, 2)
        assert_equal(path, [0, 1, 2])
        # However, with the above weight function, the shortest path
        # should be [0, 2], since that has a very small weight.
        distance, path = nx.single_source_dijkstra(G, 0, 2, weight=weight)
        assert_equal(distance, 1 / 10)
        assert_equal(path, [0, 2])
Example #2
0
def ego_graph(G,n,radius=1,center=True,undirected=False,distance=None):
    """Returns induced subgraph of neighbors centered at node n within
    a given radius.
    
    Parameters
    ----------
    G : nxgraph
      A NetworkX Graph or DiGraph

    n : node 
      A single node 

    radius : number, optional
      Include all neighbors of distance<=radius from n.
      
    center : bool, optional
      If False, do not include center node in nxgraph

    undirected : bool, optional      
      If True use both in- and out-neighbors of directed graphs.

    distance : key, optional      
      Use specified edge data key as distance.  For example, setting
      distance='weight' will use the edge weight to measure the
      distance from the node n.

    Notes
    -----
    For directed graphs D this produces the "out" neighborhood
    or successors.  If you want the neighborhood of predecessors
    first reverse the nxgraph with D.reverse().  If you want both
    directions use the keyword argument undirected=True.

    Node, edge, and nxgraph attributes are copied to the returned subgraph.
    """
    if undirected:
        if distance is not None:
            sp,_=nx.single_source_dijkstra(G.to_undirected(),
                                           n,cutoff=radius,
                                           weight=distance)
        else:
            sp=nx.single_source_shortest_path_length(G.to_undirected(),
                                                     n,cutoff=radius)
    else:
        if distance is not None:
            sp,_=nx.single_source_dijkstra(G,
                                           n,cutoff=radius,
                                           weight=distance)
        else:
            sp=nx.single_source_shortest_path_length(G,n,cutoff=radius)

    H=G.subgraph(sp).copy()
    if not center:
        H.remove_node(n)
    return  H
 def shortest_path_tree(self, node, search_type='time', cutoff=None):
     if node in self.graph_time.nodes():
         if search_type == 'distance':
             dist, path = networkx.single_source_dijkstra(self.graph_dist, node, cutoff=cutoff)
         elif search_type == 'time':
             dist, path = networkx.single_source_dijkstra(self.graph_time, node, cutoff=cutoff)
         else:
             print 'invalid search type; valid values for variable - distance or time'
             return None
     else:
         print 'Source node not found in the graph'
         return None
     return dist, path
Example #4
0
def main():
    '''
    This is the main function
    http://networkx.lanl.gov/reference/algorithms.operators.html
    '''    
    # Get distance matrices
    walking_times = read_weights_from_file(walking_time_filename)  
    shuttle_times = read_weights_from_file(shuttle_time_filename)
    shuttle_connection_times = read_weights_from_file(shuttle_connection_time_filename)
    outdoorness_matrix = read_weights_from_file(outdoorness_filename)
    #print outdoorness_matrix
    
    # Add penalties
    shuttle_connection_times = apply_penalty(shuttle_connection_times, shuttle_penalty/2, 'add') # /2 because we get in and out the shuttle, so we don't want to have a double penalty
    walking_times = apply_penalty(walking_times, walking_penalty , 'multiply') 
    walking_times = apply_outdoor_penalty(walking_times, outdoorness_matrix, outdoorness_penalty)
    
    # Create subgraphs
    walking_graph = nx.DiGraph(data=walking_times)
    #print G.edges(data=True)
    walking_graph = nx.relabel_nodes(walking_graph,convert_list_to_dict(read_node_labels(walking_time_filename)))    
    print 'walking_graph', walking_graph.edges(data=True)
    
    shuttle_graph = nx.DiGraph(data=shuttle_times)
    shuttle_graph = nx.relabel_nodes(shuttle_graph,convert_list_to_dict(read_node_labels(shuttle_time_filename)))
    print 'shuttle_graph', shuttle_graph.edges(data=True)
    
    shuttle_connection_graph = nx.DiGraph(data=shuttle_connection_times)
    shuttle_connection_graph = nx.relabel_nodes(shuttle_connection_graph,convert_list_to_dict(read_node_labels(shuttle_connection_time_filename)))
    print 'shuttle_connection_graph', shuttle_connection_graph.edges(data=True)
    
    # Create main graph
    main_graph = nx.compose(walking_graph, shuttle_graph)
    print 'main_graph', main_graph.edges(data=True)    
    main_graph = nx.compose(main_graph, shuttle_connection_graph)
    print 'main_graph', main_graph.edges(data=True)
    
    # Compute the shortest paths and path lengths between nodes in the graph.
    # http://networkx.lanl.gov/reference/algorithms.shortest_paths.html
    compute_shortest_path(main_graph, '32', 'NW86')
    compute_shortest_path(main_graph, 'W7', 'W20')
    compute_shortest_path(main_graph, '50', '35')
    #print nx.dijkstra_predecessor_and_distance(main_graph, 'NW86')
    
    # Compute shortest paths and lengths in a weighted graph G. TODO: Return farthest region.
    print nx.single_source_dijkstra(main_graph, '32', 'NW86')
    
    # Compute KSP (k-shortest paths) using https://github.com/Pent00/YenKSP
    yenksp_digraph = convert_nx_digraph_into_yenksp_digraph(main_graph)
    print ksp_yen(yenksp_digraph, 'NW86', '32', 2)
def mst_of_g(g,terminals,verbose=False,weighted=True,cutoff=7,return_gL=False,bidir=False):
	STARTTIME=time.time()
	if verbose:
		logger.info("Starting MST construction")
		sys.stdout.flush()

	STARTTIME=time.time()
	gLedges=[]
	shortest_network=model.AnnotatedGraph()

	for i in range(len(terminals)):
		src=terminals[i]
		if src not in g:
			if verbose:
				logger.info("Node %s not in g"%(src))
			continue
		if weighted:
			costs,paths=nx.single_source_dijkstra(g, src, weight='weight',cutoff=cutoff)
		else:
			paths=nx.single_source_shortest_path(g,src,cutoff=cutoff)
			costs=dict([(k,len(v)) for k,v in paths.items()])

		if bidir:
			span=range(len(terminals))
		else:
			span=range(i+1,len(terminals))
		for j in span:
			if j==i:
				continue
			tgt=terminals[j]
			if tgt not in paths:
				if verbose:
					logger.info("no paths between %s and %s"%(src,tgt))
				continue
			shortest_network.add_path(paths[tgt])
			gLedges.append((src,tgt,{'weight':costs[tgt],'path':paths[tgt]}))
		if verbose:
			logger.info("Done %s. Still %d to go"%(src,len(terminals)-i))
			sys.stdout.flush()			
	if verbose:
		logger.info("Computed Metric closure in %f seconds"%(time.time() - STARTTIME))
		STARTTIME=time.time()
		sys.stdout.flush()			
	gL=nx.Graph()
	gL.add_edges_from(gLedges)
	# Min spanning Tree
	tL=nx.minimum_spanning_tree(gL)
	if verbose:
		logger.info("Computed Min spanning tree in %f seconds"%(time.time() - STARTTIME))
		STARTTIME=time.time()
		sys.stdout.flush()	

	mst=model.AnnotatedGraph()
	for e in tL.edges(data=True):
		mst.add_path(e[2]["path"])
	copy_attributes_from_g(mst,g)
	if return_gL:
		return mst,gL,shortest_network
	else:
		return mst
Example #6
0
    def path_to(self, source, target):
        """Return distance, path.

        path[target]
        distance[target]
        """
        return nx.single_source_dijkstra(self.graph, source, target)
Example #7
0
def topk_naive2(G, s, R, K):
    """
    finds all business in the region and returns an iterator of K shortest paths
    find shortest path to all reachable nodes from source by Disjktra's
    return paths and lengths for filtered nodes in the region by R-Tree
    :param G: NetworkX Graph instance
    :param s: Source vertex's ID as a string or number that can be found in G
    :param R: Region of interest as list of co-ordinates [nelat, nelong, swlat, swlong]
    :param K: Number of shortest paths to compute
    :return: Iterator of tuples (distance from s, path from s)
    """
    # start = time.time()
    # print '\nStarted Algorithm at %s' % (start,)
    biz = business_in_loc(R[0], R[1], R[2], R[3])
    # print 'After %ss: Found %s businesses in the region %s' % (time.time() - start, len(biz), R)
    length, path = nx.single_source_dijkstra(G, s)
    res = []
    for b in biz:
        b = BUSINESS_NODE_PREFIX + b
        try:
            res.append((length[b], path[b], b))
        except KeyError:
            # This business is not reachable from s
            res.append((float("inf"), [], b))
            # print 'After %ss: Found shortest path from %s to %s' % (time.time() - start, s, b)
    res.sort()
    return res[:K]
def connect_shortest_v3(weigthed_graph,nodes,weighted=True,cutoff=None,verbose=False):
	STARTTIME=time.time()
	if verbose:
		print "Starting SHOV3 construction"
		sys.stdout.flush()

	STARTTIME=time.time()

	res=nx.Graph()
	for i in range(len(nodes)):
		src=nodes[i]
		if src not in weigthed_graph:
			continue
		if weighted:
			costs,spaths=nx.single_source_dijkstra(weigthed_graph, src, weight='weight',cutoff=cutoff)
		else:
			spaths=nx.single_source_shortest_path(weigthed_graph, src,cutoff=cutoff)
		for j in range(i+1, len(nodes)):
			t=nodes[j]
			if t not in spaths:
				continue
			if cutoff and (len(spaths[t])>cutoff):
				continue
			res.add_path(spaths[t])
		if verbose:
			print "Done",src,"to go:",len(nodes)-i
			sys.stdout.flush()			
	if verbose:
		print "Computed SHOV3,",time.time() - STARTTIME,"seconds"
		STARTTIME=time.time()
		sys.stdout.flush()	
	return res
Example #9
0
def prepare(neighbours, costs, benefits, S, C, handpicked_targets=None):
    # return moves, visitations, cars, score
    if handpicked_targets is None:
        return {i: [S] for i in xrange(C)}, set(), sort_cars([car_type(i, S, S, 0, 0) for i in xrange(C)]), 0

    score = 0

    G = nx.DiGraph()
    for (fr, tos) in neighbours.iteritems():
        G.add_node(fr)
        for to in tos:
            G.add_edge(fr, to, weight=costs[(fr, to)])

    distances, shortest_paths =  nx.single_source_dijkstra(G, S)
    paths = {target: (distances[target], shortest_paths[target]) for target in handpicked_targets}
    cars = []
    visitations = set()
    moves = {}
    for (i, (target, (dist, path))) in enumerate(paths.items()):
        assert target == path[-1]
        cars.append(car_type(i, path[-2], path[-1],  None, dist))
        for (k, l) in zip(path[:-1], path[1:]):
            if (k, l) not in visitations and (l, k) not in visitations:
                score += benefits[(k, l)]
            visitations.add((k, l))
            visitations.add((l, k))
        moves[i] = path

    return moves, visitations, cars, score
Example #10
0
def yen_ksp(G, src, tgt, top_K):
    from copy import deepcopy

    def getWeight(p, w=0):
        for i in range(len(p) - 1):
            w += G[p[i]][p[i + 1]]['weight']
        return w

    _cost, _path = nx.single_source_dijkstra(G, src, tgt)
    A = [_path[tgt]]
    costs = [_cost[tgt]]
    B = PriorityQueue()

    for k in range(1, top_K):
        _G = deepcopy(G)
        for i in range(len(A[k - 1]) - 1):
            spurNode = A[k - 1][i]
            rootPath = A[k - 1][:i]
            for path in A:
                if A[k - 1][:i + 1] == path[:i + 1] and _G.has_edge(path[i], path[i + 1]):
                    _G.remove_edge(path[i], path[i + 1])

            if len(rootPath) > 0 and spurNode != tgt:
                extra_edges = _G.edges(rootPath[len(rootPath) - 1])
                for ed in extra_edges:
                    _G.remove_edge(ed[0], ed[1])

            try:
                spurPathCost, spurPath = nx.single_source_dijkstra(_G, spurNode, tgt)
                spurPath = spurPath[tgt]
            except Exception as e:
                spurPath = []

            if len(spurPath) > 0:
                totalPath = rootPath + spurPath
                B.put((getWeight(totalPath), totalPath))
        if B.empty():
            break
        while not B.empty():
            cost, path = B.get()
            if path not in A:
                A.append(path)
                costs.append(cost)
                break
    return A, costs
def sampling(G,cent,hop,cover):
	
	G2 = share.vincity(G,cent,hop)
	sp = nx.single_source_dijkstra(G2,cent)
	for path in sp[1].values():
		if len(path) >= hop:
			if len(set(path) & set(cover))==0:
				return True
	return False
    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.NetworkXError,nx.dijkstra_path,self.G,'s','moon')
        assert_raises(nx.NetworkXError,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])
def diameter_dic(graph):
    ds = {}
    for start_nodes in graph:
        distance_dic, path_dic = nx.single_source_dijkstra(graph,start_nodes)
        far_node = max(distance_dic, key=distance_dic.get) #Farthest Node
        ds[start_nodes] = [far_node]
        dis_from_far_node = distance_dic[far_node]
        ds[start_nodes].append(dis_from_far_node)

    return ds
Example #14
0
    def get_Rel_one(self,ipt,tp,N,cut=6.0):
        if N>= len( nx.node_connected_component(self.G, ipt) ):
            N=len( nx.node_connected_component(self.G, ipt) )

        T2L,T2P=nx.single_source_dijkstra(self.G,ipt,cutoff=cut,weight=tp)
        count=len(T2L.keys())

        while count<N:
            cut=cut+1.0
            T2L,T2P=nx.single_source_dijkstra(self.G,ipt,cutoff=cut,weight=tp)
            count=len(T2L.keys())

        sorted_T=sorted(T2L.keys(),key=T2L.get)[:N]
        Rel=[]
        for t in sorted_T:
            Rel.append((t,[T2L[t],T2P[t]]))
        Rel=collections.OrderedDict(Rel)

        return Rel
Example #15
0
def get_effdist_tree(G, source, cutoff=None, create_using=nx.DiGraph, weight="weight", effdist_key="effdist"):

    T = create_using()
    T.graph["root"] = source
    T.add_node(source)

    length, path = nx.single_source_dijkstra(G, source, cutoff=cutoff, weight=weight)

    for n in path.keys():
        T.add_path(path[n])
        T.node[n][effdist_key] = length[n]

    return T
    def build_prism_between_nodes_static(self, g, source, dest, t_s, t_d):
        ti = time.time()
        reached_d, reached_path = networkx.single_source_dijkstra(g, source, cutoff=t_d-t_s)
        #print '\tReached retrieved in', time.time()-ti

        ti = time.time()
        left_d, left_path = networkx.single_source_dijkstra(g, dest, cutoff=t_d-t_s)
        #print '\tLeft retrieved in', time.time()-ti

        #print ('\tDestination(s) reached from source starting at %s within %s analysis intervals is %s' %
        #       (t_s, t_d, len(reached_d)))
        #print ('\tDestination(s) accessed to destination by %s start after %s analysis intervals is %s' %
        #       (t_d, t_s, len(left_d)))

        #print 'cutoff = ', t_d-t_s
        #print 'max_dist = ', max(reached_d.values()), max(left_d.values())
        dests_accessible = {}
        for i in reached_d:
            if i in left_d and ((reached_d[i] + left_d[i]) < t_d - t_s):
                dests_accessible[i] = reached_d[i]

        return dests_accessible
Example #17
0
    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])
def mst_of_g(g,terminals,verbose=False,weighted=True):
	STARTTIME=time.time()
	GLOBALTIME=STARTTIME
	if verbose:
		print "Starting MST construction"
		sys.stdout.flush()

	STARTTIME=time.time()
	gLedges=[]
	for i in range(len(terminals)):
		src=terminals[i]
		if src not in g:
			continue
		if weighted:
			costs,paths=nx.single_source_dijkstra(g, src, weight='weight',cutoff=7)
		else:
			paths=nx.single_source_shortest_path(g,src,cutoff=7)
			costs=dict([(k,len(v)) for k,v in paths.items()])

		for j in range(i+1,len(terminals)):
			tgt=terminals[j]
			if tgt not in paths:
				continue
			gLedges.append((src,tgt,{'weight':costs[tgt],'path':paths[tgt]}))
		if verbose:
			print "Done",src,"to go:",len(terminals)-i
			sys.stdout.flush()			
	if verbose:
		print "Computed Metric closure,",time.time() - STARTTIME,"seconds"
		STARTTIME=time.time()
		sys.stdout.flush()			
	gL=nx.Graph()
	gL.add_edges_from(gLedges)
	# Min spanning Tree
	tL=nx.minimum_spanning_tree(gL)
	if verbose:
		print "Computed Min spanning tree,",time.time() - STARTTIME,"seconds"
		STARTTIME=time.time()
		sys.stdout.flush()	

	mst=nx.Graph()
	for e in tL.edges(data=True):
		mst.add_path(e[2]["path"])
	if verbose:
		print "Totla comp time,",time.time() - GLOBALTIME,"seconds"
		sys.stdout.flush()	

	return mst
Example #19
0
def main():
    G = nx.DiGraph()  # G eh um grafo direcionado
    # gera o grafo apartir de suas arestas
    G.add_weighted_edges_from([(1,2,2.0),(1,3,1.0),(2,3,3.0),(2,4,3.0),(3,5,1.0),(4,6,2.0),(5,4,2.0),(5,6,5.0)])
    for i in G.edges():
        # print i[0], i[1]
        G[i[0]][i[1]]["color"] = "black"
    # G[1][2]["color"] = "red"
    comprimento, caminho = nx.single_source_dijkstra(G, 1)
    print caminho
    for i in caminho:
        print i, comprimento[i], caminho[i]
        for j in range(1, len(caminho[i])):
            #print caminho[i][j-1], caminho[i][j]
            G[caminho[i][j-1]][caminho[i][j]]["color"] = "red"
    desenhaGrafo(G, "grafo-1c.png")
Example #20
0
def local_query_edit(G,start,end,cover,k):

	G2 = share.vincity(G,start,k)
	sp = nx.single_source_dijkstra(G2,start)

	n_set = {}
	loc_dist = -1	
	if end in sp[1]:
		loc_dist = sp[0][end]

	for path in sp[1].values():
		tmp = list(set(path[1:])&set(cover))
		if len(tmp)>0:
			tmp = tmp[0]
			if tmp not in n_set:
				n_set[tmp] = sp[0][tmp]
	return [n_set,loc_dist]
Example #21
0
def main():
    G = nx.DiGraph()  # G eh um grafo direcionado
    # gera o grafo apartir de suas arestas
    G.add_weighted_edges_from([(1,2,20),(1,3,15),(2,1,2),(2,4,10),(2,5,25),(3,2,4),(3,4,25),(3,5,10),(4,6,15),(5,4,10),(5,6,4)])
    for i in G.edges():
        # print i[0], i[1]
        G[i[0]][i[1]]["color"] = "black"
    # G[1][2]["color"] = "red"
    distancia, caminho = nx.single_source_dijkstra(G,1)
    print caminho
    print distancia
    for i in caminho:
        print i, caminho[i]
        for j in range(1, len(caminho[i])):
            #print caminho[i][j-1], caminho[i][j]
            G[caminho[i][j-1]][caminho[i][j]]["color"] = "red"
    desenhaGrafo(G, "grafo-1a.png")
def buildNeighbors(graph, cutoff, source=None):
    '''
    This method returns a dictionary keyed by node source index that contains
    another dictionary keyed by target node index. The values are the weighted
    shortest path lengths from source to target that are below a certain
    cutoff value

    if a source is set, then neighbours are only calculated for this node
    '''
    if source:
        distanceDict = nx.single_source_dijkstra(graph, source, cutoff)
    else:
        print('Begin calculating for all nodes with radius %.2f.' % (cutoff))
        distanceDict = nx.all_pairs_dijkstra_path_length(graph, cutoff)
        print('Done calculating for all nodes with radius %.2f.' % (cutoff))

    return distanceDict
Example #23
0
def main():
    G = nx.DiGraph()  # G eh um grafo direcionado
    # gera o grafo apartir de suas arestas
    G.add_weighted_edges_from([(1, 2, 2), (1, 3, 6), (1, 4, 3), (2, 3, 5),
                               (2, 5, 8), (3, 5, 3), (4, 3, 2), (4, 6, 9),
                               (5, 6, 1)])
    for i in G.edges():
        # print i[0], i[1]
        G[i[0]][i[1]]["color"] = "black"
    # G[1][2]["color"] = "red"
    distancia, caminho = nx.single_source_dijkstra(G, 1)
    print distancia
    print caminho
    for i in caminho:
        print i, caminho[i]
        for j in range(1, len(caminho[i])):
            #print caminho[i][j-1], caminho[i][j]
            G[caminho[i][j - 1]][caminho[i][j]]["color"] = "red"
    desenhaGrafo(G, "grafo-1d.png")
    def all_or_nothing_assignment(self):
        """
        Method for implementing all-or-nothing assignment based on the current graph. \n
        It updates link traffic flow
        """
        for edge in self.graph.edges(data=True):
            edge[2]['object'].vol = 0

        shortestpath_graph = {}
        for i in self.origins:
            shortestpath_graph[i] = nx.single_source_dijkstra(self.graph,
                                                              i,
                                                              weight="weight")
        for (i, j) in self.od_vols:
            odvol = self.od_vols[(i, j)]
            path = shortestpath_graph[str(i)][1][str(j)]
            for p in range(len(path) - 1):
                fnode, tnode = path[p], path[p + 1]
                self.graph[fnode][tnode]["object"].vol += odvol
def shortes_path_in_graph(G, source_airport_id, destination_airport_id, k):
    # copy graph
    H = G.copy()
    airports_list = list()
    weigh_list = list()
    airline_list = list()
    for qq in range(0, k + 1):
        tmp = nx.single_source_dijkstra(H, source_airport_id, destination_airport_id, weight='weight')
        weigh_list.append(tmp[0])
        airports_list.append(tmp[1])
        airline_list_tmp = list()
        count = 0
        ptr = tmp[1]
        for i in tmp[1]:
            if count == 0:
                ptr = i
                count += 1
            else:
                wght = 99999999

                # find edge with the lowest weight that was used
                for (u, v, kk, c) in H.edges(data=True, keys=True):
                    ### c-dict data kk-key edges               
                    if u == ptr and v == i:
                        if (wght > c['weight']):
                            wght = c['weight']
                            kkey = kk
                            air_id = c['airline_id']
                airline_list_tmp.append(air_id)
                # go all the way and collect airlines numbers

                H.remove_edge(ptr, i, kkey)

                ptr = i

        airline_list.append(airline_list_tmp)

    print(weigh_list)
    print(airports_list)
    print(airline_list)

    return geo_helper.ShortestPaths(weigh_list, airports_list, airline_list)
def get_star_overlay(connectivity_graph, centrality):
    """
    Generate server connectivity graph given an underlay topology represented as an nx.Graph
    :param connectivity_graph: nx.Graph() object, each edge should have availableBandwidth:
     "latency", "availableBandwidth" and "weight";
    :param centrality: mode of centrality to use, possible: "load", "distance", "information", default="load"
    :return: nx.Graph()
    """
    if centrality == "distance":
        centrality_dict = nx.algorithms.centrality.closeness_centrality(connectivity_graph, distance="latency")
        server_node = max(centrality_dict, key=centrality_dict.get)

    elif centrality == "information":
        centrality_dict = nx.algorithms.centrality.information_centrality(connectivity_graph, weight="latency")
        server_node = max(centrality_dict, key=centrality_dict.get)

    else:
        # centrality = load_centrality
        centrality_dict = nx.algorithms.centrality.load_centrality(connectivity_graph, weight="latency")
        server_node = max(centrality_dict, key=centrality_dict.get)

    weights, paths = nx.single_source_dijkstra(connectivity_graph, source=server_node, weight="weight")

    star = nx.Graph()
    star.add_nodes_from(connectivity_graph.nodes(data=True))

    for node in paths.keys():
        if node != server_node:

            latency = 0.
            available_bandwidth = 1e32
            for idx in range(len(paths[node]) - 1):
                u = paths[node][idx]
                v = paths[node][idx + 1]

                data = connectivity_graph.get_edge_data(u, v)
                latency += data["latency"]
                available_bandwidth = data["availableBandwidth"]

            star.add_edge(server_node, node, availableBandwidth=available_bandwidth, latency=latency)

    return star
Example #27
0
def get_to_kols(therapeutic_area, country, kol_from, degree):
    if pd.notna(kol_from) and kol_from != '':
        ids = all_nodes_dupe.loc[
            ((all_nodes_dupe.country == country) | (country == None))
            & ((all_nodes_dupe.synonym == therapeutic_area)
               | (therapeutic_area == None)) &
            (all_nodes_dupe.fullname == kol_from)].sort_values(
                'eigenvector', ascending=False).id.unique()
        kol_from_id = ids[0]
        length, path = nx.single_source_dijkstra(G, kol_from_id, cutoff=degree)
        s = G.subgraph(path)
        nodes, edges = getNodesEdges(s, kol_from_id)
        to_kols = [
            (sub['id'], length[sub['id']] * 100 -
             (s.edges[kol_from_id, sub['id']]['totalLinkages']
              if length[sub['id']] == 1 else 0),
             str(int(length[sub['id']])) + '-deg ' +
             ((str(int(s.edges[kol_from_id, sub['id']]['totalLinkages'])) +
               '-linkages: ') if length[sub['id']] == 1 else ': ') +
             sub['label'] + ' (' + sub['country'] + ' - ' +
             str(sub['specialties']) + ' specialties, ' +
             ('both share ' +
              (str(
                  int(s.edges[kol_from_id,
                              sub['id']]['Shared_organization_link'])) +
               ' Orgs, ' + str(
                   int(s.edges[kol_from_id, sub['id']]
                       ['Shared_clinical_trials_link'])) + ' Clin.Trials, ' +
               str(int(s.edges[kol_from_id, sub['id']]['Shared_articles_Link'])
                   ) + ' Articles') if length[sub['id']] == 1 else '') + ')')
            for sub in nodes
            if (sub['country'] == country or country == None) &
            (therapeutic_area in sub['specialty'] or therapeutic_area == None)
        ]
        to_kols = [{'label': n, 'value': x, 'order': i} for x, i, n in to_kols]
        to_kols = [{
            'label': y['label'],
            'value': y['value']
        } for y in sorted(to_kols, key=lambda x: x['order'])]
        information = 'Display network of ' + str(
            len(to_kols)) + ' Stakeholders'
    return [information, kol_from_id, to_kols, '']
Example #28
0
def main():
    G = nx.Graph()  # G eh um grafo direcionado
    # gera o grafo apartir de suas arestas
    G.add_weighted_edges_from([(1, 2, 2), (1, 3, 15), (2, 3, 24), (2, 4, 4),
                               (2, 5, 11), (3, 4, 2), (3, 5, 10), (4, 5, 5),
                               (4, 6, 15), (5, 6, 18)])
    for i in G.edges():
        # print i[0], i[1]
        G[i[0]][i[1]]["color"] = "black"
    # G[1][2]["color"] = "red"
    comprimento, caminho = nx.single_source_dijkstra(G, 1)
    print caminho
    for i in caminho:
        # print i, comprimento[i], caminho[i]
        for j in range(1, len(caminho[i])):
            print caminho[i][j - 1], caminho[i][j]
            G[caminho[i][j - 1]][caminho[i][j]]["color"] = "red"
    desenhaGrafo(G, "grafo-6.png")
    T = nx.minimum_spanning_tree(G)
    desenhaGrafo(T, "grafo-6arv.png")
Example #29
0
def ptva_li(graph, obs_time, distribution):

    mu = distribution.mean()
    sigma = distribution.std()
    obs = np.array(list(obs_time.keys()))

    path_lengths = {}
    paths = {}
    for o in obs:
        path_lengths[o], paths[o] = nx.single_source_dijkstra(graph, o)

    ### Run the estimation
    s_est, likelihoods, d_mu, cov = se.ml_estimate(graph, obs_time, sigma, mu,
                                                   paths, path_lengths)

    ranked = sorted(likelihoods.items(),
                    key=operator.itemgetter(1),
                    reverse=True)

    return (s_est, ranked)
Example #30
0
def complete_matrix(tree, G):
	nodes = list(tree.nodes())
	print("printing nodes now", nodes)
	num = len(nodes)
	matrix = []
	max_edge = 0
	for i in range(num):
		adj_list = [0]
		for x in range(i):
			adj_list.append(0)
		node = nodes[i]
		for j in range(i + 1, num):
			node2 = nodes[j]
			if G.has_edge(node, node2):
				adj_list.append(G.get_edge_data(node, node2)['weight'])
			else:
				length, path = nx.single_source_dijkstra(tree, node, node2)
				adj_list.append(length)
		matrix.append(adj_list)
	return matrix
Example #31
0
    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(
            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]}))
Example #32
0
def dijkstra_tree_old(G, v, targets=None):
    """
	Deprecated method for finding shortest path tree
	"""
    edgeSet = set()
    T = nx.Graph()
    T.add_nodes_from(range(len(G.nodes())))
    dists, paths = nx.single_source_dijkstra(G, v)
    if targets != None:
        paths = {v: paths[v] for v in paths if v in targets}
    for p in paths.values():
        for i in range(len(p) - 1):
            edgeSet.add((p[i], p[i + 1]))
    T.add_edges_from(edgeSet)
    for e in T.edges():
        T.edges[e]['weight'] = G.edges[e]['weight']
    #remove vertices of degree 0 because they're not targets
    if targets != None:
        T.remove_nodes_from([v for v in T.nodes() if T.degree()[v] == 0])
    return T
Example #33
0
    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]}))
Example #34
0
    def augment_graph(self, pairs):

        # create a new graph and stuff in the new fake/virtual edges
        # between odd pairs.  Generate the edge metadata to make them
        # look similar to the native edges.

        log.info('pre augmentation eulerian=%s',
                 nx.is_eulerian(self.g_augmented))

        for i, pair in enumerate(pairs):
            a, b = pair

            length, path = nx.single_source_dijkstra(self.g,
                                                     a,
                                                     b,
                                                     weight='length')

            log.debug('PAIR[%s] nodes = (%s,%s), length=%s, path=%s', i, a, b,
                      length, path)

            linestring = self.path_to_linestring(self.g_augmented, path)

            # create a linestring of paths...

            data = {
                'length': length,
                'augmented': True,
                'path': path,
                'geometry': linestring,
                'from': a,
                'to': b,
            }
            log.debug('  creating new edge (%s,%s) - data=%s', a, b, data)

            self.g_augmented.add_edge(a, b, **data)
            pass

        log.info('post augmentation eulerian=%s',
                 nx.is_eulerian(self.g_augmented))

        return
Example #35
0
def single_source_dijkstra(graph,
                           source,
                           data,
                           route='route_id',
                           stop='destination',
                           return_type='list'):
    """
    :param graph: networkx DiGraph to perform the search in
    :param source: source of the dijkstra search
    :param data: dict that contains the data of the edges of the graph
        (besides the weight). route and destination station for example
    :param route: name of the group identifier (route_id, trip_id, pattern...). Most probably : 'route_id'
    :param stop: key to the stop_id in data:
    :return:
    """
    lengths, paths = nx.single_source_dijkstra(graph, source)

    to_return = {
        'stops': [{
            'source': source,
            'target': key,
            'path': [data[p][stop] for p in value],
            'routes': set([data[p][route] for p in value]),
            'transfers': len(set([data[p][route] for p in value])) - 2,
            'length': lengths[key]
        } for key, value in paths.items() if type(key) == str],
        'links': [{
            'source': source,
            'target': key,
            'path': [data[p][stop] for p in value],
            'routes': set([data[p][route] for p in value]),
            'transfers': len(set([data[p][route] for p in value])) - 2,
            'length': lengths[key]
        } for key, value in paths.items() if type(key) == int],
    }

    return to_return if return_type == 'list' else {
        kind: {item['target']: item
               for item in to_return[kind]}
        for kind in to_return.keys()
    }  # never tested, may be bugged
def CalculateSSPTree(idx_train, labels, nclass, B, isdirected):
    labels_train = labels[idx_train]
    rank_result = [None] * nclass
    weight_result = [None] * nclass
    for j in range(0, nclass):
        indexes = [idx_train[i] for i, x in enumerate(labels_train) if x == j]
        dict_l = {}
        dict_w = {}
        if bool(isdirected) == True:
            G = nx.from_numpy_matrix(np.matrix(B[j]), create_using=nx.DiGraph)
        else:
            G = nx.from_numpy_matrix(B[j])

        for z in tqdm(range(len(indexes))):
            length, path = nx.single_source_dijkstra(G,
                                                     indexes[z],
                                                     target=None,
                                                     cutoff=None,
                                                     weight='weight')
            level = {k: len(v) - 1 for k, v in path.items()}
            if len(dict_l) == 0:
                dict_l = level
                dict_w = length
            else:
                for k, v in level.items():
                    if k in dict_l:
                        if dict_l[k] > v:
                            dict_l[k] = v
                            dict_w[k] = length[k]

                        if dict_l[k] == v:
                            if dict_w[k] > length[k]:
                                dict_w[k] = length[k]
                    else:
                        dict_l[k] = v
                        dict_w[k] = length[k]

                # dict_l = {k: min(v, dict_l[k]) for k, v in level.items() if k in dict_l}
        rank_result[j] = dict_l
        weight_result[j] = dict_w
    return rank_result, weight_result
Example #37
0
 def prepare(self, model):
     self.mesh = nx.DiGraph()
     self.mesh.add_nodes_from([
         e for e in model.nodes(data=True)
         if e[1]["node_type"] == nm.NODE_TYPE_WORKER
     ])
     self.mesh.add_nodes_from(
         nx.subgraph(model,
                     [self.node_src, self.node_dst]).nodes(data=True))
     self.mesh_costs = {}
     self.mesh_paths = {}
     for node in self.mesh:
         self.mesh_costs[node], self.mesh_paths[
             node] = nx.single_source_dijkstra(G=model,
                                               source=node,
                                               weight="latency")
     for node_a in self.mesh:
         for node_b in self.mesh:
             self.mesh.add_edge(node_a,
                                node_b,
                                latency=self.mesh_costs[node_a][node_b])
def shortest_path(start_node, G, out_folder):
    '''
    :param start_node: Input node
    :param G: input graph
    :return: short path of the start node in graph
    '''

    length, path = nx.single_source_dijkstra(G,
                                             start_node,
                                             cutoff=5,
                                             weight='weight')
    dest_index = list(length.keys())
    shortest_distance = list(length.values())
    d = {
        'destination_index': dest_index,
        'shortest_path_distance': shortest_distance
    }
    df_out = pd.DataFrame(data=d)
    df_out.to_csv(out_folder + 'path_dist_index_' + str(start_node) + '.csv',
                  sep=',',
                  index=False)
Example #39
0
def get_effdist_tree(G,
                     source,
                     cutoff=None,
                     create_using=nx.DiGraph,
                     weight='weight',
                     effdist_key='effdist'):

    T = create_using()
    T.graph['root'] = source
    T.add_node(source)

    length, path = nx.single_source_dijkstra(G,
                                             source,
                                             cutoff=cutoff,
                                             weight=weight)

    for n in list(path.keys()):
        T.add_path(path[n])
        T.node[n][effdist_key] = length[n]

    return T
Example #40
0
    def test_dijkstra(self):
        (D, P) = nx.single_source_dijkstra(self.XG, 's')
        validate_path(self.XG, 's', 'v', 9, P['v'])
        assert D['v'] == 9

        validate_path(self.XG, 's', 'v', 9,
                      nx.single_source_dijkstra_path(self.XG, 's')['v'])
        assert 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 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 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 nx.dijkstra_path_length(self.XG3, 0, 3) == 15
        validate_path(self.XG4, 0, 2, 4, nx.dijkstra_path(self.XG4, 0, 2))
        assert 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])
        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 nx.dijkstra_path_length(self.G, 's', 'v') == 2

        # NetworkXError: node s not reachable from moon
        pytest.raises(nx.NetworkXNoPath, nx.dijkstra_path, self.G, 's', 'moon')
        pytest.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 nx.single_source_dijkstra(self.cycle, 0, 0) == (0, [0])
    def get_shortest_path_length_with_limit(self, vertex1, vertex2, cutoff=None):
        """
        Parameters
        ----------
        vertex1:
        vertex2:
        cutoff:

        Returns
        -------
        NxGraph: Graph object

        Examples
        --------
        >>>
        """
        try:
            return nx.single_source_dijkstra(self._graph, source=vertex1, target=vertex2, cutoff=cutoff,
                                             weight=self._weight_field)
        except nx.NetworkXNoPath:
            return 0
Example #42
0
    def getBestMove(self):
        (bestScores, bestPathes) = nx.single_source_dijkstra(self,
                                                             self.head,
                                                             cutoff=10)
        maxLen = 0
        for bestPath in bestPathes.values():
            if maxLen < len(bestPath): maxLen = len(bestPath)
        print_err("max path len = " + str(maxLen))

        bestscoreitem = sorted([(key, value)
                                for (key, value) in bestScores.items()],
                               key=lambda x: x[1] / len(bestPathes[x[0]]))
        #bestscoreitem = sorted([(key, value) for (key, value) in bestscoreitem], key=lambda x:x[1])
        bestTarget = bestscoreitem[0]
        bestMove = None
        bestScore = self.head.score
        if len(bestPathes[bestTarget[0]]) > 1:
            bestfirstTarget = bestPathes[bestTarget[0]][1]
            bestScore = bestfirstTarget.score
            bestMove = self[self.head][bestfirstTarget]['move']
        return (bestMove, bestScore)
Example #43
0
def create_paths_file(G, fn_paths, fn_times):
    counter = 0
    # pbar = ProgressBar(
    #     widgets=["Creating Paths File: ", Bar(), Percentage(), "|", ETA()],
    #     maxval=pow(len(G.nodes()), 2)).start()
    with io.open(fn_paths, "wb") as fout:
        with io.open(fn_times, "wb") as ftimes:
            writer = csv.writer(fout, delimiter=" ")
            times_writer = csv.writer(ftimes, delimiter=" ")
            times_writer.writerow([len(G.nodes())])
            for i in G.nodes():
                tts, paths = nx.single_source_dijkstra(G, i)
                rows = list()
                time_row = [-1] * len(G.nodes())
                for j in paths.keys():
                    time_row[int(j)] = tts[int(j)]
                    rows.append([int(i), int(j)] + map(int, paths[int(j)]))
                    # pbar.update(counter + 1)
                    counter += 1
                writer.writerows(rows)
                times_writer.writerow(time_row)
    def list_flights(self, flights_map, price_limit, flights_limit, departure_point):

        print("Flights from {0}:".format(flights_map.points_names[departure_point].encode(self.output_encoding)))

        costs, paths = nx.single_source_dijkstra(flights_map.map, departure_point)
        self._find_cycle_from_dep_point(flights_map.map, departure_point, costs, paths, price_limit)

        price_w = len(str(max(costs)))
        
        for point in sorted(costs, key=lambda y: costs[y]):
            print("{0:{1}} {2} - {3}".format(costs[point], price_w, self.webpage_currency, flights_map.points_names[point].encode(self.output_encoding))),

            p = paths[point][1:-1]

            if len(p)>0 :
                print('\t( via'),
                for c in p:
                    print(flights_map.points_names[c].encode(self.output_encoding)),
                print(")"),

            print("")
Example #45
0
    def validate(self, g):
        """

        :param g:
        :return:
        """
        self.property_map = {
            k: v
            for k, v in self.property_map.items() if v != self.infinity
        }
        p = nx.single_source_dijkstra(g, self.source_vertex)
        if p[0] == self.property_map:
            return True
        else:
            print("Error: The algorithm is faulty!!!")
            for k, v in p[0].items():
                if p[0][k] != self.property_map[k]:
                    print("vertex ", k, " value in ground truth is ", p[0][k],
                          " and value in delta stepping is ",
                          self.property_map[k])
            return False
Example #46
0
def test_dijkstra(n, p=0.2, min_w=0, max_w=10, directed=True):
    """Tests the dijkstra implementation on a random weighted graph with
    n vertices.

    :param n: order of the  graph to test on
    :param p: the edge probability in G
    :param min_w: minimum edge weight in G
    :param max_w: maximum edge weight in G
    :param directed: whether or not the graph is directed.
    :return: True iff the distance output of dijkstra is the same
    as that generated by networkx's built in dijkstra function.
    """
    G, w, s = random_dijkstra_instance(n, p, min_w, max_w, directed)
    expected_ds, expected_path = nx.single_source_dijkstra(G, s)
    print(expected_path)
    print(expected_ds)
    actual_ds, parents = dijkstra(G, w, s)

    for v in G.nodes:
        assert actual_ds[v] == expected_ds[v]
    return True
Example #47
0
    def get_point_path_machine(self, point, cutoff=None):
        point_path_machine = None
        if self._add_visibility_edges(point):
            path_legths, paths = nx.single_source_dijkstra(
                self.visibility_graph, point, None, cutoff)

            def point_path_machine(point1):
                if self._is_visible(point, point1):
                    return [point, point1]
                visible_points = [
                    point2
                    for point2 in (self._get_visible_points(point1) or [])
                    if point2 in path_legths
                ]
                if visible_points:
                    return paths[min(visible_points,
                                     key=lambda point2: point1.distance(point2)
                                     + path_legths[point2])] + [point1]

        self.visibility_graph.remove_node(point)
        return point_path_machine
Example #48
0
    def all_relationship_weights(self, source_id):
        connections = {}

        lengths, paths = nx.single_source_dijkstra(self.GlobalGraph, source_id)
        del paths[source_id]

        for target in paths:
            if len(paths[target]) < 3:
                connections[target] = [lengths[target]]
            else:
                connections[target] = []
                for index, node in enumerate(paths[target]):
                    if index + 1 < len(paths[target]):
                        next_node_in_path = paths[target][index + 1]

                        weight = self.GlobalGraph[node][next_node_in_path][
                            node]['weight']

                        connections[target].append(weight)

        return connections
Example #49
0
def find_midpoint(G, start_node, dist):
	#Inputs: G, index of start_node, distance of walk
	#Returns: index of midpoint_node, list of indices of nodes along path to midpoint

	#Step 1: Identify contender midpoints within factor1*dist
	factor1 = 0.5
	contender_midpoints = nx.single_source_dijkstra(G, start_node, weight = 'length', cutoff = factor1*dist)
	#Returns 2 dicts: first of end nodes:distance and second of end node:node path

	#Dict [node index]:distance from start node
	contender_paths = contender_midpoints[0]

	#All contender nodes that are within factor2 of target length
	factor2 = 0.9
	farthest_node_considered = max(contender_paths.values())
	midpoint_nodes = [k for (k, v) in contender_paths.items() if v >= factor2*farthest_node_considered]

	#Step 2: Find contender midpoint node in a tree-rich area
	midpoints = beautreeful_node(G, midpoint_nodes)
	
	return midpoints
Example #50
0
def create_paths_file(G, fn_paths, fn_times):
    counter = 0
    # pbar = ProgressBar(
    #     widgets=["Creating Paths File: ", Bar(), Percentage(), "|", ETA()],
    #     maxval=pow(len(G.nodes()), 2)).start()
    with io.open(fn_paths, "wb") as fout:
        with io.open(fn_times, "wb") as ftimes:
            writer = csv.writer(fout, delimiter=" ")
            times_writer = csv.writer(ftimes, delimiter=" ")
            times_writer.writerow([len(G.nodes())])
            for i in G.nodes():
                tts, paths = nx.single_source_dijkstra(G, i)
                rows = list()
                time_row = [-1] * len(G.nodes())
                for j in paths.keys():
                    time_row[int(j)] = tts[int(j)]
                    rows.append([int(i), int(j)] + map(int, paths[int(j)]))
                    # pbar.update(counter + 1)
                    counter += 1
                writer.writerows(rows)
                times_writer.writerow(time_row)
Example #51
0
def pointsToBackbone(points, uvframe):
    # Generate a complete graph over these points,
    # weighted by Euclidean distances
    g = nx.Graph()
    # Graph vertices are point numbers, except points which are set to None
    nodes = filter(lambda x: points[x] is not None, range(len(points)))
    g.add_nodes_from(nodes)
    for i in range(len(points)):
        if points[i] is None:
            continue
        for j in range(i+1, len(points)):
            # TODO: scipy's cpair? but we will need to construct
            # a graph anyway
            if points[j] is None:
                continue
            # Eschew lines crossing dark areas
            lineSum = lineSumValue(points[i], points[j], uvframe)
            # print i, j, points[i], points[j], lineSum, math.sqrt(pointSquaredDistance(points[i], points[j]) * (LINE_VALUE_THRESHOLD ** 2))
            if lineSum ** 2 < pointSquaredDistance(points[i], points[j]) * (LINE_VALUE_THRESHOLD ** 2):
                #print '-->'
                continue
            g.add_edge(i, j, {'weight': math.pow(points[i][0]-points[j][0], 2) + math.pow(points[i][1]-points[j][1], 2)})

    # Reduce the complete graph to MST
    gmst = nx.minimum_spanning_tree(g)

    # Show the MST
    # f = plt.figure()
    # imgplot = plt.imshow(uvframe, cmap=plt.cm.gray)
    # display_graph(f.add_subplot(111), gmst, points)
    # plt.show()

    # Diameter of the minimum spanning tree will generate
    # a "likely pose walk" through the graph
    tip0 = max(nx.single_source_dijkstra_path_length(gmst, nodes[0]).items(), key=lambda x:x[1])[0] # funky argmax
    (tip1_lengths, tip1_paths) = nx.single_source_dijkstra(gmst, tip0)
    tip1 = max(tip1_lengths.items(), key=lambda x:x[1])[0]
    backbone = tip1_paths[tip1]

    return backbone
Example #52
0
    def converter(self, a, b):
        """returns a function that converts elements of type `a` to element with type `b`.

        """

        def c(n1, n2):
            data = self.get_edge_data(n1, n2)
            return data['fn']


        import inspect, itertools

        from_type = _ptype(a)
        to_type = _ptype(b)

        mro = inspect.getmro(from_type)  # inherited from

        resolve_order = [from_type] + list(mro)
        for start in resolve_order:
            try:
                (length, paths) = networkx.single_source_dijkstra(self, start, to_type, 'precedence')

                if to_type not in length:
                    continue  # not found a valid path, try super class

                path = paths[to_type]

                edges = zip(path[:-1], path[1:])
                converters = list(itertools.starmap(c, edges))

                def fn(val):
                    return reduce(lambda val, convert: convert(val),
                                  converters, val)

                return fn
            except KeyError as e:
                # : Unknown node
                pass

        raise MSMLMissingConversionException("Could not find a conversion for %s -> %s" % (from_type, to_type))
Example #53
0
def find_spt(digraph, root):
    """
    Finding the shortest-path-tree
    See algorithm here:
    https://web.archive.org/web/20200124171216/http://www.me.utexas.edu/~jensen/exercises/mst_spt/spt_demo/spt1.html
    (Original link is dead: http://www.me.utexas.edu/~jensen/exercises/mst_spt/spt_demo/spt1.html)
    :param digraph: graph
    :param root: root node
    :return: spt
    """
    spt = nx.Graph()
    s1 = {root}
    s2 = set(G.nodes())
    s2.remove(root)
    while s2:
        nodes_from_s2_to_s1 = set()
        direct_reachable_nodes = set()

        for _s in s1:
            for _i in digraph.adj[_s]:
                direct_reachable_nodes.add(_i)

        direct_reachable_nodes = direct_reachable_nodes - s1
        shortest_paths = [
            nx.single_source_dijkstra(digraph,
                                      source=root,
                                      target=t,
                                      weight="weight")
            for t in direct_reachable_nodes
        ]
        shortest_path = min(shortest_paths)

        edge_to_add = (shortest_path[1][-2], shortest_path[1][-1],
                       shortest_path[0])
        spt.add_weighted_edges_from([edge_to_add])
        nodes_from_s2_to_s1.add(shortest_path[1][-1])
        s1.update(nodes_from_s2_to_s1)
        s2.difference_update(nodes_from_s2_to_s1)

    return spt
Example #54
0
def get_shopabas(G,
                 seed,
                 data_shape,
                 max_d=10,
                 init_dist_val=None,
                 suppxls=None,
                 using_superpixels=False):
    if init_dist_val is None:
        init_dist_val = 2 * max_d

    n_pts = np.prod(data_shape)

    # urceni vzdalenosti od noveho seedu
    dists, _ = nx.single_source_dijkstra(G, seed, cutoff=max_d)

    # z rostouci vzdalenosti udelam klesajici (penalizacni) energii
    energy_s = np.zeros(n_pts)
    dists_items_array = np.array(dists.items())
    dist_layer = init_dist_val * np.ones(data_shape)

    if using_superpixels:
        idxs = dists_items_array[:, 0].astype(np.uint32)
        dists = dists_items_array[:, 1]
        energy_s_im = np.zeros(data_shape)
        for i in range(len(idxs)):
            suppxl = suppxls == idxs[i]
            energy_s_im[np.nonzero(suppxl)] = max_d - dists[i]
            energy_s = energy_s_im.flatten()
            dist_layer[np.nonzero(suppxl)] = dists[i]
    else:
        energy_s[dists_items_array[:, 0].astype(
            np.uint32)] = max_d - dists_items_array[:, 1]

        # vsechny body inicializuji na maximalni vzdalenost max_d
        dist_layer = init_dist_val * np.ones(n_pts)
        dist_layer[dists_items_array[:, 0].astype(
            np.uint32)] = dists_items_array[:, 1]
        dist_layer = dist_layer.reshape(data_shape)

    return dist_layer, energy_s
Example #55
0
    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 test_correctness(self):
        """
        This test check the correctness of shortest path and connected_component
        by compar it to the results from networkx on the same graph.
        :return:None
        """
        ga = GraphAlgo.GraphAlgo()
        filename = '../data/G_20000_160000_1.json'
        ga.load_from_json(filename)
        ganx = self.graph_nx(ga.get_graph())

        l = ga.shortest_path(0, 2)

        l2 = nx.single_source_dijkstra(ganx, 0, 2)
        self.assertEqual(l, l2)
        l = ga.connected_components()

        l2 = list(nx.strongly_connected_components(ganx))

        for i in range(len(l)):
            l[i].sort()
            self.assertTrue(set(l[i]) in l2)
    def  _find_cycle_from_dep_point(map, point, costs, paths, price_limit):

        costs[point] = float("inf")
        
        if map.edge[point].has_key(point) and map.edge[point][point]["weight"] <= price_limit:
            costs[point] = map.edge[point][point]["weight"]

        map.add_node("point_copy")

        for p in map.edge[point].copy():
            map.add_edge(p, "point_copy", weight=map.edge[point][p]["weight"])

        copy_cost, copy_path = nx.single_source_dijkstra(map, point, "point_copy")

        if copy_cost["point_copy"] < costs[point] and copy_cost["point_copy"] <= price_limit:
            costs[point] = copy_cost["point_copy"]
            paths[point] = copy_path["point_copy"]

        map.remove_node("point_copy")

        if costs[point] == float("inf"):
            costs.pop(point, None)
Example #58
0
def get_lineage_distances_across_time(early_tree, late_tree):
    """                                                                                                                                                                                                     
    Returns the matrix of lineage distances between leaves of early_tree and leaves in                                                                                                                              
    late_tree. Assumes that early_tree is a truncated version of late_tree                                                                                                                                  
    """
    num_cells_early = len(get_leaves(early_tree)) - 1
    num_cells_late = len(get_leaves(late_tree)) - 1

    d = np.zeros([num_cells_early, num_cells_late])

    cells_early = get_leaves(early_tree, include_root=False)
    cells_late = get_leaves(late_tree, include_root=False)

    # get length of path up to parent of early_cell and back to early_cell
    for late_cell in cells_late:
        distance_dictionary, tmp = nx.single_source_dijkstra(
            late_tree.to_undirected(), late_cell, weight='time')
        for early_cell in cells_early:
            d[early_cell,
              late_cell] = (distance_dictionary[next(
                  early_tree.predecessors(early_cell))] +
                            early_tree.nodes[early_cell]['time_to_parent'])

    # correct distances to descendants
    for early_cell in cells_early:
        parent = next(early_tree.predecessors(early_cell))
        late_cell = None
        for child in late_tree.successors(parent):
            if late_tree.nodes[child]['cell'].seed == early_tree.nodes[
                    early_cell]['cell'].seed:
                late_cell = child
                break
        if late_cell is not None:
            descendants = get_leaf_descendants(late_tree, late_cell)
            d[early_cell, descendants] = (
                d[early_cell, descendants] -
                2 * early_tree.nodes[early_cell]['time_to_parent'])

    return d
Example #59
0
def get_shortest_path(
        graph: nx.DiGraph, departure_airport: str, destination_airport: str
) -> Union[Tuple[int, list], Tuple[None, None]]:
    """
    Get the shortest path between nodes

    Handles missing nodes, and no path available
    :param graph: Graph holding the airport connection information
    :param departure_airport: The source node
    :param destination_airport: The destination node
    :return: total lenght of the path, the path taken
    """
    try:
        length, path = nx.single_source_dijkstra(graph,
                                                 departure_airport,
                                                 destination_airport,
                                                 weight="Time")
    except nx.exception.NetworkXNoPath:
        length, path = None, None
    except nx.NodeNotFound:
        length, path = None, None
    return length, path
Example #60
0
def findPlayerDistances(G, player_name, pathQ=False):
   """Find players distances to others in the graph.
      If pathQ = True returns a dictionary of the shortest paths,
      else returns distances."""
   import networkx as nx

   pos = findPlayer(players_list,player_name)
   go = False
   if len(pos)>1:
      print 'Found players ', [players_list[i].name for i in pos]
      print 'Please use more specific name.'
   elif len(pos)==1:
      print 'Found player', players_list[pos[0]].name
      go = True
   else:
      print 'No players found.'

   if go:
      res = nx.single_source_dijkstra(G, pos[0])
      if pathQ:
         return res[1]
      else:
         return res[0]