Koa*_*c21 1 python graph-theory networkx weighted-graph
我已经设法创建了一个随机的无向加权图,用于使用 Dijkstra 算法进行测试,但是我怎样才能做到让每个节点至少有一条边将它们连接到图?
我正在使用 Networkx,我的图形生成器如下:
import networkx as nx
import random
random.seed()
nodes = random.randint(5,10)
seed = random.randint(1,10)
probability = random.random()
G = nx.gnp_random_graph(nodes,probability,seed, False)
for (u, v) in G.edges():
G.edges[u,v]['weight'] = random.randint(0,10)
Run Code Online (Sandbox Code Playgroud)
这很好地创建了图形,我设法绘制了它,所以我实际上可以看到它,我的问题是边缘创建的概率。我不希望它太高以至于所有节点都具有最大边数,但是设置一个低值可能会导致节点具有 0 个边。有没有办法确保每个节点至少有一条边?
似乎没有NetworkX 图生成器可以直接生成满足此类要求的图。
但是,您可以稍微调整 中使用的方法nx.gnp_random_graph,这样我们就不会以随机概率在所有可能的边组合中设置一条边,而是随机为每个节点添加一条边,然后以 概率添加其余边p。
下面的方法不仅生成了一个图,其中每个节点至少有一条边,而且还生成了一个连通图。这在附加说明中解释如下-
def gnp_random_connected_graph(n, p):
"""
Generates a random undirected graph, similarly to an Erd?s-Rényi
graph, but enforcing that the resulting graph is conneted
"""
edges = combinations(range(n), 2)
G = nx.Graph()
G.add_nodes_from(range(n))
if p <= 0:
return G
if p >= 1:
return nx.complete_graph(n, create_using=G)
for _, node_edges in groupby(edges, key=lambda x: x[0]):
node_edges = list(node_edges)
random_edge = random.choice(node_edges)
G.add_edge(*random_edge)
for e in node_edges:
if random.random() < p:
G.add_edge(*e)
return G
Run Code Online (Sandbox Code Playgroud)
样品运行-
如下例所示,即使分配非常低的概率,结果图也是连通的:
from itertools import combinations, groupby
import networkx as nx
import random
nodes = random.randint(5,10)
seed = random.randint(1,10)
probability = 0.1
G = gnp_random_connected_graph(nodes,probability)
plt.figure(figsize=(8,5))
nx.draw(G, node_color='lightblue',
with_labels=True,
node_size=500)
Run Code Online (Sandbox Code Playgroud)
nodes = 40
seed = random.randint(1,10)
probability = 0.001
G = gnp_random_connected_graph(nodes,probability)
plt.figure(figsize=(10,6))
nx.draw(G, node_color='lightblue',
with_labels=True,
node_size=500)
Run Code Online (Sandbox Code Playgroud)
补充说明——
上面的方法,不仅保证了每个节点至少有一条边,而且如前所述,结果图是连通的。这是因为我们使用来自 的结果为每个节点设置至少一条边itertools.combinations(range(n_nodes), 2)。举个例子可能更清楚:
edges = combinations(range(5), 2)
for _, node_edges in groupby(edges, key=lambda x: x[0]):
print(list(node_edges))
#[(0, 1), (0, 2), (0, 3), (0, 4)]
#[(1, 2), (1, 3), (1, 4)]
#[(2, 3), (2, 4)]
#[(3, 4)]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们在每种情况下设置至少一条边,random.choice从每次迭代的可用边中取 a ,这些边是尚未设置的边。这是使用 的结果itertools.combinations设置边的结果。对于无向图,如果之前已经以概率添加了这些边,则在每次迭代时遍历所有现有边是没有意义的p。
这不是采用permutations(参见有向图案例的源代码)的情况。在有向图的情况下,无法保证遵循这种方法的连通性,因为可能有两个节点由相反方向的两条边连接,并与图的其余部分隔离。所以应该遵循另一种方法(也许扩展上述想法)。
| 归档时间: |
|
| 查看次数: |
3249 次 |
| 最近记录: |