Python networkx.bfs_tree() Examples

The following are 20 code examples of networkx.bfs_tree(). 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: graph.py    From ScaffoldGraph with MIT License 6 votes vote down vote up
def get_scaffolds_for_molecule(self, molecule_id, data=False, default=None):
        """Return a list of scaffold SMILES connected to a query molecule ID.

        Parameters
        ----------
        molecule_id: (string) ID of query molecule.
        data : (string or bool, optional (default=False)) The scaffold node attribute returned in 2-tuple
            (n, dict[data]). If True, return entire scaffold node attribute dict as (n, dict).
            If False, return just the scaffold nodes n.
        default : (value, optional (default=None)) Value used for scaffold nodes that don’t have the
            requested attribute. Only relevant if data is not True or False.
        """
        scaffolds = []
        if molecule_id not in self:
            return scaffolds
        for succ in nx.bfs_tree(self, molecule_id, reverse=True):
            if self.nodes[succ].get('type') == 'scaffold':
                if data is False:
                    scaffolds.append(succ)
                elif data is True:
                    scaffolds.append((succ, self.nodes[succ]))
                else:
                    scaffolds.append((succ, self.nodes[succ].get(data, default)))
        return scaffolds 
Example #2
Source File: test_bfs.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_bfs_tree(self):
        T = nx.bfs_tree(self.G, source=0)
        assert_equal(sorted(T.nodes()), sorted(self.G.nodes()))
        assert_equal(sorted(T.edges()), [(0, 1), (1, 2), (1, 3), (2, 4)]) 
Example #3
Source File: abstract_trainer.py    From autogluon with Apache License 2.0 5 votes vote down vote up
def get_minimum_model_set(self, model):
        if not isinstance(model, str):
            model = model.name
        return list(nx.bfs_tree(self.model_graph, model, reverse=True)) 
Example #4
Source File: test_bfs.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_bfs_tree_isolates(self):
        G = nx.Graph()
        G.add_node(1)
        G.add_node(2)
        T = nx.bfs_tree(G, source=1)
        assert_equal(sorted(T.nodes()), [1])
        assert_equal(sorted(T.edges()), []) 
Example #5
Source File: test_bfs.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_bfs_tree(self):
        T = nx.bfs_tree(self.G, source=0)
        assert_equal(sorted(T.nodes()), sorted(self.G.nodes()))
        assert_equal(sorted(T.edges()), [(0, 1), (1, 2), (1, 3), (2, 4)]) 
Example #6
Source File: breadth_first_search.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def bfs_tree(G, source, reverse=False):
    """Return an oriented tree constructed from of a breadth-first-search
    starting at source.

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

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

    reverse : bool, optional
       If True traverse a directed graph in the reverse direction

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

    Examples
    --------
    >>> G = nx.path_graph(3)
    >>> print(list(nx.bfs_tree(G,1).edges()))
    [(1, 0), (1, 2)]

    Notes
    -----
    Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
    by D. Eppstein, July 2004.
    """
    T = nx.DiGraph()
    T.add_node(source)
    T.add_edges_from(bfs_edges(G, source, reverse=reverse))
    return T 
Example #7
Source File: test_bfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bfs_test_tree(self):
        T = nx.bfs_tree(self.G, source=3, depth_limit=1)
        assert_equal(sorted(T.edges()), [(3, 2), (3, 4)]) 
Example #8
Source File: test_bfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bfs_tree_isolates(self):
        G = nx.Graph()
        G.add_node(1)
        G.add_node(2)
        T = nx.bfs_tree(G, source=1)
        assert_equal(sorted(T.nodes()), [1])
        assert_equal(sorted(T.edges()), []) 
Example #9
Source File: test_bfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bfs_tree(self):
        T = nx.bfs_tree(self.G, source=0)
        assert_equal(sorted(T.nodes()), sorted(self.G.nodes()))
        assert_equal(sorted(T.edges()), [(0, 1), (1, 2), (1, 3), (2, 4)]) 
Example #10
Source File: test_bfs.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_bfs_tree_isolates(self):
        G = nx.Graph()
        G.add_node(1)
        G.add_node(2)
        T = nx.bfs_tree(G, source=1)
        assert_equal(sorted(T.nodes()), [1])
        assert_equal(sorted(T.edges()), []) 
