How to use the networkx.shortest_path function in networkx

To help you get started, we’ve selected a few networkx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cogeorg / BlackRhino / networkx / algorithms / shortest_paths / generic.py View on Github external
def has_path(G, source, target):
    """Return *True* if *G* has a path from *source* to *target*.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path

    target : node
       Ending node for path
    """
    try:
        sp = nx.shortest_path(G, source, target)
    except nx.NetworkXNoPath:
        return False
    return True
github jacobmarks / QTop / src / decoders / gcc.py View on Github external
def GCC_One_Color_Transport(s, e, cc, uc, code, t, ct):
	k, k_end = s[1]['charge'], e[1]['charge']

	d = code.dimension
	t1, t2 = code.complementaryTypes(t)
	dual1 = nx.shortest_path(code.Dual[t1], s[0], e[0])
	if s[0] in uc:
		cc.remove((s[0], {'charge':k,'type':t}))
		uc.remove_node(s[0])
		code.Stabilizers[t][s[0]]['charge'][ct] = 0

	num_loops = (len(dual1)-1)/2
	for i in range(num_loops):
		start, end = dual1[2*i], dual1[2*i+2]
		k1, k2 = code.Stabilizers[t][start]['charge'][ct], code.Stabilizers[t][end]['charge'][ct]
		if any((start in code.External[type] and end in code.External[type]) for type in code.External):
			continue

		dual2 = nx.shortest_path(code.Dual[t2], end, start)
		triangle1 = dual1[2*i:(2*i+2)] + dual2[1:]
		triangle2 =  dual2[:2] + dual1[2*i+1:(2*i+3)]
		loop1 = path.Path(triangle1)
github PacificBiosciences / FALCON / examples / DA_ASM / src / falcon_asm_s.py View on Github external
# construct the bundle graph                
    associate_graph_nodes = set(associate_graph.nodes())
    bundle_graph = nx.DiGraph()
    bundle_graph.add_path( path )
    for i in range(len(non_branch_subpaths)-1):
        if len(non_branch_subpaths[i]) == 0 or len( non_branch_subpaths[i+1] ) == 0:
            continue
        e1, e2 = non_branch_subpaths[i: i+2]
        v = e1[-1]
        w = e2[0]
        if v == w:
            continue
        in_between_node_count = nodes_idx[w] - nodes_idx[v] 
        if v in associate_graph_nodes and w in associate_graph_nodes:
            try:
                a_path = nx.shortest_path(associate_graph, v, w, "n_weight")    
            except nx.NetworkXNoPath:
                continue
            bundle_graph.add_path( a_path )      
            bundle_paths.append( a_path )

    return bundle_graph, bundle_paths, sub_graph2_edges
github PacificBiosciences / FALCON / src / py / generate_string_bundle2.py View on Github external
orientation = "E" if orientation == "B" else "E"
                        visited.add( r_id +":" + orientation)
                        if not is_branch_node(sub_graph_r, e[1]):
                        #if not is_branch_node(u_graph_r, e[1]):
                            tips.add(e[1])
        ct += 1
        #print ct, len(tips)
        
    last_node = None
    longest_len = 0
    sub_graph2_nodes = sub_graph2.nodes()
    sub_graph2_edges = sub_graph2.edges()
    new_path = [path[0]]
    for n in sub_graph2_nodes:
        if len(sub_graph2.out_edges(n)) == 0 :
            path_t = nx.shortest_path(sub_graph2, source = path[0], target = n, weight = "n_weight")
            path_len = len(path_t)
            if path_len > longest_len:
                last_node = n
                longest_len = path_len
                new_path = path_t

    if last_node == None:
        for n in sub_graph2_nodes:
            path_t = nx.shortest_path(sub_graph2, source = path[0], target = n, weight = "n_weight")
            path_len = len(path_t)
            if path_len > longest_len:
                last_node = n
                longest_len = path_len


    #new_path = nx.shortest_path(sub_graph2, path[0], last_node, "n_weight")
