Python networkx.dfs_successors() Examples
The following are 17
code examples of networkx.dfs_successors().
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: cfg_model.py From angr with BSD 2-Clause "Simplified" License | 6 votes |
def get_all_predecessors(self, cfgnode, depth_limit=None): """ Get all predecessors of a specific node on the control flow graph. :param CFGNode cfgnode: The CFGNode object :param int depth_limit: Optional depth limit for the depth-first search :return: A list of predecessors in the CFG :rtype: list """ # use the reverse graph and query for successors (networkx.dfs_predecessors is misleading) # dfs_successors returns a dict of (node, [predecessors]). We ignore the keyset and use the values predecessors = set().union(*networkx.dfs_successors(self.graph.reverse(), cfgnode, depth_limit).values()) return list(predecessors)
Example #2
Source File: bioconductor_skeleton.py From bioconda-utils with MIT License | 6 votes |
def packagesNeedingX(packages): """ Return a set of all packages needing X. Packages needing X are defines as those that directly or indirectly require rgl. """ depTree = nx.DiGraph() for p, meta in packages.items(): p = p.lower() if p not in depTree: depTree.add_node(p) for field in ["Imports", "Depends", "LinkingTo"]: if field in meta: for dep in meta[field].split(","): # This is a simplified form for BioCProjectPage._parse_dependencies dep = dep.strip().split("(")[0].strip().lower() if dep not in depTree: depTree.add_node(dep) depTree.add_edge(dep, p) Xset = set() for cxp in CRAN_X_PACKAGES: if cxp in depTree: for xp in itertools.chain(*nx.dfs_successors(depTree, cxp).values()): Xset.add(xp) return Xset
Example #3
Source File: cfg.py From polyfile with Apache License 2.0 | 5 votes |
def descendants(self, node) -> frozenset: return frozenset(nx.dfs_successors(self, node).keys())
Example #4
Source File: test_dfs.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def dls_test_successor(self): result = nx.dfs_successors(self.G, source=4, depth_limit=3) assert_equal({n: set(v) for n, v in result.items()}, {2: {1, 7}, 3: {2}, 4: {3, 5}, 5: {6}}) result = nx.dfs_successors(self.D, source=7, depth_limit=2) assert_equal({n: set(v) for n, v in result.items()}, {8: {9}, 2: {3}, 7: {8, 2}})
Example #5
Source File: test_dfs.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_successor(self): assert_equal(nx.dfs_successors(self.G,source=0), {0: [1], 1: [2], 2: [4], 4: [3]}) assert_equal(nx.dfs_successors(self.D), {0: [1], 2: [3]})
Example #6
Source File: test_dfs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def dls_test_successor(self): result = nx.dfs_successors(self.G, source=4, depth_limit=3) assert_equal({n: set(v) for n, v in result.items()}, {2: {1, 7}, 3: {2}, 4: {3, 5}, 5: {6}}) result = nx.dfs_successors(self.D, source=7, depth_limit=2) assert_equal({n: set(v) for n, v in result.items()}, {8: {9}, 2: {3}, 7: {8, 2}})
Example #7
Source File: test_dfs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_successor(self): assert_equal(nx.dfs_successors(self.G, source=0), {0: [1], 1: [2], 2: [4], 4: [3]}) assert_equal(nx.dfs_successors(self.D), {0: [1], 2: [3]})
Example #8
Source File: test_dfs.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_successor(self): assert_equal(nx.dfs_successors(self.G,source=0), {0: [1], 1: [2], 2: [4], 4: [3]}) assert_equal(nx.dfs_successors(self.D), {0: [1], 2: [3]})
Example #9
Source File: depth_first_search.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
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 #10
Source File: dataset.py From floweaver with MIT License | 5 votes |
def leaves_below(tree, node): return set(sum(([vv for vv in v if tree.out_degree(vv) == 0] for k, v in nx.dfs_successors(tree, node).items()), []))
Example #11
Source File: hierarchy.py From floweaver with MIT License | 5 votes |
def _leaves_below(self, node): leaves = sum(([vv for vv in v if self.tree.out_degree(vv) == 0] for k, v in nx.dfs_successors(self.tree, node).items()), []) return sorted(leaves) or [node]
Example #12
Source File: cfg_model.py From angr with BSD 2-Clause "Simplified" License | 5 votes |
def get_all_successors(self, cfgnode, depth_limit=None): """ Get all successors of a specific node on the control flow graph. :param CFGNode cfgnode: The CFGNode object :param int depth_limit: Optional depth limit for the depth-first search :return: A list of successors in the CFG :rtype: list """ # dfs_successors returns a dict of (node, [predecessors]). We ignore the keyset and use the values successors = set().union(*networkx.dfs_successors(self.graph, cfgnode, depth_limit).values()) return list(successors)
Example #13
Source File: build.py From bioconda-utils with MIT License | 5 votes |
def get_subdags(dag, n_workers, worker_offset): if n_workers > 1 and worker_offset >= n_workers: raise ValueError( "n-workers is less than the worker-offset given! " "Either decrease --n-workers or decrease --worker-offset!") # Get connected subdags and sort by nodes if n_workers > 1: root_nodes = sorted([k for k, v in dag.in_degree().items() if v == 0]) nodes = set() found = set() for idx, root_node in enumerate(root_nodes): # Flatten the nested list children = itertools.chain(*nx.dfs_successors(dag, root_node).values()) # This is the only obvious way of ensuring that all nodes are included # in exactly 1 subgraph found.add(root_node) if idx % n_workers == worker_offset: nodes.add(root_node) for child in children: if child not in found: nodes.add(child) found.add(child) else: for child in children: found.add(child) subdags = dag.subgraph(list(nodes)) logger.info("Building and testing sub-DAGs %i in each group of %i, which is %i packages", worker_offset, n_workers, len(subdags.nodes())) else: subdags = dag return subdags
Example #14
Source File: depth_first_search.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
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 #15
Source File: network.py From ditto with BSD 3-Clause "New" or "Revised" License | 4 votes |
def get_all_elements_downstream(self, model, source): """Returns all the DiTTo objects which location is downstream of a given node. This might be handy when trying to find all the objects below a substation such that the network can be properly seperated in different feeders for analysis. """ _elts = set() model.set_names() # Checking that the network is already built # TODO: Log instead of printing... if not self.is_built: logger.debug( "Warning. Trying to use Network model without building the network." ) logger.debug("Calling build() with source={}".format(source)) self.build(model, source=source) # Checking that the attributes have been set # TODO: Log instead of printing... if not self.attributes_set: logger.debug( "Warning. Trying to use Network model without setting the attributes first." ) logger.debug("Setting the attributes...") self.set_attributes(model) # Run the dfs or die trying... try: childrens = nx.dfs_successors(self.digraph, source) except: traceback.print_exc() raise ValueError("dfs failed with source={}".format(source)) # Following two lines extract the data stored in the edges # More precisely, the type of equipment and the name of the equipment # that makes the connection (usually a line or a transformer) # edge_equipment = nx.get_edge_attributes(self.graph, "equipment") edge_equipment_name = nx.get_edge_attributes(self.graph, "equipment_name") # Build the list of equipment names downstream for source, destinations in childrens.items(): _elts.add(source) for destination in destinations: _elts.add(destination) if (source, destination) in edge_equipment_name: _elts.add(edge_equipment_name[(source, destination)]) elif (destination, source) in edge_equipment_name: _elts.add(edge_equipment_name[(destination, source)]) # Get the corresponding DiTTo objects # Warning: This will fail if set_names() has not been called before. _obj = [] for x in _elts: try: _obj.append(model[x]) except: raise ValueError("Unable to get DiTTo object with name {}".format(x)) return _obj
Example #16
Source File: molecules.py From CatKit with GNU General Public License v3.0 | 4 votes |
def get_3D_positions(atoms, bond_index=None): """Return an estimation of the 3D structure of a Gratoms object based on its graph. WARNING: This function operates on the atoms object in-place. Parameters ---------- atoms : Gratoms object Structure with connectivity matrix to provide a 3D structure. bond_index : int Index of the atoms to consider as the origin of a surface bonding site. Returns ------- atoms : Gratoms object Structure with updated 3D positions. """ branches = nx.dfs_successors(atoms.graph, bond_index) complete = [] for i, branch in enumerate(branches.items()): root, nodes = branch if len(nodes) == 0: continue c0 = atoms[root].position if i == 0: basis = catkit.gen.utils.get_basis_vectors([c0, [0, 0, -1]]) else: bond_index = None for j, base_root in enumerate(complete): if root in branches[base_root]: c1 = atoms[base_root].position # Flip the basis for every alternate step down the chain. basis = catkit.gen.utils.get_basis_vectors([c0, c1]) if (i - j) % 2 != 0: basis[2] *= -1 break complete.insert(0, root) positions = _branch_molecule(atoms, branch, basis, bond_index) atoms.positions[nodes] = positions return atoms
Example #17
Source File: depth_first_search.py From aws-kube-codesuite with Apache License 2.0 | 4 votes |
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)