[英]How to find all the parent nodes of each node in a directed acyclic graph?
[英]How to find edges hierarchy graph from directed acyclic graph in python
您想构建原始图中节点之间边缘的图形作为节点,原始图形中的节点作为边缘,我理解。 在这种情况下,帖子中的图表不正确。 例如:你有节点be
,这是一个继任者ae
,但在原图这是不正确的, ae
和be
是平行的。 我构造了一个代码来解决这个问题:
import networkx as nx
import random
from itertools import groupby
# Create a random DAG
G = nx.gnp_random_graph(10,0.3,directed=True)
DAG = nx.DiGraph([(u,v) for (u,v) in G.edges() if u<v])
res = nx.DiGraph()
# Create nodes in new DAG as edges in original DAG
res.add_nodes_from(list(DAG.edges()))
sorted_res_nodes = sorted(res.nodes, key=lambda x: x[1])
# Connect all nodes with end of node1 is equal to start of node2
for n1 in sorted_res_nodes:
for n2 in sorted_res_nodes:
if n1[1] == n2[0]:
res.add_edge(n1, n2)
# Draw graphs
nx.draw(
DAG,
with_labels=True,
pos=nx.drawing.nx_agraph.graphviz_layout(
DAG, prog='dot'
)
)
nx.draw(
res,
with_labels=True,
pos=nx.drawing.nx_agraph.graphviz_layout(
res, prog='dot'
)
)
对于此图:
将构建新图:
请注意,原始DAG中根的所有边都转换为新DAG中的根。 另请注意,对于每个边,起始节点的末尾等于结束节点的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.