code stringlengths 17 6.64M |
|---|
class IfThen():
def __init__(self, ifpart, thenpart, supposed_to_be_valid=True):
self.ifpart = [Polynomial(p) for p in ifpart]
self.thenpart = [Polynomial(p) for p in thenpart]
self.supposedToBeValid = supposed_to_be_valid
def __str__(self):
return ((('If(AND(' + ', '.join((f... |
def if_then(i, t, supposed_to_be_valid=True):
return IfThen(i, t, supposed_to_be_valid)
|
def declare_ring(blocks, context=None):
'\n Declare Ring is the preferred function to create a ring and declare a variable scheme,\n the number of variables is automatically determined, usually you pass globals() as context\n argument to store the ring and the variable mapping.\n\n EXAMPLES::\n\n ... |
def declare_block_scheme(blocks, context):
start = 0
block_starts = []
for b in blocks:
if start:
block_starts.append(start)
if isinstance(b, str):
context[b] = context['internalVariable'](start)
start = (start + 1)
else:
b.register(s... |
def main():
r = Ring(1000)
ablock = AlternatingBlock(['a', 'b', 'c'], 100)
declare_block_scheme([ablock], globals())
for i in range(10):
print(r.variable(i))
print(list(ablock))
declare_block_scheme([Block(var_name='x', size=100), HigherOrderBlock('y', (3, 4, 11, 2)), AlternatingBlock(... |
class CNFEncoder():
def __init__(self, r, random_seed=16):
self.random_generator = Random(random_seed)
self.one_set = r.one().set()
self.empty_set = r.zero().set()
self.r = r
def zero_blocks(self, f):
'\n Divide the zero set of f into blocks.\n\n TESTS::... |
class CryptoMiniSatEncoder(CNFEncoder):
group_counter = 0
def dimacs_encode_polynomial(self, p):
'\n\n TESTS::\n\n sage: from sage.rings.polynomial.pbori import *\n sage: d=dict()\n sage: r = declare_ring(["x", "y", "z"], d)\n sage: from sage.rings.p... |
def easy_linear_polynomials(p):
'\n Get linear polynomials implied by given polynomial.\n\n EXAMPLES::\n\n sage: from sage.rings.polynomial.pbori.frontend import x\n sage: from sage.rings.polynomial.pbori.easy_polynomials import easy_linear_polynomials\n sage: easy_linear_polynomials(x(... |
def easy_linear_polynomials_via_interpolation(p):
'\n Get linear polynomials implied by given polynomial using interpolation of the variety.\n\n TESTS::\n\n sage: from sage.rings.polynomial.pbori.frontend import x\n sage: from sage.rings.polynomial.pbori.easy_polynomials import easy_linear_pol... |
def _fglm(I, from_ring, to_ring):
'\n Unchecked variant of fglm\n '
vec = BoolePolynomialVector(I)
return FGLMStrategy(from_ring, to_ring, vec).main()
|
def fglm(I, from_ring, to_ring):
"\n Convert *reduced* Groebner Basis in ``from_ring`` to a GroebnerBasis\n in ``to_ring``.\n\n It acts independent of the global ring, which is restored at the end of the\n computation.\n\n TESTS::\n\n sage: from sage.rings.polynomial.pbori import *\n ... |
def vars_real_divisors(monomial, monomial_set):
'\n Return all elements of ``monomial_set``, which result multiplied by a variable in monomial.\n\n EXAMPLES::\n\n sage: from sage.rings.polynomial.pbori.pbori import *\n sage: from sage.rings.polynomial.pbori.PyPolyBoRi import OrderCode\n ... |
def m_k_plus_one(completed_elements, variables):
'\n Calculate `m_{k+1}` from the FGLM algorithm.\n\n Calculate `m_{k+1}` from the FGLM algorithm as described in Wichmann [Wich1997]_.\n\n .. NOTE::\n\n It would be nice to be able to efficiently extract the smallest term of a polynomial.\n\n EXA... |
def block_scheme_names(blocks):
'\n Helper for Singular interface.\n '
context = {}
from .blocks import declare_block_scheme
declare_block_scheme(blocks, context)
return list(context.keys())
|
def polybori_start(global_context):
def declare_ring(blocks, context=None):
if (context is None):
context = global_context
return orig_declare_ring(blocks, context)
declare_ring.__doc__ = orig_declare_ring.__doc__
global_context['declare_ring'] = declare_ring
print((ipbnam... |
def get_options_from_function(f):
(argnames, varargs, varopts, defaults) = getargspec(f)[:4]
return dict(zip(argnames[(- len(defaults)):], defaults))
|
def filter_oldstyle_options(**options):
filtered = {}
for key in options:
newkey = key
for prefix in ['use_', 'opt_allow_', 'opt_']:
newkey = newkey.replace(prefix, '')
filtered[newkey] = options[key]
return filtered
|
def filter_newstyle_options(func, **options):
allowed = get_options_from_function(func).keys()
filtered = {}
for key in options.keys():
for prefix in ['', 'use_', 'opt_', 'opt_allow_']:
if ((prefix + key) in allowed):
filtered[(prefix + key)] = options[key]
return f... |
def want_interpolation_gb(G):
if ((not G) or (G[0].ring().get_order_code() != OrderCode.lp) or (len(G) != 1)):
return False
p = Polynomial(G[0])
return (not ((p.lead_deg() <= 1) or (p.set().n_nodes() > 1000)))
|
def ll_is_good(I):
lex_lead = set()
for p in I:
if (not p.is_zero()):
m = p.lex_lead()
if (m.deg() == 1):
lex_lead.add(next(iter(m.variables())).index())
if (len(lex_lead) >= (0.8 * len(I))):
uv = used_vars_set(I).deg()
if (len(lex_lead) > (0... |
def ll_heuristic(d):
d = copy(d)
I = d['I']
if (('llfirstonthefly' not in d) and ('llfirst' not in d)):
hint = ll_is_good(I)
if hint:
d[hint] = True
return d
|
def change_order_heuristic(d):
d_orig = d
d = copy(d)
I = d['I']
if (not I):
return d
switch_table = {OrderCode.lp: OrderCode.dp_asc, OrderCode.dlex: OrderCode.dp_asc}
if ('other_ordering_first' not in d):
code = next(iter(I)).ring().get_order_code()
if (code in switch_... |
def interpolation_gb_heuristic(d):
d = copy(d)
I = d['I']
if ((not d.get('other_ordering_opts', False)) and want_interpolation_gb(I)):
d['interpolation_gb'] = True
d['other_ordering_first'] = False
return d
|
def linear_algebra_heuristic(d):
d = copy(d)
I = d['I']
def want_la():
if (not I):
return False
n_used_vars = None
bound = None
if next(iter(I)).ring().has_degree_order():
new_bound = 200
n_used_vars = used_vars_set(I, bound=new_bound).d... |
def trivial_heuristic(d):
return d
|
class HeuristicalFunction():
def __call__(self, *args, **kwds):
complete_dict = copy(kwds)
heuristic = True
try:
heuristic = complete_dict['heuristic']
except KeyError:
pass
for (k, v) in zip(self.argnames, args):
complete_dict[k] = v
... |
def with_heuristic(heuristic_function):
def make_wrapper(f):
wrapped = HeuristicalFunction(f, heuristic_function)
wrapped.__name__ = f.__name__
return wrapped
return make_wrapper
|
def clean_polys_pre(I):
wrap = (Polynomial(p) for p in I)
return (list(set((p for p in wrap if (not p.is_zero())))), None)
|
def gb_with_pre_post_option(option, pre=None, post=None, if_not_option=tuple(), default=False):
def make_wrapper(f):
def wrapper(I, **kwds):
prot = kwds.get('prot', False)
for o in if_not_option:
if (((o in kwds) and kwds[o]) or ((o not in kwds) and groebner_basis... |
def redsb_post(I, state):
if (not I):
return []
return I.minimalize_and_tail_reduce()
|
def minsb_post(I, state):
if (not I):
return []
return I.minimalize()
|
def invert_all(I):
return [p.map_every_x_to_x_plus_one() for p in I]
|
def invert_all_pre(I):
return (invert_all(I), None)
|
def invert_all_post(I, state):
return invert_all(I)
|
def llfirst_pre(I, prot):
(eliminated, llnf, I) = eliminate(I, on_the_fly=False, prot=prot)
return (I, eliminated)
|
def ll_constants_pre(I):
ll_res = []
while (len([p for p in I if ((p.lex_lead_deg() == 1) and (p + p.lex_lead()).constant())]) > 0):
I_new = []
ll = []
leads = set()
for p in I:
if (p.lex_lead_deg() == 1):
l = p.lead()
if ((not (l in ... |
def variety_size_from_gb(I):
'\n TESTS::\n\n sage: from sage.rings.polynomial.pbori import Ring, Monomial, Polynomial\n sage: from sage.rings.polynomial.pbori.gbcore import variety_size_from_gb\n sage: r = Ring(100)\n sage: x = r.variable\n sage: variety_size_from_gb([])\n ... |
def other_ordering_pre(I, option_set, kwds):
"\n TESTS::\n\n sage: from sage.rings.polynomial.pbori.blocks import declare_ring\n sage: r = declare_ring(['x0', 'x1', 'x2', 'x3', 'x4'], globals())\n sage: id = [x1*x3 + x1 + x2*x3 + x3 + x4, x0*x3 + x0 + x1*x2 + x2 + 1, x1*x3 + x1*x4 + x3*x4... |
def llfirstonthefly_pre(I, prot):
(eliminated, llnf, I) = eliminate(I, on_the_fly=True)
return (I, eliminated)
|
def gauss_on_linear_pre(I, prot):
return (gauss_on_linear(I), None)
|
def easy_linear_polynomials_pre(I):
res = []
for p in I:
res.append(p)
res.extend(easy_linear_polynomials(p))
return (list(set(res)), None)
|
def llfirst_post(I, state, prot, kwds):
eliminated = state
for p in I:
if p.is_one():
return [p]
if eliminated:
I = list(chain(I, eliminated))
kwds = copy(kwds)
kwds.update(dict(llfirst=False, llfirstonthefly=False, ll_constants=False, deg_bound=False, other_ord... |
def ll_constants_post(I, state):
eliminated = state
for p in I:
if p.is_one():
return [p]
if eliminated:
I = list(chain(I, eliminated))
return I
|
def result_to_list_post(I, state):
return list(I)
|
def fix_deg_bound_post(I, state):
if isinstance(I, GroebnerStrategy):
return I.all_generators()
return I
|
def incremental_pre(I, prot, kwds):
def sort_key(p):
p = Polynomial(p)
return (p.navigation().value(), (- p.deg()))
I = sorted(I, key=sort_key)
inc_sys = []
kwds = copy(kwds)
kwds['incremental'] = False
for p in I[:(- 1)]:
inc_sys.append(p)
inc_sys = groebner_b... |
def eliminate_identical_variables_pre(I, prot):
changed = True
ll_system = []
treated_linears = set()
while changed:
changed = False
rules = {}
for p in I:
t = (p + p.lead())
if (p.lead_deg() == 1):
l = p.lead()
if (l in t... |
@gb_with_pre_post_option('clean_arguments', pre=clean_polys_pre, default=True)
@gb_with_pre_post_option('easy_linear_polynomials', pre=easy_linear_polynomials_pre, default=True)
@gb_with_pre_post_option('result_to_list', post=result_to_list_post, default=True)
@with_heuristic(interpolation_gb_heuristic)
@gb_with_pre_... |
def build_groebner_basis_doc_string():
additional_options_from_buchberger = filter_oldstyle_options(**get_options_from_function(symmGB_F2_python))
for k in list(additional_options_from_buchberger):
if (k in groebner_basis.options):
del additional_options_from_buchberger[k]
groebner_bas... |
def _test():
import doctest
doctest.testmod()
|
def reencode_blocks(block_str):
return str(block_str).replace(',', '_')
|
def parse_blocks(block_str, data):
if (block_str == AUTO):
return data.block_start_hints
if (block_str == SINGLE):
return []
return [int(i) for i in block_str.split(',')]
|
def load_ref_raw(s):
s = re.sub('data/', '', s)
s = re.sub('data\\.', '', s)
s = re.sub('\\.py', '', s)
s = re.sub('\\.', '/', s)
ref_file = (('ref/' + s) + '.ref')
with open(ref_file) as res_f:
res = res_f.read()
return res
|
def load_ref(s, ordering='lp', blocks=SINGLE):
return load_ref_gz_uu(s, ordering, blocks)
|
def ordering_suffix(o, blocks=None):
if (o == 'lp'):
return ''
if re.match('block', o):
return ((('.' + o) + '_') + reencode_blocks(blocks))
return ('.' + o)
|
def number_of_declared_vars(data):
try:
return data.number_of_declared_vars
except AttributeError:
return data.r.ngens()
|
def load_ref_gz_uu(s, o, b):
s = re.sub('data/', '', s)
s = re.sub('data\\.', '', s)
s = re.sub('\\.py', '', s)
s = re.sub('\\.', '/', s)
ref_file = ((('ref/' + s) + ordering_suffix(o, b)) + '.ref.gz.uu')
res = StringIO()
uu.decode(ref_file, res)
res = res.getvalue()
res = StringIO... |
def convert_refs(ref_file_orig):
content = open(ref_file_orig).read()
buf_out = StringIO()
zipped = gzip.GzipFile(filename=ref_file_orig, mode='w', fileobj=buf_out)
zipped.write(content)
zipped.close()
val = buf_out.getvalue()
with open((ref_file_orig + '.gz.uu'), 'w') as out:
uu.e... |
def dyn_generate(content, name):
module = ModuleType(name)
import_header = 'from .PyPolyBoRi import Variable,Monomial, Polynomial, Ring, OrderCode\nfrom itertools import chain\nfrom .blocks import AlternatingBlock,Block,AdderBlock,if_then,HigherOrderBlock,declare_ring as orig_declare_ring,declare_block_scheme... |
def clean_data(data):
for a in dir(data):
if (a != 'r'):
delattr(data, a)
|
def load_data(file_name, base_dir='./'):
in_file = file_name
if (not re.match('^data', in_file)):
in_file = ('data/' + in_file)
in_file = re.sub('.py$', '', in_file)
in_file = re.sub('\\.', '/', in_file)
in_file = (in_file + '.py')
with open((base_dir + in_file)) as f:
in_file ... |
def load_file(file_name):
with open(file_name) as f:
in_file = f.read()
return dyn_generate(in_file, 'pb_data')
|
def dense_system(I):
I = (Polynomial(p) for p in I)
I = (p for p in I if (not p.is_zero()))
for p in I:
d = p.deg()
if (d == 1):
continue
try:
if (len(p) > ((2 ** d) + 5)):
return True
except OverflowError:
return True
... |
def gauss_on_linear(I):
I = (Polynomial(p) for p in I)
linear = []
non_linear = []
for p in I:
if p.is_zero():
continue
if (p.deg() <= 1):
linear.append(p)
else:
non_linear.append(p)
if (not linear):
return non_linear
linear =... |
def add_up_poly_list(l, init):
v = BoolePolynomialVector()
for p in l:
v.append(p)
return add_up_polynomials(v, init)
|
def bench_interpolate(degree, nvariables, points):
c = points
h = (len(points) / 2)
terms = set(c.terms())
part1 = generator.sample(terms, h)
part1 = add_up_poly_list(part1, Polynomial(c.ring().zero()))
part2 = (c + part1)
p = part1
q = part2
assert part1.set().intersect(part2).emp... |
def nf_lex_points(f, p):
f = Polynomial(f)
p = BooleSet(p)
z = f.zeros_in(p)
return interpolate_smallest_lex(z, p.diff(z))
|
def gen_random_o_z(points, points_p):
k = generator.randrange((len(points) + 1))
ones = generator.sample(points, k)
vec = BoolePolynomialVector()
for p in ones:
vec.append(p)
ones = add_up_polynomials(vec, Polynomial(points_p.ring().zero()))
return interpolate_smallest_lex(points_p.set... |
def variety_lex_leading_terms(points, variables):
assert isinstance(points, BooleSet), 'Points needs to be a BooleSet'
ring = variables.ring()
standards = BooleSet(ring.zero())
points_tuple = tuple(points)
myvars_div = variables.divisors()
if (points != myvars_div):
standards = BooleSe... |
def lex_groebner_basis_points(points, variables):
leads = variety_lex_leading_terms(points, variables)
return [(nf_lex_points(l, points) + l) for l in leads]
|
def lex_groebner_basis_for_polynomial_via_variety(p):
variables = p.vars_as_monomial()
return lex_groebner_basis_points(p.zeros_in(variables.divisors()), variables)
|
def interred(l, completely=False):
'\n Compute a new generating system (g1, ...,gn),\n spanning the same ideal modulo field equations.\n\n The system is interreduced: For i!=j:\n gi.lead() does not divide any leading term of gj.\n\n If completely is set to ``True``, then also terms in the\n tail... |
def combine(reductors, p, reduce=None):
p_nav = p.navigation()
assert (p_nav.value() < reductors.navigation().value())
p_else = BooleSet(p_nav.else_branch(), p.ring())
if reduce:
p_else = reduce(p_else, reductors)
return if_then_else(p_nav.value(), reductors, p_else)
|
def llredsb_Cudd_style(polys):
if polys:
reductors = Polynomial(polys[0].ring().one()).set()
else:
reductors = None
linear_lead = sorted(polys, key=lead_index, reverse=True)
assert (len(set((p.lex_lead() for p in linear_lead))) == len(polys))
assert (not any((p.constant() for p in ... |
def ll_encode(polys, reduce=False, prot=False, reduce_by_linear=True):
polys = [Polynomial(p) for p in polys]
linear_lead = sorted(polys, key=lead_index, reverse=True)
assert (len(set((p.lex_lead() for p in linear_lead))) == len(polys))
assert (not any((p.constant() for p in polys)))
assert (len([... |
def eliminate(polys, on_the_fly=False, prot=False, reduction_function=None, optimized=True):
'\n There exists an optimized variant, which reorders the variable in a different ring.\n '
polys = [Polynomial(p) for p in polys]
rest = []
linear_leads = []
linear_leading_monomials = set()
for... |
def construct_map_by_indices(to_ring, idx_mapping):
v = BoolePolynomialVector(((max(idx_mapping.keys()) + 1) * [to_ring.zero()]))
for (from_idx, to_idx) in idx_mapping.items():
val = to_ring.variable(to_idx)
v[from_idx] = val
return v
|
def eliminate_ll_ranked(ll_system, to_reduce, reduction_function=ll_red_nf_noredsb, reduce_ll_system=False, prot=False):
assert ll_system
from_ring = ll_system[0].ring()
ll_ranks = rank(ll_system)
add_vars = set(used_vars_set(to_reduce).variables()).difference(ll_ranks.keys())
for v in add_vars:
... |
class RingMap():
'\n Define a mapping between two rings by common variable names.\n\n TESTS::\n\n sage: from sage.rings.polynomial.pbori.pbori import *\n sage: from sage.rings.polynomial.pbori.blocks import declare_ring, Block\n sage: to_ring = declare_ring([Block("x", 10)], globals())\... |
class GeneratorLimitExceeded(Exception):
'\n Docstring for GeneratorLimitExceeded\n '
def __init__(self, strat):
self.strat = strat
|
def pkey(p):
return (p[0], len(p))
|
def build_and_print_matrices(v, strat):
'\n Old solution using PIL, the currently used implementation is done in C++\n and plots the same matrices, as being calculated\n '
treated = BooleSet()
v = list(v)
rows = 0
polys_in_mat = []
if (not v):
return
while v:
rows ... |
def multiply_polynomials(l, ring):
'\n\n TESTS::\n\n sage: from sage.rings.polynomial.pbori import *\n sage: r=Ring(1000)\n sage: x=r.variable\n sage: from sage.rings.polynomial.pbori.nf import multiply_polynomials\n sage: multiply_polynomials([x(3), x(2)+x(5)*x(6), x(0), x(0... |
def build_and_print_matrices_deg_colored(v, strat):
'\n old PIL solution using a different color for each degree\n '
if (not v):
return
treated = BooleSet()
v = list(v)
rows = 0
polys_in_mat = []
while v:
rows = (rows + 1)
p = v[0]
v = v[1:]
fo... |
def high_probability_polynomials_trick(p, strat):
lead_deg = p.lead_deg()
if (lead_deg <= 4):
return
ring = p.ring()
factor = multiply_polynomials(easy_linear_factors(p), ring)
p = (p / factor)
lead_deg = p.lead_deg()
if (lead_deg <= 3):
return
if (lead_deg > 9):
... |
def symmGB_F2_python(G, deg_bound=1000000000000, over_deg_bound=0, use_faugere=False, use_noro=False, opt_lazy=True, opt_red_tail=True, max_growth=2.0, step_factor=1.0, implications=False, prot=False, full_prot=False, selection_size=1000, opt_exchange=True, opt_allow_recursion=False, ll=False, opt_linear_algebra_in_l... |
def GPS(G, vars_start, vars_end):
def step(strat, trace, var, val):
print('plugin: ', var, val)
print('npairs', strat.npairs())
strat = GroebnerStrategy(strat)
print('npairs', strat.npairs())
strat.add_generator_delayed(Polynomial((Monomial(Variable(var, strat.r)) + val)))... |
def GPS_with_proof_path(G, proof_path, deg_bound, over_deg_bound):
def step(strat, trace, proof_path, pos, val):
print(proof_path)
print('plugin: ', pos, val, proof_path[pos])
print('npairs', strat.npairs())
strat = GroebnerStrategy(strat)
print('npairs', strat.npairs())
... |
def GPS_with_suggestions(G, deg_bound, over_deg_bound, opt_lazy=True, opt_red_tail=True, initial_bb=True):
def step(strat, trace, var, val):
print(trace)
plug_p = (val + var)
print('plugin: ', len(trace), plug_p)
trace = (trace + [plug_p])
strat = GroebnerStrategy(strat)
... |
def GPS_with_non_binary_proof_path(G, proof_path, deg_bound, over_deg_bound):
def step(strat, trace, proof_path, pos, choice):
print(proof_path)
print('plugin: ', pos)
print('npairs', strat.npairs())
strat = GroebnerStrategy(strat)
print('npairs', strat.npairs())
p... |
def symmGB_F2_C(G, opt_exchange=True, deg_bound=1000000000000, opt_lazy=False, over_deg_bound=0, opt_red_tail=True, max_growth=2.0, step_factor=1.0, implications=False, prot=False, full_prot=False, selection_size=1000, opt_allow_recursion=False, use_noro=False, use_faugere=False, ll=False, opt_linear_algebra_in_last_... |
def normal_form(poly, ideal, reduced=True):
"\n Simple normal form computation of a polynomial against an ideal.\n\n TESTS::\n\n sage: from sage.rings.polynomial.pbori import declare_ring, normal_form\n sage: r=declare_ring(['x','y'], globals())\n sage: normal_form(x+y, [y],reduced=Tru... |
def _test():
import doctest
doctest.testmod()
|
def to_fast_pickable(l):
'\n Convert a list of polynomials into a builtin Python value, which is fast pickable and compact.\n\n INPUT:\n\n - a list of Boolean polynomials\n\n OUTPUT:\n\n It is converted to a tuple consisting of\n - codes referring to the polynomials\n - list of conversions of... |
def from_fast_pickable(l, r):
'\n Undo the operation :func:`to_fast_pickable`.\n\n The first argument is an object created by :func:`to_fast_pickable`.\n\n For the specified format, see the documentation of :func:`to_fast_pickable`.\n The second argument is ring, in which this polynomial should be cre... |
def _calculate_gb_with_keywords(args):
(I, kwds_as_single_arg) = args
return groebner_basis(I, **kwds_as_single_arg)
|
def _decode_polynomial(code):
return from_fast_pickable(*code)[0]
|
def _encode_polynomial(poly):
return (to_fast_pickable([poly]), poly.ring())
|
def pickle_polynomial(self):
return (_decode_polynomial, (_encode_polynomial(self),))
|
def pickle_bset(self):
return (BooleSet, (Polynomial(self),))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.