为什么我不能将 networkx LFR 基准图转换为 GML?

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

我在尝试将在 networkx 中创建的 LFR 基准图写入 GraphML XML 格式时遇到问题。

例如,当 G 是一个简单的星图时,以下工作正常:

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

但是,现在假设 G 是 LFR 基准图,按照 networkx 文档中的示例输入 (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')

最后一行导致如下所示的错误消息:

问题是 graphml 无法将可迭代对象作为节点属性处理(如讨论的那样 and here)。在这种情况下,LFR 使用一个集合来存储每个节点的所有社区成员资格。

一个快速而肮脏的解决方法是将社区集映射到一个字符串中:

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')

社区集现在是一个 csv 列表:

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'