Python networkx.single_source_shortest_path() Examples

The following are 16 code examples of networkx.single_source_shortest_path(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: dependencyGraph.py    From gtos with MIT License 6 votes vote down vote up
def collect_concepts_and_relations(self):
        g = self.graph
        nodes, depths, is_connected = self.bfs()
        concepts = [self.name2concept[n] for n in nodes] 
        relations = dict()
        for i, src in enumerate(nodes):
            relations[i] = dict()
            paths = nx.single_source_shortest_path(g, src)
            for j, tgt in enumerate(nodes):
                relations[i][j] = list()
                assert tgt in paths
                path = paths[tgt]
                info = dict()
                #info['node'] = path[1:-1]
                info['edge'] = [g[path[i]][path[i+1]]['label'] for i in range(len(path)-1)]
                info['length'] = len(info['edge'])
                relations[i][j].append(info)

        ## TODO, we just use the sequential order
        depths = nodes
        return concepts, depths, relations, is_connected 
Example #2
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_single_source_shortest_path(self):
        p = nx.shortest_path(self.cycle, 0)
        assert_equal(p[3], [0, 1, 2, 3])
        assert_equal(p, nx.single_source_shortest_path(self.cycle, 0))
        p = nx.shortest_path(self.grid, 1)
        validate_grid_path(4, 4, 1, 12, p[12])
        # now with weights
        p = nx.shortest_path(self.cycle, 0, weight='weight')
        assert_equal(p[3], [0, 1, 2, 3])
        assert_equal(p, nx.single_source_dijkstra_path(self.cycle, 0))
        p = nx.shortest_path(self.grid, 1, weight='weight')
        validate_grid_path(4, 4, 1, 12, p[12])
        # weights and method specified
        p = nx.shortest_path(self.cycle, 0, method='dijkstra', weight='weight')
        assert_equal(p[3], [0, 1, 2, 3])
        assert_equal(p, nx.single_source_shortest_path(self.cycle, 0))
        p = nx.shortest_path(self.cycle, 0, method='bellman-ford',
                             weight='weight')
        assert_equal(p[3], [0, 1, 2, 3])
        assert_equal(p, nx.single_source_shortest_path(self.cycle, 0)) 
Example #3
Source File: _remove_unused_toplevel_elems.py    From tmppy with Apache License 2.0 5 votes vote down vote up
def remove_unused_toplevel_elems(header: ir.Header, linking_final_header: bool):
    toplevel_elem_names = {elem.name
                           for elem in itertools.chain(header.toplevel_content, header.template_defns)
                           if not isinstance(elem, (ir.StaticAssert, ir.NoOpStmt))}

    public_names = header.public_names
    if not linking_final_header:
        public_names = public_names.union(split_name
                                          for _, split_name in header.split_template_name_by_old_name_and_result_element_name)

    elem_dependency_graph = nx.DiGraph()
    for elem in itertools.chain(header.template_defns, header.toplevel_content):
        if isinstance(elem, (ir.TemplateDefn, ir.ConstantDef, ir.Typedef)):
            elem_name = elem.name
        else:
            # We'll use a dummy name for non-template toplevel elems.
            elem_name = ''

        elem_dependency_graph.add_node(elem_name)

        if elem_name in public_names or (isinstance(elem, (ir.ConstantDef, ir.Typedef)) and any(isinstance(expr, ir.TemplateInstantiation) and expr.instantiation_might_trigger_static_asserts
                                                                                                for expr in elem.transitive_subexpressions)):
            # We also add an edge from the node '' to all toplevel defns that must remain, so that we can use '' as a source below.
            elem_dependency_graph.add_edge('', elem_name)

        for identifier in elem.referenced_identifiers:
            if identifier in toplevel_elem_names:
                elem_dependency_graph.add_edge(elem_name, identifier)

    elem_dependency_graph.add_node('')
    used_elem_names = nx.single_source_shortest_path(elem_dependency_graph, source='').keys()

    return ir.Header(template_defns=tuple(template_defn for template_defn in header.template_defns if
                                          template_defn.name in used_elem_names),
                     toplevel_content=tuple(elem for elem in header.toplevel_content if
                                            isinstance(elem, (ir.StaticAssert, ir.NoOpStmt)) or elem.name in used_elem_names),
                     public_names=header.public_names,
                     split_template_name_by_old_name_and_result_element_name=header.split_template_name_by_old_name_and_result_element_name,
                     check_if_error_specializations=header.check_if_error_specializations) 
Example #4
Source File: test_generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_single_source_shortest_path(self):
        p=nx.shortest_path(self.cycle,0)
        assert_equal(p[3],[0,1,2,3])
        assert_equal(p,nx.single_source_shortest_path(self.cycle,0))
        p=nx.shortest_path(self.grid,1)
        validate_grid_path(4, 4, 1, 12, p[12])
        # now with weights
        p=nx.shortest_path(self.cycle,0,weight='weight')
        assert_equal(p[3],[0,1,2,3])
        assert_equal(p,nx.single_source_dijkstra_path(self.cycle,0))
        p=nx.shortest_path(self.grid,1,weight='weight')
        validate_grid_path(4, 4, 1, 12, p[12]) 
Example #5
Source File: test_unweighted.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_single_source_shortest_path(self):
        p=nx.single_source_shortest_path(self.cycle,0)
        assert_equal(p[3],[0,1,2,3])
        p=nx.single_source_shortest_path(self.cycle,0, cutoff=0)
        assert_equal(p,{0 : [0]}) 
Example #6
Source File: unweighted.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def all_pairs_shortest_path(G, cutoff=None):
    """Compute shortest paths between all nodes.

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

    cutoff : integer, optional
        Depth at which to stop the search. Only paths of length at most
        ``cutoff`` are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by source and target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> path = nx.all_pairs_shortest_path(G)
    >>> print(path[0][4])
    [0, 1, 2, 3, 4]

    See Also
    --------
    floyd_warshall()

    """
    # TODO This can be trivially parallelized.
    return {n: single_source_shortest_path(G, n, cutoff=cutoff) for n in G} 
Example #7
Source File: test_unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_single_source_shortest_path(self):
        p = nx.single_source_shortest_path(self.directed_cycle, 3)
        assert_equal(p[0], [3, 4, 5, 6, 0])
        p = nx.single_source_shortest_path(self.cycle, 0)
        assert_equal(p[3], [0, 1, 2, 3])
        p = nx.single_source_shortest_path(self.cycle, 0, cutoff=0)
        assert_equal(p, {0: [0]}) 
Example #8
Source File: unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def all_pairs_shortest_path(G, cutoff=None):
    """Compute shortest paths between all nodes.

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

    cutoff : integer, optional
        Depth at which to stop the search. Only paths of length at most
        `cutoff` are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by source and target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> path = dict(nx.all_pairs_shortest_path(G))
    >>> print(path[0][4])
    [0, 1, 2, 3, 4]

    See Also
    --------
    floyd_warshall()

    """
    # TODO This can be trivially parallelized.
    for n in G:
        yield (n, single_source_shortest_path(G, n, cutoff=cutoff)) 
Example #9
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_single_source_shortest_path(self):
        p=nx.shortest_path(self.cycle,0)
        assert_equal(p[3],[0,1,2,3])
        assert_equal(p,nx.single_source_shortest_path(self.cycle,0))
        p=nx.shortest_path(self.grid,1)
        validate_grid_path(4, 4, 1, 12, p[12])
        # now with weights
        p=nx.shortest_path(self.cycle,0,weight='weight')
        assert_equal(p[3],[0,1,2,3])
        assert_equal(p,nx.single_source_dijkstra_path(self.cycle,0))
        p=nx.shortest_path(self.grid,1,weight='weight')
        validate_grid_path(4, 4, 1, 12, p[12]) 
Example #10
Source File: test_unweighted.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_single_source_shortest_path(self):
        p = nx.single_source_shortest_path(self.directed_cycle, 3)
        assert_equal(p[0], [3, 4, 5, 6, 0])
        p = nx.single_source_shortest_path(self.cycle, 0)
        assert_equal(p[3], [0, 1, 2, 3])
        p = nx.single_source_shortest_path(self.cycle, 0, cutoff=0)
        assert_equal(p,{0 : [0]}) 
Example #11
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def all_pairs_shortest_path(G, cutoff=None):
    """Compute shortest paths between all nodes.

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

    cutoff : integer, optional
        Depth at which to stop the search. Only paths of length at most
        `cutoff` are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by source and target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> path = dict(nx.all_pairs_shortest_path(G))
    >>> print(path[0][4])
    [0, 1, 2, 3, 4]

    See Also
    --------
    floyd_warshall()

    """
    # TODO This can be trivially parallelized.
    for n in G:
        yield (n, single_source_shortest_path(G, n, cutoff=cutoff)) 
Example #12
Source File: unweighted.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def single_source_shortest_path(G,source,cutoff=None):
    """Compute shortest path between source
    and all other nodes reachable from source.

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

    source : node label
       Starting node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by target, of shortest paths.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> path=nx.single_source_shortest_path(G,0)
    >>> path[4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    The shortest path is not necessarily unique. So there can be multiple
    paths between the source and each target node, all of which have the
    same 'shortest' length. For each target node, this function returns
    only one of those paths.

    See Also
    --------
    shortest_path
    """
    level=0                  # the current level
    nextlevel={source:1}       # list of nodes to check at next level
    paths={source:[source]}  # paths dictionary  (paths to key from source)
    if cutoff==0:
        return paths
    while nextlevel:
        thislevel=nextlevel
        nextlevel={}
        for v in thislevel:
            for w in G[v]:
                if w not in paths:
                    paths[w]=paths[v]+[w]
                    nextlevel[w]=1
        level=level+1
        if (cutoff is not None and cutoff <= level):  break
    return paths 
Example #13
Source File: unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def single_source_shortest_path(G, source, cutoff=None):
    """Compute shortest path between source
    and all other nodes reachable from source.

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

    source : node label
       Starting node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> path = nx.single_source_shortest_path(G, 0)
    >>> path[4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    The shortest path is not necessarily unique. So there can be multiple
    paths between the source and each target node, all of which have the
    same 'shortest' length. For each target node, this function returns
    only one of those paths.

    See Also
    --------
    shortest_path
    """
    if source not in G:
        raise nx.NodeNotFound("Source {} not in G".format(source))

    def join(p1, p2):
        return p1 + p2
    if cutoff is None:
        cutoff = float('inf')
    nextlevel = {source: 1}     # list of nodes to check at next level
    paths = {source: [source]}  # paths dictionary  (paths to key from source)
    return dict(_single_shortest_path(G.adj, nextlevel, paths, cutoff, join)) 
Example #14
Source File: unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def single_target_shortest_path(G, target, cutoff=None):
    """Compute shortest path to target from all nodes that reach target.

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

    target : node label
       Target node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5, create_using=nx.DiGraph())
    >>> path = nx.single_target_shortest_path(G, 4)
    >>> path[0]
    [0, 1, 2, 3, 4]

    Notes
    -----
    The shortest path is not necessarily unique. So there can be multiple
    paths between the source and each target node, all of which have the
    same 'shortest' length. For each target node, this function returns
    only one of those paths.

    See Also
    --------
    shortest_path, single_source_shortest_path
    """
    if target not in G:
        raise nx.NodeNotFound("Target {} not in G".format(target))

    def join(p1, p2):
        return p2 + p1
    # handle undirected graphs
    adj = G.pred if G.is_directed() else G.adj
    if cutoff is None:
        cutoff = float('inf')
    nextlevel = {target: 1}     # list of nodes to check at next level
    paths = {target: [target]}  # paths dictionary  (paths to key from source)
    return dict(_single_shortest_path(adj, nextlevel, paths, cutoff, join)) 
Example #15
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def single_source_shortest_path(G, source, cutoff=None):
    """Compute shortest path between source
    and all other nodes reachable from source.

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

    source : node label
       Starting node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> path = nx.single_source_shortest_path(G, 0)
    >>> path[4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    The shortest path is not necessarily unique. So there can be multiple
    paths between the source and each target node, all of which have the
    same 'shortest' length. For each target node, this function returns
    only one of those paths.

    See Also
    --------
    shortest_path
    """
    if source not in G:
        raise nx.NodeNotFound("Source {} not in G".format(source))

    def join(p1, p2):
        return p1 + p2
    if cutoff is None:
        cutoff = float('inf')
    nextlevel = {source: 1}     # list of nodes to check at next level
    paths = {source: [source]}  # paths dictionary  (paths to key from source)
    return dict(_single_shortest_path(G.adj, nextlevel, paths, cutoff, join)) 
Example #16
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def single_target_shortest_path(G, target, cutoff=None):
    """Compute shortest path to target from all nodes that reach target.

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

    target : node label
       Target node for path

    cutoff : integer, optional
        Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    lengths : dictionary
        Dictionary, keyed by target, of shortest paths.

    Examples
    --------
    >>> G = nx.path_graph(5, create_using=nx.DiGraph())
    >>> path = nx.single_target_shortest_path(G, 4)
    >>> path[0]
    [0, 1, 2, 3, 4]

    Notes
    -----
    The shortest path is not necessarily unique. So there can be multiple
    paths between the source and each target node, all of which have the
    same 'shortest' length. For each target node, this function returns
    only one of those paths.

    See Also
    --------
    shortest_path, single_source_shortest_path
    """
    if target not in G:
        raise nx.NodeNotFound("Target {} not in G".format(source))

    def join(p1, p2):
        return p2 + p1
    # handle undirected graphs
    adj = G.pred if G.is_directed() else G.adj
    if cutoff is None:
        cutoff = float('inf')
    nextlevel = {target: 1}     # list of nodes to check at next level
    paths = {target: [target]}  # paths dictionary  (paths to key from source)
    return dict(_single_shortest_path(adj, nextlevel, paths, cutoff, join))