Python networkx.dfs_edges() Examples

The following are 26 code examples of networkx.dfs_edges(). 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: inference.py    From science_rcn with MIT License 10 votes vote down vote up
def get_tree_schedule(frcs, graph):
    """
    Find the most constrained tree in the graph and returns which messages to compute
    it.  This is the minimum spanning tree of the perturb_radius edge attribute.

    See forward_pass for parameters.

    Returns
    -------
    tree_schedules : numpy.ndarray of numpy.int
        Describes how to compute the max marginal for the most constrained tree.
        Nx3 2D array of (source pool_idx, target pool_idx, perturb radius), where
        each row represents a single outgoing factor message computation.
    """
    min_tree = nx.minimum_spanning_tree(graph, 'perturb_radius')
    return np.array([(target, source, graph.edge[source][target]['perturb_radius'])
                     for source, target in nx.dfs_edges(min_tree)])[::-1] 
Example #2
Source File: test_cfgemulated.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_max_steps():

    binary_path = os.path.join(test_location, "x86_64", "fauxware")
    b = angr.Project(binary_path, load_options={'auto_load_libs': False})
    cfg = b.analyses.CFGEmulated(max_steps=5, fail_fast=True)

    dfs_edges = networkx.dfs_edges(cfg.graph)

    depth_map = {}
    for src, dst in dfs_edges:
        if src not in depth_map:
            depth_map[src] = 0
        if dst not in depth_map:
            depth_map[dst] = depth_map[src] + 1
        depth_map[dst] = max(depth_map[src] + 1, depth_map[dst])

    nose.tools.assert_less_equal(max(depth_map.values()), 5) 
Example #3
Source File: greedy_coloring.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def strategy_connected_sequential(G, colors, traversal='bfs'):
    """
    Connected sequential ordering (CS). Yield nodes in such an order, that
    each node, except the first one, has at least one neighbour in the
    preceeding sequence. The sequence can be generated using both BFS and
    DFS search (using the strategy_connected_sequential_bfs and
    strategy_connected_sequential_dfs method). The default is bfs.
    """
    for component_graph in nx.connected_component_subgraphs(G):
        source = component_graph.nodes()[0]

        yield source  # Pick the first node as source

        if traversal == 'bfs':
            tree = nx.bfs_edges(component_graph, source)
        elif traversal == 'dfs':
            tree = nx.dfs_edges(component_graph, source)
        else:
            raise nx.NetworkXError(
                'Please specify bfs or dfs for connected sequential ordering')

        for (_, end) in tree:
            # Then yield nodes in the order traversed by either BFS or DFS
            yield end 
Example #4
Source File: dag.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def transitive_reduction(G):
    """ Returns transitive reduction of a directed graph

    The transitive reduction 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 (v,w) is
    in E and there is no path from v to w in G with length greater than 1.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)

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

    Raises
    ------
    NetworkXError
        If `G` is not a directed acyclic graph (DAG) transitive reduction is
        not uniquely defined and a :exc:`NetworkXError` exception is raised.

    References
    ----------
    https://en.wikipedia.org/wiki/Transitive_reduction

    """
    if not is_directed_acyclic_graph(G):
        raise nx.NetworkXError(
            "Transitive reduction only uniquely defined on directed acyclic graphs.")
    TR = nx.DiGraph()
    TR.add_nodes_from(G.nodes())
    for u in G:
        u_edges = set(G[u])
        for v in G[u]:
            u_edges -= {y for x, y in nx.dfs_edges(G, v)}
        TR.add_edges_from((u, v) for v in u_edges)
    return TR 
Example #5
Source File: director.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _dfs_edges(graph, source, max_steps=None):
        """
        Perform a depth-first search on the given DiGraph, with a limit on maximum steps.

        :param networkx.DiGraph graph:  The graph to traverse.
        :param Any source:              The source to begin traversal.
        :param int max_steps:           Maximum steps of the traversal, or None if not limiting steps.
        :return: An iterator of edges.
        """

        if max_steps is None:
            yield networkx.dfs_edges(graph, source)

        else:
            steps_map = defaultdict(int)
            traversed = { source }
            stack = [ source ]

            while stack:
                src = stack.pop()
                for dst in graph.successors(src):
                    if dst in traversed:
                        continue
                    traversed.add(dst)

                    dst_steps = max(steps_map[src] + 1, steps_map[dst])

                    if dst_steps > max_steps:
                        continue

                    yield src, dst

                    steps_map[dst] = dst_steps
                    stack.append(dst) 