Example #11
Source File: postprocessing.py    From diluvian with MIT License 5 votes vote down vote up
def skeleton_to_swc(skeleton, offset, resolution):
    import networkx as nx

    g = nx.Graph()
    g.add_nodes_from(skeleton.nodes())
    g.add_edges_from((e.u, e.v) for e in skeleton.edges())

    # Find a directed tree for mapping to a skeleton.
    if nx.number_of_nodes(g) > 1:
        # This discards cyclic edges in the graph.
        t = nx.bfs_tree(nx.minimum_spanning_tree(g), g.nodes()[0])
    else:
        t = nx.DiGraph()
        t.add_nodes_from(g)
    # Copy node attributes
    for n in t.nodes_iter():
        loc = skeleton.locations(n)
        # skeletopyze is z, y, x (as it should be).
        loc = np.array(loc)
        loc = np.multiply(loc + offset, resolution)
        t.node[n].update({'x': loc[0],
                          'y': loc[1],
                          'z': loc[2],
                          'radius': skeleton.diameters(n) / 2.0})

    # Set parent node ID
    for n, nbrs in t.adjacency_iter():
        for nbr in nbrs:
            t.node[nbr]['parent_id'] = n
            if 'radius' not in t.node[nbr]:
                t.node[nbr]['radius'] = -1

    return [[
        node_id,
        0,
        n['x'], n['y'], n['z'],
        n['radius'],
        n.get('parent_id', -1)] for node_id, n in t.nodes(data=True)] 
Example #12
Source File: SpreadingActivation.py    From Quadflor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fit(self, X, y=None):
        if self.assert_tree:
                assert self.root is not None
                self.hierarchy = nx.bfs_tree(self.hierarchy, self.root)
        return self 
Example #13
Source File: graph.py    From ScaffoldGraph with MIT License 5 votes vote down vote up
def get_child_scaffolds(self, scaffold_smiles, data=False, default=None, max_levels=-1):
        """Return a list of child scaffolds for a query scaffold.

        Parameters
        ----------
        scaffold_smiles : (string)  SMILES of query scaffold.
        data : (string or bool, optional (default=False)) The scaffold node attribute returned in 2-tuple
            (n, dict[data]). If True, return entire scaffold node attribute dict as (n, dict).
            If False, return just the scaffold nodes n.
        default : (value, optional (default=None)) Value used for scaffold nodes that don’t have the
            requested attribute. Only relevant if data is not True or False.
        max_levels : (integer, optional (default=-1)) If > 0 only return scaffolds with a hierarchy
            difference to the query scaffold of max_levels.
        """
        children = []
        if scaffold_smiles not in self:
            scaffold_smiles = canonize_smiles(scaffold_smiles, failsafe=True)
            if scaffold_smiles not in self:
                return children
        level = self.nodes[scaffold_smiles].get('hierarchy', float('inf'))
        bfs = iter(nx.bfs_tree(self, scaffold_smiles, reverse=False).nodes)
        next(bfs)  # first entry is the query node
        for succ in bfs:
            d = self.nodes[succ]
            if d.get('type') == 'scaffold' and (max_levels < 0 or d.get('hierarchy', 0) - level <= max_levels):
                if data is False:
                    children.append(succ)
                elif data is True:
                    children.append((succ, self.nodes[succ]))
                else:
                    children.append((succ, self.nodes[succ].get(data, default)))
        return children 
Example #14
Source File: graph.py    From ScaffoldGraph with MIT License 5 votes vote down vote up
def get_parent_scaffolds(self, scaffold_smiles, data=False, default=None, max_levels=-1):
        """Return a list of parent scaffolds for a query scaffold.

        Parameters
        ----------
        scaffold_smiles : (string)  SMILES of query scaffold.
        data : (string or bool, optional (default=False)) The scaffold node attribute returned in 2-tuple
            (n, dict[data]). If True, return entire scaffold node attribute dict as (n, dict).
            If False, return just the scaffold nodes n.
        default : (value, optional (default=None)) Value used for scaffold nodes that don’t have the
            requested attribute. Only relevant if data is not True or False.
        max_levels : (integer, optional (default=-1)) If > 0 only return scaffolds with a hierarchy
            difference to the query scaffold of max_levels.
        """
        parents = []
        if scaffold_smiles not in self:
            scaffold_smiles = canonize_smiles(scaffold_smiles, failsafe=True)
            if scaffold_smiles not in self:
                return parents
        level = self.nodes[scaffold_smiles].get('hierarchy', float('inf'))
        bfs = iter(nx.bfs_tree(self, scaffold_smiles, reverse=True).nodes)
        next(bfs)  # first entry is the query node
        for succ in bfs:
            d = self.nodes[succ]
            if d.get('type') == 'scaffold' and (max_levels < 0 or level - d.get('hierarchy', 0) <= max_levels):
                if data is False:
                    parents.append(succ)
                elif data is True:
                    parents.append((succ, self.nodes[succ]))
                else:
                    parents.append((succ, self.nodes[succ].get(data, default)))
        return parents 
