Python networkx.dfs_preorder_nodes() Examples

The following are 20 code examples of networkx.dfs_preorder_nodes(). 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: clustering.py    From clusim with MIT License 6 votes vote down vote up
def downstream_elements(self, cluster):
        """
        This method finds all elements contained in a cluster from a
        hierarchical clustering by visiting all downstream clusters
        and adding their elements.

        :param cluster: the name of the parent cluster

        :returns: element list


        """
        if cluster in self.hier_graph.leaves():
            return self.clu2elm_dict[cluster]
        else:
            el = set([])
            for c in nx.dfs_preorder_nodes(self.hier_graph, cluster):
                try:
                    el.update(self.clu2elm_dict[c])
                except KeyError:
                    pass

            return el 
Example #2
Source File: drg.py    From pyMARS with MIT License 6 votes vote down vote up
def graph_search(graph, target_species):
    """Search nodal graph and generate list of species to remove

    Parameters
    ----------
    graph : networkx.DiGraph
        graph representing reaction system
    target_species : list
        List of target species to search from

    Returns
    -------
    reached_species : list of str
        List of species reachable from targets in graph

    """
    reached_species = []
    for target in target_species:
        reached_species += list(networkx.dfs_preorder_nodes(graph, target))
    reached_species = list(set(reached_species))

    return reached_species 
Example #3
Source File: pfa.py    From pyMARS with MIT License 6 votes vote down vote up
def graph_search(graph, target_species):
    """Search nodal graph and generate list of species to remove

    Parameters
    ----------
    graph : networkx.DiGraph
        graph representing reaction system
    target_species : list
        List of target species to search from

    Returns
    -------
    reached_species : list of str
        List of species reachable from targets in graph

    """
    reached_species = []
    for target in target_species:
        reached_species += list(networkx.dfs_preorder_nodes(graph, target))
    reached_species = list(set(reached_species))

    return reached_species 
Example #4
Source File: dag.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def transitive_closure(G):
    """ Returns transitive closure of a directed graph

    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
    for all v,w in V there is an edge (v,w) in E+ if and only if there
    is a non-null path from v to w in G.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed graph

    Returns
    -------
    NetworkX DiGraph
        The transitive closure of `G`

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed

    References
    ----------
    .. [1] http://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py

    """
    TC = nx.DiGraph()
    TC.add_nodes_from(G.nodes())
    TC.add_edges_from(G.edges())
    for v in G:
        TC.add_edges_from((v, u) for u in nx.dfs_preorder_nodes(G, source=v)
                          if v != u)
    return TC 
Example #5
Source File: demography.py    From momi2 with GNU General Public License v3.0 5 votes vote down vote up
def _n_at_node(self, node):
        return sum(self._G.node[(pop, idx)]['lineages']
                   for pop, idx in nx.dfs_preorder_nodes(self._G, node)
                   if idx == 0) 
Example #6
Source File: test_dfs.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def dls_test_preorder_nodes(self):
        assert_equal(list(nx.dfs_preorder_nodes(self.G, source=0,
                     depth_limit=2)), [0, 1, 2])
        assert_equal(list(nx.dfs_preorder_nodes(self.D, source=1,
                     depth_limit=2)), ([1, 0])) 
Example #7
Source File: test_dfs.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_preorder_nodes(self):
        assert_equal(list(nx.dfs_preorder_nodes(self.G,source=0)),
                     [0, 1, 2, 4, 3])
        assert_equal(list(nx.dfs_preorder_nodes(self.D)),[0, 1, 2, 3]) 
Example #8
Source File: dag.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def transitive_closure(G):
    """ Returns transitive closure of a directed graph

    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
    for all v,w in V there is an edge (v,w) in E+ if and only if there
    is a non-null path from v to w in G.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed graph

    Returns
    -------
    NetworkX DiGraph
        The transitive closure of `G`

    Raises
    ------
    NetworkXNotImplemented
        If `G` is not directed

    References
    ----------
    .. [1] http://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py

    """
    TC = G.copy()
    for v in G:
        TC.add_edges_from((v, u) for u in nx.dfs_preorder_nodes(G, source=v)
                          if v != u)
    return TC 
