Search code examples
pythonnetworkxgraphml

Why can't I convert a networkx LFR benchmark graph to GML?


I'm encountering a problem when trying to write an LFR benchmark graph, created in networkx, to GraphML XML format.

For example, the following works fine, when G is a simple star graph:

import networkx as nx
G=nx.star_graph(10)
nx.write_graphml(G,'graph.graphml')

However, now suppose G is an LFR benchmark graph, entered as in the example found in the networkx documentation (https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.community.community_generators.LFR_benchmark_graph.html)

from networkx.algorithms.community import LFR_benchmark_graph
n =250
tau1 = 3
tau2 = 1.5
mu = 0.1
G=LFR_benchmark_graph(n,tau1,tau2,mu,average_degree=5,min_community=20,seed=10)
nx.write_graphml(G,'graph.graphml')

The last line results in the error message shown below: enter image description here


Solution

  • The problem is that graphml can't handle iterables as node attributes (as discussed here and here). In this case, LFR uses a set to store all of the community memberships for each node.

    A quick and dirty work around is to map the community set into a string:

    nx.set_node_attributes(G, {n:','.join(map(str, G.nodes[n]['community'])) for n in G.nodes()}, 'community')
    nx.write_graphml(G,'graph.graphml')
    

    Where the community set is now a csv list:

    G.nodes['0']['community'] = '0,1,2,4,5,6,9,10,11,15,17,25,26,30,32,35,41,42,43,47,48,49,50,51,52,53,56,57,59,60,62,64,66,67,68,71,73,74,77,79,81,84,86,87,88,91,92,94,95,96,97,98,99,100,101,103,104,107,108,109,110,111,112,113,115,116,119,120,123,126,128,130,131,132,135,137,138,139,140,141,143,145,146,147,148,149,150,151,152,154,155,156,159,160,161,163,164,165,166,170,171,172,174,176,177,179,181,183,185,186,187,188,189,191,192,194,195,196,197,198,199,200,201,202,204,205,206,207,208,211,212,213,214,215,217,218,220,221,222,223,227,228,230,231,232,233,234,235,236,238,240,241,242,243,244,245,246'