I am trying to subclass a networkx Graph object. My __init__
has one variable passed to it. However, this means that when I try to use the following method which calls 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)
I would really prefer not to remove my initialization class variable. Is there a way I can still use the connected_component_iter
method from Graph
?
You could work around the problem by giving your new initialization variable, val
, a default value:
class MyGraph(nx.Graph):
def __init__(self, data=None, val=None, **attr):
super(MyGraph, self).__init__()
self.val = val
Above, the default value for val
is None. So
H = self.__class__()
would initialize a new subgraph with val
equal to None
.
However, it seems likely that you'd like the subgraph to inherit the same value of val
as the parent MyGraph. In that case, we'd need to change
H = self.__class__()
to
H = self.__class__(val=self.val)
We can do this by overriding the subgraph
method by defining our slightly altered version in MyGraph
. For example, the code might look something like:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.