簡體   English   中英

繼承networkx圖並使用nx.connected_component_subgraphs

[英]inheriting networkx Graph and using nx.connected_component_subgraphs

我試圖子類化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

我收到此錯誤:

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)

我真的不希望刪除我的初始化類變量。 有沒有辦法我仍然可以使用Graphconnected_component_iter方法?

您可以通過給您的新初始化變量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__()

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

我們可以通過在MyGraph定義稍有改動的版本來覆蓋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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM