其他分享
首页 > 其他分享> > 如何在这个循环中利用置换对称性?

如何在这个循环中利用置换对称性?

作者:互联网

我有一个标量函数f(a,b,c,d),它具有以下排列对称性

f(a,b,c,d)= f(c,d,a,b)= -f(b,a,d,c)= -f(d,c,b,a)

我用它来完全填充4D阵列.下面的代码(使用python / NumPy)有效:

A = np.zeros((N,N,N,N))
for a in range(N):
    for b in range(N):
        for c in range(N):
            for d in range(N):
                A[a,b,c,d] = f(a,b,c,d)

但显然我想利用对称性来减少这部分代码的执行时间.我试过了:

A = np.zeros((N,N,N,N))
ab = 0
for a in range(N):
    for b in range(N):
        ab += 1
        cd  = 0
        for c in range(N):
            for d in range(N):
                cd += 1
                if ab >= cd:
                    A[a,b,c,d] = A[c,d,a,b] = f(a,b,c,d)

这将执行时间缩短了一半.但是为了最后的对称,我尝试了:

A = np.zeros((N,N,N,N))
ab = 0
for a in range(N):
    for b in range(N):
        ab += 1
        cd  = 0
        for c in range(N):
            for d in range(N):
                cd += 1
                if ab >= cd:
                    if ((a >= b) or (c >= d)):
                        A[a,b,c,d] = A[c,d,a,b] = f(a,b,c,d)
                        A[b,a,d,c] = A[d,c,b,a] = -A[a,b,c,d]

哪个有效,但不会让我接近另外两个加速的因素.我不认为这是正确的理由,但不明白为什么.

我怎样才能更好地利用这种特定的排列对称?

解决方法:

有趣的问题!

对于N = 3,应该有81个具有4个元素的组合.
使用循环,您可以创建156.

看起来重复的主要来源是或者在(a> = b)或(c> = d)中,它太宽容了.但是,(a> = b)和(c> = d)限制性太强.

但是,您可以比较c> = b d.要获得几毫秒(如果有的话),你可以在第三个循环中将c保存为ac:

A = np.zeros((N,N,N,N))
ab = 0
for a in range(N):
    for b in range(N):
        ab += 1
        cd  = 0
        for c in range(N):
            ac = a + c
            for d in range(N):
                cd += 1
                if (ab >= cd and ac >= b+d):
                    A[a,b,c,d] = A[c,d,a,b] = f(a,b,c,d)
                    A[b,a,d,c] = A[d,c,b,a] = -A[a,b,c,d]

使用此代码,我们创建了112个组合,因此与您的方法相比,重复次数更少,但可能仍会有一些优化.

更新

这是我用来计算创建组合数的代码:

from itertools import product

N = 3
ab = 0

all_combinations = set(product(range(N), repeat=4))
zeroes = ((x, x, y, y) for x, y in product(range(N), repeat=2))
calculated = list()

for a in range(N):
    for b in range(N):
        ab += 1
        cd = 0
        for c in range(N):
            ac = a + c
            for d in range(N):
                cd += 1
                if (ab >= cd and ac >= b + d) and not (a == b and c == d):
                    calculated.append((a, b, c, d))
                    calculated.append((c, d, a, b))
                    calculated.append((b, a, d, c))
                    calculated.append((d, c, b, a))

missing = all_combinations - set(calculated) - set(zeroes)

if missing:
    print "Some sets weren't calculated :"
    for s in missing:
        print s
else:
    print "All cases were covered"
    print len(calculated)

有和没有(a == b和c == d),数字下降到88.

标签:python,permutation,symmetry
来源: https://codeday.me/bug/20190705/1392018.html