Search code examples
pythongraphnetworkxisomorphism

How to get an isomorphic graph from another in networkx?


Good morning, everyone.

I am currently doing a unit test of a function that processes graphs and it should give similar results in front of isomorphic graphs. So, I would like to output only an isomorphic graph from a networkx graph, but I can't find if that functionality exists. Here it talks about the checks needed to see if two graphs are isomorphic, but not about how to get one.

Is there such functionality in the networkx library or does anyone know how to get one?


Solution

  • So basically any graph that you change the names / labels of the nodes is isomorphic to the original graph and different from it. The reason there does not exist a built in function to do that is because it's trivial and not really usable. For example:

    import networkx as nx
    
    G1 = nx.DiGraph()
    nx.add_path(G1, [1, 2, 3, 4], weight=1)
    
    G_iso = G1.copy()
    
    mapping = {
        1: 'a',
        2: 'b',
        3: 'c',
        4: 'd'
    }
    
    G_iso = nx.relabel_nodes(G_iso, mapping)
    
    print(f"{nx.is_isomorphic(G1, G_iso)=}")
    

    Outputs:

    nx.is_isomorphic(G1, G_iso)=True
    

    Hope that helps.