Python - Networkx 为每条边创建一个具有自定义键概率的随机图

Python - Networkx create a random graph with a custom bond probability for each edge

我只是想知道是否有一种方法可以实现大小为 N 的随机图,其中每对节点之间的键的概率由 概率矩阵中的特定单元格给出,假设大小为 NxN 的 P,其中 P_{ij} 表示节点 n_{i} 和 n_{j} 之间形成键的概率。

也许该函数应该类似于函数 networkx.generators.random_graphs.gnp_random_graph 但可以添加概率矩阵 P,而不是表示概率的浮点数 p 任何节点对之间的键创建。

我认为您只需要根据您的要求设置节点和边并将其传递给图形构造器

例如-

import networkx as nx
import itertools
import random
def setup_nodes_edges(n, p_matrix):
    nodes = list(range(n))
    edges = set()
    for combination in itertools.combinations(nodes, 2):
        x, y = combination
        if p_matrix[x][y] <= random.random():
            edges.add(combination)
    return nodes, edges

nodes, edges = setup_nodes_edges(3, p_matrix) # I assume you have a p_matrix
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)

为这种情况推出自己的图形生成器非常容易。

#!/usr/bin/env python
import numpy as np
import networkx as nx

N = 10 # number of nodes
P = np.random.rand(10, 10) # your "matrix of probabilities"
adjacency = np.random.rand(*P.shape) <= P # adjacency[ii, jj] is True with probability P[ii, jj]
graph = nx.from_numpy_matrix(adjacency, nx.DiGraph) # assuming the graph is supposed to be directed, presumably if P[ii, jj] != P[jj, ii]
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

N = 8
m = np.random.random(N*N).reshape(N, N)
for i in range(N): m[i, i] = 0

nodes = range(N)
edges = {}
for i in range(N):
    for j in range(N):
        if np.random.random() < m[i, j]:
            edges[(i, j)] = round(m[i, j], 2)

G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edges)
plt.show()

result