Example #6
Source File: test_dfs.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_dls_edges(self):
        edges = nx.dfs_edges(self.G, source=9, depth_limit=4)
        assert_equal(list(edges),[(9, 8), (8, 7),
                     (7, 2), (2, 1), (2, 3), (9, 10)]) 
Example #7
Source File: test_dfs.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_dfs_edges(self):
        edges=nx.dfs_edges(self.G,source=0)
        assert_equal(list(edges),[(0, 1), (1, 2), (2, 4), (4, 3)])
        edges=nx.dfs_edges(self.D)
        assert_equal(list(edges),[(0, 1), (2, 3)]) 
Example #8
Source File: depth_first_search.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def dfs_predecessors(G, source=None, depth_limit=None):
    """Return dictionary of predecessors in depth-first-search 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.

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

    Returns
    -------
    pred: dict
       A dictionary with nodes as keys and predecessor nodes as values.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.dfs_predecessors(G, source=0)
    {1: 0, 2: 1, 3: 2}
    >>> nx.dfs_predecessors(G, source=0, depth_limit=2)
    {1: 0, 2: 1}

    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
    """
    return {t: s for s, t in dfs_edges(G, source, depth_limit)} 
Example #9
Source File: depth_first_search.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def dfs_tree(G, source=None, depth_limit=None):
    """Return oriented tree constructed from a depth-first-search from source.

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

    source : node, optional
       Specify starting node for depth-first search.

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

    Returns
    -------
    T : NetworkX DiGraph
       An oriented tree

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

    """
    T = nx.DiGraph()
    if source is None:
        T.add_nodes_from(G)
    else:
        T.add_node(source)
    T.add_edges_from(dfs_edges(G, source, depth_limit))
    return T 
Example #10
Source File: greedy_coloring.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def strategy_connected_sequential(G, colors, traversal='bfs'):
    """Returns an iterable over nodes in ``G`` in the order given by a
    breadth-first or depth-first traversal.

    ``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
    representing depth-first traversal or breadth-first traversal,
    respectively.

    The generated sequence has the property that for each node except
    the first, at least one neighbor appeared earlier in the sequence.

    ``G`` is a NetworkX graph. ``colors`` is ignored.

    """
    if traversal == 'bfs':
        traverse = nx.bfs_edges
    elif traversal == 'dfs':
        traverse = nx.dfs_edges
    else:
        raise nx.NetworkXError("Please specify one of the strings 'bfs' or"
                               " 'dfs' for connected sequential ordering")
    for component in nx.connected_component_subgraphs(G):
        source = arbitrary_element(component)
        # Yield the source node, then all the nodes in the specified
        # traversal order.
        yield source
        for (_, end) in traverse(component, source):
            yield end 
Example #11
Source File: test_dfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dls_edges(self):
        edges = nx.dfs_edges(self.G, source=9, depth_limit=4)
        assert_equal(list(edges), [(9, 8), (8, 7),
                                   (7, 2), (2, 1), (2, 3), (9, 10)]) 
Example #12
Source File: test_dfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dfs_edges(self):
        edges = nx.dfs_edges(self.G, source=0)
        assert_equal(list(edges), [(0, 1), (1, 2), (2, 4), (4, 3)])
        edges = nx.dfs_edges(self.D)
        assert_equal(list(edges), [(0, 1), (2, 3)]) 
Example #13
Source File: depth_first_search.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dfs_predecessors(G, source=None, depth_limit=None):
    """Returns dictionary of predecessors in depth-first-search 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.

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

    Returns
    -------
    pred: dict
       A dictionary with nodes as keys and predecessor nodes as values.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.dfs_predecessors(G, source=0)
    {1: 0, 2: 1, 3: 2}
    >>> nx.dfs_predecessors(G, source=0, depth_limit=2)
    {1: 0, 2: 1}

    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
    """
    return {t: s for s, t in dfs_edges(G, source, depth_limit)} 
Example #14
Source File: depth_first_search.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dfs_tree(G, source=None, depth_limit=None):
    """Returns oriented tree constructed from a depth-first-search from source.

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

    source : node, optional
       Specify starting node for depth-first search.

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

    Returns
    -------
    T : NetworkX DiGraph
       An oriented tree

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

    """
    T = nx.DiGraph()
    if source is None:
        T.add_nodes_from(G)
    else:
        T.add_node(source)
    T.add_edges_from(dfs_edges(G, source, depth_limit))
    return T 
