Reputation: 105
assume I have four different graphs in a project and I want to iterate through them by using for-loops. First of all, the graph structure will look like this:
import networkx as nx
Gx = nx.DiGraph()
Gx.add_node('x1', server = 5)
Gx.add_node('x2', service = 3)
Ga = nx.DiGraph()
Ga.add_node('a1', server = 8)
Ga.add_node('a2', service = 4)
Gb = nx.DiGraph()
Gb.add_node('b1', server = 12)
Gb.add_node('b2', service = 5)
Gc = nx.DiGraph()
Gc.add_node('c1', server = 5)
Gc.add_node('c2', service = 3)
Now, I want to go through every graph and select one node randomly, after this set the attribute = 0 (e.g. simulating a server fail). So my function should look something like this:
for 'every graph' in 'DiGraphs':
random_node = random.sample(Gx/a/b/c.nodes, 1)
new_value_random_node = random_node['attribute'] * 0
Which would then throw out the graph structure like this after executing the code:
import networkx as nx
Gx = nx.DiGraph()
Gx.add_node('x1', server = 5)
Gx.add_node('x2', service = 0) # service fail
Ga = nx.DiGraph()
Ga.add_node('a1', server = 0) # server fail
Ga.add_node('a2', service = 4)
Gb = nx.DiGraph()
Gb.add_node('b1', server = 0) # server fail
Gb.add_node('b2', service = 5)
Gc = nx.DiGraph()
Gc.add_node('c1', server = 5)
Gc.add_node('c2', service = 0) # service fail
Summarizing I want to do two things:
1. Go through every Graph (Gx,Ga,Gb,Gc)
2. In every graph -> select one node randomly
3. Set attribute of random node (either server or service) = 0
Can someone help me with this?
Upvotes: 0
Views: 720
Reputation: 1476
I propose the following:
import networkx as nx
Gx = nx.DiGraph()
Gx.add_node('x1', server = 5)
Gx.add_node('x2', service = 3)
Ga = nx.DiGraph()
Ga.add_node('a1', server = 8)
Ga.add_node('a2', service = 4)
Gb = nx.DiGraph()
Gb.add_node('b1', server = 12)
Gb.add_node('b2', service = 5)
Gc = nx.DiGraph()
Gc.add_node('c1', server = 5)
Gc.add_node('c2', service = 3)
import random
for graph in [Gx, Ga, Gb, Gc]:
random_node = random.sample(graph.nodes, 1)[0]
attr = list(graph.nodes.data()[random_node].keys())[0]
graph.nodes[random_node][attr] = 0
Upvotes: 1