我试图弄清楚如何ete3.Tree
从有向图构建对象networkx
?我以我认为会产生预期结果的方式添加了每一个child
,但我遇到了麻烦。
edges = [('lvl-1', 'lvl-2.1'), ('lvl-1', 'lvl-2.2'), ('lvl-2.1', 'lvl-3.1'), ('lvl-2.1', 2), ('lvl-2.2', 4), ('lvl-2.2', 6), ('lvl-3.1', 'lvl-4.1'), ('lvl-3.1', 5), ('lvl-4.1', 1), ('lvl-4.1', 3), ('input', 'lvl-1')]
graph = nx.OrderedDiGraph()
graph.add_edges_from(edges)
nx.draw(graph, pos=nx.nx_agraph.graphviz_layout(graph, prog="dot"), with_labels=True, node_size=1000, node_color="lightgray")
tree = ete3.Tree()
for parent, children in itertools.groupby(graph.edges(), lambda edge:edge[0]):
subtree = ete3.Tree(name=parent)
for child in children:
subtree.add_child(name=child[1])
tree.add_child(child=subtree, name=parent)
print(tree)
# /-lvl-2.1
# /-|
# | \-lvl-2.2
# |
# | /-lvl-3.1
# |--|
# | \-2
# |
# | /-4
# |--|
# --| \-6
# |
# | /-lvl-4.1
# |--|
# | \-5
# |
# | /-1
# |--|
# | \-3
# |
# \- /-lvl-1
我也尝试了以下方法,但没有奏效:
tree = ete3.Tree()
for parent, child in graph.edges():
if parent not in tree:
tree.add_child(name=parent)
subtree = tree.search_nodes(name=parent)[0]
subtree.add_child(name=child)
print(tree)
# /-1
# /-|
# /-| \-3
# | |
# /-| \-5
# | |
# /-| \-2
# | |
# | | /-4
# --| \-|
# | \-6
# |
# \- /-lvl-1