###############################################################################
# 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()
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()))
您可以将整个过程分为三个步骤:
red_graph
和{combined
图。这只是一个棘手的问题,因为两个随机图中的节点具有相同的名称,但是您可以通过在blue_graph
中的每个节点名中添加N
来轻松解决这个问题。在combined
图中,以概率red_graph
和{red_graph
和{下面是一个完整的示例,其结果随机图如下:
下面的代码允许子图也有不同数量的节点。它利用了
nx.bipartite_random_graph
,它有一个特别有效的实现:O(V+E),其中V是顶点数,E是边数。实现二部随机图的标准方法是O(N*M),其中这些是每个分区中的节点数。它使用了fast_gnp_random_graph
作为O(V+E)而不是O(v2)的相同技巧。在相关问题 更多 >
编程相关推荐