pygraphviz 或 networkx:获取给定节点的所有子图的名称

pygraphviz or networkx: getting the name of all subgraphs given node

我想知道给定节点的子图结构。

我也同意 networkx 解决方案。

这是我的代码。

import pygraphviz as pgv

class Test:
    subgraph1 = 'foo'
    subgraph2 = 'bar'

    def __init__(self):
        self.G = pgv.AGraph(directed=True)
        self.G.add_subgraph(label=self.subgraph1, name='cluster_' + self.subgraph1)

        s1 = self.G.get_subgraph('cluster_' + self.subgraph1)
        s1.add_subgraph(label=self.subgraph2, name='cluster_' + self.subgraph2)
        s1.add_node('s1 node')

        s2 = s1.get_subgraph('cluster_' + self.subgraph2)
        s2.add_node('s2 node')

    def main(self):
        print(self.G.subgraph('1st node'))
        print(self.G.subgraph_parent('1st node'))
        print(self.G.subgraph_root('1st node'))
        n = self.G.get_node('1st node')
        print(n.attr['subgraph'])
        print(n.attr['label'])


if __name__ == '__main__': Test().main()

我想要一个函数,它将 return 给定整个图中任何节点的子图列表。像这样...

在: subgraph_structure_as_list('s2 node')

输出: ['foo', 'bar']

在: subgraph_structure_as_list('s1 node')

输出: ['foo']

您可以使用这样的递归方法:

import pygraphviz as pgv

class Test:
    subgraph1 = 'foo'
    subgraph2 = 'bar'

    def __init__(self):
        self.structure = []
        self.G = pgv.AGraph(directed=True)
        self.G.add_subgraph(label=self.subgraph1, name='cluster_' + self.subgraph1)

        s1 = self.G.get_subgraph('cluster_' + self.subgraph1)
        s1.add_subgraph(label=self.subgraph2, name='cluster_' + self.subgraph2)
        s1.add_node('s1 node')

        s2 = s1.get_subgraph('cluster_' + self.subgraph2)
        s2.add_node('s2 node')

    #  ... other methods here ...

    def get_structure(self, node_name, node=None):
        if node is None:
            node = self.G
        for subgraph in node.subgraphs():
            if node_name in subgraph.nodes():
                self.structure.append(subgraph.node_attr['label'])
            self.get_structure(node_name, subgraph)

    def subgraph_structure_as_list(self, node_name):
        self.structure = []
        self.get_structure(node_name)
        return self.structure

您可以像这样使用 subgraph_structure_as_list

a = Test()
print(a.subgraph_structure_as_list('s2 node'))
print(a.subgraph_structure_as_list('s1 node'))

输出:

['foo', 'bar']
['foo']