如何从SAGE加速因子功能

时间:2014-08-20 23:20:59

标签: python sage

我写了一个方法来获得GF(2 ^ pp)中的多项式p \的符号系数[X0,...,X_ {nvars-1}]转换为GF(2)[t] 。例如,对于pp = 2.多项式p = X0 * X1 =(x_00 + x_01 * t)*(x_10 + x_11 * t)=(x_00 * x_10 + x_01 * x_11)+(x_01 * x_11 + x_01 * x_10 + x_00 * x_11)* t然后方法得到[(x_00 * x_10 + x_01 * x_11),(x_01 * x_11 + x_01 * x_10 + x_00 * x_11)]。我的问题是pp和nvars的数量很高。我已经把时间和指令需要更多的时间是p.factor()。然后我的问题是我将如何加速该代码?

pp = 2
nvars = 2
k.<t>=GF(2^pp)
vars_GF = []
vars_gf2 = []
for i in range(nvars):
    vars_GF.append(var("X"+str(i)))
    for j in range(pp):
    vars_gf2.append(var("x"+str(i)+str(j)))
vars_GF = None        
vars_GF = ["X%d"%i for i in range(nvars)]  
R=PolynomialRing(k,names=vars_gf2)
P=PolynomialRing(k,names=vars_GF)
p=P.random_element(degree=2)
subsvar=[sum((t^i*R.gen(i+pp*j) for i in range(pp))) for j in range(nvars)]        
p = p(subsvar)
print type(p)
var("t")
timeit('SR(p)')
p = SR(p)
p = p.factor()
timeit('p.factor()')
p = p.collect(t)
timeit('p.collect(t)')
print "p",p
print p.coefficients()

1 个答案:

答案 0 :(得分:2)

似乎你只想在变量t中获得x_i_j的幂次系数作为多项式,所以我不清楚为什么你需要考虑因素。

建议:使用适当的多项式环,而不是符号环。

sage: q = 2
sage: nvars = 2
sage: k.<t> = GF(2^q)
sage: x_i = []
sage: x_i_j = []
sage: for i in range(nvars):
....:     x_i.append(var('x_'+str(i)))
....:     for j in range(q):
....:         x_i_j.append(var('x_'+str(i)+'_'+str(j)))
....:         
sage: P = PolynomialRing(k,names=x_i)
sage: R = PolynomialRing(k,names=x_i_j)
sage: S = PolynomialRing(R,'t')
sage: subsvar = [sum((t^i*R.gen(i+q*j) for i in range(q))) for j in range(nvars)]

用法:

sage: p = P.random_element(degree=2)
sage: p
(t)*x_0^2 + (t + 1)*x_1^2 + (t + 1)*x_0 + (t + 1)*x_1
sage: pp = S(str(p(subsvar)))
sage: pp.coefficients()
[x_0_1^2 + x_1_0^2 + x_0_0 + x_0_1 + x_1_0 + x_1_1, x_0_0^2 + x_1_0^2 + x_1_1^2 + x_0_0 + x_1_0]

注意将环R中的多项式转换为环S中的多项式的技巧:将其设为字符串并使S读取字符串。

使用您的示例进行说明:

sage: p = P('x_0 * x_1')
sage: p
x_0*x_1
sage: pp = p(subsvar)
sage: pp
x_0_0*x_1_0 + (t)*x_0_1*x_1_0 + (t)*x_0_0*x_1_1 + (t + 1)*x_0_1*x_1_1
sage: ppp = S(str(pp))
sage: ppp
(x_0_1*x_1_0 + x_0_0*x_1_1 + x_0_1*x_1_1)*t + x_0_0*x_1_0 + x_0_1*x_1_1
sage: ppp.coefficients()
[x_0_0*x_1_0 + x_0_1*x_1_1, x_0_1*x_1_0 + x_0_0*x_1_1 + x_0_1*x_1_1]

以下是我为合并操作获得的时间:

sage: timeit('S(str(p(subsvar))).coefficients()')
625 loops, best of 3: 1.31 ms per loop

作为参考,我正在使用Sage 6.3。

sage: version()
'Sage Version 6.3, Release Date: 2014-08-10'