Example #9
Source File: test_dfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dls_test_preorder_nodes(self):
        assert_equal(list(nx.dfs_preorder_nodes(self.G, source=0,
                                                depth_limit=2)), [0, 1, 2])
        assert_equal(list(nx.dfs_preorder_nodes(self.D, source=1,
                                                depth_limit=2)), ([1, 0])) 
Example #10
Source File: test_dfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_preorder_nodes(self):
        assert_equal(list(nx.dfs_preorder_nodes(self.G, source=0)),
                     [0, 1, 2, 4, 3])
        assert_equal(list(nx.dfs_preorder_nodes(self.D)), [0, 1, 2, 3]) 
Example #11
Source File: dag.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def transitive_closure(G):
    """ Returns transitive closure of a directed graph

    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
    for all v,w in V there is an edge (v,w) in E+ if and only if there
    is a non-null path from v to w in G.

    Parameters
    ----------
    G : NetworkX DiGraph
        Graph

    Returns
    -------
    TC : NetworkX DiGraph
        Graph

    Raises
    ------
    NetworkXNotImplemented
        If G is not directed

    References
    ----------
    .. [1] http://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py

    """
    TC = nx.DiGraph()
    TC.add_nodes_from(G.nodes_iter())
    TC.add_edges_from(G.edges_iter())
    for v in G:
        TC.add_edges_from((v, u) for u in nx.dfs_preorder_nodes(G, source=v)
                          if v != u)
    return TC 
Example #12
Source File: test_dfs.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_preorder_nodes(self):
        assert_equal(list(nx.dfs_preorder_nodes(self.G,source=0)),
                     [0, 1, 2, 4, 3])
        assert_equal(list(nx.dfs_preorder_nodes(self.D)),[0, 1, 2, 3]) 
Example #13
Source File: depth_first_search.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def dfs_preorder_nodes(G, source=None):
    """Produce nodes in a depth-first-search pre-ordering starting
    from source.

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

    source : node, optional
       Specify starting node for depth-first search and return edges in
       the component reachable from source.

    Returns
    -------
    nodes: generator
       A generator of nodes in a depth-first-search pre-ordering.

    Examples
    --------
    >>> G = nx.Graph()
    >>> G.add_path([0,1,2])
    >>> print(list(nx.dfs_preorder_nodes(G,0)))
    [0, 1, 2]

    Notes
    -----
    Based on http://www.ics.uci.edu/~eppstein/PADS/DFS.py
    by D. Eppstein, July 2004.

    If a source is not specified then a source is chosen arbitrarily and
    repeatedly until all components in the graph are searched.
    """
    pre=(v for u,v,d in nx.dfs_labeled_edges(G,source=source)
         if d['dir']=='forward')
    # potential modification: chain source to beginning of pre-ordering
    # return chain([source],pre)
    return pre 
Example #14
Source File: test_highlevel.py    From tskit with MIT License 5 votes vote down vote up
def verify_nx_algorithm_equivalence(self, tree, g):
        for root in tree.roots:
            self.assertTrue(nx.is_directed_acyclic_graph(g))

            # test descendants
            self.assertSetEqual(
                {u for u in tree.nodes() if tree.is_descendant(u, root)},
                set(nx.descendants(g, root)) | {root},
            )

            # test MRCA
            if tree.num_nodes < 20:
                for u, v in itertools.combinations(tree.nodes(), 2):
                    mrca = nx.lowest_common_ancestor(g, u, v)
                    if mrca is None:
                        mrca = -1
                    self.assertEqual(tree.mrca(u, v), mrca)

            # test node traversal modes
            self.assertEqual(
                list(tree.nodes(root=root, order="breadthfirst")),
                [root] + [v for u, v in nx.bfs_edges(g, root)],
            )
            self.assertEqual(
                list(tree.nodes(root=root, order="preorder")),
                list(nx.dfs_preorder_nodes(g, root)),
            ) 
