从具有条件的图中删除节点

remove nodes from a graph with a condition

我的代码首先读取包含节点和带属性的弧的图形,然后计算节点 attributes('criticité')。之后,它会根据条件删除节点。

这是我的代码,我收到的类型错误是 TypeError: unhashable type: 'dict'

#parsing
import matplotlib.pyplot as plt
import networkx as nx
G=nx.read_graphml("C:/Users/PlacisAdmin/Desktop/gephi/ex2.graphml",node_type=str)
nx.draw(G, with_labels=True)
plt.show()


# chnage nodes attributes
for u, v, weight in G.edges.data('weight'):
          if weight !=1:
             G.node[u]['criticité'] = float(G.node[u]['occurence']) * float (G.node[u]['détection']) * float (G.node[u]['gravité']) * weight
             G.node[v]['criticité'] = float(G.node[v]['occurence']) * float (G.node[v]['détection']) * float (G.node[v]['gravité']) * weight
print ("avant")
print (G.nodes.data('label'))
print (G.nodes.data('criticité'))


# calculate system crticité
for n in G.nodes():
    if G.node[n]['label']in ['1','2','3','4']:
        G.node[n]['criticité']=sum(G.node[t]['criticité'] for t in G.successors(n))

print ("après")
print (G.nodes.data('label'))
print (G.nodes.data('criticité'))

# eliminate nodes 
for d in G.nodes():
    if G.node[d]['label']in ['1','2','3','4'] and G.node[d]['criticité']> 30:
      G.remove_nodes_from(G.node[t]for t in G.successors(d) )

# show the graph
nx.draw(G, with_labels=True)
plt.show()

可能与此重复:

dict 是可变的,因此不能被散列。您可以创建自己的可散列字典,并在其 id(d) 上进行散列,例如(不可变的东西)。

我认为你的错误在这一行:

G.remove_nodes_from(G.node[t]for t in G.successors(d) )

G.node[t] 是一个包含节点 t 所有属性的字典。所以它正在寻找一个节点t属性字典的节点。但是,networkx 不允许节点成为字典。因此,当它开始寻找要删除的节点时,它会给您一条错误消息。

您几乎肯定是要打电话

G.remove_nodes_from(t for t in G.successors(d))