本文整理汇总了Python中networkx.dfs_successors方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.dfs_successors方法的具体用法?Python networkx.dfs_successors怎么用?Python networkx.dfs_successors使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.dfs_successors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: packagesNeedingX
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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
示例2: get_subdags
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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
示例3: get_all_predecessors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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)
示例4: get_all_successors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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)
示例5: _leaves_below
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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]
示例6: leaves_below
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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()), []))
示例7: descendants
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
def descendants(self, node) -> frozenset:
return frozenset(nx.dfs_successors(self, node).keys())
示例8: dfs_successors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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)
示例9: test_successor
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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]})
示例10: test_successor
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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]})
示例11: dls_test_successor
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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}})
示例12: get_3D_positions
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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
示例13: get_all_elements_downstream
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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
示例14: dfs_successors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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)
示例15: dfs_successors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import dfs_successors [as 别名]
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)