本文整理汇总了Python中networkx.topological_sort方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.topological_sort方法的具体用法?Python networkx.topological_sort怎么用?Python networkx.topological_sort使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.topological_sort方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: order_build
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def order_build(graph):
'''
Assumes that packages are in graph.
Builds a temporary graph of relevant nodes and returns it topological sort.
Relevant nodes selected in a breadth first traversal sourced at each pkg
in packages.
'''
reorder_cyclical_test_dependencies(graph)
try:
order = list(nx.topological_sort(graph))
order.reverse()
except nx.exception.NetworkXUnfeasible:
raise ValueError("Cycles detected in graph: %s", nx.find_cycle(graph,
orientation='reverse'))
return order
示例2: topological_sort_of_nucleotides
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def topological_sort_of_nucleotides(graph: nx.DiGraph) -> List[Nucleotide]:
"""
Perform topological order of the graph
Parameters
----------
graph
Returns
-------
sorted_nucleotides
list of nucleotides sorted in topological order
"""
nucleotides_without_inputs = [
each_nucleotide for each_nucleotide in graph
if not list(graph.predecessors(each_nucleotide))]
nucleotides_without_inputs_sorted = sorted(
nucleotides_without_inputs, key=lambda x: x.name)
topological_order = list(nx.topological_sort(graph))
topological_order_only_with_inputs = [
each_nucleotide for each_nucleotide in topological_order
if each_nucleotide not in nucleotides_without_inputs]
topological_order_sorted = (nucleotides_without_inputs_sorted
+ topological_order_only_with_inputs)
return topological_order_sorted
示例3: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def __init__(self, config: Dict, recipe_folder: str,
exclude: List[str] = None, nocatch: bool=False) ->None:
self.config = config
self.recipe_folder = recipe_folder
self.skip = self.load_skips()
self.exclude = exclude or []
self.nocatch = nocatch
self._messages = []
dag = nx.DiGraph()
dag.add_nodes_from(str(check) for check in get_checks())
dag.add_edges_from(
(str(check), str(check_dep))
for check in get_checks()
for check_dep in check.requires
)
self.checks_dag = dag
try:
self.checks_ordered = nx.topological_sort(dag, reverse=True)
except nx.NetworkXUnfeasible:
raise RunTimeError("Cycle in LintCheck requirements!")
self.reload_checks()
示例4: CreateGraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def CreateGraph(model, input_quantizers=None,
default_source_quantizer=cfg.default_source_quantizer,
debug=False):
"""create graph."""
K.set_image_data_format("channels_last")
(graph, source_quantizer_list) = GenerateGraphFromModel(
model, input_quantizers, default_source_quantizer)
GraphAddSingleSourceSingleSink(graph)
GraphRemoveNodeWithNodeType(graph, "Dropout")
GraphRemoveNodeWithNodeType(graph, "InputLayer")
scheduler = list(nx.topological_sort(graph))
if debug:
for vertex in scheduler[1:-1]:
for _, v in graph.edges(vertex):
if v == SINK:
continue
print("... calling", graph.nodes[v][
"layer"][0].name, graph.nodes[v]["type"])
return (graph, source_quantizer_list)
示例5: from_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def from_networkx(cls, graph):
"""Take a networkx MultiDigraph and create a new DAGCircuit.
Args:
graph (networkx.MultiDiGraph): The graph to create a DAGCircuit
object from. The format of this MultiDiGraph format must be
in the same format as returned by to_networkx.
Returns:
DAGCircuit: The dagcircuit object created from the networkx
MultiDiGraph.
"""
dag = DAGCircuit()
for node in nx.topological_sort(graph):
if node.type == 'out':
continue
if node.type == 'in':
dag._add_wire(node.wire)
elif node.type == 'op':
dag.apply_operation_back(node.op.copy(), node.qargs,
node.cargs, node.condition)
return dag
示例6: print_pipeline
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def print_pipeline(self, pipeline_graph):
"""Prints a complete definition of the pipeline with all the tags."""
for block_name in nx.topological_sort(pipeline_graph):
block_data = pipeline_graph.nodes(data=True)[block_name]
print("Block: {}".format(block_name))
print("Previous Blocks:")
if 'previous_blocks' in block_data['tags']:
pprint.pprint(block_data['tags']['previous_blocks'], width=1)
print("Ins")
if 'ins' in block_data:
pprint.pprint(sorted(block_data['ins']), width=1)
print("Outs")
if 'outs' in block_data:
pprint.pprint(sorted(block_data['outs']), width=1)
print()
print("-------------------------------")
print()
示例7: order_build
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def order_build(graph):
'''
Assumes that packages are in graph.
Builds a temporary graph of relevant nodes and returns it topological sort.
Relevant nodes selected in a breadth first traversal sourced at each pkg
in packages.
'''
reorder_cyclical_test_dependencies(graph)
try:
order = list(nx.topological_sort(graph))
order.reverse()
except nx.exception.NetworkXUnfeasible:
raise ValueError("Cycles detected in graph: %s", nx.find_cycle(graph))
return order
示例8: to_dendropy_tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def to_dendropy_tree(self, taxon_namespace=None, weighted=False):
import dendropy
tree = dendropy.Tree(taxon_namespace=taxon_namespace)
seed_node = self.roots()[0]
if weighted:
def edge_length(par, child):
return np.abs(self.linkage_dist[par] -
self.linkage_dist[child])
else:
def edge_length(par, child): return 1.0
tree_dict = {seed_node: tree.seed_node}
for clus in nx.topological_sort(self):
for child in self.successors(clus):
tree_dict[child] = tree_dict[clus].new_child(
edge_length=edge_length(clus, child))
for clus in self.leaves():
tree_dict[clus].taxon = taxon_namespace.get_taxon(str(clus))
return tree
示例9: resolve_hook_order
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def resolve_hook_order(self, hook_tuples: List[HookTuple]) -> List[HookTuple]:
dag = nx.DiGraph()
for hook_tuple in hook_tuples:
dag.add_node(hook_tuple.Hook.name, hook_tuple=hook_tuple)
for dep_name in hook_tuple.Hook.run_after:
dag.add_edge(hook_tuple.Hook.name, dep_name)
for successor_name in hook_tuple.Hook.run_before:
dag.add_edge(successor_name, hook_tuple.Hook.name)
try:
order = reversed(list(nx.topological_sort(dag)))
except nx.NetworkXUnfeasible:
msg = 'Circular dependency detected between hooks'
problem_graph = ', '.join(f'{a} -> {b}'
for a, b in nx.find_cycle(dag))
raise Exception(f'{msg}: {problem_graph}')
rv = []
for hook_name in order:
hook_tuple = dag.nodes[hook_name].get('hook_tuple')
if hook_tuple:
rv.append(hook_tuple)
return rv
示例10: store_queries_in_order
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def store_queries_in_order(dependency_graph: nx.DiGraph) -> Dict[str, "Future"]:
"""
Execute queries in an order that ensures each query store is triggered after its dependencies.
Parameters
----------
dependency_graph : networkx.DiGraph
Dependency graph of query objects to be stored
Returns
-------
dict
Mapping from query nodes to Future objects representing the store tasks
"""
ordered_list_of_queries = list(nx.topological_sort(dependency_graph))[::-1]
logger.debug(f"Storing queries with IDs: {ordered_list_of_queries}")
store_futures = {}
for query in ordered_list_of_queries:
try:
store_futures[query] = dependency_graph.nodes[query]["query_object"].store()
except UnstorableQueryError:
# Some queries cannot be stored
pass
return store_futures
示例11: _resolve_dependencies
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def _resolve_dependencies(G):
'''
Traverse the dependency graph starting from resolved nodes
'''
context = {}
for name in nx.topological_sort(G):
node = G.node[name]
try:
context[name] = _render(node, context)
except Exception as e:
LOG.debug('Failed to render %s: %s', name, e, exc_info=True)
msg = 'Failed to render parameter "%s": %s' % (name, six.text_type(e))
raise ParamException(msg)
return context
示例12: generate
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def generate(self, rescale=True):
"""Generate data from an FCM defined in ``self.init_variables()``.
Args:
rescale (bool): rescale the generated data (recommended)
Returns:
tuple: (pandas.DataFrame, networkx.DiGraph), respectively the
generated data and graph.
"""
if self.cfunctions is None:
self.init_variables()
for i in nx.topological_sort(self.g):
# Root cause
if not sum(self.adjacency_matrix[:, i]):
self.data['V{}'.format(i)] = self.cfunctions[i](self.npoints)
# Generating causes
else:
self.data['V{}'.format(i)] = self.cfunctions[i](self.data.iloc[:, self.adjacency_matrix[:, i].nonzero()[0]].values)
if rescale:
self.data['V{}'.format(i)] = scale(self.data['V{}'.format(i)].values)
return self.data, self.g
示例13: is_directed_acyclic_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def is_directed_acyclic_graph(G):
"""Return True if the graph G is a directed acyclic graph (DAG) or
False if not.
Parameters
----------
G : NetworkX graph
A graph
Returns
-------
is_dag : bool
True if G is a DAG, false otherwise
"""
if not G.is_directed():
return False
try:
topological_sort(G, reverse=True)
return True
except nx.NetworkXUnfeasible:
return False
示例14: test_reverse_topological_sort1
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def test_reverse_topological_sort1(self):
DG = nx.DiGraph()
DG.add_edges_from([(1, 2), (1, 3), (2, 3)])
assert_equal(nx.topological_sort(DG, reverse=True), [3, 2, 1])
assert_equal(
nx.topological_sort_recursive(DG, reverse=True), [3, 2, 1])
DG.add_edge(3, 2)
assert_raises(nx.NetworkXUnfeasible,
nx.topological_sort, DG, reverse=True)
assert_raises(nx.NetworkXUnfeasible,
nx.topological_sort_recursive, DG, reverse=True)
DG.remove_edge(2, 3)
assert_equal(nx.topological_sort(DG, reverse=True), [2, 3, 1])
assert_equal(
nx.topological_sort_recursive(DG, reverse=True), [2, 3, 1])
示例15: test_topological_sort3
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import topological_sort [as 别名]
def test_topological_sort3(self):
DG = nx.DiGraph()
DG.add_edges_from([(1, i) for i in range(2, 5)])
DG.add_edges_from([(2, i) for i in range(5, 9)])
DG.add_edges_from([(6, i) for i in range(9, 12)])
DG.add_edges_from([(4, i) for i in range(12, 15)])
def validate(order):
ok_(isinstance(order, list))
assert_equal(set(order), set(DG))
for u, v in combinations(order, 2):
assert_false(nx.has_path(DG, v, u))
validate(nx.topological_sort_recursive(DG))
validate(nx.topological_sort(DG))
DG.add_edge(14, 1)
assert_raises(nx.NetworkXUnfeasible, nx.topological_sort, DG)
assert_raises(nx.NetworkXUnfeasible, nx.topological_sort_recursive, DG)