Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a random networkx graph with random weights [closed]

I am attempting to create a random networkx graph with each edge having a random weight (representing length).

At the moment I am using the gnm_random_graph function from the set of networkx graph generators:

g=nx.gnm_random_graph(5,5)

However, I am struggling to add the random weights. My attempt is based on answers to this question.

for u,v,w in in g.edges(data=True):
     w = np.random.randint(0,10)

I am doing this so I can explore and (hopefully) understand the networkx library.

My question has two parts:

1. What is the best way generate a simple networkx graph for example purposes?

2. What is the best way to add weights to an existing networkx graph?

like image 278
atomh33ls Avatar asked Aug 04 '15 08:08

atomh33ls


1 Answers

Just addressing question 2 (Q1 is very dependent on context)

you could use (I believe in both networkx 1.x and 2.x):

import random
#code creating G here
for (u,v,w) in G.edges(data=True):
    w['weight'] = random.randint(0,10)

The variable w is a dictionary whose keys are all the different edge attributes.

Alternatively in networkx 2.x you can do

for (u, v) in G.edges():
    G.edges[u,v]['weight'] = random.randint(0,10)

or in networkx 1.x you can do

for (u, v) in G.edges():
    G.edge[u][v]['weight'] = random.randint(0,10)
like image 90
Joel Avatar answered Oct 01 '22 14:10

Joel