Created
October 14, 2016 19:39
-
-
Save RobertTalbert/40620892ecc468e5f8dbf5dd1170aa44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Generates a random weighted graph. | |
n = Number of nodes. | |
p = Probability of two nodes being connected. Must be between 0 and 1. | |
Weights on the edges are randomly generated integers situated between lower_weight and upper_weight. | |
Example: random_weighted_graph(6, 0.25, 10, 20) creates a weighted graph with 6 nodes, a 1/4 probability | |
of two nodes being connected, and weights on the edges randomly selected between 10 and 20. | |
''' | |
def gnp_random_weighted_graph(n,p,wlow,whigh): | |
import random | |
G = nx.random_graphs.gnp_random_graph(n,p) | |
m = G.number_of_edges() | |
weights = [random.randint(wlow,whigh) for r in range(m)] | |
unweighted_edges = G.edges() | |
weighted_edges = [(unweighted_edges[i][0], unweighted_edges[i][1], {'weight':weights[i]}) for i in range(m)] | |
return nx.Graph(weighted_edges) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment