给出一个节点集,枚举其上的图

问题描述 投票:1回答:1

我有一个节点集

N = [1,2,.... n]

我可以在此节点集上定义2 ^(nC2)个图。我想按边缘数量的不降序枚举它们。在python networkx中有有效的方法吗?假设无向图,并且通过枚举图,我基本上是指枚举邻接矩阵。

algorithm networkx graph-algorithm combinatorics discrete-mathematics
1个回答
1
投票

这可以使用下面的代码来实现。基本上,我们使用itertools生成代表所有可能图形的列表,按照它们包含的边数对其进行排序,生成代表该图形的列表的字典,然后返回与列表的这些格对应的networkx图形的列表。

代码:

from math import factorial as f
import networkx as nx
import itertools

def nCr(n,r):
    return f(n) // f(r) // f(n-r)

def get_all_graphs(n):
    rows = sorted(itertools.product(range(2), repeat=nCr(n,2)), key= lambda x: sum(x))

    indices = [sum(range(n-1, n-i-1, -1)) for i in range(n)] + [sum(range(n))]

    graphs = [{node: [j+node+1 for j, edge in enumerate(row[indices[node] : indices[node+1]]) if edge == 1] for node in range(n)} for row in rows]

    return [nx.from_dict_of_lists(x) for x in graphs]

示例:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=2, ncols=4)

graphs = get_all_graphs(3)

for i, row in enumerate(ax):
    for j, col in enumerate(row):

        nx.draw(graphs[i*4+j], with_labels=True, ax=col)

plt.tight_layout()
plt.show()

输出:

enter image description here

或以上示例适用于n = 4:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.