er2 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- er2/__init__.py +33 -0
- er2/__main__.py +86 -0
- er2/_lazy.py +88 -0
- er2/backends/__init__.py +4 -0
- er2/backends/pari_backend.py +1146 -0
- er2/backends/pari_closures.py +111 -0
- er2/backends/sympy_backend.py +220 -0
- er2/data/pari_functions.csv +1169 -0
- er2/dispatch.py +741 -0
- er2/importer.py +71 -0
- er2/kernel.py +113 -0
- er2/oeis.py +285 -0
- er2/prelude.py +118 -0
- er2/preparser.py +342 -0
- er2/printing.py +276 -0
- er2/runtime/__init__.py +1 -0
- er2/runtime/dirichlet.py +229 -0
- er2/runtime/factorization.py +97 -0
- er2/runtime/finite_field.py +440 -0
- er2/runtime/modular.py +246 -0
- er2/runtime/number_field.py +293 -0
- er2/runtime/numbers.py +214 -0
- er2/runtime/qfb.py +104 -0
- er2/session.py +227 -0
- er2-0.7.0.dist-info/METADATA +292 -0
- er2-0.7.0.dist-info/RECORD +29 -0
- er2-0.7.0.dist-info/WHEEL +4 -0
- er2-0.7.0.dist-info/entry_points.txt +3 -0
- er2-0.7.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1146 @@
|
|
|
1
|
+
"""The PARI backend: number theory through cypari2 (ARCHITECTURE.md §3.7).
|
|
2
|
+
|
|
3
|
+
There is a single ``cypari2.Pari()`` instance. Arguments are converted
|
|
4
|
+
with ``to_pari`` and results with ``from_pari``, so users never receive a
|
|
5
|
+
raw ``cypari2.gen`` unless they ask for one through ``pari.raw``.
|
|
6
|
+
|
|
7
|
+
The functions come from ``er2/data/pari_functions.csv`` (§3.5, D10):
|
|
8
|
+
``PRELUDE`` holds the ``prelude`` rows, which become top-level names, and
|
|
9
|
+
``pari`` gives every ``prelude`` and ``namespace`` row as ``pari.<name>``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import csv
|
|
13
|
+
import functools
|
|
14
|
+
import inspect
|
|
15
|
+
import re
|
|
16
|
+
from fractions import Fraction
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import cypari2
|
|
20
|
+
|
|
21
|
+
from er2 import _lazy
|
|
22
|
+
from er2.runtime.factorization import Factorization
|
|
23
|
+
from er2.runtime.finite_field import FiniteField, FiniteFieldElement
|
|
24
|
+
from er2.runtime.modular import Mod
|
|
25
|
+
from er2.runtime.numbers import Integer, Rational
|
|
26
|
+
from er2.runtime.qfb import Qfb
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"PARI",
|
|
30
|
+
"PariError",
|
|
31
|
+
"PRELUDE",
|
|
32
|
+
"charpoly",
|
|
33
|
+
"dedekind_psi",
|
|
34
|
+
"det",
|
|
35
|
+
"discriminant",
|
|
36
|
+
"expand_series",
|
|
37
|
+
"euler_product",
|
|
38
|
+
"euler_product_series",
|
|
39
|
+
"factor",
|
|
40
|
+
"factor_polynomial",
|
|
41
|
+
"factor_polynomial_mod",
|
|
42
|
+
"ff_charpoly",
|
|
43
|
+
"ff_coefficients",
|
|
44
|
+
"ff_element",
|
|
45
|
+
"ff_lift",
|
|
46
|
+
"ff_minpoly",
|
|
47
|
+
"ff_modulus",
|
|
48
|
+
"ff_polynomial",
|
|
49
|
+
"from_pari",
|
|
50
|
+
"gcd_mod",
|
|
51
|
+
"hadamard_product",
|
|
52
|
+
"hermite_form",
|
|
53
|
+
"isirreducible",
|
|
54
|
+
"inverse",
|
|
55
|
+
"is_modular_polynomial",
|
|
56
|
+
"is_prime_number",
|
|
57
|
+
"is_rational_polynomial",
|
|
58
|
+
"is_rational_univariate",
|
|
59
|
+
"jordan_totient",
|
|
60
|
+
"kernel",
|
|
61
|
+
"minpoly",
|
|
62
|
+
"number_field",
|
|
63
|
+
"number_field_class_group",
|
|
64
|
+
"pari",
|
|
65
|
+
"prime_ideals",
|
|
66
|
+
"prime_power",
|
|
67
|
+
"radical",
|
|
68
|
+
"rank",
|
|
69
|
+
"resultant",
|
|
70
|
+
"set_precision",
|
|
71
|
+
"series_laplace",
|
|
72
|
+
"series_reverse",
|
|
73
|
+
"set_stack",
|
|
74
|
+
"smith_form",
|
|
75
|
+
"solve_linear",
|
|
76
|
+
"to_pari",
|
|
77
|
+
"variable",
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
TABLE_PATH = Path(__file__).resolve().parent.parent / "data/pari_functions.csv"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _SympyOnDemand:
|
|
84
|
+
"""``sympy.X`` imports SymPy on first use (``er2._lazy``).
|
|
85
|
+
|
|
86
|
+
Number theory never needs SymPy; only conversions of SymPy objects and
|
|
87
|
+
of PARI polynomials, series and reals do.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __getattr__(self, name):
|
|
91
|
+
return getattr(_lazy.sympy(), name)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
sympy = _SympyOnDemand()
|
|
95
|
+
|
|
96
|
+
PARI = cypari2.Pari()
|
|
97
|
+
PariError = cypari2.PariError
|
|
98
|
+
|
|
99
|
+
# PARI's default maximum stack is only ~8 MB. The maximum is reserved
|
|
100
|
+
# address space; the stack grows into it only when a computation needs it.
|
|
101
|
+
DEFAULT_STACK_MAX = 2**30
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def set_stack(size=None, max_size=None):
|
|
105
|
+
"""Set the PARI stack size and its maximum, in bytes.
|
|
106
|
+
|
|
107
|
+
This clears the PARI stack, so call it before a computation, not
|
|
108
|
+
during one. ``None`` keeps the current value.
|
|
109
|
+
"""
|
|
110
|
+
size = PARI.stacksize() if size is None else size
|
|
111
|
+
max_size = PARI.stacksizemax() if max_size is None else max_size
|
|
112
|
+
PARI.allocatemem(size, max(size, max_size), silent=True)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
set_stack(max_size=DEFAULT_STACK_MAX)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def set_precision(digits):
|
|
119
|
+
"""Set the precision of real results, in decimal digits."""
|
|
120
|
+
PARI.set_real_precision(digits)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# cypari2 lowers PARI's real precision to 15 digits (a Python float); ER2
|
|
124
|
+
# uses GP's default, 38 digits. cypari2 methods do not read this default,
|
|
125
|
+
# so ``_function`` passes it to every method that takes ``precision``.
|
|
126
|
+
DEFAULT_PRECISION = 38
|
|
127
|
+
set_precision(DEFAULT_PRECISION)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def to_pari(obj):
|
|
131
|
+
"""Convert an ER2, Python or SymPy object to a PARI object.
|
|
132
|
+
|
|
133
|
+
Numbers, ``Mod``, ``Qfb``, lists, SymPy polynomials and rational
|
|
134
|
+
functions (``t_POL``, ``t_RFRAC``), series with an ``O`` term
|
|
135
|
+
(``t_SER``), matrices, and ``oo`` are supported.
|
|
136
|
+
"""
|
|
137
|
+
if isinstance(obj, cypari2.gen.Gen):
|
|
138
|
+
return obj
|
|
139
|
+
if isinstance(obj, (bool, int)):
|
|
140
|
+
return PARI(int(obj))
|
|
141
|
+
if isinstance(obj, Fraction):
|
|
142
|
+
return PARI(obj.numerator) / obj.denominator
|
|
143
|
+
if isinstance(obj, Mod):
|
|
144
|
+
if obj.is_polynomial:
|
|
145
|
+
return PARI.Mod(to_pari(obj.lift()), to_pari(obj.modulus))
|
|
146
|
+
return PARI.Mod(int(obj.lift()), int(obj.modulus))
|
|
147
|
+
if isinstance(obj, FiniteFieldElement):
|
|
148
|
+
return ff_element(obj)
|
|
149
|
+
if isinstance(obj, Qfb):
|
|
150
|
+
return PARI.Qfb(int(obj.a), int(obj.b), int(obj.c))
|
|
151
|
+
if isinstance(obj, float):
|
|
152
|
+
return PARI(obj)
|
|
153
|
+
if isinstance(obj, (list, tuple)):
|
|
154
|
+
return PARI([to_pari(item) for item in obj])
|
|
155
|
+
if isinstance(obj, str):
|
|
156
|
+
return obj
|
|
157
|
+
if not _lazy.sympy_loaded():
|
|
158
|
+
raise TypeError(f"cannot convert {type(obj).__name__} to PARI")
|
|
159
|
+
if isinstance(obj, sympy.MatrixBase):
|
|
160
|
+
return _matrix_to_pari(obj)
|
|
161
|
+
if isinstance(obj, sympy.Basic):
|
|
162
|
+
return _sympy_to_pari(obj)
|
|
163
|
+
raise TypeError(f"cannot convert {type(obj).__name__} to PARI")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _matrix_to_pari(obj):
|
|
167
|
+
"""Convert a SymPy matrix.
|
|
168
|
+
|
|
169
|
+
A matrix over Z or Q — the only kind dispatch sends to PARI — is
|
|
170
|
+
read out of SymPy's ``DomainMatrix`` as plain integers or fractions,
|
|
171
|
+
which costs about a tenth of what ``flat()`` costs, because it never
|
|
172
|
+
builds the ``sympy.Integer`` objects in between. Conversion is most
|
|
173
|
+
of ER2's time on a matrix call (ARCHITECTURE §2.1), so this is where
|
|
174
|
+
that time is. Any other matrix takes the general route.
|
|
175
|
+
"""
|
|
176
|
+
domain = getattr(getattr(obj, "_rep", None), "domain", None)
|
|
177
|
+
if domain is not None and domain.is_ZZ:
|
|
178
|
+
entries = [int(v) for v in obj._rep.to_list_flat()]
|
|
179
|
+
elif domain is not None and domain.is_QQ:
|
|
180
|
+
entries = [
|
|
181
|
+
PARI(int(v.numerator)) / int(v.denominator)
|
|
182
|
+
for v in obj._rep.to_list_flat()
|
|
183
|
+
]
|
|
184
|
+
else:
|
|
185
|
+
entries = [to_pari(entry) for entry in obj.flat()]
|
|
186
|
+
return PARI.matrix(obj.rows, obj.cols, entries)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# Fixed GP functions used by the conversions. Only these constant texts
|
|
190
|
+
# are ever parsed by GP; user values are passed as arguments.
|
|
191
|
+
_GP_REAL = PARI("(q, bits) -> localbitprec(bits); q * 1.")
|
|
192
|
+
_GP_SERIES = PARI("(p, v, n) -> p + O(v^n)")
|
|
193
|
+
_GP_FACTORIAL = PARI("(n) -> n!")
|
|
194
|
+
# Members of a ``t_FFELT``: cypari2 has no attribute access for them.
|
|
195
|
+
_GP_FF_COEFFICIENTS = PARI("(x) -> Vecrev(x.pol)")
|
|
196
|
+
_GP_FF_FIELD = PARI("(x) -> [x.p, Vecrev(lift(x.mod)), variable(x.mod)]")
|
|
197
|
+
_GP_INFINITY = {1: PARI("+oo"), -1: PARI("-oo")}
|
|
198
|
+
_IDENTIFIER = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
|
|
199
|
+
# Names created with ``varhigher`` because GP reserves them.
|
|
200
|
+
_CREATED = set()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def variable(name):
|
|
204
|
+
"""Return the PARI variable called ``name``.
|
|
205
|
+
|
|
206
|
+
GP's own variable (``'x``) is used for ordinary names. GP reserves
|
|
207
|
+
the names of its functions and constants (``sigma``, ``I``, ``Pi``),
|
|
208
|
+
so those get a new variable with that name, created once and found
|
|
209
|
+
again in ``variables()``.
|
|
210
|
+
|
|
211
|
+
This never triggers a PARI error and never keeps a PARI object between
|
|
212
|
+
calls: inside a Python callback (``pari.sum(f, ...)``) a PARI error
|
|
213
|
+
would abort the outer PARI call, and a kept object would outlive
|
|
214
|
+
PARI's temporary stack.
|
|
215
|
+
"""
|
|
216
|
+
if _IDENTIFIER.fullmatch(name) and name not in _GP_NAMES:
|
|
217
|
+
return PARI("'" + name)
|
|
218
|
+
if name in _CREATED:
|
|
219
|
+
for var in PARI.variables():
|
|
220
|
+
if str(var) == name:
|
|
221
|
+
return var
|
|
222
|
+
_CREATED.add(name)
|
|
223
|
+
return PARI.varhigher(name)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _sympy_to_pari(expr):
|
|
227
|
+
"""Convert a SymPy number, polynomial, rational function or series."""
|
|
228
|
+
if isinstance(expr, sympy.Rational):
|
|
229
|
+
return PARI(int(expr.p)) / int(expr.q)
|
|
230
|
+
if isinstance(expr, sympy.Float):
|
|
231
|
+
exact = sympy.Rational(expr)
|
|
232
|
+
return _GP_REAL(to_pari(exact), expr._prec)
|
|
233
|
+
if expr is sympy.oo or expr is sympy.S.NegativeInfinity:
|
|
234
|
+
return _GP_INFINITY[1 if expr is sympy.oo else -1]
|
|
235
|
+
if expr is sympy.I:
|
|
236
|
+
return PARI("I")
|
|
237
|
+
order = expr.getO() if isinstance(expr, sympy.Expr) else None
|
|
238
|
+
if order is not None:
|
|
239
|
+
return _series_to_pari(expr, order)
|
|
240
|
+
if not isinstance(expr, sympy.Expr):
|
|
241
|
+
raise TypeError(f"cannot convert {type(expr).__name__} to PARI")
|
|
242
|
+
if expr.is_number:
|
|
243
|
+
re, im = expr.as_real_imag()
|
|
244
|
+
if all(part.is_Rational or part.is_Float for part in (re, im)):
|
|
245
|
+
if im == 0:
|
|
246
|
+
return _sympy_to_pari(re)
|
|
247
|
+
return _sympy_to_pari(re) + _sympy_to_pari(im) * PARI("I")
|
|
248
|
+
# An inexact number (pi, sqrt(2), log(3)) becomes a real, as in GP.
|
|
249
|
+
digits = int(PARI.get_real_precision()) + 5
|
|
250
|
+
value = expr.evalf(digits)
|
|
251
|
+
if value.is_number and value != expr:
|
|
252
|
+
return _sympy_to_pari(value)
|
|
253
|
+
raise TypeError(f"cannot convert the number {expr} to PARI")
|
|
254
|
+
fast = _univariate_to_pari(expr)
|
|
255
|
+
if fast is not None:
|
|
256
|
+
return fast
|
|
257
|
+
numerator, denominator = sympy.fraction(sympy.together(expr))
|
|
258
|
+
result = _polynomial_to_pari(numerator)
|
|
259
|
+
if denominator != 1:
|
|
260
|
+
result = result / _polynomial_to_pari(denominator)
|
|
261
|
+
return result
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _univariate_to_pari(expr):
|
|
265
|
+
"""Build a ``t_POL`` from a univariate polynomial over Q, or None.
|
|
266
|
+
|
|
267
|
+
The general route below calls ``together`` to split a rational
|
|
268
|
+
function into a numerator and a denominator, and that single call
|
|
269
|
+
is about three quarters of what converting a degree-4 polynomial
|
|
270
|
+
costs — for polynomials, to learn that the denominator is 1. A
|
|
271
|
+
polynomial over Z or Q instead goes straight to ``Pol``, which is
|
|
272
|
+
one PARI call rather than one per term (ARCHITECTURE §2.1).
|
|
273
|
+
|
|
274
|
+
Returns None for anything this cannot prove it handles — a rational
|
|
275
|
+
function, several variables, irrational or symbolic coefficients —
|
|
276
|
+
and that takes the general route unchanged.
|
|
277
|
+
"""
|
|
278
|
+
symbols = expr.free_symbols
|
|
279
|
+
if len(symbols) != 1:
|
|
280
|
+
return None
|
|
281
|
+
(symbol,) = symbols
|
|
282
|
+
try:
|
|
283
|
+
poly = sympy.Poly(expr, symbol)
|
|
284
|
+
except sympy.PolynomialError:
|
|
285
|
+
return None
|
|
286
|
+
# ``Poly(sin(x), x)`` succeeds with ``sin(x)`` as its generator.
|
|
287
|
+
if poly.gens != (symbol,):
|
|
288
|
+
return None
|
|
289
|
+
domain = poly.domain
|
|
290
|
+
if domain.is_ZZ:
|
|
291
|
+
coefficients = [int(c) for c in poly.all_coeffs()]
|
|
292
|
+
elif domain.is_QQ:
|
|
293
|
+
coefficients = [PARI(int(c.p)) / int(c.q) for c in poly.all_coeffs()]
|
|
294
|
+
else:
|
|
295
|
+
return None
|
|
296
|
+
return PARI.Pol(coefficients, variable(symbol.name))
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _polynomial_to_pari(expr):
|
|
300
|
+
"""Build a PARI polynomial from a SymPy polynomial expression."""
|
|
301
|
+
symbols = sorted(expr.free_symbols, key=lambda s: s.name)
|
|
302
|
+
if not symbols:
|
|
303
|
+
return _sympy_to_pari(sympy.sympify(expr))
|
|
304
|
+
try:
|
|
305
|
+
poly = sympy.Poly(expr, *symbols)
|
|
306
|
+
except sympy.PolynomialError:
|
|
307
|
+
raise TypeError(f"{expr} is not a polynomial") from None
|
|
308
|
+
variables = [variable(s.name) for s in symbols]
|
|
309
|
+
result = PARI(0)
|
|
310
|
+
for exponents, coefficient in poly.terms():
|
|
311
|
+
term = _sympy_to_pari(sympy.sympify(coefficient))
|
|
312
|
+
for var, exponent in zip(variables, exponents):
|
|
313
|
+
term = term * var**exponent
|
|
314
|
+
result = result + term
|
|
315
|
+
return result
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _series_to_pari(expr, order):
|
|
319
|
+
"""Convert ``p + O(x^n)`` (around 0, one variable) to a PARI series."""
|
|
320
|
+
variables = order.variables
|
|
321
|
+
if len(variables) != 1 or any(point != 0 for point in order.point):
|
|
322
|
+
raise TypeError("only series around 0 in one variable convert to PARI")
|
|
323
|
+
(var,) = variables
|
|
324
|
+
term = order.expr
|
|
325
|
+
exponent = sympy.degree(term, var) if term != 1 else 0
|
|
326
|
+
return _GP_SERIES(
|
|
327
|
+
to_pari(expr.removeO()), variable(var.name), int(exponent)
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def from_pari(obj):
|
|
332
|
+
"""Convert a PARI object to ER2 numbers, lists and SymPy objects.
|
|
333
|
+
|
|
334
|
+
Raises ``TypeError`` for PARI types that ER2 does not support
|
|
335
|
+
(``t_PADIC``, ``t_FFELT``, ``t_CLOSURE``, ...); ``pari.raw`` gives the
|
|
336
|
+
unconverted result.
|
|
337
|
+
"""
|
|
338
|
+
if not isinstance(obj, cypari2.gen.Gen):
|
|
339
|
+
return obj
|
|
340
|
+
kind = obj.type()
|
|
341
|
+
converter = _FROM_PARI.get(kind)
|
|
342
|
+
if converter is None:
|
|
343
|
+
raise TypeError(
|
|
344
|
+
f"ER2 cannot convert the PARI type {kind} yet; "
|
|
345
|
+
"use pari.raw to get the raw PARI object"
|
|
346
|
+
)
|
|
347
|
+
return converter(obj)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _real(obj):
|
|
351
|
+
"""Convert a ``t_REAL`` exactly to a SymPy ``Float``."""
|
|
352
|
+
bits = int(PARI.bitprecision(obj))
|
|
353
|
+
if obj == 0:
|
|
354
|
+
return sympy.Float(0, precision=bits)
|
|
355
|
+
shift = bits - 1 - int(PARI.exponent(obj))
|
|
356
|
+
mantissa = int(PARI.truncate(obj * PARI(2) ** shift))
|
|
357
|
+
return sympy.Float(
|
|
358
|
+
sympy.Integer(mantissa) / sympy.Integer(2) ** shift, precision=bits
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _sympify(value):
|
|
363
|
+
"""Return ``value`` as a SymPy object, for use as a coefficient."""
|
|
364
|
+
try:
|
|
365
|
+
return sympy.sympify(value, strict=True)
|
|
366
|
+
except (sympy.SympifyError, TypeError):
|
|
367
|
+
raise TypeError(
|
|
368
|
+
f"ER2 cannot use {value!r} as a coefficient of a polynomial"
|
|
369
|
+
) from None
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _polynomial(obj):
|
|
373
|
+
"""Convert a ``t_POL`` to a SymPy expression."""
|
|
374
|
+
var = sympy.Symbol(str(PARI.variable(obj)))
|
|
375
|
+
coefficients = [_sympify(from_pari(c)) for c in PARI.Vecrev(obj)]
|
|
376
|
+
return sympy.Add(*(c * var**k for k, c in enumerate(coefficients)))
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _series(obj):
|
|
380
|
+
"""Convert a ``t_SER`` to a SymPy series ``p + O(x^n)``.
|
|
381
|
+
|
|
382
|
+
``expand`` only when there is something to expand. ``_polynomial``
|
|
383
|
+
already returns an expanded ``Add`` when the coefficients are
|
|
384
|
+
numbers, and ``expand`` on an expanded expression still costs about
|
|
385
|
+
250 us — two thirds of this conversion (ARCHITECTURE §2.1). Two
|
|
386
|
+
cases do need it, and both are checked rather than assumed:
|
|
387
|
+
coefficients that are polynomials in another variable, where PARI
|
|
388
|
+
writes ``(y + 1)*x^2``; and a negative valuation, where ``truncate``
|
|
389
|
+
gives a rational function, so ``1/x + 1`` arrives as ``(x + 1)/x``.
|
|
390
|
+
"""
|
|
391
|
+
var = PARI.variable(obj)
|
|
392
|
+
precision = int(PARI.serprec(obj, var))
|
|
393
|
+
truncated = PARI.truncate(obj)
|
|
394
|
+
body = _sympify(from_pari(truncated))
|
|
395
|
+
if truncated.type() != "t_POL" or len(body.free_symbols) != 1:
|
|
396
|
+
body = sympy.expand(body)
|
|
397
|
+
return body + sympy.O(sympy.Symbol(str(var)) ** precision)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _matrix(obj):
|
|
401
|
+
"""Convert a ``t_MAT`` to a SymPy matrix.
|
|
402
|
+
|
|
403
|
+
The way back from PARI is the same story as ``_matrix_to_pari``
|
|
404
|
+
(ARCHITECTURE §2.1): building the matrix through SymPy's public
|
|
405
|
+
constructor sympifies every entry one at a time. A matrix over Z
|
|
406
|
+
or Q can instead be handed to SymPy as a ``DomainMatrix``, which is
|
|
407
|
+
the representation ``Matrix`` keeps internally anyway, and that is
|
|
408
|
+
about seven times faster. Anything else takes the general route.
|
|
409
|
+
"""
|
|
410
|
+
rows, cols = map(int, PARI.matsize(obj))
|
|
411
|
+
entries = [obj[i, j] for i in range(rows) for j in range(cols)]
|
|
412
|
+
kinds = {entry.type() for entry in entries}
|
|
413
|
+
if entries and kinds <= {"t_INT"}:
|
|
414
|
+
domain = sympy.ZZ
|
|
415
|
+
values = [domain(int(entry)) for entry in entries]
|
|
416
|
+
elif entries and kinds <= {"t_INT", "t_FRAC"}:
|
|
417
|
+
domain = sympy.QQ
|
|
418
|
+
values = [
|
|
419
|
+
domain(int(PARI.numerator(e)), int(PARI.denominator(e)))
|
|
420
|
+
for e in entries
|
|
421
|
+
]
|
|
422
|
+
else:
|
|
423
|
+
flat = [_sympify(from_pari(entry)) for entry in entries]
|
|
424
|
+
return sympy.Matrix(rows, cols, flat)
|
|
425
|
+
from sympy.polys.matrices import DomainMatrix
|
|
426
|
+
|
|
427
|
+
grid = [values[i * cols : (i + 1) * cols] for i in range(rows)]
|
|
428
|
+
return DomainMatrix(grid, (rows, cols), domain).to_Matrix()
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
_FROM_PARI = {
|
|
432
|
+
"t_INT": lambda obj: Integer(int(obj)),
|
|
433
|
+
"t_FRAC": lambda obj: Rational(
|
|
434
|
+
int(PARI.numerator(obj)), int(PARI.denominator(obj))
|
|
435
|
+
),
|
|
436
|
+
"t_REAL": _real,
|
|
437
|
+
"t_COMPLEX": lambda obj: (
|
|
438
|
+
_sympify(from_pari(PARI.real(obj)))
|
|
439
|
+
+ sympy.I * _sympify(from_pari(PARI.imag(obj)))
|
|
440
|
+
),
|
|
441
|
+
"t_INTMOD": lambda obj: Mod(int(PARI.lift(obj)), int(obj.mod())),
|
|
442
|
+
"t_POLMOD": lambda obj: Mod(
|
|
443
|
+
from_pari(PARI.lift(obj)), from_pari(obj.mod())
|
|
444
|
+
),
|
|
445
|
+
"t_POL": _polynomial,
|
|
446
|
+
"t_RFRAC": lambda obj: (
|
|
447
|
+
_polynomial(PARI.numerator(obj)) / _polynomial(PARI.denominator(obj))
|
|
448
|
+
),
|
|
449
|
+
"t_SER": _series,
|
|
450
|
+
"t_QFB": lambda obj: Qfb(int(obj[0]), int(obj[1]), int(obj[2])),
|
|
451
|
+
"t_FFELT": lambda obj: FiniteFieldElement(
|
|
452
|
+
_finite_field(obj), ff_coefficients(obj)
|
|
453
|
+
),
|
|
454
|
+
"t_INFINITY": lambda obj: sympy.oo if obj > 0 else -sympy.oo,
|
|
455
|
+
"t_VEC": lambda obj: [from_pari(item) for item in obj],
|
|
456
|
+
"t_COL": lambda obj: [from_pari(item) for item in obj],
|
|
457
|
+
"t_VECSMALL": lambda obj: [Integer(int(item)) for item in obj],
|
|
458
|
+
"t_MAT": _matrix,
|
|
459
|
+
"t_STR": str,
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _factor_rows(matrix):
|
|
464
|
+
"""Yield the ``(factor, exponent)`` rows of a PARI factorization."""
|
|
465
|
+
for i in range(int(PARI.matsize(matrix)[0])):
|
|
466
|
+
yield matrix[i, 0], int(matrix[i, 1])
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _positive_integer(n, function):
|
|
470
|
+
"""Return ``n`` in PARI, or raise if it is not a positive integer."""
|
|
471
|
+
n = to_pari(n)
|
|
472
|
+
if n.type() != "t_INT" or n <= 0:
|
|
473
|
+
raise ValueError(f"{function}() needs a positive integer")
|
|
474
|
+
return n
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _call(pari_name, *args, **kwargs):
|
|
478
|
+
function = getattr(PARI, pari_name)
|
|
479
|
+
args = [to_pari(arg) for arg in args]
|
|
480
|
+
kwargs = {key: to_pari(value) for key, value in kwargs.items()}
|
|
481
|
+
return from_pari(function(*args, **kwargs))
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def factor(n, limit=None):
|
|
485
|
+
"""Factor an integer or a rational number with PARI.
|
|
486
|
+
|
|
487
|
+
``limit=B`` gives a partial factorization: only primes up to ``B``
|
|
488
|
+
are found by trial division, and factors that may be composite are
|
|
489
|
+
listed in ``unfactored`` (D7). A full factorization can take very
|
|
490
|
+
long for large numbers; Ctrl-C interrupts it.
|
|
491
|
+
"""
|
|
492
|
+
n = to_pari(n)
|
|
493
|
+
if limit is None:
|
|
494
|
+
matrix = PARI.factor(n)
|
|
495
|
+
else:
|
|
496
|
+
matrix = PARI.factor(n, to_pari(limit))
|
|
497
|
+
pairs = [(int(p), e) for p, e in _factor_rows(matrix)]
|
|
498
|
+
unit = 1
|
|
499
|
+
if pairs and pairs[0][0] == -1:
|
|
500
|
+
unit = -1
|
|
501
|
+
pairs.pop(0)
|
|
502
|
+
unfactored = ()
|
|
503
|
+
if limit is not None:
|
|
504
|
+
unfactored = [p for p, _ in pairs if not PARI.ispseudoprime(p)]
|
|
505
|
+
return Factorization(pairs, unit=unit, unfactored=unfactored)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def is_rational_univariate(expr):
|
|
509
|
+
"""Whether ``expr`` is a univariate polynomial over Q.
|
|
510
|
+
|
|
511
|
+
That is the case where PARI factors much faster than SymPy.
|
|
512
|
+
|
|
513
|
+
``Poly`` answers both questions at once, so this does not also call
|
|
514
|
+
``is_polynomial``, which walked the expression a second time: a
|
|
515
|
+
generator other than ``var`` (``Poly(sin(x), x)``) means the same
|
|
516
|
+
as ``is_polynomial`` returning False. A dispatch predicate runs
|
|
517
|
+
before any work is done, so its own cost is pure overhead (§2.1).
|
|
518
|
+
"""
|
|
519
|
+
if not isinstance(expr, sympy.Expr):
|
|
520
|
+
return False
|
|
521
|
+
symbols = expr.free_symbols
|
|
522
|
+
if len(symbols) != 1:
|
|
523
|
+
return False
|
|
524
|
+
(var,) = symbols
|
|
525
|
+
try:
|
|
526
|
+
poly = sympy.Poly(expr, var)
|
|
527
|
+
except sympy.PolynomialError:
|
|
528
|
+
return False
|
|
529
|
+
return poly.gens == (var,) and poly.domain in (sympy.ZZ, sympy.QQ)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def expand_series(expr):
|
|
533
|
+
"""Expand arithmetic on truncated power series with PARI.
|
|
534
|
+
|
|
535
|
+
SymPy leaves ``s * t`` unevaluated, so a user writes ``expand(s * t)``
|
|
536
|
+
— and SymPy's ``expand`` on series is very slow: 11 ms for two
|
|
537
|
+
six-term series, 612 ms at eighty terms, against 3.9 ms and 51 ms
|
|
538
|
+
here (ARCHITECTURE §2.1). PARI's ``t_SER`` arithmetic is eager and
|
|
539
|
+
truncates the way SymPy does, including when the two operands have
|
|
540
|
+
different precisions.
|
|
541
|
+
|
|
542
|
+
The tree is walked rather than converted in one call because
|
|
543
|
+
``to_pari`` cannot convert an unevaluated ``Mul``.
|
|
544
|
+
"""
|
|
545
|
+
try:
|
|
546
|
+
return from_pari(_series_tree(expr))
|
|
547
|
+
except (TypeError, PariError):
|
|
548
|
+
# The predicate cannot prove that every leaf converts, so this
|
|
549
|
+
# is a safety net rather than a path: the answer a user gets
|
|
550
|
+
# must never depend on which backend ran (CLAUDE.md).
|
|
551
|
+
from er2.backends import sympy_backend
|
|
552
|
+
|
|
553
|
+
return sympy_backend.expand(expr)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _series_tree(node):
|
|
557
|
+
"""Evaluate a SymPy ``Add``/``Mul``/``Pow`` tree with PARI operands."""
|
|
558
|
+
if node.is_Add:
|
|
559
|
+
total = PARI(0)
|
|
560
|
+
for term in node.args:
|
|
561
|
+
total = total + _series_tree(term)
|
|
562
|
+
return total
|
|
563
|
+
if node.is_Mul:
|
|
564
|
+
product = PARI(1)
|
|
565
|
+
for factor in node.args:
|
|
566
|
+
product = product * _series_tree(factor)
|
|
567
|
+
return product
|
|
568
|
+
if node.is_Pow and node.args[1].is_Integer:
|
|
569
|
+
return _series_tree(node.args[0]) ** int(node.args[1])
|
|
570
|
+
return to_pari(node)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def factor_polynomial(expr):
|
|
574
|
+
"""Factor a univariate polynomial over Q with PARI, as SymPy would.
|
|
575
|
+
|
|
576
|
+
The result has SymPy's form, ``-(x - 1)*(x + 1)``: PARI's primitive
|
|
577
|
+
factors with the rational unit kept in front.
|
|
578
|
+
"""
|
|
579
|
+
from sympy.core.mul import _keep_coeff
|
|
580
|
+
|
|
581
|
+
poly = to_pari(expr)
|
|
582
|
+
matrix = PARI.factor(poly)
|
|
583
|
+
factors = [(from_pari(f), e) for f, e in _factor_rows(matrix)]
|
|
584
|
+
unit = from_pari(poly / PARI.factorback(matrix))
|
|
585
|
+
product = sympy.Mul(*(f**e for f, e in factors))
|
|
586
|
+
return _keep_coeff(sympy.sympify(unit), product)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def factorial(n):
|
|
590
|
+
"""Return ``n!`` exactly (GP's ``n!``; PARI's ``factorial`` is real)."""
|
|
591
|
+
if isinstance(n, bool) or int(n) != n or n < 0:
|
|
592
|
+
raise ValueError("factorial() needs a nonnegative integer")
|
|
593
|
+
return from_pari(_GP_FACTORIAL(int(n)))
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def dedekind_psi(n):
|
|
597
|
+
"""Dedekind psi: ``n * prod(1 + 1/p)`` over the primes ``p`` of ``n``.
|
|
598
|
+
|
|
599
|
+
``psi`` is not used as a name, because PARI's ``psi`` is the digamma
|
|
600
|
+
function (``pari.digamma``), as is SciPy's (D5).
|
|
601
|
+
"""
|
|
602
|
+
n = _positive_integer(n, "dedekind_psi")
|
|
603
|
+
result = n
|
|
604
|
+
for p in PARI.factor(n)[0]:
|
|
605
|
+
result = result / p * (p + 1)
|
|
606
|
+
return from_pari(result)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def jordan_totient(n, k):
|
|
610
|
+
"""Jordan's totient ``J_k(n) = n^k * prod(1 - 1/p^k)`` over ``p | n``.
|
|
611
|
+
|
|
612
|
+
``J_k(n)`` counts the ``k``-tuples in ``[1, n]`` whose gcd with ``n``
|
|
613
|
+
is 1. ``J_1`` is Euler's totient ``phi`` (PARI ``eulerphi``), and
|
|
614
|
+
``J_2(n) / phi(n)`` is ``dedekind_psi(n)``.
|
|
615
|
+
"""
|
|
616
|
+
n, k = _positive_integer(n, "jordan_totient"), to_pari(k)
|
|
617
|
+
if k.type() != "t_INT" or k < 0:
|
|
618
|
+
raise ValueError("jordan_totient() needs a nonnegative integer k")
|
|
619
|
+
result = n**k
|
|
620
|
+
for p in PARI.factor(n)[0]:
|
|
621
|
+
power = p**k
|
|
622
|
+
result = result / power * (power - 1)
|
|
623
|
+
return from_pari(result)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def radical(n):
|
|
627
|
+
"""Return ``rad(n)``, the product of the distinct primes of ``n``.
|
|
628
|
+
|
|
629
|
+
GP: ``factorback(factorint(n)[, 1])``.
|
|
630
|
+
"""
|
|
631
|
+
n = _positive_integer(n, "radical")
|
|
632
|
+
return from_pari(PARI.factorback(PARI.factor(n)[0]))
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
# Polynomials over a prime field F_p (M5). PARI's ``factormod`` is much
|
|
636
|
+
# faster than SymPy (×40 at degree 49), and the result is rebuilt in
|
|
637
|
+
# SymPy's form: monic factors with coefficients in ``(-p/2, p/2]`` and the
|
|
638
|
+
# leading coefficient in front, exactly what ``factor(f, modulus=p)``
|
|
639
|
+
# gives in SymPy. Polynomials over GF(p^k) need a polynomial type of
|
|
640
|
+
# their own (not in 0.5); ``pari.factormod`` factors them.
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _symmetric(value, p):
|
|
644
|
+
"""Return the representative of ``value`` mod ``p`` nearest to 0."""
|
|
645
|
+
value = int(value) % p
|
|
646
|
+
return value - p if 2 * value > p else value
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _mod_polynomial(obj, p, var):
|
|
650
|
+
"""Return a PARI polynomial over F_p as a SymPy expression."""
|
|
651
|
+
coefficients = [_symmetric(c, p) for c in PARI.Vecrev(PARI.lift(obj))] or [
|
|
652
|
+
0
|
|
653
|
+
]
|
|
654
|
+
return sympy.Add(
|
|
655
|
+
*(c * var**i for i, c in enumerate(coefficients)), evaluate=True
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _polynomial_variable(expr):
|
|
660
|
+
"""Return the single symbol of a univariate polynomial expression."""
|
|
661
|
+
(var,) = sympy.sympify(expr).free_symbols
|
|
662
|
+
return var
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def is_rational_polynomial(expr, var):
|
|
666
|
+
"""Whether ``expr`` is a polynomial in ``var`` over Q, in ``var`` alone.
|
|
667
|
+
|
|
668
|
+
Unlike ``is_rational_univariate``, a constant passes: the resultant
|
|
669
|
+
of a polynomial and a number is defined.
|
|
670
|
+
"""
|
|
671
|
+
if isinstance(expr, (int, Fraction)):
|
|
672
|
+
return True
|
|
673
|
+
if not isinstance(expr, sympy.Expr) or not expr.free_symbols <= {var}:
|
|
674
|
+
return False
|
|
675
|
+
if not expr.is_polynomial(var):
|
|
676
|
+
return False
|
|
677
|
+
return sympy.Poly(expr, var).domain in (sympy.ZZ, sympy.QQ)
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def resultant(f, g, var):
|
|
681
|
+
"""Return the resultant of ``f`` and ``g`` in ``var`` (PARI).
|
|
682
|
+
|
|
683
|
+
PARI's ``polresultant`` follows the standard definition, which is
|
|
684
|
+
the one ER2 uses (ARCHITECTURE §3.4).
|
|
685
|
+
"""
|
|
686
|
+
return from_pari(
|
|
687
|
+
PARI.polresultant(to_pari(f), to_pari(g), variable(var.name))
|
|
688
|
+
)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def discriminant(f, var):
|
|
692
|
+
"""Return the discriminant of ``f`` in ``var`` (PARI ``poldisc``)."""
|
|
693
|
+
return from_pari(PARI.poldisc(to_pari(f), variable(var.name)))
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def is_prime_number(n):
|
|
697
|
+
"""Whether ``n`` is a prime number (PARI ``isprime``, a proof)."""
|
|
698
|
+
return bool(PARI.isprime(int(n)))
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
def is_modular_polynomial(expr, modulus):
|
|
702
|
+
"""Whether ``expr`` is a univariate polynomial over Z, nonzero mod p.
|
|
703
|
+
|
|
704
|
+
A polynomial that vanishes modulo ``p`` stays with SymPy, which leaves
|
|
705
|
+
it as it is (``factor(5*x^2, modulus=5)`` is ``5*x^2``).
|
|
706
|
+
"""
|
|
707
|
+
if not is_rational_univariate(expr):
|
|
708
|
+
return False
|
|
709
|
+
poly = sympy.Poly(expr, _polynomial_variable(expr))
|
|
710
|
+
if poly.domain != sympy.ZZ:
|
|
711
|
+
return False
|
|
712
|
+
return any(int(c) % int(modulus) for c in poly.all_coeffs())
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def factor_polynomial_mod(expr, modulus):
|
|
716
|
+
"""Factor a univariate polynomial over ``F_p`` (PARI ``factormod``)."""
|
|
717
|
+
from sympy.core.mul import _keep_coeff
|
|
718
|
+
|
|
719
|
+
p = int(modulus)
|
|
720
|
+
var = _polynomial_variable(expr)
|
|
721
|
+
# SymPy takes the integer content out first and does not reduce it
|
|
722
|
+
# modulo p: ``factor(9*x - 9, modulus=5)`` is ``9*(x - 1)``.
|
|
723
|
+
content, primitive = sympy.Poly(expr, var).primitive()
|
|
724
|
+
poly = to_pari(primitive.as_expr())
|
|
725
|
+
unit = content * _symmetric(
|
|
726
|
+
PARI.lift(PARI.pollead(poly * PARI.Mod(1, p))), p
|
|
727
|
+
)
|
|
728
|
+
factors = [
|
|
729
|
+
(_mod_polynomial(f, p, var), e)
|
|
730
|
+
for f, e in _factor_rows(PARI.factormod(poly, p))
|
|
731
|
+
]
|
|
732
|
+
product = sympy.Mul(*(f**e for f, e in factors))
|
|
733
|
+
return _keep_coeff(sympy.Integer(unit), product)
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def gcd_mod(a, b, modulus):
|
|
737
|
+
"""Return the monic gcd of two polynomials over ``F_p``."""
|
|
738
|
+
p = int(modulus)
|
|
739
|
+
var = _polynomial_variable(a if a != 0 else b)
|
|
740
|
+
one = PARI.Mod(1, p)
|
|
741
|
+
result = PARI.gcd(to_pari(a) * one, to_pari(b) * one)
|
|
742
|
+
if result == 0:
|
|
743
|
+
return sympy.S.Zero
|
|
744
|
+
return _mod_polynomial(result / PARI.pollead(result), p, var)
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def isirreducible(expr, modulus=None):
|
|
748
|
+
"""Whether a polynomial is irreducible over Q, or over ``F_p``.
|
|
749
|
+
|
|
750
|
+
As in PARI, a constant is not irreducible; SymPy says it is.
|
|
751
|
+
"""
|
|
752
|
+
poly = to_pari(expr)
|
|
753
|
+
if modulus is not None:
|
|
754
|
+
poly = poly * PARI.Mod(1, int(modulus))
|
|
755
|
+
return bool(PARI.polisirreducible(poly))
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
# Finite fields (M5, D13). An ER2 element carries its coefficients, so
|
|
759
|
+
# every operation rebuilds the PARI generator: no PARI object outlives the
|
|
760
|
+
# call that made it (M4).
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def prime_power(q):
|
|
764
|
+
"""Return ``(p, k)`` with ``q = p^k``, or raise ``ValueError``."""
|
|
765
|
+
if isinstance(q, bool) or not isinstance(q, int) or q < 2:
|
|
766
|
+
raise ValueError(f"{q} is not a prime power")
|
|
767
|
+
k = int(PARI.isprimepower(q))
|
|
768
|
+
if k == 0:
|
|
769
|
+
raise ValueError(f"{q} is not a prime power")
|
|
770
|
+
return Integer(PARI.sqrtnint(q, k)), Integer(k)
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def ff_modulus(p, k, name):
|
|
774
|
+
"""Return the coefficients of PARI's ``ffinit(p, k)``, constant first.
|
|
775
|
+
|
|
776
|
+
The defining polynomial is PARI's choice (D13): ER2 needs no table of
|
|
777
|
+
Conway polynomials, so field elements may print differently from
|
|
778
|
+
SageMath's.
|
|
779
|
+
"""
|
|
780
|
+
modulus = PARI.lift(PARI.ffinit(int(p), int(k), variable(name)))
|
|
781
|
+
return [Integer(c) for c in PARI.Vecrev(modulus)]
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def _ff_generator(field):
|
|
785
|
+
"""Return the PARI generator (``t_FFELT``) of an ER2 finite field."""
|
|
786
|
+
coefficients = [int(c) for c in field.modulus_coefficients()]
|
|
787
|
+
variables = variable(field.name)
|
|
788
|
+
modulus = PARI.Polrev(coefficients, variables) * PARI.Mod(
|
|
789
|
+
1, int(field.characteristic)
|
|
790
|
+
)
|
|
791
|
+
return PARI.ffgen(modulus)
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def ff_element(element):
|
|
795
|
+
"""Return an ER2 finite field element as a PARI ``t_FFELT``."""
|
|
796
|
+
generator = _ff_generator(element.parent)
|
|
797
|
+
result = generator * 0
|
|
798
|
+
for coefficient in reversed(element.coefficients()):
|
|
799
|
+
result = result * generator + int(coefficient)
|
|
800
|
+
return result
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
def ff_coefficients(obj):
|
|
804
|
+
"""Return the coefficients of a PARI ``t_FFELT``, constant first."""
|
|
805
|
+
return [Integer(c) for c in _GP_FF_COEFFICIENTS(obj)]
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def _finite_field(obj):
|
|
809
|
+
"""Return the ER2 field of a PARI ``t_FFELT``."""
|
|
810
|
+
p, modulus, name = _GP_FF_FIELD(obj)
|
|
811
|
+
coefficients = [Integer(c) for c in modulus]
|
|
812
|
+
return FiniteField(
|
|
813
|
+
Integer(p), len(coefficients) - 1, str(name), coefficients
|
|
814
|
+
)
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def ff_polynomial(name, element, var):
|
|
818
|
+
"""Return ``minpoly`` or ``charpoly`` of a field element over ``F_p``.
|
|
819
|
+
|
|
820
|
+
The coefficients are lifted to integers in ``[0, p)``, so the result
|
|
821
|
+
is an ordinary SymPy polynomial.
|
|
822
|
+
"""
|
|
823
|
+
from er2 import _lazy
|
|
824
|
+
|
|
825
|
+
var = _lazy.sympy().Symbol("x") if var is None else var
|
|
826
|
+
function = getattr(PARI, name)
|
|
827
|
+
return from_pari(
|
|
828
|
+
PARI.lift(function(ff_element(element), variable(var.name)))
|
|
829
|
+
)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def ff_minpoly(element, var):
|
|
833
|
+
"""Return the minimal polynomial of a finite field element."""
|
|
834
|
+
return ff_polynomial("minpoly", element, var)
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def ff_charpoly(element, var):
|
|
838
|
+
"""Return the characteristic polynomial of a finite field element."""
|
|
839
|
+
return ff_polynomial("charpoly", element, var)
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def ff_lift(name, element):
|
|
843
|
+
"""Return ``trace`` or ``norm`` of a field element, as an integer."""
|
|
844
|
+
function = getattr(PARI, name)
|
|
845
|
+
return Integer(PARI.lift(function(ff_element(element))))
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
# Linear algebra over Q (M5, D12). Matrices are SymPy matrices with
|
|
849
|
+
# rational entries; ``dispatch`` sends the others to SymPy. Errors are
|
|
850
|
+
# SymPy's own exceptions, so both backends fail in the same way.
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def det(matrix):
|
|
854
|
+
"""Return the determinant of a square rational matrix."""
|
|
855
|
+
return from_pari(PARI.matdet(to_pari(matrix)))
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def inverse(matrix):
|
|
859
|
+
"""Return the inverse of a square rational matrix."""
|
|
860
|
+
from sympy.matrices.exceptions import NonInvertibleMatrixError
|
|
861
|
+
|
|
862
|
+
try:
|
|
863
|
+
return from_pari(to_pari(matrix) ** -1)
|
|
864
|
+
except cypari2.PariError:
|
|
865
|
+
raise NonInvertibleMatrixError(
|
|
866
|
+
"Matrix det == 0; not invertible."
|
|
867
|
+
) from None
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
def rank(matrix):
|
|
871
|
+
"""Return the rank of a rational matrix."""
|
|
872
|
+
return Integer(PARI.matrank(to_pari(matrix)))
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def kernel(matrix):
|
|
876
|
+
"""Return a basis of ``{v : matrix * v = 0}`` as column matrices."""
|
|
877
|
+
basis = from_pari(PARI.matker(to_pari(matrix)))
|
|
878
|
+
return [basis[:, j] for j in range(basis.cols)]
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
def charpoly(matrix, var):
|
|
882
|
+
"""Return the characteristic polynomial ``det(var*I - matrix)``."""
|
|
883
|
+
return from_pari(PARI.charpoly(to_pari(matrix), variable(var.name)))
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def minpoly(obj, var):
|
|
887
|
+
"""Return the minimal polynomial of a rational matrix or a ``Mod``."""
|
|
888
|
+
return from_pari(PARI.minpoly(to_pari(obj), variable(var.name)))
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def solve_linear(matrix, rhs):
|
|
892
|
+
"""Return the solution ``v`` of ``matrix * v = rhs`` (square, regular)."""
|
|
893
|
+
from sympy.matrices.exceptions import NonInvertibleMatrixError
|
|
894
|
+
|
|
895
|
+
try:
|
|
896
|
+
return from_pari(PARI.matsolve(to_pari(matrix), to_pari(rhs)))
|
|
897
|
+
except cypari2.PariError:
|
|
898
|
+
raise NonInvertibleMatrixError(
|
|
899
|
+
"Matrix det == 0; not invertible."
|
|
900
|
+
) from None
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
def hermite_form(matrix):
|
|
904
|
+
"""Return the Hermite normal form of an integer matrix.
|
|
905
|
+
|
|
906
|
+
PARI's ``mathnf``: upper triangular, and its columns are a basis of
|
|
907
|
+
the lattice spanned by the columns of ``matrix`` (SymPy's
|
|
908
|
+
``hermite_normal_form`` gives the same matrix).
|
|
909
|
+
"""
|
|
910
|
+
if matrix.cols == 0:
|
|
911
|
+
# PARI has no m x 0 matrix: it writes one as ``[;]``, a 0 x 0,
|
|
912
|
+
# so the round trip would lose the row count. SymPy's
|
|
913
|
+
# ``hermite_normal_form`` keeps the shape and ER2 follows it,
|
|
914
|
+
# as ``smith_form`` below does by rebuilding the result.
|
|
915
|
+
return sympy.zeros(matrix.rows, 0)
|
|
916
|
+
return from_pari(PARI.mathnf(to_pari(matrix)))
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def smith_form(matrix):
|
|
920
|
+
"""Return the Smith normal form of an integer matrix.
|
|
921
|
+
|
|
922
|
+
A diagonal matrix of the same shape, with ``d_1 | d_2 | ...`` on the
|
|
923
|
+
diagonal, as SymPy's ``smith_normal_form``. PARI's ``matsnf`` gives
|
|
924
|
+
the elementary divisors in the opposite order.
|
|
925
|
+
"""
|
|
926
|
+
divisors = [from_pari(d) for d in PARI.matsnf(to_pari(matrix))][::-1]
|
|
927
|
+
result = sympy.zeros(matrix.rows, matrix.cols)
|
|
928
|
+
for i in range(min(matrix.rows, matrix.cols)):
|
|
929
|
+
result[i, i] = divisors[i]
|
|
930
|
+
return result
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
# Number fields (M5, D14). Every PARI structure is read out inside the
|
|
934
|
+
# call that built it and returned as plain Python data, so no ``nf`` or
|
|
935
|
+
# ``bnf`` outlives it (M4) and ``pari.set_stack`` can never invalidate a
|
|
936
|
+
# cached field. ``nfinit`` is cheap; ``bnfinit`` is the expensive one and
|
|
937
|
+
# the caller caches what it returns.
|
|
938
|
+
|
|
939
|
+
_GP_NF = PARI("(n) -> [poldegree(n.pol), n.disc]")
|
|
940
|
+
_GP_NF_ZK = PARI("(n) -> n.zk")
|
|
941
|
+
_GP_BNF = PARI("(b) -> [b.no, b.cyc, b.fu, b.tu[1]]")
|
|
942
|
+
_GP_PRID = PARI("(P) -> [P.p, P.e, P.f, P.gen[2]]")
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def number_field(polynomial):
|
|
946
|
+
"""Return ``(degree, discriminant, integral_basis)`` of ``Q[x]/(f)``.
|
|
947
|
+
|
|
948
|
+
The basis elements come back as ``Mod`` objects (``t_POLMOD``).
|
|
949
|
+
``polynomial`` must be monic over Z: PARI silently presents a
|
|
950
|
+
non-monic one by a different polynomial, which would no longer match
|
|
951
|
+
the field's own elements.
|
|
952
|
+
"""
|
|
953
|
+
nf = PARI.nfinit(to_pari(polynomial))
|
|
954
|
+
degree, discriminant = _GP_NF(nf)
|
|
955
|
+
modulus = to_pari(polynomial)
|
|
956
|
+
basis = [from_pari(PARI.Mod(b, modulus)) for b in _GP_NF_ZK(nf)]
|
|
957
|
+
return from_pari(degree), from_pari(discriminant), basis
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def number_field_class_group(polynomial, certify=False):
|
|
961
|
+
"""Return ``(class_number, invariants, units, torsion_order)``.
|
|
962
|
+
|
|
963
|
+
``bnfinit`` can take minutes on a large field; Ctrl-C interrupts it
|
|
964
|
+
(D7). Its results assume the GRH unless ``certify`` is true, which
|
|
965
|
+
runs ``bnfcertify`` on the same structure.
|
|
966
|
+
"""
|
|
967
|
+
bnf = PARI.bnfinit(to_pari(polynomial), 1)
|
|
968
|
+
if certify and not PARI.bnfcertify(bnf):
|
|
969
|
+
raise ValueError("bnfcertify() could not certify this field")
|
|
970
|
+
number, invariants, units, torsion = _GP_BNF(bnf)
|
|
971
|
+
return (
|
|
972
|
+
from_pari(number),
|
|
973
|
+
[from_pari(c) for c in invariants],
|
|
974
|
+
[from_pari(u) for u in units],
|
|
975
|
+
from_pari(torsion),
|
|
976
|
+
)
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
def prime_ideals(polynomial, p):
|
|
980
|
+
"""Return ``(p, e, f, alpha)`` for each prime ideal above ``p``.
|
|
981
|
+
|
|
982
|
+
``alpha`` is the second generator of PARI's two-element form, as a
|
|
983
|
+
``Mod``: the ideal is ``(p, alpha)``.
|
|
984
|
+
"""
|
|
985
|
+
nf = PARI.nfinit(to_pari(polynomial))
|
|
986
|
+
out = []
|
|
987
|
+
for prime in PARI.idealprimedec(nf, int(p)):
|
|
988
|
+
rational, e, f, generator = _GP_PRID(prime)
|
|
989
|
+
alpha = from_pari(PARI.nfbasistoalg(nf, generator))
|
|
990
|
+
out.append((from_pari(rational), from_pari(e), from_pari(f), alpha))
|
|
991
|
+
return out
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
# Prelude predicates that return a Python bool. ``ispower`` and
|
|
995
|
+
# ``isprimepower`` return an exponent, as in PARI (0 when false).
|
|
996
|
+
_BOOLEAN = {"isprime", "ispseudoprime", "issquare", "issquarefree"}
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
def _function(row):
|
|
1000
|
+
"""Return the ER2 function for a row of the PARI table."""
|
|
1001
|
+
pari_name, er2_name = row["pari_name"], row["er2_name"]
|
|
1002
|
+
call = functools.partial(_call, pari_name)
|
|
1003
|
+
takes_precision = "precision" in _parameters(getattr(PARI, pari_name))
|
|
1004
|
+
convert = bool if er2_name in _BOOLEAN else _same
|
|
1005
|
+
|
|
1006
|
+
def function(*args, **kwargs):
|
|
1007
|
+
if takes_precision and "precision" not in kwargs:
|
|
1008
|
+
kwargs["precision"] = PARI.get_real_precision_bits()
|
|
1009
|
+
return convert(call(*args, **kwargs))
|
|
1010
|
+
|
|
1011
|
+
function.__name__ = function.__qualname__ = er2_name
|
|
1012
|
+
function.__doc__ = (
|
|
1013
|
+
f"{row['summary']}\n\nPARI function ``{pari_name}``."
|
|
1014
|
+
if row["summary"]
|
|
1015
|
+
else f"PARI function ``{pari_name}``."
|
|
1016
|
+
)
|
|
1017
|
+
return function
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
def _same(value):
|
|
1021
|
+
return value
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
def _parameters(method):
|
|
1025
|
+
try:
|
|
1026
|
+
return inspect.signature(method).parameters
|
|
1027
|
+
except (TypeError, ValueError):
|
|
1028
|
+
return {}
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
def _read_table():
|
|
1032
|
+
with TABLE_PATH.open(newline="", encoding="utf-8") as fh:
|
|
1033
|
+
return list(csv.DictReader(fh))
|
|
1034
|
+
|
|
1035
|
+
|
|
1036
|
+
_TABLE = _read_table()
|
|
1037
|
+
# Every GP function and constant: GP reserves these names (``variable``).
|
|
1038
|
+
_GP_NAMES = frozenset(row["pari_name"] for row in _TABLE)
|
|
1039
|
+
_ALL_ROWS = [
|
|
1040
|
+
row
|
|
1041
|
+
for row in _TABLE
|
|
1042
|
+
if row["status"] in ("prelude", "namespace", "wrapper")
|
|
1043
|
+
]
|
|
1044
|
+
# The rows that cypari2 methods implement directly.
|
|
1045
|
+
_ROWS = [row for row in _ALL_ROWS if row["status"] != "wrapper"]
|
|
1046
|
+
|
|
1047
|
+
# Top-level ER2 functions (the ``prelude`` rows); ``factor`` has its own.
|
|
1048
|
+
PRELUDE = {
|
|
1049
|
+
row["er2_name"]: _function(row)
|
|
1050
|
+
for row in _ROWS
|
|
1051
|
+
if row["status"] == "prelude"
|
|
1052
|
+
}
|
|
1053
|
+
PRELUDE["factor"] = factor
|
|
1054
|
+
|
|
1055
|
+
|
|
1056
|
+
class PariNamespace:
|
|
1057
|
+
"""PARI functions by their ER2 names: ``pari.eulerphi`` is ``phi``.
|
|
1058
|
+
|
|
1059
|
+
Every function converts its arguments and results (ER2 numbers in and
|
|
1060
|
+
out). Functions that take a GP expression in GP take a Python
|
|
1061
|
+
function instead: ``pari.sum(lambda n: 1/n^2, 1, 10)``. ``pari.raw``
|
|
1062
|
+
is the cypari2 instance itself, for the rare cases that need raw PARI
|
|
1063
|
+
objects.
|
|
1064
|
+
"""
|
|
1065
|
+
|
|
1066
|
+
def __init__(self, rows):
|
|
1067
|
+
"""Index the ``prelude``, ``namespace`` and ``wrapper`` rows."""
|
|
1068
|
+
self._rows = {row["er2_name"]: row for row in rows}
|
|
1069
|
+
self.raw = PARI
|
|
1070
|
+
self.set_stack = set_stack
|
|
1071
|
+
self.set_precision = set_precision
|
|
1072
|
+
|
|
1073
|
+
def __getattr__(self, name):
|
|
1074
|
+
"""Return the ER2 function for ``name`` (created on first use)."""
|
|
1075
|
+
row = self.__dict__.get("_rows", {}).get(name)
|
|
1076
|
+
if row is None:
|
|
1077
|
+
raise AttributeError(f"PARI has no ER2 function {name!r}")
|
|
1078
|
+
if row["status"] == "wrapper":
|
|
1079
|
+
from er2.backends import pari_closures
|
|
1080
|
+
|
|
1081
|
+
function = pari_closures.function(name, row["summary"])
|
|
1082
|
+
else:
|
|
1083
|
+
function = PRELUDE.get(name) or _function(row)
|
|
1084
|
+
setattr(self, name, function)
|
|
1085
|
+
return function
|
|
1086
|
+
|
|
1087
|
+
def __dir__(self):
|
|
1088
|
+
"""List the available functions."""
|
|
1089
|
+
return sorted({*self._rows, "raw", "set_precision", "set_stack"})
|
|
1090
|
+
|
|
1091
|
+
def __repr__(self):
|
|
1092
|
+
"""Return a short description."""
|
|
1093
|
+
return f"<PARI functions ({len(self._rows)}), use dir(pari)>"
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
pari = PariNamespace(_ALL_ROWS)
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
# Power series operations SymPy does not have (M6 task 1). Each is here
|
|
1100
|
+
# because SymPy offers no equivalent, not merely a slower one: §1.4 rules
|
|
1101
|
+
# out a second way to write what Python can already write, which is why
|
|
1102
|
+
# there is no ``coefficient`` — ``s.coeff(x, n)`` is SymPy's and works.
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def series_reverse(s):
|
|
1106
|
+
"""Return the compositional inverse of a power series."""
|
|
1107
|
+
return from_pari(PARI.serreverse(to_pari(s)))
|
|
1108
|
+
|
|
1109
|
+
|
|
1110
|
+
def hadamard_product(s, t):
|
|
1111
|
+
"""Return the coefficientwise product of two power series."""
|
|
1112
|
+
return from_pari(PARI.serconvol(to_pari(s), to_pari(t)))
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
def series_laplace(s):
|
|
1116
|
+
"""Turn an exponential generating function into an ordinary one."""
|
|
1117
|
+
return from_pari(PARI.serlaplace(to_pari(s)))
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
# Dirichlet series and Euler products (M6 tasks 3 and 4).
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
def euler_product_series(factor, terms):
|
|
1124
|
+
"""Return the coefficients of a Dirichlet Euler product.
|
|
1125
|
+
|
|
1126
|
+
PARI's ``direuler``: ``factor(p, x)`` gives the local factor at the
|
|
1127
|
+
prime ``p`` as a rational function of ``x``, which stands for
|
|
1128
|
+
``p^{-s}``. Returns plain coefficients, so no PARI object outlives
|
|
1129
|
+
this call (M4).
|
|
1130
|
+
"""
|
|
1131
|
+
from er2.backends import pari_closures
|
|
1132
|
+
|
|
1133
|
+
direuler = pari_closures.function("direuler", "Dirichlet Euler product")
|
|
1134
|
+
return list(direuler(factor, 2, terms))
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
def euler_product(factor, start, stop):
|
|
1138
|
+
"""Return a numeric Euler product over the primes in a range.
|
|
1139
|
+
|
|
1140
|
+
PARI's ``prodeuler``: a floating-point approximation of the product
|
|
1141
|
+
of ``factor(p)`` over the primes between ``start`` and ``stop``.
|
|
1142
|
+
"""
|
|
1143
|
+
from er2.backends import pari_closures
|
|
1144
|
+
|
|
1145
|
+
prodeuler = pari_closures.function("prodeuler", "Euler product")
|
|
1146
|
+
return prodeuler(factor, start, stop)
|