-
Notifications
You must be signed in to change notification settings - Fork 121
/
__init__.py
298 lines (257 loc) · 11.5 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import logging
from sage.all import QQ
from sage.all import Sequence
from sage.all import ZZ
from sage.all import gcd
from sage.all import matrix
from sage.all import solve
from sage.all import var
DEBUG_ROOTS = None
def log_lattice(L):
"""
Logs a lattice.
:param L: the lattice
"""
for row in range(L.nrows()):
r = ""
for col in range(L.ncols()):
if L[row, col] == 0:
r += "_ "
else:
r += "X "
logging.debug(r)
def create_lattice(pr, shifts, bounds, order="invlex", sort_shifts_reverse=False, sort_monomials_reverse=False):
"""
Creates a lattice from a list of shift polynomials.
:param pr: the polynomial ring
:param shifts: the shifts
:param bounds: the bounds
:param order: the order to sort the shifts/monomials by
:param sort_shifts_reverse: set to true to sort the shifts in reverse order
:param sort_monomials_reverse: set to true to sort the monomials in reverse order
:return: a tuple of lattice and list of monomials
"""
logging.debug(f"Creating a lattice with {len(shifts)} shifts ({order = }, {sort_shifts_reverse = }, {sort_monomials_reverse = })...")
if pr.ngens() > 1:
pr_ = pr.change_ring(ZZ, order=order)
shifts = [pr_(shift) for shift in shifts]
monomials = set()
for shift in shifts:
monomials.update(shift.monomials())
shifts.sort(reverse=sort_shifts_reverse)
monomials = sorted(monomials, reverse=sort_monomials_reverse)
L = matrix(ZZ, len(shifts), len(monomials))
for row, shift in enumerate(shifts):
for col, monomial in enumerate(monomials):
L[row, col] = shift.monomial_coefficient(monomial) * monomial(*bounds)
monomials = [pr(monomial) for monomial in monomials]
return L, monomials
def reduce_lattice(L, delta=0.8):
"""
Reduces a lattice basis using a lattice reduction algorithm (currently LLL).
:param L: the lattice basis
:param delta: the delta parameter for LLL (default: 0.8)
:return: the reduced basis
"""
logging.debug(f"Reducing a {L.nrows()} x {L.ncols()} lattice...")
return L.LLL(delta)
def reconstruct_polynomials(B, f, modulus, monomials, bounds, preprocess_polynomial=lambda x: x, divide_gcd=True):
"""
Reconstructs polynomials from the lattice basis in the monomials.
:param B: the lattice basis
:param f: the original polynomial (if set to None, polynomials will not be divided by f if possible)
:param modulus: the original modulus
:param monomials: the monomials
:param bounds: the bounds
:param preprocess_polynomial: a function which preprocesses a polynomial before it is added to the list (default: identity function)
:param divide_gcd: if set to True, polynomials will be pairwise divided by their gcd if possible (default: True)
:return: a list of polynomials
"""
divide_original = f is not None
modulus_bound = modulus is not None
logging.debug(f"Reconstructing polynomials ({divide_original = }, {modulus_bound = }, {divide_gcd = })...")
polynomials = []
for row in range(B.nrows()):
norm_squared = 0
w = 0
polynomial = 0
for col, monomial in enumerate(monomials):
if B[row, col] == 0:
continue
norm_squared += B[row, col] ** 2
w += 1
assert B[row, col] % monomial(*bounds) == 0
polynomial += B[row, col] * monomial // monomial(*bounds)
# Equivalent to norm >= modulus / sqrt(w)
if modulus_bound and norm_squared * w >= modulus ** 2:
logging.debug(f"Row {row} is too large, ignoring...")
continue
polynomial = preprocess_polynomial(polynomial)
if divide_original and polynomial % f == 0:
logging.debug(f"Original polynomial divides reconstructed polynomial at row {row}, dividing...")
polynomial //= f
if divide_gcd:
for i in range(len(polynomials)):
g = gcd(polynomial, polynomials[i])
# TODO: why are we only allowed to divide out g if it is constant?
if g != 1 and g.is_constant():
logging.debug(f"Reconstructed polynomial has gcd {g} with polynomial at {i}, dividing...")
polynomial //= g
polynomials[i] //= g
if polynomial.is_constant():
logging.debug(f"Polynomial at row {row} is constant, ignoring...")
continue
if DEBUG_ROOTS is not None:
logging.debug(f"Polynomial at row {row} roots check: {polynomial(*DEBUG_ROOTS)}")
polynomials.append(polynomial)
logging.debug(f"Reconstructed {len(polynomials)} polynomials")
return polynomials
def find_roots_univariate(x, polynomial):
"""
Returns a generator generating all roots of a univariate polynomial in an unknown.
:param x: the unknown
:param polynomial: the polynomial
:return: a generator generating dicts of (x: root) entries
"""
if polynomial.is_constant():
return
for root in polynomial.roots(multiplicities=False):
if root != 0:
yield {x: int(root)}
def find_roots_gcd(pr, polynomials):
"""
Returns a generator generating all roots of a polynomial in some unknowns.
Uses pairwise gcds to find trivial roots.
:param pr: the polynomial ring
:param polynomials: the reconstructed polynomials
:return: a generator generating dicts of (x0: x0root, x1: x1root, ...) entries
"""
if pr.ngens() != 2:
return
logging.debug("Computing pairwise gcds to find trivial roots...")
x, y = pr.gens()
for i in range(len(polynomials)):
for j in range(i):
g = gcd(polynomials[i], polynomials[j])
if g.degree() == 1 and g.nvariables() == 2 and g.constant_coefficient() == 0:
# g = ax + by
a = int(g.monomial_coefficient(x))
b = int(g.monomial_coefficient(y))
yield {x: b, y: a}
yield {x: -b, y: a}
def find_roots_groebner(pr, polynomials):
"""
Returns a generator generating all roots of a polynomial in some unknowns.
Uses Groebner bases to find the roots.
:param pr: the polynomial ring
:param polynomials: the reconstructed polynomials
:return: a generator generating dicts of (x0: x0root, x1: x1root, ...) entries
"""
# We need to change the ring to QQ because groebner_basis is much faster over a field.
# We also need to change the term order to lexicographic to allow for elimination.
gens = pr.gens()
s = Sequence(polynomials, pr.change_ring(QQ, order="lex"))
while len(s) > 0:
G = s.groebner_basis()
logging.debug(f"Sequence length: {len(s)}, Groebner basis length: {len(G)}")
if len(G) == len(gens):
logging.debug(f"Found Groebner basis with length {len(gens)}, trying to find roots...")
roots = {}
for polynomial in G:
vars = polynomial.variables()
if len(vars) == 1:
for root in find_roots_univariate(vars[0], polynomial.univariate_polynomial()):
roots |= root
if len(roots) == pr.ngens():
yield roots
return
logging.debug(f"System is underdetermined, trying to find constant root...")
G = Sequence(s, pr.change_ring(ZZ, order="lex")).groebner_basis()
vars = tuple(map(lambda x: var(x), gens))
for solution_dict in solve([polynomial(*vars) for polynomial in G], vars, solution_dict=True):
logging.debug(solution_dict)
found = False
roots = {}
for i, v in enumerate(vars):
s = solution_dict[v]
if s.is_constant():
if not s.is_zero():
found = True
roots[gens[i]] = int(s) if s.is_integer() else int(s) + 1
else:
roots[gens[i]] = 0
if found:
yield roots
return
return
else:
# Remove last element (the biggest vector) and try again.
s.pop()
def find_roots_resultants(gens, polynomials):
"""
Returns a generator generating all roots of a polynomial in some unknowns.
Recursively computes resultants to find the roots.
:param polynomials: the reconstructed polynomials
:param gens: the unknowns
:return: a generator generating dicts of (x0: x0root, x1: x1root, ...) entries
"""
if len(polynomials) == 0:
return
if len(gens) == 1:
if polynomials[0].is_univariate():
yield from find_roots_univariate(gens[0], polynomials[0].univariate_polynomial())
else:
resultants = [polynomials[0].resultant(polynomials[i], gens[0]) for i in range(1, len(gens))]
for roots in find_roots_resultants(gens[1:], resultants):
for polynomial in polynomials:
polynomial = polynomial.subs(roots)
if polynomial.is_univariate():
for root in find_roots_univariate(gens[0], polynomial.univariate_polynomial()):
yield roots | root
def find_roots_variety(pr, polynomials):
"""
Returns a generator generating all roots of a polynomial in some unknowns.
Uses the Sage variety (triangular decomposition) method to find the roots.
:param pr: the polynomial ring
:param polynomials: the reconstructed polynomials
:return: a generator generating dicts of (x0: x0root, x1: x1root, ...) entries
"""
# We need to change the ring to QQ because variety requires a field.
s = Sequence([], pr.change_ring(QQ))
for polynomial in polynomials:
s.append(polynomial)
I = s.ideal()
dim = I.dimension()
logging.debug(f"Sequence length: {len(s)}, Ideal dimension: {dim}")
if dim == -1:
s.pop()
elif dim == 0:
logging.debug("Found ideal with dimension 0, computing variety...")
for roots in I.variety(ring=ZZ):
yield {k: int(v) for k, v in roots.items()}
return
def find_roots(pr, polynomials, method="groebner"):
"""
Returns a generator generating all roots of a polynomial in some unknowns.
The method used depends on the method parameter.
:param pr: the polynomial ring
:param polynomials: the reconstructed polynomials
:param method: the method to use, can be "groebner", "resultants", or "variety" (default: "groebner")
:return: a generator generating dicts of (x0: x0root, x1: x1root, ...) entries
"""
if pr.ngens() == 1:
logging.debug("Using univariate polynomial to find roots...")
for polynomial in polynomials:
yield from find_roots_univariate(pr.gen(), polynomial)
else:
# Always try this method because it can find roots the others can't.
yield from find_roots_gcd(pr, polynomials)
if method == "groebner":
logging.debug("Using Groebner basis method to find roots...")
yield from find_roots_groebner(pr, polynomials)
elif method == "resultants":
logging.debug("Using resultants method to find roots...")
yield from find_roots_resultants(pr.gens(), polynomials)
elif method == "variety":
logging.debug("Using variety method to find roots...")
yield from find_roots_variety(pr, polynomials)