如何在Sage

时间:2018-11-18 20:15:24

标签: python sage

我正在尝试将SageMath用于涉及大量布尔多项式操纵的事情。

以下是系数向量是的一些示例:

 x0*x1*x2 + 1 has coefficient vector 10000001
  x1 + x0 + 1 has coefficient vector 11100000  
      x1 + x0 has coefficient vector 01100000

(x0是最低有效位。)

问题在于Sage的API似乎不鼓励直接操作单项式或系数向量,这可能是因为Sage的内部使用的数据结构是ZDD而不是位数组。

sage: P
x0*x1*x2 + x0*x1 + x0*x2 + x0 + x1*x2 + x1 + x2 + 1
sage: list(P.set())
[x0*x1*x2, x0*x1, x0*x2, x0, x1*x2, x1, x2, 1]
sage: P.terms()
[x0*x1*x2, x0*x1, x0*x2, x0, x1*x2, x1, x2, 1]

在此代码中,问题似乎在于,字节序与人们期望的相反。 x0是最低有效位。

问题实际上不止于此。例如:

#!/usr/bin/env python
from sage.all import *
from sage.crypto.boolean_function import BooleanFunction

# "input_str" is a truth table. 
# Returns a polynomial that has that truth table.
def truth_str_to_poly(input_str):
    # assumes that the length of input_str is a power of two
    num_vars = int(log(len(input_str),2))
    truth_table = []
    # convert string to list of ints expected by BooleanFunction 
    for i in list(input_str):
        truth_table.append(int(i))
    B = BooleanFunction(truth_table)
    P = B.algebraic_normal_form()
    return P

# Return the polynomial with coefficient vector 1,1,...,1.
# (This is neccessary because we can't directly manipulate coef. vectors.)
def super_poly(num_vars):
    input_str = ["0"]*(2**num_vars)
    input_str[0] = "1"
    input_str = "".join(input_str)
    return truth_str_to_poly(input_str)

# Return the coefficient vector of P.
# This is the function that is broken.
def poly_to_coef_str(P, num_vars):
    res = ""
    #for i in super_poly(num_vars).terms():
    for i in list(super_poly(num_vars).set()):
        res += str(P.monomial_coefficient(i))
    return res

num_vars = 3
print(super_poly(num_vars).monomials())

# This should have coefficient vector "01000000" = x0
input_poly = "01010101"
P = truth_str_to_poly(input_poly) # Gives correct result
res = poly_to_coef_str(P, 3)
print(" in:"+input_poly)
print("out:"+res)

输出:

[x0*x1*x2, x0*x1, x0*x2, x0, x1*x2, x1, x2, 1]
 in:01010101
out:00010000

这意味着它不仅仅使字节序错误,而且以某种方式不一致地对待变量的位置值。

有更好的方法吗?

0 个答案:

没有答案