【问题标题】:Extracting different trees with in a graph or forest在图形或森林中提取不同的树
【发布时间】:2019-10-31 20:20:30
【问题描述】:

我在图中有多个独立的树。我想分别提取它们。我正在使用 pydot 来绘制图表。 我分别想要父 1 图表和父 2 图表。在我的用例中,树会随机生长(不是一棵一棵)。

graph = pydot.Dot(graph_type="digraph")

parent_node_1 = pydot.Node(name='Parent_1', style='filled', fillcolor='yellow')
parent_node_2 = pydot.Node(name='Parent_2', style='filled', fillcolor='yellow')

child_node_1 = pydot.Node(name='Child 1', style='filled', fillcolor='yellow')
child_node_2 = pydot.Node(name='Child 2', style='filled', fillcolor='yellow')

e1 = pydot.Edge('Parent_1', 'Child 1')
e2 = pydot.Edge('Parent_2', 'Child 2')

graph.add_node(parent_node_1)
graph.add_node(parent_node_2)

graph.add_node(child_node_1)
graph.add_node(child_node_2)

graph.add_edge(e1)
graph.add_edge(e2)

graph.write_png('dummy_graph.png')

Output of program

【问题讨论】:

    标签: python graphviz pydot


    【解决方案1】:

    这在pydot中是个麻烦的问题,因为你需要能够以简单的方式遍历图。这是可能的,但我不会推荐它。在您的测试用例中工作的简单代码在下面的 sn-p 中。我敢打赌它在某个地方有一些错误,所以请谨慎使用。

    def get_out_edges_and_children(g, node):
        out_edges = {e for e in g.get_edges() if e.get_source() == node.get_name()}
        children_names = {e.get_destination() for e in out_edges}
        children = [n for n in graph.get_nodes() if n.get_name() in children_names]
        return out_edges, children
    
    
    all_node_names = {n.get_name() for n in graph.get_nodes()}
    all_children_names = {e.get_destination() for e in graph.get_edges()}
    all_roots = all_node_names - all_children_names #roots are children to noone
    
    trees = []
    for r in all_roots:
        nodes_to_process= graph.get_node(r)
        t = pydot.Dot()
        t.add_node(nodes_to_process[0])
    
        i = 0
        while i < len(nodes_to_process):
            current_node=nodes_to_process[i]
            edges,children = get_out_edges_and_children(graph,current_node)
            for c in children: t.add_node(c)
            for e in edges: t.add_edge(e)
            nodes_to_process += children
            i += 1
    
        trees.append(t)
    
    

    请查看其他图形库以获得更强大的解决方案,例如 networkx。也可以import pydot objects,所以过渡应该很顺利吧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2013-12-31
      • 2020-09-02
      • 2016-07-31
      • 2011-07-26
      • 2012-10-27
      相关资源
      最近更新 更多