Example #15
Source File: dag.py    From clusim with MIT License 5 votes vote down vote up
def random_prune_regraft(self):
        roots = self.roots()
        subtree_root = np.random.choice(self.nodes(), 1)[0]
        while subtree_root in roots and (len(roots) == 1):
            subtree_root = np.random.choice(self.nodes(), 1)[0]

        subtree_vertices = self.subgraph(
            nx.dfs_preorder_nodes(self, subtree_root)).nodes()
        prune_vertex = list(self.predecessors(subtree_root))[0]

        graft_vertex = np.random.choice(self.nodes(), 1)[0]
        while (graft_vertex in subtree_vertices) or\
              (graft_vertex in roots) or\
              (graft_vertex == prune_vertex):
            graft_vertex = np.random.choice(self.nodes(), 1)[0]

        # now we have to do the graph edits

        # merge connections through the pruned vertex
        for source in self.predecessors(prune_vertex):
            for sink in self.successors(prune_vertex):
                if sink != subtree_root:
                    self.add_edge(source, sink)

        # prune the vertex
        self.remove_node(prune_vertex)

        # reattach the pruned vertex
        for source in list(self.predecessors(graft_vertex)):
            self.add_edge(source, prune_vertex)
            self.remove_edge(source, graft_vertex)

        # reattach the subtree
        self.add_edge(prune_vertex, subtree_root)
        self.add_edge(prune_vertex, graft_vertex) 
Example #16
Source File: depth_first_search.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def dfs_postorder_nodes(G, source=None, depth_limit=None):
    """Generate nodes in a depth-first-search post-ordering starting at source.

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

    source : node, optional
       Specify starting node for depth-first search and return edges in
       the component reachable from source.

    depth_limit : int, optional (default=len(G))
       Specify the maximum search depth.

    Returns
    -------
    nodes: generator
       A generator of nodes in a depth-first-search post-ordering.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> list(nx.dfs_postorder_nodes(G, source=0))
    [4, 3, 2, 1, 0]
    >>> list(nx.dfs_postorder_nodes(G, source=0, depth_limit=2))
    [1, 0]

    Notes
    -----
    If a source is not specified then a source is chosen arbitrarily and
    repeatedly until all components in the graph are searched.

    The implementation of this function is adapted from David Eppstein's
    depth-first search function in `PADS`_, with modifications
    to allow depth limits based on the Wikipedia article
    "`Depth-limited search`_".

    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search

    See Also
    --------
    dfs_edges
    dfs_preorder_nodes
    dfs_labeled_edges
    """
    edges = nx.dfs_labeled_edges(G, source=source, depth_limit=depth_limit)
    return (v for u, v, d in edges if d == 'reverse') 
Example #17
Source File: depth_first_search.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def dfs_preorder_nodes(G, source=None, depth_limit=None):
    """Generate nodes in a depth-first-search pre-ordering starting at source.

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

    source : node, optional
       Specify starting node for depth-first search and return edges in
       the component reachable from source.

    depth_limit : int, optional (default=len(G))
       Specify the maximum search depth.

    Returns
    -------
    nodes: generator
       A generator of nodes in a depth-first-search pre-ordering.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> list(nx.dfs_preorder_nodes(G, source=0))
    [0, 1, 2, 3, 4]
    >>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=2))
    [0, 1, 2]

    Notes
    -----
    If a source is not specified then a source is chosen arbitrarily and
    repeatedly until all components in the graph are searched.

    The implementation of this function is adapted from David Eppstein's
    depth-first search function in `PADS`_, with modifications
    to allow depth limits based on the Wikipedia article
    "`Depth-limited search`_".

    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search

    See Also
    --------
    dfs_edges
    dfs_postorder_nodes
    dfs_labeled_edges
    """
    edges = nx.dfs_labeled_edges(G, source=source, depth_limit=depth_limit)
    return (v for u, v, d in edges if d == 'forward') 
