网络x中的边缘生成

时间:2021-05-29 17:36:24

标签: python graph networkx bipartite

我想问一个关于通过 Networkx 生成二部图的问题。我试图找到方法,如何为二部图生成节点。但我不是很成功。

#!/usr/bin/python3

import networkx as nx
import matplotlib.pyplot as plt

#max_diameter_cnt = 4
#max_nodes_cnt = 7
#max_degree_cnt = 2

G = nx.Graph()
# data example
G.add_edges_from([('0', '1'), ('0', '2'), ('1', '3'),
                  ('3', '5'), ('2', '4'), ('4', '6'),
                  ('5', '6')])

print(nx.diameter(G))

nx.draw(G, with_labels=True)
plt.show()

目前一切都是硬编码的。但我想根据参数生成它。

  1. 直径必须设置为“4”。 (节点之间的最大距离。)
  2. 对于 2 度数,摩尔界计算为 7。但我想像 <2,3,4> 一样改变它。摩尔界计算为 <7,22,53>。
  3. 那么如何生成节点列表,尤其是邻居边?

非常感谢您的支持。

安迪

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,则以下内容应该有效。此解决方案使用 gnmk_random_graph(),但您当然可以改用 random_graph()。输出由随机过程生成,但解是否随机分布取决于您如何定义要采样的图集。

import numpy as np
import networkx as nx
from networkx.algorithms.bipartite.generators import gnmk_random_graph

nodes_in_A = 3  # Primary parameter to change

nodes_in_B = 2 * nodes_in_A
diam = 4
max_attempts = 1000

for attempt in range(max_attempts):
    num_edges = np.random.randint(nodes_in_B, nodes_in_A * nodes_in_B)
    G = gnmk_random_graph(nodes_in_A, nodes_in_B, num_edges)
    if not nx.is_connected(G):
        pass
    elif nx.diameter(G) == diam:
        node_color = [d['bipartite'] for n, d in G.nodes(data=True)]
        nx.draw(G, with_labels=True, node_color=node_color, cmap='bwr')
        break
    if attempt == max_attempts - 1:
        print('Graph generation failed with current parameters.')

例如:

diameter_4_bipartite_graph