假设我有下一个图表:red_graph
和blue_graph
N
个节点,这些节点随机构建,概率p1
和p2
连接成对节点:
red_graph = nx.fast_gnp_random_graph(N, p1)
blue_graph = nx.fast_gnp_random_graph(N, p2)
现在我想以一定的概率将这两个图表加入到1中(让我们说q
)。所以q
- 概率红色节点连接到蓝色节点。我没有在NetworkX文档中找到任何关于它的功能。有什么想法吗?
答案 0 :(得分:1)
您可以将整个过程分解为三个步骤:
red_graph
和blue_graph
。combined
图表中。这只是棘手的,因为两个随机图中的节点具有相同的名称,但您可以通过将N
添加到blue_graph
中的每个节点名称来轻松解决此问题。combined
和red_graph
中的节点blue_graph
添加边缘,概率为q
。您可以使用列表解析在一行中执行此操作并获取red_graph
和blue_graph
中的product
个节点。这是一个完整的例子,下面是随机图:
###############################################################################
# Step 0: Load required modules and set and parameters
###############################################################################
import networkx as nx, matplotlib.pyplot as plt
from itertools import product
from random import random
# Parameters
N = 5
p1 = 0.5
p2 = 0.5
q = 0.25
###############################################################################
# Step 1: Create the random graphs
###############################################################################
red_graph = nx.fast_gnp_random_graph(N, p1)
blue_graph = nx.fast_gnp_random_graph(N, p2)
###############################################################################
# Step 2: Combine the random graphs
###############################################################################
combined = nx.Graph()
red = red_graph.nodes()
# rename the blue nodes
blue = [ N + node for node in blue_graph.nodes() ]
combined.add_nodes_from(red)
combined.add_edges_from(red_graph.edges())
combined.add_nodes_from(blue)
# Rename the blue edges with their new node names
combined.add_edges_from([ (N + u, N + v) for u, v in blue_graph.edges() ])
###############################################################################
# Step 3: Connect nodes in the blue/red graphs with probability q
###############################################################################
combined.add_edges_from([ (u, v) for u, v in product(red, blue) if random() < q ])
###############################################################################
# Step 4: Plot the graph, including the color of each node
###############################################################################
pos = nx.spring_layout(combined)
nx.draw_networkx_nodes(combined, pos=pos, nodelist=red, node_color='r')
nx.draw_networkx_nodes(combined, pos=pos, nodelist=blue, node_color='b')
nx.draw_networkx_edges(combined, pos=pos)
plt.show()
答案 1 :(得分:0)
这里的代码允许子图也有不同数量的节点。它利用nx.bipartite_random_graph
具有特别有效的实现:O(V + E)其中V是顶点数,E是边数。实现二分随机图的标准方法是O(N * M),其中这些是每个分区中的节点数。它使用fast_gnp_random_graph
使用的相同技巧O(V + E)而不是O(V ^ 2)。
Nr= N
Nb = N
red_graph = nx.fast_gnp_random_graph(Nr, p1)
blue_graph = nx.fast_gnp_random_graph(Nb, p2)
main_graph = nx.bipartite_random_graph(Nr, Nb, q)
main_graph.add_edges_from(red_graph.edges_iter())
main_graph.add_edges_from(((Nr+x,Nr+y) for x,y in blue_graph.edges_iter()))