Example #15
Source File: greedy_coloring.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def strategy_connected_sequential(G, colors, traversal='bfs'):
    """Returns an iterable over nodes in ``G`` in the order given by a
    breadth-first or depth-first traversal.

    ``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
    representing depth-first traversal or breadth-first traversal,
    respectively.

    The generated sequence has the property that for each node except
    the first, at least one neighbor appeared earlier in the sequence.

    ``G`` is a NetworkX graph. ``colors`` is ignored.

    """
    if traversal == 'bfs':
        traverse = nx.bfs_edges
    elif traversal == 'dfs':
        traverse = nx.dfs_edges
    else:
        raise nx.NetworkXError("Please specify one of the strings 'bfs' or"
                               " 'dfs' for connected sequential ordering")
    for component in nx.connected_component_subgraphs(G):
        source = arbitrary_element(component)
        # Yield the source node, then all the nodes in the specified
        # traversal order.
        yield source
        for (_, end) in traverse(component, source):
            yield end 
Example #16
Source File: depth_first_search.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def dfs_successors(G, source=None):
    """Return dictionary of successors in depth-first-search 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
    -------
    succ: dict
       A dictionary with nodes as keys and list of successor nodes as values.

    Examples
    --------
    >>> G = nx.Graph()
    >>> G.add_path([0,1,2])
    >>> print(nx.dfs_successors(G,0))
    {0: [1], 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.
    """
    d = defaultdict(list)
    for s,t in dfs_edges(G,source=source):
        d[s].append(t)
    return dict(d) 
Example #17
Source File: depth_first_search.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def dfs_predecessors(G, source=None):
    """Return dictionary of predecessors in depth-first-search 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
    -------
    pred: dict
       A dictionary with nodes as keys and predecessor nodes as values.

    Examples
    --------
    >>> G = nx.Graph()
    >>> G.add_path([0,1,2])
    >>> print(nx.dfs_predecessors(G,0))
    {1: 0, 2: 1}

    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.
    """
    return dict((t,s) for s,t in dfs_edges(G,source=source)) 
Example #18
Source File: depth_first_search.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def dfs_tree(G, source):
    """Return oriented tree constructed from a depth-first-search from source.

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

    source : node, optional
       Specify starting node for depth-first search.

    Returns
    -------
    T : NetworkX DiGraph
       An oriented tree

    Examples
    --------
    >>> G = nx.Graph()
    >>> G.add_path([0,1,2])
    >>> T = nx.dfs_tree(G,0)
    >>> print(T.edges())
    [(0, 1), (1, 2)]
    """
    T = nx.DiGraph()
    if source is None:
        T.add_nodes_from(G)
    else:
        T.add_node(source)
    T.add_edges_from(dfs_edges(G,source))
    return T 
Example #19
Source File: graph.py    From cppdep with GNU General Public License v3.0 5 votes vote down vote up
def __transitive_reduction(self):
        """Transitive reduction for acyclic graphs."""
        assert nx.is_directed_acyclic_graph(self.digraph)
        for u in self.digraph:
            transitive_vertex = []
            for v in self.digraph[u]:
                transitive_vertex.extend(
                    x for _, x in nx.dfs_edges(self.digraph, v))
            self.digraph.remove_edges_from((u, x) for x in transitive_vertex) 
Example #20
Source File: depth_first_search.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def dfs_successors(G, source=None, depth_limit=None):
    """Returns dictionary of successors in depth-first-search 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.

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

    Returns
    -------
    succ: dict
       A dictionary with nodes as keys and list of successor nodes as values.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> nx.dfs_successors(G, source=0)
    {0: [1], 1: [2], 2: [3], 3: [4]}
    >>> nx.dfs_successors(G, source=0, depth_limit=2)
    {0: [1], 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
    """
    d = defaultdict(list)
    for s, t in dfs_edges(G, source=source, depth_limit=depth_limit):
        d[s].append(t)
    return dict(d) 
Example #21
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 #22
Source File: dag.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def transitive_reduction(G):
    """ Returns transitive reduction of a directed graph

    The transitive reduction 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 (v,w) is
    in E and there is no path from v to w in G with length greater than 1.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)

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

    Raises
    ------
    NetworkXError
        If `G` is not a directed acyclic graph (DAG) transitive reduction is
        not uniquely defined and a :exc:`NetworkXError` exception is raised.

    References
    ----------
    https://en.wikipedia.org/wiki/Transitive_reduction

    """
    if not is_directed_acyclic_graph(G):
        msg = "Directed Acyclic Graph required for transitive_reduction"
        raise nx.NetworkXError(msg)
    TR = nx.DiGraph()
    TR.add_nodes_from(G.nodes())
    descendants = {}
    # count before removing set stored in descendants
    check_count = dict(G.in_degree)
    for u in G:
        u_nbrs = set(G[u])
        for v in G[u]:
            if v in u_nbrs:
                if v not in descendants:
                    descendants[v] = {y for x, y in nx.dfs_edges(G, v)}
                u_nbrs -= descendants[v]
            check_count[v] -= 1
            if check_count[v] == 0:
                del descendants[v]
        TR.add_edges_from((u, v) for v in u_nbrs)
    return TR 
Example #23
Source File: depth_first_search.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def dfs_successors(G, source=None, depth_limit=None):
    """Return dictionary of successors in depth-first-search 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.

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

    Returns
    -------
    succ: dict
       A dictionary with nodes as keys and list of successor nodes as values.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> nx.dfs_successors(G, source=0)
    {0: [1], 1: [2], 2: [3], 3: [4]}
    >>> nx.dfs_successors(G, source=0, depth_limit=2)
    {0: [1], 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
    """
    d = defaultdict(list)
    for s, t in dfs_edges(G, source=source, depth_limit=depth_limit):
        d[s].append(t)
    return dict(d) 
Example #24
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 #25
Source File: depth_first_search.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def dfs_edges(G, source=None):
    """Produce edges in a depth-first-search (DFS).

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

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

    Returns
    -------
    edges: generator
       A generator of edges in the depth-first-search.

    Examples
    --------
    >>> G = nx.Graph()
    >>> G.add_path([0,1,2])
    >>> print(list(nx.dfs_edges(G,0)))
    [(0, 1), (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.
    """
    if source is None:
        # produce edges for all components
        nodes = G
    else:
        # produce edges for components with source
        nodes = [source]
    visited=set()
    for start in nodes:
        if start in visited:
            continue
        visited.add(start)
        stack = [(start,iter(G[start]))]
        while stack:
            parent,children = stack[-1]
            try:
                child = next(children)
                if child not in visited:
                    yield parent,child
                    visited.add(child)
                    stack.append((child,iter(G[child])))
            except StopIteration:
                stack.pop() 
Example #26
Source File: OrientedNormalEstimation.py    From pcloudpy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def update(self):

        array_with_color  = numpy_from_polydata(self.input_)
        normals = np.empty_like(array_with_color[:,0:3])
        coord = array_with_color[:,0:3]

        neigh = NearestNeighbors(self.number_neighbors)
        neigh.fit(coord)

        for i in xrange(0,len(coord)):
            #Determine the neighbours of point
            d = neigh.kneighbors(coord[i])
            #Add coordinates of neighbours , dont include center point to array. Determine coordinate by the index of the neighbours.
            y = np.zeros((self.number_neighbors-1,3))
            y = coord[d[1][0][1:self.number_neighbors],0:3]
            #Get information content
            #Assign information content to each point i.e xyzb
            normals[i,0:3] = self.get_normals(y)

        #Get the point with highest z value , this will be used as the starting point for my depth search
        z_max_point = np.where(coord[:,2]== np.max(coord[:,2]))
        z_max_point = int(z_max_point[0])

        if normals[z_max_point,2] < 0 : #ie normal doesnt point out
            normals[z_max_point,:]=-normals[z_max_point,:]

        #Create a graph
        G = nx.Graph()

        #Add all points and there neighbours to graph, make the weight equal to the distance between points
        for i in xrange(0,len(coord)):

            d = neigh.kneighbors(coord[i,:3])
            for c in range(1,self.number_neighbors):
                p1 = d[1][0][0]
                p2 = d[1][0][c]
                n1 = normals[d[1][0][0],:]
                n2 = normals[d[1][0][c],:]
                dot = np.dot(n1,n2)
                G.add_edge(p1,p2,weight =1-np.abs(dot))


        T = nx.minimum_spanning_tree(G)

        x=[]
        for i in nx.dfs_edges(T,z_max_point):
            x+=i


        inds = np.where(np.diff(x))[0]
        out = np.split(x,inds[np.diff(inds)==1][1::2]+1)

        for j in range(0,len(out)):
            for i in range(0,len(out[j])-1):
                n1 = normals[out[j][i],:]
                n2 = normals[out[j][i+1],:]
                if np.dot(n2,n1)<0:
                    normals[out[j][i+1],:]=-normals[out[j][i+1],:]


        self.output_ = copy_polydata_add_normals(self.input_, normals)