2

Serializing GraphML

 3 years ago
source link: https://bbengfort.github.io/2016/09/serialize-graphml/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Serializing GraphML

September 9, 2016 · 1 min · Benjamin Bengfort

This is mostly a post of annoyance. I’ve been working with graphs in Python via NetworkX and trying to serialize them to GraphML for use in Gephi and graph-tool. Unfortunately the following error is really starting to get on my nerves:

networkx.exception.NetworkXError: GraphML writer does not support <class 'datetime.datetime'> as data values.

Also it doesn’t support <type NoneType> or list or dict or …

So I have to do something about it:

def write_graphml(g, outpath): """ Converts data types then writes the graphml """

def convert(data): """ Converts a dictionary """ for key in list(data.keys()): val = data[key]

if isinstance(val, datetime): data[key] = val.strftime(ISO8601_DATETIME)

if isinstance(val, type(None)): del data[key]

# Convert node data types for node in g.nodes(): convert(g.node[node])

# Convert edge data types for edge in g.edges(): convert(g[edge[0]][edge[1]])

nx.write_graphml(g, outpath)

#!/usr/bin/env python3

import pickle import networkx as nx

def read_pickle_graph(path): """ Reads a NetworkX graph serialized as a pickle file (use the write_graphml function above). """ with open(path, 'wb') as f: return pickle.load(f)

This is my first attempt, I’m simply going through all nodes and edges and directly updating/serializing their data values (note that Graph properties are missing). This pretty much makes the graph worthless after writing to disk. It also means that you have to do the deserialization after reading in the GraphML. There has to be a better way.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK