Search code examples
pythonserializationnetworkx

Representing Networkx graphs as strings in a consistent way


I have multiple Networkx graphs (with node attributes), and I need to represent them as strings. There are several ways to do that, but I need to always get the same string for equal graphs (not isomorphic, by equal I mean that graphs_equal returns true). Is there a way to turn a graph into a string that guarantees this?


Solution

  • I think the sort of thing done below should work.

    import networkx as nx
    
    
    def graph_to_str(g):
        return str(sorted(list(g.nodes.data()))), str(
            sorted(e if e[0] < e[1] else (e[1], e[0], e[2]) for e in list(g.edges.data()))
        )
    
    
    g1 = nx.complete_graph(4)
    g2 = nx.Graph([(1, 2), (2, 3), (0, 1), (1, 3), (0, 2), (0, 3)])
    
    for g in [g1, g2]:
        nx.set_node_attributes(g, {1: {"hello": "world"}})
        nx.set_edge_attributes(g, {(2, 3): {"foo": "bar"}})
    
    print(nx.utils.graphs_equal(g1, g2), graph_to_str(g1) == graph_to_str(g2))  # True True
    

    There may also be some other way explained in this documentation on reading/writing Networkx graphs.