Example #15
Source File: graph.py    From ScaffoldGraph with MIT License 5 votes vote down vote up
def get_molecules_for_scaffold(self, scaffold_smiles, data=False, default=None):
        """Return a list of molecule IDs which are represented by a scaffold in the graph.

        Note: This is determined by traversing the graph. In the case of a scaffold tree
        the results represent the rules used to prioritize the scaffolds.

        Parameters
        ----------
        scaffold_smiles : (string) SMILES of query scaffold.
        data : (string or bool, optional (default=False)) The molecule node attribute returned in 2-tuple
            (n, dict[data]). If True, return entire molecule node attribute dict as (n, dict).
            If False, return just the molecule nodes n.
        default : (value, optional (default=None)) Value used for molecule nodes that don’t have the
            requested attribute. Only relevant if data is not True or False.
        """
        molecules = []
        if scaffold_smiles not in self:
            scaffold_smiles = canonize_smiles(scaffold_smiles, failsafe=True)
            if scaffold_smiles not in self:
                return molecules
        for succ in nx.bfs_tree(self, scaffold_smiles, reverse=False):
            if self.nodes[succ].get('type') == 'molecule':
                if data is False:
                    molecules.append(succ)
                elif data is True:
                    molecules.append((succ, self.nodes[succ]))
                else:
                    molecules.append((succ, self.nodes[succ].get(data, default)))
        return molecules 
Example #16
Source File: hierarchies.py    From ReGraph with MIT License 5 votes vote down vote up
def bfs_tree(self, graph, reverse=False):
        """BFS tree from the graph to all other reachable graphs."""
        return list(nx.bfs_tree(self._graph, graph, reverse=reverse))[1:] 
Example #17
Source File: backward_slice.py    From angr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def is_taint_related_to_ip(self, simrun_addr, stmt_idx, taint_type, simrun_whitelist=None):
        """
        Query in taint graph to check if a specific taint will taint the IP in the future or not.
        The taint is specified with the tuple (simrun_addr, stmt_idx, taint_type).

        :param simrun_addr:         Address of the SimRun.
        :param stmt_idx:            Statement ID.
        :param taint_type:          Type of the taint, might be one of the following: 'reg', 'tmp', 'mem'.
        :param simrun_whitelist:    A list of SimRun addresses that are whitelisted, i.e. the tainted exit will be
                                    ignored if it is in those SimRuns.
        :returns:                   True/False
        """

        if simrun_whitelist is None:
            simrun_whitelist = set()
        if type(simrun_whitelist) is not set:
            simrun_whitelist = set(simrun_whitelist)

        # Find the specific taint in our graph
        taint = None
        for n in self.taint_graph.nodes():
            if n.type == taint_type and n.addr == simrun_addr and n.stmt_id == stmt_idx:
                taint = n
                break

        if taint is None:
            raise AngrBackwardSlicingError('The specific taint is not found')

        bfs_tree = networkx.bfs_tree(self.taint_graph, taint)

        # A node is tainting the IP if one of the following criteria holds:
        # - a descendant tmp variable is used as a default exit or a conditional exit of its corresponding SimRun
        # - a descendant register is the IP itself

        for descendant in bfs_tree.nodes():
            if descendant.type == 'exit':
                if descendant.addr not in simrun_whitelist:
                    return True
            elif descendant.type == 'reg' and descendant.reg == self.project.arch.ip_offset:
                return True

        return False 
