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

时间:2017-02-06 11:40:16

标签: python numpy itertools directed-acyclic-graphs

我试图在给定一组节点的情况下生成所有可能的双向图。我将我的图形存储为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

翻译为:

import numpy as np
graph = np.array([0,0,1,0,0,1,0,0,0])
singleGraph= np.vstack( np.array_split(np.array(graph), nargs))

>>[[0 0 1]
[0 0 1]
[0 0 0]]
# Where the first row represent node 0's relationships with nodes 0, 1, 2
# the second row represents node 1's relationships with nodes 0, 1, 2 etc

我想要的是生成所有可能的方式,然后可以构建这两个集合(即所有可能的节点组合作为向量)。目前我使用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

由于

0 个答案:

没有答案