Setting nodes within a networkx graph as infected and uninfected

325 Views Asked by At

I have the karate club graph, I wish to determine a few random nodes within there as infected nodes, while the rest are uninfected. I tried to use:

G = nx.karate_club_graph()
#pos = nx.spectral_layout(G)
bb = tuple(nx.betweenness_centrality(G))
nx.set_node_attributes(G, 'betweenness', bb)
G.nodes[1]['betweenness']

As an example to see if it can work. Though it returns a key error for 'betweenness' in the final line. What ways are there to manually or randomly select a few nodes in the graph, and give them a 1 for infected while the the rest are 0. Or is there a better way to set infections within this graph?

1

There are 1 best solutions below

0
Abhi On

just follow the correct function call for set_node_attributes

Correct syntax:

set_node_attributes(G, values, name=None)

so your variable bb will come before name betweenness

code:

import networkx as nx
G = nx.karate_club_graph()
bb = tuple(nx.betweenness_centrality(G))
# changed
nx.set_node_attributes(G,  bb, 'betweenness')
print(G.nodes[1])

Result:

enter image description here

Also if you remove the tuple part, you will get score output:

import networkx as nx
G = nx.karate_club_graph()
bb = tuple(nx.betweenness_centrality(G))
# changed
bb = nx.betweenness_centrality(G)
nx.set_node_attributes(G,  bb, 'betweenness')
print(G.nodes[1])

Result:

enter image description here