Example #18
Source File: breadth_first_search.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def bfs_tree(G, source, reverse=False, depth_limit=None):
    """Returns an oriented tree constructed from of a breadth-first-search
    starting at source.

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

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

    reverse : bool, optional
       If True traverse a directed graph in the reverse direction

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

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

    Examples
    --------
    >>> G = nx.path_graph(3)
    >>> print(list(nx.bfs_tree(G,1).edges()))
    [(1, 0), (1, 2)]
    >>> H = nx.Graph()
    >>> nx.add_path(H, [0, 1, 2, 3, 4, 5, 6])
    >>> nx.add_path(H, [2, 7, 8, 9, 10])
    >>> print(sorted(list(nx.bfs_tree(H, source=3, depth_limit=3).edges())))
    [(1, 0), (2, 1), (2, 7), (3, 2), (3, 4), (4, 5), (5, 6), (7, 8)]


    Notes
    -----
    Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
    by D. Eppstein, July 2004. The modifications
    to allow depth limits based on the Wikipedia article
    "`Depth-limited-search`_".

    .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search
    """
    T = nx.DiGraph()
    T.add_node(source)
    edges_gen = bfs_edges(G, source, reverse=reverse, depth_limit=depth_limit)
    T.add_edges_from(edges_gen)
    return T 
Example #19
Source File: cse.py    From ScaffoldGraph with MIT License 4 votes vote down vote up
def fit(self, graph, bioactivity_map, progress=True):
        """Fit CSE to a scaffold graph.

        Parameters
        ----------
        graph : (sg.ScaffoldGraph)
            constructed scaffold graph
        bioactivity_map : (dict {str: float})
            dictionary containing a mapping of molecule IDs to
            a bio-activity value i.e. {MOLID: bioactivity}
        progress : (bool)
            if True show a progress bar to monitor progress
        """

        if not issubclass(type(graph), ScaffoldGraph):
            raise ValueError('Input graph must be a subclass of ScaffoldGraph')

        mapping = {k: d for k, d in bioactivity_map.items() if k in graph.nodes}

        def get_activity(scaffold):
            distribution = []
            succ = nx.bfs_tree(graph, scaffold)
            for node in succ.nodes:
                if graph.nodes[node]['type'] == 'molecule':
                    try:
                        distribution.append(mapping[node])
                    except KeyError:
                        continue
            return scaffold, distribution

        activity = (get_activity(x) for x in graph.get_scaffold_nodes())

        if self._hyp_str == 'ks':
            self._fit_ks(list(mapping.values()), activity, progress)
        elif self._hyp_str == 'binom':
            self._fit_binom(activity, progress)

        if self._bonferroni:
            hier = graph.get_hierarchy_sizes()
            for x in hier:
                hier[x] = self._crit / hier[x]
            for x in self._X.keys():
                h = graph.nodes[x]['hierarchy']
                self._X[x]['CRIT'] = hier[h]
        else:
            for x in self._X.keys():
                self._X[x]['CRIT'] = self._crit

        self.is_fit = True 
Example #20
Source File: backward_slice.py    From angr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def is_taint_impacting_stack_pointers(self, simrun_addr, stmt_idx, taint_type, simrun_whitelist=None):
        """
        Query in taint graph to check if a specific taint will taint the stack pointer in the future or not.
        The taint is specified with the tuple (simrun_addr, stmt_idx, taint_type).

        :param simrun_addr:         Address of the SimRun.
        :param stmt_idx:            Statement ID.
        :param taint_type:          Type of the taint, might be one of the following: 'reg', 'tmp', 'mem'.
        :param simrun_whitelist:    A list of SimRun addresses that are whitelisted.
        :returns:                   True/False.
        """

        if simrun_whitelist is None:
            simrun_whitelist = set()
        if type(simrun_whitelist) is not set:
            simrun_whitelist = set(simrun_whitelist)

        # Find the specific taint in our graph
        taint = None
        for n in self.taint_graph.nodes():
            if n.type == taint_type and n.addr == simrun_addr and n.stmt_id == stmt_idx:
                taint = n
                break

        if taint is None:
            raise AngrBackwardSlicingError('The specific taint is not found')

        bfs_tree = networkx.bfs_tree(self.taint_graph, taint)

        # A node is tainting the stack pointer if one of the following criteria holds:
        # - a descendant register is the sp/bp itself

        for descendant in bfs_tree.nodes():
            if descendant.type == 'reg' and (
                        descendant.reg in (self.project.arch.sp_offset, self.project.arch.bp_offset)
            ):
                return True

        return False

    #
    # Private methods
    #