用networkx修改python中两种不同种群的ErdosRenyi随机图

2024-06-13 12:50:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我要实现以下模型:

  • 取2*n个节点。前n个节点代表A型个体,其余节点代表B型个体。

  • 对于概率p,在A的个体和B的个体之间存在一条边。

我是这样做的,但我希望它更快:

def modified_Erdos_Renyi(n,p):
    G = nx.empty_graph(2*n)
    for i in range (n):       
        for j in range(n,2*n):
            r = rd.random()
            if r<=p:
                G.add_edge(i,j)
    return G

我在networkx源代码中看到了一个传统G\U np的快速算法:

def fast_gnp_random_graph(n, p):
    G = empty_graph(n)
    G.name="fast_gnp_random_graph(%s,%s)"%(n,p)

    w = -1
    lp = math.log(1.0 - p)
    v = 1
    while v < n:
        lr = math.log(1.0 - random.random())
        w = w + 1 + int(lr/lp)
        while w >= v and v < n:
            w = w - v
            v = v + 1
        if v < n:
            G.add_edge(v, w)
    return G

如何用修改后的模型实现这个算法?你知道吗


Tags: in模型addforreturnif节点def
1条回答
网友
1楼 · 发布于 2024-06-13 12:50:43

您试图创建的算法是already implemented in networkx作为nx.bipartite.random_graph(m,n,p)m是组A中的数字,n是组B中的数字,p是边缘概率。你知道吗

顺便说一句-如果您想了解fast_gnp_random_graph的工作原理,我推荐this paper I cowrote with one of the original developers of networkx的第2节。你知道吗

相关问题 更多 >