gpt4 book ai didi

python - 如何用边连接两个子图?

转载 作者:行者123 更新时间:2023-12-01 07:07:15 26 4
gpt4 key购买 nike

G1,G2,G3为三个图。每个都有 N[i] 个节点。

3x3 矩阵 A 表示不相交图 G1,G2,G3 的节点之间接触的概率。

所以A_ij表示Gi处的节点与Gj处的节点有边的概率。

Aii 将是在 Gi 处的节点之间具有边的概率。

我需要一些帮助来完成此操作,并以这样的方式命名节点,以便在联合图中我将能够看到哪些节点来自哪个 Gi

import networkx as nx
import numpy as np

A = np.array([[0.2, 0.4, 0.2], [0.4, 0.1, 0.5], [0.2, 0.5, 0.3]])
N = [20,30,40]

def get_number_edges(A,N,n):
return int(A[n-1,n-1]*N[n-1])

G1=nx.dense_gnm_random_graph(N[0],get_number_edges(A,N,1))
G2=nx.dense_gnm_random_graph(N[1],get_number_edges(A,N,2))
G3=nx.dense_gnm_random_graph(N[2],get_number_edges(A,N,3))

C=nx.disjoint_union(nx.disjoint_union(G1,G2),G3)
  1. 我不确定如何将节点从 Gi 连接到 Gj,其中 i!=j
  2. 我不确定如何使用标签来注释 C 处的节点,以指示这些节点源自哪个图 Gi

最佳答案

我将首先创建完整的图 C,然后根据需要创建子图。

import itertools
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

A = np.array([[0.2, 0.4, 0.2], [0.4, 0.1, 0.5], [0.2, 0.5, 0.3]])
N = [20,30,40]

# create a square probability matrix with dimensions (total nodes, total nodes)
# and populate it with the values given in A
indices = []
ctr = 0
for n in N:
indices.append(list(range(ctr, ctr+n)))
ctr += n

# TODO:
# remove this horrible triple loop;
# have a cold and am not smart enough to do it properly now
total_nodes = sum(N)
probability = np.zeros((total_nodes, total_nodes), dtype=np.float)
for ii, sources in enumerate(indices):
for jj, targets in enumerate(indices):
for source, target in itertools.product(sources, targets):
probability[source, target] = A[ii, jj]
plt.imshow(probability, cmap='gray'); plt.show()

# convert probability matrix into an adjacency matrix
adjacency = probability >= np.random.rand(*probability.shape)
plt.imshow(adjacency, cmap='gray'); plt.show()

# create networkx graph object
C = nx.from_numpy_array(adjacency)

# to get any subgraph, use the indices
G1 = C.subgraph(indices[0])
# etc

关于python - 如何用边连接两个子图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com