生成所有可能的双向图的最佳方法Python

2024-10-02 00:36:56 发布

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

我试图生成给定一组节点的所有可能的双向图。我将图形存储为numpy向量,并且需要这样的方式,因为有一些下游代码使用这种格式的图形。

假设我有两组节点,其中同一组中的节点不连接。然而,有可能有两个集合的成员根本不相交的图。

posArgs= [0,1]      # (0->1) / (1->1) is not allowed..neither is (0->1)
negArgs= [2]        # (0->2) is possible, and so is (0 2) - meaning no connection.

为了说明我的意思:

enter image description here

翻译为:

^{pr2}$

我想要的是生成所有可能的方法,然后这两个集合可以被构造(即所有可能的节点组合作为向量)。目前我正在使用itertools.product为了生成所有节点的幂集,我创建了一组向量,其中有循环连接和相同的集合连接。然后我将它们从powerset中删除。因此,使用上述集合,我有以下代码:

import numpy as np
import itertools

posArgs= [0,1]      # 0->1 / 1->1 is not allowed..neither is 0->1
negArgs= [2]

nargs= len(posArgs+ negArgs)
allPermutations= np.array(list(itertools.product([0,1], repeat=nargs*nargs)))

# Create list of Attacks that we will never need. Circular attacks, and attacks between arguments of same polarity
circularAttacks = (np.arange(0, nargs*nargs, nargs+1)).tolist()
samePolarityAttacks = []
posList = list(itertools.permutations(posArgs, 2))
negList = list(itertools.permutations(negArgs, 2))
totList = posList + negList

for l in totList:
    ptn = ((l[0]+1)*nargs)- ((nargs+1) - l[1]) + 1 # All the odd +1 are to account for the shift in 0 index
    samePolarityAttacks.append(ptn)


graphsToDelete = np.unique([circularAttacks + samePolarityAttacks])
subGraphs = allPermutations[:,graphsToDelete]
cutDownGraphs = np.delete(allPermutations, (np.where(subGraphs>0)[0]).tolist(), axis = 0)

for graph in cutDownGraphs:
    singleGraph= np.vstack( np.array_split(np.array(graph), nargs))
    print(singleGraph)

我的问题是当我的两个集合中有超过5个节点时itertools.product正在尝试生成(2^25)组向量。这当然是非常昂贵的,给我留下了内存泄漏。

你知道有一种聪明的方法,我可以重塑代码,同时确保我的图形保持这种numpy数组格式?

--附加信息:

对于两个集合,一个节点一个集合,所有可能的组合如下所示:

enter image description here

谢谢


Tags: 代码numpy图形节点isnpproductarray

热门问题