Reputation: 5207
i have attached numpy-array to nodes in a networkx graph. How to store the graph in gexf-format on disk? (without the numpy vector, as its just something intermediate...)
def create():
G = nx.Graph()
for i in range(256):
G.add_node(i, vector=np.arange(20))
for i in range(1,20):
for j in range(1,256, 10):
G.add_edge(i,j)
temp = tempfile.mktemp(suffix=".gexf")
print("dumping G = (V: %s, E: %s) to disk %s"
% (len(G.nodes()), len(G.edges()), temp))
nx.write_gexf(G, temp)
However, this breaks. I'm new to python, but to me it seems like the ndarray is not serializable?! So, how to tell networkx to ignore that node attribute?
File "...lib\site-packages\networkx\readwrite\gexf.py", line 430, in add_attributes
attr_id = self.get_attr_id(make_str(k), self.xml_type[val_type],
KeyError: <type 'numpy.ndarray'>
Upvotes: 2
Views: 2974
Reputation: 5207
I solved this by removing the property "vector" from the data items:
for (n,d) in G.nodes(data=True):
del d["vector"]
full MWE:
def create():
G = nx.Graph()
for i in range(256):
G.add_node(i, vector=np.arange(20))
for i in range(1,20):
for j in range(1,256, 10):
G.add_edge(i,j)
temp = tempfile.mktemp(suffix=".gexf")
print("dumping G = (V: %s, E: %s) to disk %s"
% (len(G.nodes()), len(G.edges()), temp))
for (n,d) in G.nodes(data=True):
del d["vector"]
nx.write_gexf(G, temp)
Upvotes: 3
Reputation: 1667
Use a library like the native pickle
, or h5py
for HDF5, to serialize your graph object. For example you can do:
import pickle
with open("pickle_file", "wb") as f:
pickle.dump(create(), f)
The pickled graph can be loaded back into Python by:
with open("pickle_file", "rb") as f:
G = pickle.load(f)
Upvotes: 2