继承networkx图并使用nx.connected_component_subgraphs

3
我正在尝试对networkx Graph对象进行子类化。我的__init__只有一个变量传递进去。然而,这意味着当我尝试使用以下调用connected_component_iter的方法时,可能会出现问题。
def connected_component_iter(self):
    """
    Yields connected components.
    """
    assert self.is_built is True
    for subgraph in nx.connected_component_subgraphs(self):
        yield subgraph

I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "src/unitigGraph.py", line 163, in connected_component_iter
    def connected_component_iter(self):
  File "/Library/Python/2.7/site-packages/networkx/algorithms/components/connected.py", line 94, in connected_component_subgraphs
    yield G.subgraph(c).copy()
  File "/Library/Python/2.7/site-packages/networkx/classes/graph.py", line 1486, in subgraph
    H = self.__class__()
TypeError: __init__() takes exactly 2 arguments (1 given)

我真的不想删除我的初始化类变量。有没有办法我仍然可以使用Graph中的connected_component_iter方法?

1个回答

5

您可以通过为新的初始化变量val提供默认值来解决问题:

class MyGraph(nx.Graph):
    def __init__(self, data=None, val=None, **attr):
        super(MyGraph, self).__init__()
        self.val = val

上面,val 的默认值是 None。因此,
H = self.__class__()

将会初始化一个新的子图,其中val等于None

然而,您可能希望子图继承与父级MyGraph相同的val值。在这种情况下,我们需要进行更改。

    H = self.__class__()

to

    H = self.__class__(val=self.val)

我们可以通过在MyGraph类中定义稍微修改过的subgraph方法来实现此操作。例如,代码可能如下所示:在subgraph方法被覆盖。
import networkx as nx
class MyGraph(nx.Graph):
    def __init__(self, data=None, val=None, **attr):
        super(MyGraph, self).__init__()
        self.val = val
        self.is_built = True

    def connected_component_iter(self):
        """
        Yields connected components.
        """
        assert self.is_built is True
        for subgraph in nx.connected_component_subgraphs(self):
            yield subgraph

    def subgraph(self, nbunch):
        bunch =self.nbunch_iter(nbunch)
        # create new graph and copy subgraph into it
        H = self.__class__(val=self.val)
        # copy node and attribute dictionaries
        for n in bunch:
            H.node[n]=self.node[n]
        # namespace shortcuts for speed
        H_adj=H.adj
        self_adj=self.adj
        # add nodes and edges (undirected method)
        for n in H.node:
            Hnbrs={}
            H_adj[n]=Hnbrs
            for nbr,d in self_adj[n].items():
                if nbr in H_adj:
                    # add both representations of edge: n-nbr and nbr-n
                    Hnbrs[nbr]=d
                    H_adj[nbr][n]=d
        H.graph=self.graph
        return H

G = MyGraph(val='val')
G.add_edges_from([(0, 1), (1, 2), (1, 3), (3, 5), (3, 6), (3, 7), (4, 8), (4, 9)])

for subgraph in G.connected_component_iter():
    print(subgraph.nodes(), subgraph.val)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接