github 3Scan / 3scan-skeleton / experimental / segmentStatsLRwhitecutoffs.py View on Github external
curveDisplacement = np.sqrt(np.sum((np.array(sourceOnTree) - np.array(item)) ** 2))
                        segmentLengthdict[segmentCountdict[sourceOnTree], sourceOnTree, item] = curveLength
                        segmentTortuositydict[segmentCountdict[sourceOnTree], sourceOnTree, item] = curveLength / curveDisplacement
                        segmentContractiondict[segmentCountdict[sourceOnTree], sourceOnTree, item] = curveDisplacement / curveLength
                        if curveDisplacement != 0.0:
                            if log(curveDisplacement) != 0.0:
                                segmentHausdorffDimensiondict[segmentCountdict[sourceOnTree], sourceOnTree, item] = log(curveLength) / log(curveDisplacement)
                    isolatedEdgeInfo[sourceOnTree, item] = curveLength
                    _removeEdgesInVisitedPath(subGraphskeleton, simplePath, 0)
    else:
        """ each node is connected to one or two other nodes implies it is a line,
        set tortuosity to 1"""
        endpoints = [k for (k, v) in nodeDegreedict.items() if v == 1]
        sourceOnLine = endpoints[0]
        targetOnLine = endpoints[1]
        simplePath = nx.shortest_path(subGraphskeleton, source=sourceOnLine, target=targetOnLine)
        curveLength = _getDistanceBetweenPointsInpath(simplePath, 0)
        isolatedEdgeInfo[sourceOnLine, targetOnLine] = curveLength
        if curveLength > 5:
            segmentCountdict[sourceOnLine] = 1
            segmentLengthdict[1, sourceOnLine, targetOnLine] = curveLength
            segmentContractiondict[1, sourceOnLine, targetOnLine] = 1
            segmentTortuositydict[1, sourceOnLine, targetOnLine] = 1
            segmentHausdorffDimensiondict[1, sourceOnLine, targetOnLine] = 1
        edges = subGraphskeleton.edges()
        subGraphskeleton.remove_edges_from(edges)
github sdss / marvin / python / marvin / db / modelGraph.py View on Github external
def _getShortestPath(self, tableA, tableB, format_out='tables',
                         removeA=False):
        """Gets the shortest path between two nodes."""

        try:
            path = nx.shortest_path(self.graph, tableA, tableB)
        except nx.NetworkXNoPath:
            raise nx.NetworkXNoPath(
                'it is not possible to join tables {0} and {1}. '
                'Please, review your query.'.format(tableA, tableB))

        if removeA:
            path.remove(tableA)

        if format_out == 'tables':
            pathSet = path
        else:
            pathSet = [self.graph.node[table]['model'] for table in path]

        return pathSet
github faucetsdn / faucet / faucet / dp.py View on Github external
def shortest_path(self, dest_dp):
        if self.stack is None:
            return None
        return networkx.shortest_path(
            self.stack['graph'], self.name, dest_dp)
github yhenon / pyimgsaliency / pyimgsaliency / saliency.py View on Github external
for v2 in vertices:
				if boundary[v2] == 1:
					color_distance = scipy.spatial.distance.euclidean(colors[v1],colors[v2])
					G.add_edge(v1,v2,weight=color_distance)

	geodesic = np.zeros((len(vertices),len(vertices)),dtype=float)
	spatial = np.zeros((len(vertices),len(vertices)),dtype=float)
	smoothness = np.zeros((len(vertices),len(vertices)),dtype=float)
	adjacency = np.zeros((len(vertices),len(vertices)),dtype=float)

	sigma_clr = 10.0
	sigma_bndcon = 1.0
	sigma_spa = 0.25
	mu = 0.1

	all_shortest_paths_color = nx.shortest_path(G,source=None,target=None,weight='weight')

	for v1 in vertices:
		for v2 in vertices:
			if v1 == v2:
				geodesic[v1,v2] = 0
				spatial[v1,v2] = 0
				smoothness[v1,v2] = 0
			else:
				geodesic[v1,v2] = path_length(all_shortest_paths_color[v1][v2],G)
				spatial[v1,v2] = scipy.spatial.distance.euclidean(centers[v1],centers[v2]) / max_dist
				smoothness[v1,v2] = math.exp( - (geodesic[v1,v2] * geodesic[v1,v2])/(2.0*sigma_clr*sigma_clr)) + mu 

	for edge in edges:
		pt1 = edge[0]
		pt2 = edge[1]
		adjacency[pt1,pt2] = 1
github trinity-project / trinity / gateway / topo.py View on Github external
def find_shortest_path_decide_by_fee(self, source, target):
        """
        :param source: start uri\n
        :param target: end uri\n
        :return type list ["A","B","C"]
        """
        sid = utils.get_public_key(source)
        tid = utils.get_public_key(target)
        try:
            path = nx.shortest_path(self._graph, sid, tid, weight='weight')
        except nx.exception.NetworkXNoPath:
            path = []
        return path
github kuleshov / architect / algorithms / mst.py View on Github external
def _mst_trunk(mst, g):
  # weigh edges according to their distance
  _reweigh_edges(mst, g, type_='lengths')

  # compute shortest path distances between nodes
  all_pairs_shortest_dists = nx.shortest_path_length(mst)

  # determine the pair that corresponds to the longest distance
  all_pairs = itertools.product(mst.nodes_iter(), mst.nodes_iter())
  s, t = max(all_pairs, key=lambda p: all_pairs_shortest_dists[p[0]][p[1]])

  # return the path between s and t
  return nx.shortest_path(mst,s,t)