Example #18
Source File: strongly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def kosaraju_strongly_connected_components(G, source=None):
    """Generate nodes in strongly connected components of graph.

    Parameters
    ----------
    G : NetworkX Graph
        An directed graph.

    Returns
    -------
    comp : generator of sets
        A genrator of sets of nodes, one for each strongly connected
        component of G.

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    Examples
    --------
    Generate a sorted list of strongly connected components, largest first.

    >>> G = nx.cycle_graph(4, create_using=nx.DiGraph())
    >>> G.add_cycle([10, 11, 12])
    >>> [len(c) for c in sorted(nx.kosaraju_strongly_connected_components(G),
    ...                         key=len, reverse=True)]
    [4, 3]

    If you only want the largest component, it's more efficient to
    use max instead of sort.

    >>> largest = max(nx.kosaraju_strongly_connected_components(G), key=len)

    See Also
    --------
    connected_components
    weakly_connected_components

    Notes
    -----
    Uses Kosaraju's algorithm.

    """
    with nx.utils.reversed(G):
        post = list(nx.dfs_postorder_nodes(G, source=source))

    seen = set()
    while post:
        r = post.pop()
        if r in seen:
            continue
        c = nx.dfs_preorder_nodes(G, r)
        new = {v for v in c if v not in seen}
        yield new
        seen.update(new) 
Example #19
Source File: depth_first_search.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def dfs_postorder_nodes(G, source=None, depth_limit=None):
    """Generate nodes in a depth-first-search post-ordering starting at source.

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

    source : node, optional
       Specify starting node for depth-first search and return edges in
       the component reachable from source.

    depth_limit : int, optional (default=len(G))
       Specify the maximum search depth.

    Returns
    -------
    nodes: generator
       A generator of nodes in a depth-first-search post-ordering.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> list(nx.dfs_postorder_nodes(G, source=0))
    [4, 3, 2, 1, 0]
    >>> list(nx.dfs_postorder_nodes(G, source=0, depth_limit=2))
    [1, 0]

    Notes
    -----
    If a source is not specified then a source is chosen arbitrarily and
    repeatedly until all components in the graph are searched.

    The implementation of this function is adapted from David Eppstein's
    depth-first search function in `PADS`_, with modifications
    to allow depth limits based on the Wikipedia article
    "`Depth-limited search`_".

    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search

    See Also
    --------
    dfs_edges
    dfs_preorder_nodes
    dfs_labeled_edges
    """
    edges = nx.dfs_labeled_edges(G, source=source, depth_limit=depth_limit)
    return (v for u, v, d in edges if d == 'reverse') 
Example #20
Source File: depth_first_search.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def dfs_preorder_nodes(G, source=None, depth_limit=None):
    """Generate nodes in a depth-first-search pre-ordering starting at source.

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

    source : node, optional
       Specify starting node for depth-first search and return edges in
       the component reachable from source.

    depth_limit : int, optional (default=len(G))
       Specify the maximum search depth.

    Returns
    -------
    nodes: generator
       A generator of nodes in a depth-first-search pre-ordering.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> list(nx.dfs_preorder_nodes(G, source=0))
    [0, 1, 2, 3, 4]
    >>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=2))
    [0, 1, 2]

    Notes
    -----
    If a source is not specified then a source is chosen arbitrarily and
    repeatedly until all components in the graph are searched.

    The implementation of this function is adapted from David Eppstein's
    depth-first search function in `PADS`_, with modifications
    to allow depth limits based on the Wikipedia article
    "`Depth-limited search`_".

    .. _PADS: http://www.ics.uci.edu/~eppstein/PADS
    .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search

    See Also
    --------
    dfs_edges
    dfs_postorder_nodes
    dfs_labeled_edges
    """
    edges = nx.dfs_labeled_edges(G, source=source, depth_limit=depth_limit)
    return (v for u, v, d in edges if d == 'forward')