applied-ai-018 commited on
Commit
fa6c897
·
verified ·
1 Parent(s): 6377ca4

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/abc.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/conftest.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/galgebra.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/this.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__init__.py +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_discrete_log.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_symbench.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py +83 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py +261 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py +134 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/crypto/__init__.py +35 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/crypto/crypto.py +3360 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py +562 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/polys/__init__.py +129 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/polys/appellseqs.py +269 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/polys/compatibility.py +1134 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/polys/constructor.py +387 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/polys/densearith.py +1875 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/polys/densebasic.py +1881 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/polys/densetools.py +1309 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/polys/dispersion.py +212 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/polys/distributedmodules.py +739 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/polys/domainmatrix.py +12 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/algebraicfield.py +605 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/complexfield.py +151 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/domain.py +1304 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/field.py +104 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/gmpyintegerring.py +104 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/modularinteger.py +205 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/old_fractionfield.py +185 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/old_polynomialring.py +462 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/pythonfinitefield.py +16 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/rationalfield.py +163 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/ring.py +118 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/polys/euclidtools.py +1893 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/polys/factortools.py +1502 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/polys/fglmtools.py +153 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/polys/fields.py +631 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/polys/galoistools.py +2363 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/polys/groebnertools.py +862 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/polys/heuristicgcd.py +149 -0
llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (28.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/abc.cpython-310.pyc ADDED
Binary file (3.53 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (2.55 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/galgebra.cpython-310.pyc ADDED
Binary file (290 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc ADDED
Binary file (197 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/__pycache__/this.cpython-310.pyc ADDED
Binary file (738 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (189 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_discrete_log.cpython-310.pyc ADDED
Binary file (2.01 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_symbench.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from time import time
3
+ from sympy.ntheory.residue_ntheory import (discrete_log,
4
+ _discrete_log_trial_mul, _discrete_log_shanks_steps,
5
+ _discrete_log_pollard_rho, _discrete_log_pohlig_hellman)
6
+
7
+
8
+ # Cyclic group (Z/pZ)* with p prime, order p - 1 and generator g
9
+ data_set_1 = [
10
+ # p, p - 1, g
11
+ [191, 190, 19],
12
+ [46639, 46638, 6],
13
+ [14789363, 14789362, 2],
14
+ [4254225211, 4254225210, 2],
15
+ [432751500361, 432751500360, 7],
16
+ [158505390797053, 158505390797052, 2],
17
+ [6575202655312007, 6575202655312006, 5],
18
+ [8430573471995353769, 8430573471995353768, 3],
19
+ [3938471339744997827267, 3938471339744997827266, 2],
20
+ [875260951364705563393093, 875260951364705563393092, 5],
21
+ ]
22
+
23
+
24
+ # Cyclic sub-groups of (Z/nZ)* with prime order p and generator g
25
+ # (n, p are primes and n = 2 * p + 1)
26
+ data_set_2 = [
27
+ # n, p, g
28
+ [227, 113, 3],
29
+ [2447, 1223, 2],
30
+ [24527, 12263, 2],
31
+ [245639, 122819, 2],
32
+ [2456747, 1228373, 3],
33
+ [24567899, 12283949, 3],
34
+ [245679023, 122839511, 2],
35
+ [2456791307, 1228395653, 3],
36
+ [24567913439, 12283956719, 2],
37
+ [245679135407, 122839567703, 2],
38
+ [2456791354763, 1228395677381, 3],
39
+ [24567913550903, 12283956775451, 2],
40
+ [245679135509519, 122839567754759, 2],
41
+ ]
42
+
43
+
44
+ # Cyclic sub-groups of (Z/nZ)* with smooth order o and generator g
45
+ data_set_3 = [
46
+ # n, o, g
47
+ [2**118, 2**116, 3],
48
+ ]
49
+
50
+
51
+ def bench_discrete_log(data_set, algo=None):
52
+ if algo is None:
53
+ f = discrete_log
54
+ elif algo == 'trial':
55
+ f = _discrete_log_trial_mul
56
+ elif algo == 'shanks':
57
+ f = _discrete_log_shanks_steps
58
+ elif algo == 'rho':
59
+ f = _discrete_log_pollard_rho
60
+ elif algo == 'ph':
61
+ f = _discrete_log_pohlig_hellman
62
+ else:
63
+ raise ValueError("Argument 'algo' should be one"
64
+ " of ('trial', 'shanks', 'rho' or 'ph')")
65
+
66
+ for i, data in enumerate(data_set):
67
+ for j, (n, p, g) in enumerate(data):
68
+ t = time()
69
+ l = f(n, pow(g, p - 1, n), g, p)
70
+ t = time() - t
71
+ print('[%02d-%03d] %15.10f' % (i, j, t))
72
+ assert l == p - 1
73
+
74
+
75
+ if __name__ == '__main__':
76
+ algo = sys.argv[1] \
77
+ if len(sys.argv) > 1 else None
78
+ data_set = [
79
+ data_set_1,
80
+ data_set_2,
81
+ data_set_3,
82
+ ]
83
+ bench_discrete_log(data_set, algo)
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # conceal the implicit import from the code quality tester
2
+ from sympy.core.numbers import (oo, pi)
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.special.bessel import besseli
7
+ from sympy.functions.special.gamma_functions import gamma
8
+ from sympy.integrals.integrals import integrate
9
+ from sympy.integrals.transforms import (mellin_transform,
10
+ inverse_fourier_transform, inverse_mellin_transform,
11
+ laplace_transform, inverse_laplace_transform, fourier_transform)
12
+
13
+ LT = laplace_transform
14
+ FT = fourier_transform
15
+ MT = mellin_transform
16
+ IFT = inverse_fourier_transform
17
+ ILT = inverse_laplace_transform
18
+ IMT = inverse_mellin_transform
19
+
20
+ from sympy.abc import x, y
21
+ nu, beta, rho = symbols('nu beta rho')
22
+
23
+ apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True)
24
+ k = Symbol('k', real=True)
25
+ negk = Symbol('k', negative=True)
26
+
27
+ mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True)
28
+ sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True,
29
+ finite=True, positive=True)
30
+ rate = Symbol('lambda', positive=True)
31
+
32
+
33
+ def normal(x, mu, sigma):
34
+ return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
35
+
36
+
37
+ def exponential(x, rate):
38
+ return rate*exp(-rate*x)
39
+ alpha, beta = symbols('alpha beta', positive=True)
40
+ betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
41
+ /gamma(alpha)/gamma(beta)
42
+ kint = Symbol('k', integer=True, positive=True)
43
+ chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2)
44
+ chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
45
+ dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1)
46
+ d1, d2 = symbols('d1 d2', positive=True)
47
+ f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
48
+ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
49
+ nupos, sigmapos = symbols('nu sigma', positive=True)
50
+ rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x*
51
+ nupos/sigmapos**2)
52
+ mu = Symbol('mu', real=True)
53
+ laplace = exp(-abs(x - mu)/bpos)/2/bpos
54
+
55
+ u = Symbol('u', polar=True)
56
+ tpos = Symbol('t', positive=True)
57
+
58
+
59
+ def E(expr):
60
+ integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
61
+ (x, 0, oo), (y, -oo, oo), meijerg=True)
62
+ integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
63
+ (y, -oo, oo), (x, 0, oo), meijerg=True)
64
+
65
+ bench = [
66
+ 'MT(x**nu*Heaviside(x - 1), x, s)',
67
+ 'MT(x**nu*Heaviside(1 - x), x, s)',
68
+ 'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)',
69
+ 'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)',
70
+ 'MT((1+x)**(-rho), x, s)',
71
+ 'MT(abs(1-x)**(-rho), x, s)',
72
+ 'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)',
73
+ 'MT((x**a-b**a)/(x-b), x, s)',
74
+ 'MT((x**a-bpos**a)/(x-bpos), x, s)',
75
+ 'MT(exp(-x), x, s)',
76
+ 'MT(exp(-1/x), x, s)',
77
+ 'MT(log(x)**4*Heaviside(1-x), x, s)',
78
+ 'MT(log(x)**3*Heaviside(x-1), x, s)',
79
+ 'MT(log(x + 1), x, s)',
80
+ 'MT(log(1/x + 1), x, s)',
81
+ 'MT(log(abs(1 - x)), x, s)',
82
+ 'MT(log(abs(1 - 1/x)), x, s)',
83
+ 'MT(log(x)/(x+1), x, s)',
84
+ 'MT(log(x)**2/(x+1), x, s)',
85
+ 'MT(log(x)/(x+1)**2, x, s)',
86
+ 'MT(erf(sqrt(x)), x, s)',
87
+
88
+ 'MT(besselj(a, 2*sqrt(x)), x, s)',
89
+ 'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)',
90
+ 'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)',
91
+ 'MT(besselj(a, sqrt(x))**2, x, s)',
92
+ 'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)',
93
+ 'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)',
94
+ 'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)',
95
+ 'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)',
96
+ 'MT(bessely(a, 2*sqrt(x)), x, s)',
97
+ 'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)',
98
+ 'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)',
99
+ 'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)',
100
+ 'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)',
101
+ 'MT(bessely(a, sqrt(x))**2, x, s)',
102
+
103
+ 'MT(besselk(a, 2*sqrt(x)), x, s)',
104
+ 'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)',
105
+ 'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)',
106
+ 'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)',
107
+ 'MT(exp(-x/2)*besselk(a, x/2), x, s)',
108
+
109
+ # later: ILT, IMT
110
+
111
+ 'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)',
112
+ 'LT(t**apos, t, s)',
113
+ 'LT(Heaviside(t), t, s)',
114
+ 'LT(Heaviside(t - apos), t, s)',
115
+ 'LT(1 - exp(-apos*t), t, s)',
116
+ 'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)',
117
+ 'LT(exp(t), t, s)',
118
+ 'LT(exp(2*t), t, s)',
119
+ 'LT(exp(apos*t), t, s)',
120
+ 'LT(log(t/apos), t, s)',
121
+ 'LT(erf(t), t, s)',
122
+ 'LT(sin(apos*t), t, s)',
123
+ 'LT(cos(apos*t), t, s)',
124
+ 'LT(exp(-apos*t)*sin(bpos*t), t, s)',
125
+ 'LT(exp(-apos*t)*cos(bpos*t), t, s)',
126
+ 'LT(besselj(0, t), t, s, noconds=True)',
127
+ 'LT(besselj(1, t), t, s, noconds=True)',
128
+
129
+ 'FT(Heaviside(1 - abs(2*apos*x)), x, k)',
130
+ 'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)',
131
+ 'FT(exp(-apos*x)*Heaviside(x), x, k)',
132
+ 'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)',
133
+ 'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)',
134
+ 'IFT(1/(apos + 2*pi*I*x), x, negk)',
135
+ 'FT(x*exp(-apos*x)*Heaviside(x), x, k)',
136
+ 'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)',
137
+ 'FT(exp(-apos*x**2), x, k)',
138
+ 'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)',
139
+ 'FT(exp(-apos*abs(x)), x, k)',
140
+
141
+ 'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
142
+ 'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
143
+ 'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
144
+ 'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
145
+ 'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
146
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
147
+ 'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
148
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
149
+ 'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
150
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
151
+ 'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
152
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
153
+ 'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
154
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
155
+ 'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
156
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
157
+ 'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
158
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
159
+ 'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
160
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
161
+ 'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)',
162
+ 'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)',
163
+ 'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)',
164
+ 'E(1)',
165
+ 'E(x*y)',
166
+ 'E(x*y**2)',
167
+ 'E((x+y+1)**2)',
168
+ 'E(x+y+1)',
169
+ 'E((x+y-1)**2)',
170
+ 'integrate(betadist, (x, 0, oo), meijerg=True)',
171
+ 'integrate(x*betadist, (x, 0, oo), meijerg=True)',
172
+ 'integrate(x**2*betadist, (x, 0, oo), meijerg=True)',
173
+ 'integrate(chi, (x, 0, oo), meijerg=True)',
174
+ 'integrate(x*chi, (x, 0, oo), meijerg=True)',
175
+ 'integrate(x**2*chi, (x, 0, oo), meijerg=True)',
176
+ 'integrate(chisquared, (x, 0, oo), meijerg=True)',
177
+ 'integrate(x*chisquared, (x, 0, oo), meijerg=True)',
178
+ 'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)',
179
+ 'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)',
180
+ 'integrate(dagum, (x, 0, oo), meijerg=True)',
181
+ 'integrate(x*dagum, (x, 0, oo), meijerg=True)',
182
+ 'integrate(x**2*dagum, (x, 0, oo), meijerg=True)',
183
+ 'integrate(f, (x, 0, oo), meijerg=True)',
184
+ 'integrate(x*f, (x, 0, oo), meijerg=True)',
185
+ 'integrate(x**2*f, (x, 0, oo), meijerg=True)',
186
+ 'integrate(rice, (x, 0, oo), meijerg=True)',
187
+ 'integrate(laplace, (x, -oo, oo), meijerg=True)',
188
+ 'integrate(x*laplace, (x, -oo, oo), meijerg=True)',
189
+ 'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)',
190
+ 'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))',
191
+
192
+ 'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)',
193
+ 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
194
+ 'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)',
195
+ 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
196
+ 'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)',
197
+
198
+ 'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))',
199
+ "gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))",
200
+
201
+ 'mellin_transform(E1(x), x, s)',
202
+ 'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))',
203
+ 'mellin_transform(expint(a, x), x, s)',
204
+ 'mellin_transform(Si(x), x, s)',
205
+ 'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))',
206
+ 'mellin_transform(Ci(sqrt(x)), x, s)',
207
+ 'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))',
208
+ 'laplace_transform(Ci(x), x, s)',
209
+ 'laplace_transform(expint(a, x), x, s)',
210
+ 'laplace_transform(expint(1, x), x, s)',
211
+ 'laplace_transform(expint(2, x), x, s)',
212
+ 'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)',
213
+ 'inverse_laplace_transform(log(s + 1)/s, s, x)',
214
+ 'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)',
215
+ 'laplace_transform(Chi(x), x, s)',
216
+ 'laplace_transform(Shi(x), x, s)',
217
+
218
+ 'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")',
219
+ 'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")',
220
+ 'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")',
221
+ 'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)',
222
+ 'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)',
223
+ 'integrate(sin(x)/x, (x, 0, z), meijerg=True)',
224
+ 'integrate(sinh(x)/x, (x, 0, z), meijerg=True)',
225
+ 'integrate(exp(-x)/x, x, meijerg=True)',
226
+ 'integrate(exp(-x)/x**2, x, meijerg=True)',
227
+ 'integrate(cos(u)/u, u, meijerg=True)',
228
+ 'integrate(cosh(u)/u, u, meijerg=True)',
229
+ 'integrate(expint(1, x), x, meijerg=True)',
230
+ 'integrate(expint(2, x), x, meijerg=True)',
231
+ 'integrate(Si(x), x, meijerg=True)',
232
+ 'integrate(Ci(u), u, meijerg=True)',
233
+ 'integrate(Shi(x), x, meijerg=True)',
234
+ 'integrate(Chi(u), u, meijerg=True)',
235
+ 'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)',
236
+ 'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)'
237
+ ]
238
+
239
+ from time import time
240
+ from sympy.core.cache import clear_cache
241
+ import sys
242
+
243
+ timings = []
244
+
245
+ if __name__ == '__main__':
246
+ for n, string in enumerate(bench):
247
+ clear_cache()
248
+ _t = time()
249
+ exec(string)
250
+ _t = time() - _t
251
+ timings += [(_t, string)]
252
+ sys.stdout.write('.')
253
+ sys.stdout.flush()
254
+ if n % (len(bench) // 10) == 0:
255
+ sys.stdout.write('%s' % (10*n // len(bench)))
256
+ print()
257
+
258
+ timings.sort(key=lambda x: -x[0])
259
+
260
+ for ti, string in timings:
261
+ print('%.2fs %s' % (ti, string))
llmeval-env/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from sympy.core.random import random
3
+ from sympy.core.numbers import (I, Integer, pi)
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.core.sympify import sympify
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.trigonometric import sin
8
+ from sympy.polys.polytools import factor
9
+ from sympy.simplify.simplify import simplify
10
+ from sympy.abc import x, y, z
11
+ from timeit import default_timer as clock
12
+
13
+
14
+ def bench_R1():
15
+ "real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))"
16
+ def f(z):
17
+ return sqrt(Integer(1)/3)*z**2 + I/3
18
+ f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0]
19
+
20
+
21
+ def bench_R2():
22
+ "Hermite polynomial hermite(15, y)"
23
+ def hermite(n, y):
24
+ if n == 1:
25
+ return 2*y
26
+ if n == 0:
27
+ return 1
28
+ return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand()
29
+
30
+ hermite(15, y)
31
+
32
+
33
+ def bench_R3():
34
+ "a = [bool(f==f) for _ in range(10)]"
35
+ f = x + y + z
36
+ [bool(f == f) for _ in range(10)]
37
+
38
+
39
+ def bench_R4():
40
+ # we don't have Tuples
41
+ pass
42
+
43
+
44
+ def bench_R5():
45
+ "blowup(L, 8); L=uniq(L)"
46
+ def blowup(L, n):
47
+ for i in range(n):
48
+ L.append( (L[i] + L[i + 1]) * L[i + 2] )
49
+
50
+ def uniq(x):
51
+ v = set(x)
52
+ return v
53
+ L = [x, y, z]
54
+ blowup(L, 8)
55
+ L = uniq(L)
56
+
57
+
58
+ def bench_R6():
59
+ "sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in range(100))"
60
+ sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in range(100))
61
+
62
+
63
+ def bench_R7():
64
+ "[f.subs(x, random()) for _ in range(10**4)]"
65
+ f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21
66
+ [f.subs(x, random()) for _ in range(10**4)]
67
+
68
+
69
+ def bench_R8():
70
+ "right(x^2,0,5,10^4)"
71
+ def right(f, a, b, n):
72
+ a = sympify(a)
73
+ b = sympify(b)
74
+ n = sympify(n)
75
+ x = f.atoms(Symbol).pop()
76
+ Deltax = (b - a)/n
77
+ c = a
78
+ est = 0
79
+ for i in range(n):
80
+ c += Deltax
81
+ est += f.subs(x, c)
82
+ return est*Deltax
83
+
84
+ right(x**2, 0, 5, 10**4)
85
+
86
+
87
+ def _bench_R9():
88
+ "factor(x^20 - pi^5*y^20)"
89
+ factor(x**20 - pi**5*y**20)
90
+
91
+
92
+ def bench_R10():
93
+ "v = [-pi,-pi+1/10..,pi]"
94
+ def srange(min, max, step):
95
+ v = [min]
96
+ while (max - v[-1]).evalf() > 0:
97
+ v.append(v[-1] + step)
98
+ return v[:-1]
99
+ srange(-pi, pi, sympify(1)/10)
100
+
101
+
102
+ def bench_R11():
103
+ "a = [random() + random()*I for w in [0..1000]]"
104
+ [random() + random()*I for w in range(1000)]
105
+
106
+
107
+ def bench_S1():
108
+ "e=(x+y+z+1)**7;f=e*(e+1);f.expand()"
109
+ e = (x + y + z + 1)**7
110
+ f = e*(e + 1)
111
+ f.expand()
112
+
113
+
114
+ if __name__ == '__main__':
115
+ benchmarks = [
116
+ bench_R1,
117
+ bench_R2,
118
+ bench_R3,
119
+ bench_R5,
120
+ bench_R6,
121
+ bench_R7,
122
+ bench_R8,
123
+ #_bench_R9,
124
+ bench_R10,
125
+ bench_R11,
126
+ #bench_S1,
127
+ ]
128
+
129
+ report = []
130
+ for b in benchmarks:
131
+ t = clock()
132
+ b()
133
+ t = clock() - t
134
+ print("%s%65s: %f" % (b.__name__, b.__doc__, t))
llmeval-env/lib/python3.10/site-packages/sympy/crypto/__init__.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.crypto.crypto import (cycle_list,
2
+ encipher_shift, encipher_affine, encipher_substitution,
3
+ check_and_join, encipher_vigenere, decipher_vigenere, bifid5_square,
4
+ bifid6_square, encipher_hill, decipher_hill,
5
+ encipher_bifid5, encipher_bifid6, decipher_bifid5,
6
+ decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa,
7
+ kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key,
8
+ rsa_public_key, encipher_rsa, lfsr_connection_polynomial,
9
+ lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse,
10
+ elgamal_private_key, elgamal_public_key, decipher_elgamal,
11
+ encipher_elgamal, dh_private_key, dh_public_key, dh_shared_key,
12
+ padded_key, encipher_bifid, decipher_bifid, bifid_square, bifid5,
13
+ bifid6, bifid10, decipher_gm, encipher_gm, gm_public_key,
14
+ gm_private_key, bg_private_key, bg_public_key, encipher_bg, decipher_bg,
15
+ encipher_rot13, decipher_rot13, encipher_atbash, decipher_atbash,
16
+ encipher_railfence, decipher_railfence)
17
+
18
+ __all__ = [
19
+ 'cycle_list', 'encipher_shift', 'encipher_affine',
20
+ 'encipher_substitution', 'check_and_join', 'encipher_vigenere',
21
+ 'decipher_vigenere', 'bifid5_square', 'bifid6_square', 'encipher_hill',
22
+ 'decipher_hill', 'encipher_bifid5', 'encipher_bifid6', 'decipher_bifid5',
23
+ 'decipher_bifid6', 'encipher_kid_rsa', 'decipher_kid_rsa',
24
+ 'kid_rsa_private_key', 'kid_rsa_public_key', 'decipher_rsa',
25
+ 'rsa_private_key', 'rsa_public_key', 'encipher_rsa',
26
+ 'lfsr_connection_polynomial', 'lfsr_autocorrelation', 'lfsr_sequence',
27
+ 'encode_morse', 'decode_morse', 'elgamal_private_key',
28
+ 'elgamal_public_key', 'decipher_elgamal', 'encipher_elgamal',
29
+ 'dh_private_key', 'dh_public_key', 'dh_shared_key', 'padded_key',
30
+ 'encipher_bifid', 'decipher_bifid', 'bifid_square', 'bifid5', 'bifid6',
31
+ 'bifid10', 'decipher_gm', 'encipher_gm', 'gm_public_key',
32
+ 'gm_private_key', 'bg_private_key', 'bg_public_key', 'encipher_bg',
33
+ 'decipher_bg', 'encipher_rot13', 'decipher_rot13', 'encipher_atbash',
34
+ 'decipher_atbash', 'encipher_railfence', 'decipher_railfence',
35
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.65 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc ADDED
Binary file (93.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/crypto/crypto.py ADDED
@@ -0,0 +1,3360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file contains some classical ciphers and routines
3
+ implementing a linear-feedback shift register (LFSR)
4
+ and the Diffie-Hellman key exchange.
5
+
6
+ .. warning::
7
+
8
+ This module is intended for educational purposes only. Do not use the
9
+ functions in this module for real cryptographic applications. If you wish
10
+ to encrypt real data, we recommend using something like the `cryptography
11
+ <https://cryptography.io/en/latest/>`_ module.
12
+
13
+ """
14
+
15
+ from string import whitespace, ascii_uppercase as uppercase, printable
16
+ from functools import reduce
17
+ import warnings
18
+
19
+ from itertools import cycle
20
+
21
+ from sympy.core import Symbol
22
+ from sympy.core.numbers import igcdex, mod_inverse, igcd, Rational
23
+ from sympy.core.random import _randrange, _randint
24
+ from sympy.matrices import Matrix
25
+ from sympy.ntheory import isprime, primitive_root, factorint
26
+ from sympy.ntheory import totient as _euler
27
+ from sympy.ntheory import reduced_totient as _carmichael
28
+ from sympy.ntheory.generate import nextprime
29
+ from sympy.ntheory.modular import crt
30
+ from sympy.polys.domains import FF
31
+ from sympy.polys.polytools import gcd, Poly
32
+ from sympy.utilities.misc import as_int, filldedent, translate
33
+ from sympy.utilities.iterables import uniq, multiset
34
+
35
+
36
+ class NonInvertibleCipherWarning(RuntimeWarning):
37
+ """A warning raised if the cipher is not invertible."""
38
+ def __init__(self, msg):
39
+ self.fullMessage = msg
40
+
41
+ def __str__(self):
42
+ return '\n\t' + self.fullMessage
43
+
44
+ def warn(self, stacklevel=3):
45
+ warnings.warn(self, stacklevel=stacklevel)
46
+
47
+
48
+ def AZ(s=None):
49
+ """Return the letters of ``s`` in uppercase. In case more than
50
+ one string is passed, each of them will be processed and a list
51
+ of upper case strings will be returned.
52
+
53
+ Examples
54
+ ========
55
+
56
+ >>> from sympy.crypto.crypto import AZ
57
+ >>> AZ('Hello, world!')
58
+ 'HELLOWORLD'
59
+ >>> AZ('Hello, world!'.split())
60
+ ['HELLO', 'WORLD']
61
+
62
+ See Also
63
+ ========
64
+
65
+ check_and_join
66
+
67
+ """
68
+ if not s:
69
+ return uppercase
70
+ t = isinstance(s, str)
71
+ if t:
72
+ s = [s]
73
+ rv = [check_and_join(i.upper().split(), uppercase, filter=True)
74
+ for i in s]
75
+ if t:
76
+ return rv[0]
77
+ return rv
78
+
79
+ bifid5 = AZ().replace('J', '')
80
+ bifid6 = AZ() + '0123456789'
81
+ bifid10 = printable
82
+
83
+
84
+ def padded_key(key, symbols):
85
+ """Return a string of the distinct characters of ``symbols`` with
86
+ those of ``key`` appearing first. A ValueError is raised if
87
+ a) there are duplicate characters in ``symbols`` or
88
+ b) there are characters in ``key`` that are not in ``symbols``.
89
+
90
+ Examples
91
+ ========
92
+
93
+ >>> from sympy.crypto.crypto import padded_key
94
+ >>> padded_key('PUPPY', 'OPQRSTUVWXY')
95
+ 'PUYOQRSTVWX'
96
+ >>> padded_key('RSA', 'ARTIST')
97
+ Traceback (most recent call last):
98
+ ...
99
+ ValueError: duplicate characters in symbols: T
100
+
101
+ """
102
+ syms = list(uniq(symbols))
103
+ if len(syms) != len(symbols):
104
+ extra = ''.join(sorted({
105
+ i for i in symbols if symbols.count(i) > 1}))
106
+ raise ValueError('duplicate characters in symbols: %s' % extra)
107
+ extra = set(key) - set(syms)
108
+ if extra:
109
+ raise ValueError(
110
+ 'characters in key but not symbols: %s' % ''.join(
111
+ sorted(extra)))
112
+ key0 = ''.join(list(uniq(key)))
113
+ # remove from syms characters in key0
114
+ return key0 + translate(''.join(syms), None, key0)
115
+
116
+
117
+ def check_and_join(phrase, symbols=None, filter=None):
118
+ """
119
+ Joins characters of ``phrase`` and if ``symbols`` is given, raises
120
+ an error if any character in ``phrase`` is not in ``symbols``.
121
+
122
+ Parameters
123
+ ==========
124
+
125
+ phrase
126
+ String or list of strings to be returned as a string.
127
+
128
+ symbols
129
+ Iterable of characters allowed in ``phrase``.
130
+
131
+ If ``symbols`` is ``None``, no checking is performed.
132
+
133
+ Examples
134
+ ========
135
+
136
+ >>> from sympy.crypto.crypto import check_and_join
137
+ >>> check_and_join('a phrase')
138
+ 'a phrase'
139
+ >>> check_and_join('a phrase'.upper().split())
140
+ 'APHRASE'
141
+ >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
142
+ 'ARAE'
143
+ >>> check_and_join('a phrase!'.upper().split(), 'ARE')
144
+ Traceback (most recent call last):
145
+ ...
146
+ ValueError: characters in phrase but not symbols: "!HPS"
147
+
148
+ """
149
+ rv = ''.join(''.join(phrase))
150
+ if symbols is not None:
151
+ symbols = check_and_join(symbols)
152
+ missing = ''.join(sorted(set(rv) - set(symbols)))
153
+ if missing:
154
+ if not filter:
155
+ raise ValueError(
156
+ 'characters in phrase but not symbols: "%s"' % missing)
157
+ rv = translate(rv, None, missing)
158
+ return rv
159
+
160
+
161
+ def _prep(msg, key, alp, default=None):
162
+ if not alp:
163
+ if not default:
164
+ alp = AZ()
165
+ msg = AZ(msg)
166
+ key = AZ(key)
167
+ else:
168
+ alp = default
169
+ else:
170
+ alp = ''.join(alp)
171
+ key = check_and_join(key, alp, filter=True)
172
+ msg = check_and_join(msg, alp, filter=True)
173
+ return msg, key, alp
174
+
175
+
176
+ def cycle_list(k, n):
177
+ """
178
+ Returns the elements of the list ``range(n)`` shifted to the
179
+ left by ``k`` (so the list starts with ``k`` (mod ``n``)).
180
+
181
+ Examples
182
+ ========
183
+
184
+ >>> from sympy.crypto.crypto import cycle_list
185
+ >>> cycle_list(3, 10)
186
+ [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
187
+
188
+ """
189
+ k = k % n
190
+ return list(range(k, n)) + list(range(k))
191
+
192
+
193
+ ######## shift cipher examples ############
194
+
195
+
196
+ def encipher_shift(msg, key, symbols=None):
197
+ """
198
+ Performs shift cipher encryption on plaintext msg, and returns the
199
+ ciphertext.
200
+
201
+ Parameters
202
+ ==========
203
+
204
+ key : int
205
+ The secret key.
206
+
207
+ msg : str
208
+ Plaintext of upper-case letters.
209
+
210
+ Returns
211
+ =======
212
+
213
+ str
214
+ Ciphertext of upper-case letters.
215
+
216
+ Examples
217
+ ========
218
+
219
+ >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
220
+ >>> msg = "GONAVYBEATARMY"
221
+ >>> ct = encipher_shift(msg, 1); ct
222
+ 'HPOBWZCFBUBSNZ'
223
+
224
+ To decipher the shifted text, change the sign of the key:
225
+
226
+ >>> encipher_shift(ct, -1)
227
+ 'GONAVYBEATARMY'
228
+
229
+ There is also a convenience function that does this with the
230
+ original key:
231
+
232
+ >>> decipher_shift(ct, 1)
233
+ 'GONAVYBEATARMY'
234
+
235
+ Notes
236
+ =====
237
+
238
+ ALGORITHM:
239
+
240
+ STEPS:
241
+ 0. Number the letters of the alphabet from 0, ..., N
242
+ 1. Compute from the string ``msg`` a list ``L1`` of
243
+ corresponding integers.
244
+ 2. Compute from the list ``L1`` a new list ``L2``, given by
245
+ adding ``(k mod 26)`` to each element in ``L1``.
246
+ 3. Compute from the list ``L2`` a string ``ct`` of
247
+ corresponding letters.
248
+
249
+ The shift cipher is also called the Caesar cipher, after
250
+ Julius Caesar, who, according to Suetonius, used it with a
251
+ shift of three to protect messages of military significance.
252
+ Caesar's nephew Augustus reportedly used a similar cipher, but
253
+ with a right shift of 1.
254
+
255
+ References
256
+ ==========
257
+
258
+ .. [1] https://en.wikipedia.org/wiki/Caesar_cipher
259
+ .. [2] https://mathworld.wolfram.com/CaesarsMethod.html
260
+
261
+ See Also
262
+ ========
263
+
264
+ decipher_shift
265
+
266
+ """
267
+ msg, _, A = _prep(msg, '', symbols)
268
+ shift = len(A) - key % len(A)
269
+ key = A[shift:] + A[:shift]
270
+ return translate(msg, key, A)
271
+
272
+
273
+ def decipher_shift(msg, key, symbols=None):
274
+ """
275
+ Return the text by shifting the characters of ``msg`` to the
276
+ left by the amount given by ``key``.
277
+
278
+ Examples
279
+ ========
280
+
281
+ >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
282
+ >>> msg = "GONAVYBEATARMY"
283
+ >>> ct = encipher_shift(msg, 1); ct
284
+ 'HPOBWZCFBUBSNZ'
285
+
286
+ To decipher the shifted text, change the sign of the key:
287
+
288
+ >>> encipher_shift(ct, -1)
289
+ 'GONAVYBEATARMY'
290
+
291
+ Or use this function with the original key:
292
+
293
+ >>> decipher_shift(ct, 1)
294
+ 'GONAVYBEATARMY'
295
+
296
+ """
297
+ return encipher_shift(msg, -key, symbols)
298
+
299
+ def encipher_rot13(msg, symbols=None):
300
+ """
301
+ Performs the ROT13 encryption on a given plaintext ``msg``.
302
+
303
+ Explanation
304
+ ===========
305
+
306
+ ROT13 is a substitution cipher which substitutes each letter
307
+ in the plaintext message for the letter furthest away from it
308
+ in the English alphabet.
309
+
310
+ Equivalently, it is just a Caeser (shift) cipher with a shift
311
+ key of 13 (midway point of the alphabet).
312
+
313
+ References
314
+ ==========
315
+
316
+ .. [1] https://en.wikipedia.org/wiki/ROT13
317
+
318
+ See Also
319
+ ========
320
+
321
+ decipher_rot13
322
+ encipher_shift
323
+
324
+ """
325
+ return encipher_shift(msg, 13, symbols)
326
+
327
+ def decipher_rot13(msg, symbols=None):
328
+ """
329
+ Performs the ROT13 decryption on a given plaintext ``msg``.
330
+
331
+ Explanation
332
+ ============
333
+
334
+ ``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
335
+ ``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
336
+ key of 13 will return the same results. Nonetheless,
337
+ ``decipher_rot13`` has nonetheless been explicitly defined here for
338
+ consistency.
339
+
340
+ Examples
341
+ ========
342
+
343
+ >>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
344
+ >>> msg = 'GONAVYBEATARMY'
345
+ >>> ciphertext = encipher_rot13(msg);ciphertext
346
+ 'TBANILORNGNEZL'
347
+ >>> decipher_rot13(ciphertext)
348
+ 'GONAVYBEATARMY'
349
+ >>> encipher_rot13(msg) == decipher_rot13(msg)
350
+ True
351
+ >>> msg == decipher_rot13(ciphertext)
352
+ True
353
+
354
+ """
355
+ return decipher_shift(msg, 13, symbols)
356
+
357
+ ######## affine cipher examples ############
358
+
359
+
360
+ def encipher_affine(msg, key, symbols=None, _inverse=False):
361
+ r"""
362
+ Performs the affine cipher encryption on plaintext ``msg``, and
363
+ returns the ciphertext.
364
+
365
+ Explanation
366
+ ===========
367
+
368
+ Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
369
+ where ``N`` is the number of characters in the alphabet.
370
+ Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
371
+ where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
372
+ In particular, for the map to be invertible, we need
373
+ `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
374
+ not true.
375
+
376
+ Parameters
377
+ ==========
378
+
379
+ msg : str
380
+ Characters that appear in ``symbols``.
381
+
382
+ a, b : int, int
383
+ A pair integers, with ``gcd(a, N) = 1`` (the secret key).
384
+
385
+ symbols
386
+ String of characters (default = uppercase letters).
387
+
388
+ When no symbols are given, ``msg`` is converted to upper case
389
+ letters and all other characters are ignored.
390
+
391
+ Returns
392
+ =======
393
+
394
+ ct
395
+ String of characters (the ciphertext message)
396
+
397
+ Notes
398
+ =====
399
+
400
+ ALGORITHM:
401
+
402
+ STEPS:
403
+ 0. Number the letters of the alphabet from 0, ..., N
404
+ 1. Compute from the string ``msg`` a list ``L1`` of
405
+ corresponding integers.
406
+ 2. Compute from the list ``L1`` a new list ``L2``, given by
407
+ replacing ``x`` by ``a*x + b (mod N)``, for each element
408
+ ``x`` in ``L1``.
409
+ 3. Compute from the list ``L2`` a string ``ct`` of
410
+ corresponding letters.
411
+
412
+ This is a straightforward generalization of the shift cipher with
413
+ the added complexity of requiring 2 characters to be deciphered in
414
+ order to recover the key.
415
+
416
+ References
417
+ ==========
418
+
419
+ .. [1] https://en.wikipedia.org/wiki/Affine_cipher
420
+
421
+ See Also
422
+ ========
423
+
424
+ decipher_affine
425
+
426
+ """
427
+ msg, _, A = _prep(msg, '', symbols)
428
+ N = len(A)
429
+ a, b = key
430
+ assert gcd(a, N) == 1
431
+ if _inverse:
432
+ c = mod_inverse(a, N)
433
+ d = -b*c
434
+ a, b = c, d
435
+ B = ''.join([A[(a*i + b) % N] for i in range(N)])
436
+ return translate(msg, A, B)
437
+
438
+
439
+ def decipher_affine(msg, key, symbols=None):
440
+ r"""
441
+ Return the deciphered text that was made from the mapping,
442
+ `x \rightarrow ax+b` (mod `N`), where ``N`` is the
443
+ number of characters in the alphabet. Deciphering is done by
444
+ reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
445
+ where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
446
+
447
+ Examples
448
+ ========
449
+
450
+ >>> from sympy.crypto.crypto import encipher_affine, decipher_affine
451
+ >>> msg = "GO NAVY BEAT ARMY"
452
+ >>> key = (3, 1)
453
+ >>> encipher_affine(msg, key)
454
+ 'TROBMVENBGBALV'
455
+ >>> decipher_affine(_, key)
456
+ 'GONAVYBEATARMY'
457
+
458
+ See Also
459
+ ========
460
+
461
+ encipher_affine
462
+
463
+ """
464
+ return encipher_affine(msg, key, symbols, _inverse=True)
465
+
466
+
467
+ def encipher_atbash(msg, symbols=None):
468
+ r"""
469
+ Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
470
+
471
+ Explanation
472
+ ===========
473
+
474
+ Atbash is a substitution cipher originally used to encrypt the Hebrew
475
+ alphabet. Atbash works on the principle of mapping each alphabet to its
476
+ reverse / counterpart (i.e. a would map to z, b to y etc.)
477
+
478
+ Atbash is functionally equivalent to the affine cipher with ``a = 25``
479
+ and ``b = 25``
480
+
481
+ See Also
482
+ ========
483
+
484
+ decipher_atbash
485
+
486
+ """
487
+ return encipher_affine(msg, (25, 25), symbols)
488
+
489
+
490
+ def decipher_atbash(msg, symbols=None):
491
+ r"""
492
+ Deciphers a given ``msg`` using Atbash cipher and returns it.
493
+
494
+ Explanation
495
+ ===========
496
+
497
+ ``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
498
+ However, it has still been added as a separate function to maintain
499
+ consistency.
500
+
501
+ Examples
502
+ ========
503
+
504
+ >>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
505
+ >>> msg = 'GONAVYBEATARMY'
506
+ >>> encipher_atbash(msg)
507
+ 'TLMZEBYVZGZINB'
508
+ >>> decipher_atbash(msg)
509
+ 'TLMZEBYVZGZINB'
510
+ >>> encipher_atbash(msg) == decipher_atbash(msg)
511
+ True
512
+ >>> msg == encipher_atbash(encipher_atbash(msg))
513
+ True
514
+
515
+ References
516
+ ==========
517
+
518
+ .. [1] https://en.wikipedia.org/wiki/Atbash
519
+
520
+ See Also
521
+ ========
522
+
523
+ encipher_atbash
524
+
525
+ """
526
+ return decipher_affine(msg, (25, 25), symbols)
527
+
528
+ #################### substitution cipher ###########################
529
+
530
+
531
+ def encipher_substitution(msg, old, new=None):
532
+ r"""
533
+ Returns the ciphertext obtained by replacing each character that
534
+ appears in ``old`` with the corresponding character in ``new``.
535
+ If ``old`` is a mapping, then new is ignored and the replacements
536
+ defined by ``old`` are used.
537
+
538
+ Explanation
539
+ ===========
540
+
541
+ This is a more general than the affine cipher in that the key can
542
+ only be recovered by determining the mapping for each symbol.
543
+ Though in practice, once a few symbols are recognized the mappings
544
+ for other characters can be quickly guessed.
545
+
546
+ Examples
547
+ ========
548
+
549
+ >>> from sympy.crypto.crypto import encipher_substitution, AZ
550
+ >>> old = 'OEYAG'
551
+ >>> new = '034^6'
552
+ >>> msg = AZ("go navy! beat army!")
553
+ >>> ct = encipher_substitution(msg, old, new); ct
554
+ '60N^V4B3^T^RM4'
555
+
556
+ To decrypt a substitution, reverse the last two arguments:
557
+
558
+ >>> encipher_substitution(ct, new, old)
559
+ 'GONAVYBEATARMY'
560
+
561
+ In the special case where ``old`` and ``new`` are a permutation of
562
+ order 2 (representing a transposition of characters) their order
563
+ is immaterial:
564
+
565
+ >>> old = 'NAVY'
566
+ >>> new = 'ANYV'
567
+ >>> encipher = lambda x: encipher_substitution(x, old, new)
568
+ >>> encipher('NAVY')
569
+ 'ANYV'
570
+ >>> encipher(_)
571
+ 'NAVY'
572
+
573
+ The substitution cipher, in general, is a method
574
+ whereby "units" (not necessarily single characters) of plaintext
575
+ are replaced with ciphertext according to a regular system.
576
+
577
+ >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
578
+ >>> print(encipher_substitution('abc', ords))
579
+ \97\98\99
580
+
581
+ References
582
+ ==========
583
+
584
+ .. [1] https://en.wikipedia.org/wiki/Substitution_cipher
585
+
586
+ """
587
+ return translate(msg, old, new)
588
+
589
+
590
+ ######################################################################
591
+ #################### Vigenere cipher examples ########################
592
+ ######################################################################
593
+
594
+ def encipher_vigenere(msg, key, symbols=None):
595
+ """
596
+ Performs the Vigenere cipher encryption on plaintext ``msg``, and
597
+ returns the ciphertext.
598
+
599
+ Examples
600
+ ========
601
+
602
+ >>> from sympy.crypto.crypto import encipher_vigenere, AZ
603
+ >>> key = "encrypt"
604
+ >>> msg = "meet me on monday"
605
+ >>> encipher_vigenere(msg, key)
606
+ 'QRGKKTHRZQEBPR'
607
+
608
+ Section 1 of the Kryptos sculpture at the CIA headquarters
609
+ uses this cipher and also changes the order of the
610
+ alphabet [2]_. Here is the first line of that section of
611
+ the sculpture:
612
+
613
+ >>> from sympy.crypto.crypto import decipher_vigenere, padded_key
614
+ >>> alp = padded_key('KRYPTOS', AZ())
615
+ >>> key = 'PALIMPSEST'
616
+ >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
617
+ >>> decipher_vigenere(msg, key, alp)
618
+ 'BETWEENSUBTLESHADINGANDTHEABSENC'
619
+
620
+ Explanation
621
+ ===========
622
+
623
+ The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
624
+ century diplomat and cryptographer, by a historical accident.
625
+ Vigenere actually invented a different and more complicated cipher.
626
+ The so-called *Vigenere cipher* was actually invented
627
+ by Giovan Batista Belaso in 1553.
628
+
629
+ This cipher was used in the 1800's, for example, during the American
630
+ Civil War. The Confederacy used a brass cipher disk to implement the
631
+ Vigenere cipher (now on display in the NSA Museum in Fort
632
+ Meade) [1]_.
633
+
634
+ The Vigenere cipher is a generalization of the shift cipher.
635
+ Whereas the shift cipher shifts each letter by the same amount
636
+ (that amount being the key of the shift cipher) the Vigenere
637
+ cipher shifts a letter by an amount determined by the key (which is
638
+ a word or phrase known only to the sender and receiver).
639
+
640
+ For example, if the key was a single letter, such as "C", then the
641
+ so-called Vigenere cipher is actually a shift cipher with a
642
+ shift of `2` (since "C" is the 2nd letter of the alphabet, if
643
+ you start counting at `0`). If the key was a word with two
644
+ letters, such as "CA", then the so-called Vigenere cipher will
645
+ shift letters in even positions by `2` and letters in odd positions
646
+ are left alone (shifted by `0`, since "A" is the 0th letter, if
647
+ you start counting at `0`).
648
+
649
+
650
+ ALGORITHM:
651
+
652
+ INPUT:
653
+
654
+ ``msg``: string of characters that appear in ``symbols``
655
+ (the plaintext)
656
+
657
+ ``key``: a string of characters that appear in ``symbols``
658
+ (the secret key)
659
+
660
+ ``symbols``: a string of letters defining the alphabet
661
+
662
+
663
+ OUTPUT:
664
+
665
+ ``ct``: string of characters (the ciphertext message)
666
+
667
+ STEPS:
668
+ 0. Number the letters of the alphabet from 0, ..., N
669
+ 1. Compute from the string ``key`` a list ``L1`` of
670
+ corresponding integers. Let ``n1 = len(L1)``.
671
+ 2. Compute from the string ``msg`` a list ``L2`` of
672
+ corresponding integers. Let ``n2 = len(L2)``.
673
+ 3. Break ``L2`` up sequentially into sublists of size
674
+ ``n1``; the last sublist may be smaller than ``n1``
675
+ 4. For each of these sublists ``L`` of ``L2``, compute a
676
+ new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
677
+ to the ``i``-th element in the sublist, for each ``i``.
678
+ 5. Assemble these lists ``C`` by concatenation into a new
679
+ list of length ``n2``.
680
+ 6. Compute from the new list a string ``ct`` of
681
+ corresponding letters.
682
+
683
+ Once it is known that the key is, say, `n` characters long,
684
+ frequency analysis can be applied to every `n`-th letter of
685
+ the ciphertext to determine the plaintext. This method is
686
+ called *Kasiski examination* (although it was first discovered
687
+ by Babbage). If they key is as long as the message and is
688
+ comprised of randomly selected characters -- a one-time pad -- the
689
+ message is theoretically unbreakable.
690
+
691
+ The cipher Vigenere actually discovered is an "auto-key" cipher
692
+ described as follows.
693
+
694
+ ALGORITHM:
695
+
696
+ INPUT:
697
+
698
+ ``key``: a string of letters (the secret key)
699
+
700
+ ``msg``: string of letters (the plaintext message)
701
+
702
+ OUTPUT:
703
+
704
+ ``ct``: string of upper-case letters (the ciphertext message)
705
+
706
+ STEPS:
707
+ 0. Number the letters of the alphabet from 0, ..., N
708
+ 1. Compute from the string ``msg`` a list ``L2`` of
709
+ corresponding integers. Let ``n2 = len(L2)``.
710
+ 2. Let ``n1`` be the length of the key. Append to the
711
+ string ``key`` the first ``n2 - n1`` characters of
712
+ the plaintext message. Compute from this string (also of
713
+ length ``n2``) a list ``L1`` of integers corresponding
714
+ to the letter numbers in the first step.
715
+ 3. Compute a new list ``C`` given by
716
+ ``C[i] = L1[i] + L2[i] (mod N)``.
717
+ 4. Compute from the new list a string ``ct`` of letters
718
+ corresponding to the new integers.
719
+
720
+ To decipher the auto-key ciphertext, the key is used to decipher
721
+ the first ``n1`` characters and then those characters become the
722
+ key to decipher the next ``n1`` characters, etc...:
723
+
724
+ >>> m = AZ('go navy, beat army! yes you can'); m
725
+ 'GONAVYBEATARMYYESYOUCAN'
726
+ >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
727
+ >>> auto_key = key + m[:n2 - n1]; auto_key
728
+ 'GOLDBUGGONAVYBEATARMYYE'
729
+ >>> ct = encipher_vigenere(m, auto_key); ct
730
+ 'MCYDWSHKOGAMKZCELYFGAYR'
731
+ >>> n1 = len(key)
732
+ >>> pt = []
733
+ >>> while ct:
734
+ ... part, ct = ct[:n1], ct[n1:]
735
+ ... pt.append(decipher_vigenere(part, key))
736
+ ... key = pt[-1]
737
+ ...
738
+ >>> ''.join(pt) == m
739
+ True
740
+
741
+ References
742
+ ==========
743
+
744
+ .. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
745
+ .. [2] https://web.archive.org/web/20071116100808/https://filebox.vt.edu/users/batman/kryptos.html
746
+ (short URL: https://goo.gl/ijr22d)
747
+
748
+ """
749
+ msg, key, A = _prep(msg, key, symbols)
750
+ map = {c: i for i, c in enumerate(A)}
751
+ key = [map[c] for c in key]
752
+ N = len(map)
753
+ k = len(key)
754
+ rv = []
755
+ for i, m in enumerate(msg):
756
+ rv.append(A[(map[m] + key[i % k]) % N])
757
+ rv = ''.join(rv)
758
+ return rv
759
+
760
+
761
+ def decipher_vigenere(msg, key, symbols=None):
762
+ """
763
+ Decode using the Vigenere cipher.
764
+
765
+ Examples
766
+ ========
767
+
768
+ >>> from sympy.crypto.crypto import decipher_vigenere
769
+ >>> key = "encrypt"
770
+ >>> ct = "QRGK kt HRZQE BPR"
771
+ >>> decipher_vigenere(ct, key)
772
+ 'MEETMEONMONDAY'
773
+
774
+ """
775
+ msg, key, A = _prep(msg, key, symbols)
776
+ map = {c: i for i, c in enumerate(A)}
777
+ N = len(A) # normally, 26
778
+ K = [map[c] for c in key]
779
+ n = len(K)
780
+ C = [map[c] for c in msg]
781
+ rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
782
+ return rv
783
+
784
+
785
+ #################### Hill cipher ########################
786
+
787
+
788
+ def encipher_hill(msg, key, symbols=None, pad="Q"):
789
+ r"""
790
+ Return the Hill cipher encryption of ``msg``.
791
+
792
+ Explanation
793
+ ===========
794
+
795
+ The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
796
+ was the first polygraphic cipher in which it was practical
797
+ (though barely) to operate on more than three symbols at once.
798
+ The following discussion assumes an elementary knowledge of
799
+ matrices.
800
+
801
+ First, each letter is first encoded as a number starting with 0.
802
+ Suppose your message `msg` consists of `n` capital letters, with no
803
+ spaces. This may be regarded an `n`-tuple M of elements of
804
+ `Z_{26}` (if the letters are those of the English alphabet). A key
805
+ in the Hill cipher is a `k x k` matrix `K`, all of whose entries
806
+ are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
807
+ linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
808
+ is one-to-one).
809
+
810
+
811
+ Parameters
812
+ ==========
813
+
814
+ msg
815
+ Plaintext message of `n` upper-case letters.
816
+
817
+ key
818
+ A `k \times k` invertible matrix `K`, all of whose entries are
819
+ in `Z_{26}` (or whatever number of symbols are being used).
820
+
821
+ pad
822
+ Character (default "Q") to use to make length of text be a
823
+ multiple of ``k``.
824
+
825
+ Returns
826
+ =======
827
+
828
+ ct
829
+ Ciphertext of upper-case letters.
830
+
831
+ Notes
832
+ =====
833
+
834
+ ALGORITHM:
835
+
836
+ STEPS:
837
+ 0. Number the letters of the alphabet from 0, ..., N
838
+ 1. Compute from the string ``msg`` a list ``L`` of
839
+ corresponding integers. Let ``n = len(L)``.
840
+ 2. Break the list ``L`` up into ``t = ceiling(n/k)``
841
+ sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
842
+ the last list "padded" to ensure its size is
843
+ ``k``).
844
+ 3. Compute new list ``C_1``, ..., ``C_t`` given by
845
+ ``C[i] = K*L_i`` (arithmetic is done mod N), for each
846
+ ``i``.
847
+ 4. Concatenate these into a list ``C = C_1 + ... + C_t``.
848
+ 5. Compute from ``C`` a string ``ct`` of corresponding
849
+ letters. This has length ``k*t``.
850
+
851
+ References
852
+ ==========
853
+
854
+ .. [1] https://en.wikipedia.org/wiki/Hill_cipher
855
+ .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
856
+ The American Mathematical Monthly Vol.36, June-July 1929,
857
+ pp.306-312.
858
+
859
+ See Also
860
+ ========
861
+
862
+ decipher_hill
863
+
864
+ """
865
+ assert key.is_square
866
+ assert len(pad) == 1
867
+ msg, pad, A = _prep(msg, pad, symbols)
868
+ map = {c: i for i, c in enumerate(A)}
869
+ P = [map[c] for c in msg]
870
+ N = len(A)
871
+ k = key.cols
872
+ n = len(P)
873
+ m, r = divmod(n, k)
874
+ if r:
875
+ P = P + [map[pad]]*(k - r)
876
+ m += 1
877
+ rv = ''.join([A[c % N] for j in range(m) for c in
878
+ list(key*Matrix(k, 1, [P[i]
879
+ for i in range(k*j, k*(j + 1))]))])
880
+ return rv
881
+
882
+
883
+ def decipher_hill(msg, key, symbols=None):
884
+ """
885
+ Deciphering is the same as enciphering but using the inverse of the
886
+ key matrix.
887
+
888
+ Examples
889
+ ========
890
+
891
+ >>> from sympy.crypto.crypto import encipher_hill, decipher_hill
892
+ >>> from sympy import Matrix
893
+
894
+ >>> key = Matrix([[1, 2], [3, 5]])
895
+ >>> encipher_hill("meet me on monday", key)
896
+ 'UEQDUEODOCTCWQ'
897
+ >>> decipher_hill(_, key)
898
+ 'MEETMEONMONDAY'
899
+
900
+ When the length of the plaintext (stripped of invalid characters)
901
+ is not a multiple of the key dimension, extra characters will
902
+ appear at the end of the enciphered and deciphered text. In order to
903
+ decipher the text, those characters must be included in the text to
904
+ be deciphered. In the following, the key has a dimension of 4 but
905
+ the text is 2 short of being a multiple of 4 so two characters will
906
+ be added.
907
+
908
+ >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
909
+ ... [2, 2, 3, 4], [1, 1, 0, 1]])
910
+ >>> msg = "ST"
911
+ >>> encipher_hill(msg, key)
912
+ 'HJEB'
913
+ >>> decipher_hill(_, key)
914
+ 'STQQ'
915
+ >>> encipher_hill(msg, key, pad="Z")
916
+ 'ISPK'
917
+ >>> decipher_hill(_, key)
918
+ 'STZZ'
919
+
920
+ If the last two characters of the ciphertext were ignored in
921
+ either case, the wrong plaintext would be recovered:
922
+
923
+ >>> decipher_hill("HD", key)
924
+ 'ORMV'
925
+ >>> decipher_hill("IS", key)
926
+ 'UIKY'
927
+
928
+ See Also
929
+ ========
930
+
931
+ encipher_hill
932
+
933
+ """
934
+ assert key.is_square
935
+ msg, _, A = _prep(msg, '', symbols)
936
+ map = {c: i for i, c in enumerate(A)}
937
+ C = [map[c] for c in msg]
938
+ N = len(A)
939
+ k = key.cols
940
+ n = len(C)
941
+ m, r = divmod(n, k)
942
+ if r:
943
+ C = C + [0]*(k - r)
944
+ m += 1
945
+ key_inv = key.inv_mod(N)
946
+ rv = ''.join([A[p % N] for j in range(m) for p in
947
+ list(key_inv*Matrix(
948
+ k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
949
+ return rv
950
+
951
+
952
+ #################### Bifid cipher ########################
953
+
954
+
955
+ def encipher_bifid(msg, key, symbols=None):
956
+ r"""
957
+ Performs the Bifid cipher encryption on plaintext ``msg``, and
958
+ returns the ciphertext.
959
+
960
+ This is the version of the Bifid cipher that uses an `n \times n`
961
+ Polybius square.
962
+
963
+ Parameters
964
+ ==========
965
+
966
+ msg
967
+ Plaintext string.
968
+
969
+ key
970
+ Short string for key.
971
+
972
+ Duplicate characters are ignored and then it is padded with the
973
+ characters in ``symbols`` that were not in the short key.
974
+
975
+ symbols
976
+ `n \times n` characters defining the alphabet.
977
+
978
+ (default is string.printable)
979
+
980
+ Returns
981
+ =======
982
+
983
+ ciphertext
984
+ Ciphertext using Bifid5 cipher without spaces.
985
+
986
+ See Also
987
+ ========
988
+
989
+ decipher_bifid, encipher_bifid5, encipher_bifid6
990
+
991
+ References
992
+ ==========
993
+
994
+ .. [1] https://en.wikipedia.org/wiki/Bifid_cipher
995
+
996
+ """
997
+ msg, key, A = _prep(msg, key, symbols, bifid10)
998
+ long_key = ''.join(uniq(key)) or A
999
+
1000
+ n = len(A)**.5
1001
+ if n != int(n):
1002
+ raise ValueError(
1003
+ 'Length of alphabet (%s) is not a square number.' % len(A))
1004
+ N = int(n)
1005
+ if len(long_key) < N**2:
1006
+ long_key = list(long_key) + [x for x in A if x not in long_key]
1007
+
1008
+ # the fractionalization
1009
+ row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
1010
+ r, c = zip(*[row_col[x] for x in msg])
1011
+ rc = r + c
1012
+ ch = {i: ch for ch, i in row_col.items()}
1013
+ rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
1014
+ return rv
1015
+
1016
+
1017
+ def decipher_bifid(msg, key, symbols=None):
1018
+ r"""
1019
+ Performs the Bifid cipher decryption on ciphertext ``msg``, and
1020
+ returns the plaintext.
1021
+
1022
+ This is the version of the Bifid cipher that uses the `n \times n`
1023
+ Polybius square.
1024
+
1025
+ Parameters
1026
+ ==========
1027
+
1028
+ msg
1029
+ Ciphertext string.
1030
+
1031
+ key
1032
+ Short string for key.
1033
+
1034
+ Duplicate characters are ignored and then it is padded with the
1035
+ characters in symbols that were not in the short key.
1036
+
1037
+ symbols
1038
+ `n \times n` characters defining the alphabet.
1039
+
1040
+ (default=string.printable, a `10 \times 10` matrix)
1041
+
1042
+ Returns
1043
+ =======
1044
+
1045
+ deciphered
1046
+ Deciphered text.
1047
+
1048
+ Examples
1049
+ ========
1050
+
1051
+ >>> from sympy.crypto.crypto import (
1052
+ ... encipher_bifid, decipher_bifid, AZ)
1053
+
1054
+ Do an encryption using the bifid5 alphabet:
1055
+
1056
+ >>> alp = AZ().replace('J', '')
1057
+ >>> ct = AZ("meet me on monday!")
1058
+ >>> key = AZ("gold bug")
1059
+ >>> encipher_bifid(ct, key, alp)
1060
+ 'IEILHHFSTSFQYE'
1061
+
1062
+ When entering the text or ciphertext, spaces are ignored so it
1063
+ can be formatted as desired. Re-entering the ciphertext from the
1064
+ preceding, putting 4 characters per line and padding with an extra
1065
+ J, does not cause problems for the deciphering:
1066
+
1067
+ >>> decipher_bifid('''
1068
+ ... IEILH
1069
+ ... HFSTS
1070
+ ... FQYEJ''', key, alp)
1071
+ 'MEETMEONMONDAY'
1072
+
1073
+ When no alphabet is given, all 100 printable characters will be
1074
+ used:
1075
+
1076
+ >>> key = ''
1077
+ >>> encipher_bifid('hello world!', key)
1078
+ 'bmtwmg-bIo*w'
1079
+ >>> decipher_bifid(_, key)
1080
+ 'hello world!'
1081
+
1082
+ If the key is changed, a different encryption is obtained:
1083
+
1084
+ >>> key = 'gold bug'
1085
+ >>> encipher_bifid('hello world!', 'gold_bug')
1086
+ 'hg2sfuei7t}w'
1087
+
1088
+ And if the key used to decrypt the message is not exact, the
1089
+ original text will not be perfectly obtained:
1090
+
1091
+ >>> decipher_bifid(_, 'gold pug')
1092
+ 'heldo~wor6d!'
1093
+
1094
+ """
1095
+ msg, _, A = _prep(msg, '', symbols, bifid10)
1096
+ long_key = ''.join(uniq(key)) or A
1097
+
1098
+ n = len(A)**.5
1099
+ if n != int(n):
1100
+ raise ValueError(
1101
+ 'Length of alphabet (%s) is not a square number.' % len(A))
1102
+ N = int(n)
1103
+ if len(long_key) < N**2:
1104
+ long_key = list(long_key) + [x for x in A if x not in long_key]
1105
+
1106
+ # the reverse fractionalization
1107
+ row_col = {
1108
+ ch: divmod(i, N) for i, ch in enumerate(long_key)}
1109
+ rc = [i for c in msg for i in row_col[c]]
1110
+ n = len(msg)
1111
+ rc = zip(*(rc[:n], rc[n:]))
1112
+ ch = {i: ch for ch, i in row_col.items()}
1113
+ rv = ''.join(ch[i] for i in rc)
1114
+ return rv
1115
+
1116
+
1117
+ def bifid_square(key):
1118
+ """Return characters of ``key`` arranged in a square.
1119
+
1120
+ Examples
1121
+ ========
1122
+
1123
+ >>> from sympy.crypto.crypto import (
1124
+ ... bifid_square, AZ, padded_key, bifid5)
1125
+ >>> bifid_square(AZ().replace('J', ''))
1126
+ Matrix([
1127
+ [A, B, C, D, E],
1128
+ [F, G, H, I, K],
1129
+ [L, M, N, O, P],
1130
+ [Q, R, S, T, U],
1131
+ [V, W, X, Y, Z]])
1132
+
1133
+ >>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
1134
+ Matrix([
1135
+ [G, O, L, D, B],
1136
+ [U, A, C, E, F],
1137
+ [H, I, K, M, N],
1138
+ [P, Q, R, S, T],
1139
+ [V, W, X, Y, Z]])
1140
+
1141
+ See Also
1142
+ ========
1143
+
1144
+ padded_key
1145
+
1146
+ """
1147
+ A = ''.join(uniq(''.join(key)))
1148
+ n = len(A)**.5
1149
+ if n != int(n):
1150
+ raise ValueError(
1151
+ 'Length of alphabet (%s) is not a square number.' % len(A))
1152
+ n = int(n)
1153
+ f = lambda i, j: Symbol(A[n*i + j])
1154
+ rv = Matrix(n, n, f)
1155
+ return rv
1156
+
1157
+
1158
+ def encipher_bifid5(msg, key):
1159
+ r"""
1160
+ Performs the Bifid cipher encryption on plaintext ``msg``, and
1161
+ returns the ciphertext.
1162
+
1163
+ Explanation
1164
+ ===========
1165
+
1166
+ This is the version of the Bifid cipher that uses the `5 \times 5`
1167
+ Polybius square. The letter "J" is ignored so it must be replaced
1168
+ with something else (traditionally an "I") before encryption.
1169
+
1170
+ ALGORITHM: (5x5 case)
1171
+
1172
+ STEPS:
1173
+ 0. Create the `5 \times 5` Polybius square ``S`` associated
1174
+ to ``key`` as follows:
1175
+
1176
+ a) moving from left-to-right, top-to-bottom,
1177
+ place the letters of the key into a `5 \times 5`
1178
+ matrix,
1179
+ b) if the key has less than 25 letters, add the
1180
+ letters of the alphabet not in the key until the
1181
+ `5 \times 5` square is filled.
1182
+
1183
+ 1. Create a list ``P`` of pairs of numbers which are the
1184
+ coordinates in the Polybius square of the letters in
1185
+ ``msg``.
1186
+ 2. Let ``L1`` be the list of all first coordinates of ``P``
1187
+ (length of ``L1 = n``), let ``L2`` be the list of all
1188
+ second coordinates of ``P`` (so the length of ``L2``
1189
+ is also ``n``).
1190
+ 3. Let ``L`` be the concatenation of ``L1`` and ``L2``
1191
+ (length ``L = 2*n``), except that consecutive numbers
1192
+ are paired ``(L[2*i], L[2*i + 1])``. You can regard
1193
+ ``L`` as a list of pairs of length ``n``.
1194
+ 4. Let ``C`` be the list of all letters which are of the
1195
+ form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
1196
+ string, this is the ciphertext of ``msg``.
1197
+
1198
+ Parameters
1199
+ ==========
1200
+
1201
+ msg : str
1202
+ Plaintext string.
1203
+
1204
+ Converted to upper case and filtered of anything but all letters
1205
+ except J.
1206
+
1207
+ key
1208
+ Short string for key; non-alphabetic letters, J and duplicated
1209
+ characters are ignored and then, if the length is less than 25
1210
+ characters, it is padded with other letters of the alphabet
1211
+ (in alphabetical order).
1212
+
1213
+ Returns
1214
+ =======
1215
+
1216
+ ct
1217
+ Ciphertext (all caps, no spaces).
1218
+
1219
+ Examples
1220
+ ========
1221
+
1222
+ >>> from sympy.crypto.crypto import (
1223
+ ... encipher_bifid5, decipher_bifid5)
1224
+
1225
+ "J" will be omitted unless it is replaced with something else:
1226
+
1227
+ >>> round_trip = lambda m, k: \
1228
+ ... decipher_bifid5(encipher_bifid5(m, k), k)
1229
+ >>> key = 'a'
1230
+ >>> msg = "JOSIE"
1231
+ >>> round_trip(msg, key)
1232
+ 'OSIE'
1233
+ >>> round_trip(msg.replace("J", "I"), key)
1234
+ 'IOSIE'
1235
+ >>> j = "QIQ"
1236
+ >>> round_trip(msg.replace("J", j), key).replace(j, "J")
1237
+ 'JOSIE'
1238
+
1239
+
1240
+ Notes
1241
+ =====
1242
+
1243
+ The Bifid cipher was invented around 1901 by Felix Delastelle.
1244
+ It is a *fractional substitution* cipher, where letters are
1245
+ replaced by pairs of symbols from a smaller alphabet. The
1246
+ cipher uses a `5 \times 5` square filled with some ordering of the
1247
+ alphabet, except that "J" is replaced with "I" (this is a so-called
1248
+ Polybius square; there is a `6 \times 6` analog if you add back in
1249
+ "J" and also append onto the usual 26 letter alphabet, the digits
1250
+ 0, 1, ..., 9).
1251
+ According to Helen Gaines' book *Cryptanalysis*, this type of cipher
1252
+ was used in the field by the German Army during World War I.
1253
+
1254
+ See Also
1255
+ ========
1256
+
1257
+ decipher_bifid5, encipher_bifid
1258
+
1259
+ """
1260
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
1261
+ key = padded_key(key, bifid5)
1262
+ return encipher_bifid(msg, '', key)
1263
+
1264
+
1265
+ def decipher_bifid5(msg, key):
1266
+ r"""
1267
+ Return the Bifid cipher decryption of ``msg``.
1268
+
1269
+ Explanation
1270
+ ===========
1271
+
1272
+ This is the version of the Bifid cipher that uses the `5 \times 5`
1273
+ Polybius square; the letter "J" is ignored unless a ``key`` of
1274
+ length 25 is used.
1275
+
1276
+ Parameters
1277
+ ==========
1278
+
1279
+ msg
1280
+ Ciphertext string.
1281
+
1282
+ key
1283
+ Short string for key; duplicated characters are ignored and if
1284
+ the length is less then 25 characters, it will be padded with
1285
+ other letters from the alphabet omitting "J".
1286
+ Non-alphabetic characters are ignored.
1287
+
1288
+ Returns
1289
+ =======
1290
+
1291
+ plaintext
1292
+ Plaintext from Bifid5 cipher (all caps, no spaces).
1293
+
1294
+ Examples
1295
+ ========
1296
+
1297
+ >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
1298
+ >>> key = "gold bug"
1299
+ >>> encipher_bifid5('meet me on friday', key)
1300
+ 'IEILEHFSTSFXEE'
1301
+ >>> encipher_bifid5('meet me on monday', key)
1302
+ 'IEILHHFSTSFQYE'
1303
+ >>> decipher_bifid5(_, key)
1304
+ 'MEETMEONMONDAY'
1305
+
1306
+ """
1307
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
1308
+ key = padded_key(key, bifid5)
1309
+ return decipher_bifid(msg, '', key)
1310
+
1311
+
1312
+ def bifid5_square(key=None):
1313
+ r"""
1314
+ 5x5 Polybius square.
1315
+
1316
+ Produce the Polybius square for the `5 \times 5` Bifid cipher.
1317
+
1318
+ Examples
1319
+ ========
1320
+
1321
+ >>> from sympy.crypto.crypto import bifid5_square
1322
+ >>> bifid5_square("gold bug")
1323
+ Matrix([
1324
+ [G, O, L, D, B],
1325
+ [U, A, C, E, F],
1326
+ [H, I, K, M, N],
1327
+ [P, Q, R, S, T],
1328
+ [V, W, X, Y, Z]])
1329
+
1330
+ """
1331
+ if not key:
1332
+ key = bifid5
1333
+ else:
1334
+ _, key, _ = _prep('', key.upper(), None, bifid5)
1335
+ key = padded_key(key, bifid5)
1336
+ return bifid_square(key)
1337
+
1338
+
1339
+ def encipher_bifid6(msg, key):
1340
+ r"""
1341
+ Performs the Bifid cipher encryption on plaintext ``msg``, and
1342
+ returns the ciphertext.
1343
+
1344
+ This is the version of the Bifid cipher that uses the `6 \times 6`
1345
+ Polybius square.
1346
+
1347
+ Parameters
1348
+ ==========
1349
+
1350
+ msg
1351
+ Plaintext string (digits okay).
1352
+
1353
+ key
1354
+ Short string for key (digits okay).
1355
+
1356
+ If ``key`` is less than 36 characters long, the square will be
1357
+ filled with letters A through Z and digits 0 through 9.
1358
+
1359
+ Returns
1360
+ =======
1361
+
1362
+ ciphertext
1363
+ Ciphertext from Bifid cipher (all caps, no spaces).
1364
+
1365
+ See Also
1366
+ ========
1367
+
1368
+ decipher_bifid6, encipher_bifid
1369
+
1370
+ """
1371
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
1372
+ key = padded_key(key, bifid6)
1373
+ return encipher_bifid(msg, '', key)
1374
+
1375
+
1376
+ def decipher_bifid6(msg, key):
1377
+ r"""
1378
+ Performs the Bifid cipher decryption on ciphertext ``msg``, and
1379
+ returns the plaintext.
1380
+
1381
+ This is the version of the Bifid cipher that uses the `6 \times 6`
1382
+ Polybius square.
1383
+
1384
+ Parameters
1385
+ ==========
1386
+
1387
+ msg
1388
+ Ciphertext string (digits okay); converted to upper case
1389
+
1390
+ key
1391
+ Short string for key (digits okay).
1392
+
1393
+ If ``key`` is less than 36 characters long, the square will be
1394
+ filled with letters A through Z and digits 0 through 9.
1395
+ All letters are converted to uppercase.
1396
+
1397
+ Returns
1398
+ =======
1399
+
1400
+ plaintext
1401
+ Plaintext from Bifid cipher (all caps, no spaces).
1402
+
1403
+ Examples
1404
+ ========
1405
+
1406
+ >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
1407
+ >>> key = "gold bug"
1408
+ >>> encipher_bifid6('meet me on monday at 8am', key)
1409
+ 'KFKLJJHF5MMMKTFRGPL'
1410
+ >>> decipher_bifid6(_, key)
1411
+ 'MEETMEONMONDAYAT8AM'
1412
+
1413
+ """
1414
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
1415
+ key = padded_key(key, bifid6)
1416
+ return decipher_bifid(msg, '', key)
1417
+
1418
+
1419
+ def bifid6_square(key=None):
1420
+ r"""
1421
+ 6x6 Polybius square.
1422
+
1423
+ Produces the Polybius square for the `6 \times 6` Bifid cipher.
1424
+ Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
1425
+
1426
+ Examples
1427
+ ========
1428
+
1429
+ >>> from sympy.crypto.crypto import bifid6_square
1430
+ >>> key = "gold bug"
1431
+ >>> bifid6_square(key)
1432
+ Matrix([
1433
+ [G, O, L, D, B, U],
1434
+ [A, C, E, F, H, I],
1435
+ [J, K, M, N, P, Q],
1436
+ [R, S, T, V, W, X],
1437
+ [Y, Z, 0, 1, 2, 3],
1438
+ [4, 5, 6, 7, 8, 9]])
1439
+
1440
+ """
1441
+ if not key:
1442
+ key = bifid6
1443
+ else:
1444
+ _, key, _ = _prep('', key.upper(), None, bifid6)
1445
+ key = padded_key(key, bifid6)
1446
+ return bifid_square(key)
1447
+
1448
+
1449
+ #################### RSA #############################
1450
+
1451
+ def _decipher_rsa_crt(i, d, factors):
1452
+ """Decipher RSA using chinese remainder theorem from the information
1453
+ of the relatively-prime factors of the modulus.
1454
+
1455
+ Parameters
1456
+ ==========
1457
+
1458
+ i : integer
1459
+ Ciphertext
1460
+
1461
+ d : integer
1462
+ The exponent component.
1463
+
1464
+ factors : list of relatively-prime integers
1465
+ The integers given must be coprime and the product must equal
1466
+ the modulus component of the original RSA key.
1467
+
1468
+ Examples
1469
+ ========
1470
+
1471
+ How to decrypt RSA with CRT:
1472
+
1473
+ >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
1474
+ >>> primes = [61, 53]
1475
+ >>> e = 17
1476
+ >>> args = primes + [e]
1477
+ >>> puk = rsa_public_key(*args)
1478
+ >>> prk = rsa_private_key(*args)
1479
+
1480
+ >>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
1481
+ >>> msg = 65
1482
+ >>> crt_primes = primes
1483
+ >>> encrypted = encipher_rsa(msg, puk)
1484
+ >>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
1485
+ >>> decrypted
1486
+ 65
1487
+ """
1488
+ moduluses = [pow(i, d, p) for p in factors]
1489
+
1490
+ result = crt(factors, moduluses)
1491
+ if not result:
1492
+ raise ValueError("CRT failed")
1493
+ return result[0]
1494
+
1495
+
1496
+ def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
1497
+ r"""A private subroutine to generate RSA key
1498
+
1499
+ Parameters
1500
+ ==========
1501
+
1502
+ public, private : bool, optional
1503
+ Flag to generate either a public key, a private key.
1504
+
1505
+ totient : 'Euler' or 'Carmichael'
1506
+ Different notation used for totient.
1507
+
1508
+ multipower : bool, optional
1509
+ Flag to bypass warning for multipower RSA.
1510
+ """
1511
+
1512
+ if len(args) < 2:
1513
+ return False
1514
+
1515
+ if totient not in ('Euler', 'Carmichael'):
1516
+ raise ValueError(
1517
+ "The argument totient={} should either be " \
1518
+ "'Euler', 'Carmichalel'." \
1519
+ .format(totient))
1520
+
1521
+ if totient == 'Euler':
1522
+ _totient = _euler
1523
+ else:
1524
+ _totient = _carmichael
1525
+
1526
+ if index is not None:
1527
+ index = as_int(index)
1528
+ if totient != 'Carmichael':
1529
+ raise ValueError(
1530
+ "Setting the 'index' keyword argument requires totient"
1531
+ "notation to be specified as 'Carmichael'.")
1532
+
1533
+ primes, e = args[:-1], args[-1]
1534
+
1535
+ if not all(isprime(p) for p in primes):
1536
+ new_primes = []
1537
+ for i in primes:
1538
+ new_primes.extend(factorint(i, multiple=True))
1539
+ primes = new_primes
1540
+
1541
+ n = reduce(lambda i, j: i*j, primes)
1542
+
1543
+ tally = multiset(primes)
1544
+ if all(v == 1 for v in tally.values()):
1545
+ multiple = list(tally.keys())
1546
+ phi = _totient._from_distinct_primes(*multiple)
1547
+
1548
+ else:
1549
+ if not multipower:
1550
+ NonInvertibleCipherWarning(
1551
+ 'Non-distinctive primes found in the factors {}. '
1552
+ 'The cipher may not be decryptable for some numbers '
1553
+ 'in the complete residue system Z[{}], but the cipher '
1554
+ 'can still be valid if you restrict the domain to be '
1555
+ 'the reduced residue system Z*[{}]. You can pass '
1556
+ 'the flag multipower=True if you want to suppress this '
1557
+ 'warning.'
1558
+ .format(primes, n, n)
1559
+ # stacklevel=4 because most users will call a function that
1560
+ # calls this function
1561
+ ).warn(stacklevel=4)
1562
+ phi = _totient._from_factors(tally)
1563
+
1564
+ if igcd(e, phi) == 1:
1565
+ if public and not private:
1566
+ if isinstance(index, int):
1567
+ e = e % phi
1568
+ e += index * phi
1569
+ return n, e
1570
+
1571
+ if private and not public:
1572
+ d = mod_inverse(e, phi)
1573
+ if isinstance(index, int):
1574
+ d += index * phi
1575
+ return n, d
1576
+
1577
+ return False
1578
+
1579
+
1580
+ def rsa_public_key(*args, **kwargs):
1581
+ r"""Return the RSA *public key* pair, `(n, e)`
1582
+
1583
+ Parameters
1584
+ ==========
1585
+
1586
+ args : naturals
1587
+ If specified as `p, q, e` where `p` and `q` are distinct primes
1588
+ and `e` is a desired public exponent of the RSA, `n = p q` and
1589
+ `e` will be verified against the totient
1590
+ `\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
1591
+ to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
1592
+
1593
+ If specified as `p_1, p_2, \dots, p_n, e` where
1594
+ `p_1, p_2, \dots, p_n` are specified as primes,
1595
+ and `e` is specified as a desired public exponent of the RSA,
1596
+ it will be able to form a multi-prime RSA, which is a more
1597
+ generalized form of the popular 2-prime RSA.
1598
+
1599
+ It can also be possible to form a single-prime RSA by specifying
1600
+ the argument as `p, e`, which can be considered a trivial case
1601
+ of a multiprime RSA.
1602
+
1603
+ Furthermore, it can be possible to form a multi-power RSA by
1604
+ specifying two or more pairs of the primes to be same.
1605
+ However, unlike the two-distinct prime RSA or multi-prime
1606
+ RSA, not every numbers in the complete residue system
1607
+ (`\mathbb{Z}_n`) will be decryptable since the mapping
1608
+ `\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
1609
+ will not be bijective.
1610
+ (Only except for the trivial case when
1611
+ `e = 1`
1612
+ or more generally,
1613
+
1614
+ .. math::
1615
+ e \in \left \{ 1 + k \lambda(n)
1616
+ \mid k \in \mathbb{Z} \land k \geq 0 \right \}
1617
+
1618
+ when RSA reduces to the identity.)
1619
+ However, the RSA can still be decryptable for the numbers in the
1620
+ reduced residue system (`\mathbb{Z}_n^{\times}`), since the
1621
+ mapping
1622
+ `\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
1623
+ can still be bijective.
1624
+
1625
+ If you pass a non-prime integer to the arguments
1626
+ `p_1, p_2, \dots, p_n`, the particular number will be
1627
+ prime-factored and it will become either a multi-prime RSA or a
1628
+ multi-power RSA in its canonical form, depending on whether the
1629
+ product equals its radical or not.
1630
+ `p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
1631
+
1632
+ totient : bool, optional
1633
+ If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
1634
+ :meth:`sympy.ntheory.factor_.totient` in SymPy.
1635
+
1636
+ If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
1637
+ which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
1638
+
1639
+ Unlike private key generation, this is a trivial keyword for
1640
+ public key generation because
1641
+ `\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
1642
+
1643
+ index : nonnegative integer, optional
1644
+ Returns an arbitrary solution of a RSA public key at the index
1645
+ specified at `0, 1, 2, \dots`. This parameter needs to be
1646
+ specified along with ``totient='Carmichael'``.
1647
+
1648
+ Similarly to the non-uniquenss of a RSA private key as described
1649
+ in the ``index`` parameter documentation in
1650
+ :meth:`rsa_private_key`, RSA public key is also not unique and
1651
+ there is an infinite number of RSA public exponents which
1652
+ can behave in the same manner.
1653
+
1654
+ From any given RSA public exponent `e`, there are can be an
1655
+ another RSA public exponent `e + k \lambda(n)` where `k` is an
1656
+ integer, `\lambda` is a Carmichael's totient function.
1657
+
1658
+ However, considering only the positive cases, there can be
1659
+ a principal solution of a RSA public exponent `e_0` in
1660
+ `0 < e_0 < \lambda(n)`, and all the other solutions
1661
+ can be canonicalzed in a form of `e_0 + k \lambda(n)`.
1662
+
1663
+ ``index`` specifies the `k` notation to yield any possible value
1664
+ an RSA public key can have.
1665
+
1666
+ An example of computing any arbitrary RSA public key:
1667
+
1668
+ >>> from sympy.crypto.crypto import rsa_public_key
1669
+ >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
1670
+ (3233, 17)
1671
+ >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
1672
+ (3233, 797)
1673
+ >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
1674
+ (3233, 1577)
1675
+
1676
+ multipower : bool, optional
1677
+ Any pair of non-distinct primes found in the RSA specification
1678
+ will restrict the domain of the cryptosystem, as noted in the
1679
+ explanation of the parameter ``args``.
1680
+
1681
+ SymPy RSA key generator may give a warning before dispatching it
1682
+ as a multi-power RSA, however, you can disable the warning if
1683
+ you pass ``True`` to this keyword.
1684
+
1685
+ Returns
1686
+ =======
1687
+
1688
+ (n, e) : int, int
1689
+ `n` is a product of any arbitrary number of primes given as
1690
+ the argument.
1691
+
1692
+ `e` is relatively prime (coprime) to the Euler totient
1693
+ `\phi(n)`.
1694
+
1695
+ False
1696
+ Returned if less than two arguments are given, or `e` is
1697
+ not relatively prime to the modulus.
1698
+
1699
+ Examples
1700
+ ========
1701
+
1702
+ >>> from sympy.crypto.crypto import rsa_public_key
1703
+
1704
+ A public key of a two-prime RSA:
1705
+
1706
+ >>> p, q, e = 3, 5, 7
1707
+ >>> rsa_public_key(p, q, e)
1708
+ (15, 7)
1709
+ >>> rsa_public_key(p, q, 30)
1710
+ False
1711
+
1712
+ A public key of a multiprime RSA:
1713
+
1714
+ >>> primes = [2, 3, 5, 7, 11, 13]
1715
+ >>> e = 7
1716
+ >>> args = primes + [e]
1717
+ >>> rsa_public_key(*args)
1718
+ (30030, 7)
1719
+
1720
+ Notes
1721
+ =====
1722
+
1723
+ Although the RSA can be generalized over any modulus `n`, using
1724
+ two large primes had became the most popular specification because a
1725
+ product of two large primes is usually the hardest to factor
1726
+ relatively to the digits of `n` can have.
1727
+
1728
+ However, it may need further understanding of the time complexities
1729
+ of each prime-factoring algorithms to verify the claim.
1730
+
1731
+ See Also
1732
+ ========
1733
+
1734
+ rsa_private_key
1735
+ encipher_rsa
1736
+ decipher_rsa
1737
+
1738
+ References
1739
+ ==========
1740
+
1741
+ .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
1742
+
1743
+ .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
1744
+
1745
+ .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
1746
+
1747
+ .. [4] https://www.itiis.org/digital-library/manuscript/1381
1748
+ """
1749
+ return _rsa_key(*args, public=True, private=False, **kwargs)
1750
+
1751
+
1752
+ def rsa_private_key(*args, **kwargs):
1753
+ r"""Return the RSA *private key* pair, `(n, d)`
1754
+
1755
+ Parameters
1756
+ ==========
1757
+
1758
+ args : naturals
1759
+ The keyword is identical to the ``args`` in
1760
+ :meth:`rsa_public_key`.
1761
+
1762
+ totient : bool, optional
1763
+ If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
1764
+ which is :meth:`sympy.ntheory.factor_.totient` in SymPy.
1765
+
1766
+ If ``'Carmichael'``, it uses Carmichael's totient convention
1767
+ `\lambda(n)` which is
1768
+ :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
1769
+
1770
+ There can be some output differences for private key generation
1771
+ as examples below.
1772
+
1773
+ Example using Euler's totient:
1774
+
1775
+ >>> from sympy.crypto.crypto import rsa_private_key
1776
+ >>> rsa_private_key(61, 53, 17, totient='Euler')
1777
+ (3233, 2753)
1778
+
1779
+ Example using Carmichael's totient:
1780
+
1781
+ >>> from sympy.crypto.crypto import rsa_private_key
1782
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael')
1783
+ (3233, 413)
1784
+
1785
+ index : nonnegative integer, optional
1786
+ Returns an arbitrary solution of a RSA private key at the index
1787
+ specified at `0, 1, 2, \dots`. This parameter needs to be
1788
+ specified along with ``totient='Carmichael'``.
1789
+
1790
+ RSA private exponent is a non-unique solution of
1791
+ `e d \mod \lambda(n) = 1` and it is possible in any form of
1792
+ `d + k \lambda(n)`, where `d` is an another
1793
+ already-computed private exponent, and `\lambda` is a
1794
+ Carmichael's totient function, and `k` is any integer.
1795
+
1796
+ However, considering only the positive cases, there can be
1797
+ a principal solution of a RSA private exponent `d_0` in
1798
+ `0 < d_0 < \lambda(n)`, and all the other solutions
1799
+ can be canonicalzed in a form of `d_0 + k \lambda(n)`.
1800
+
1801
+ ``index`` specifies the `k` notation to yield any possible value
1802
+ an RSA private key can have.
1803
+
1804
+ An example of computing any arbitrary RSA private key:
1805
+
1806
+ >>> from sympy.crypto.crypto import rsa_private_key
1807
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
1808
+ (3233, 413)
1809
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
1810
+ (3233, 1193)
1811
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
1812
+ (3233, 1973)
1813
+
1814
+ multipower : bool, optional
1815
+ The keyword is identical to the ``multipower`` in
1816
+ :meth:`rsa_public_key`.
1817
+
1818
+ Returns
1819
+ =======
1820
+
1821
+ (n, d) : int, int
1822
+ `n` is a product of any arbitrary number of primes given as
1823
+ the argument.
1824
+
1825
+ `d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
1826
+ exponent given, and `\phi` is a Euler totient.
1827
+
1828
+ False
1829
+ Returned if less than two arguments are given, or `e` is
1830
+ not relatively prime to the totient of the modulus.
1831
+
1832
+ Examples
1833
+ ========
1834
+
1835
+ >>> from sympy.crypto.crypto import rsa_private_key
1836
+
1837
+ A private key of a two-prime RSA:
1838
+
1839
+ >>> p, q, e = 3, 5, 7
1840
+ >>> rsa_private_key(p, q, e)
1841
+ (15, 7)
1842
+ >>> rsa_private_key(p, q, 30)
1843
+ False
1844
+
1845
+ A private key of a multiprime RSA:
1846
+
1847
+ >>> primes = [2, 3, 5, 7, 11, 13]
1848
+ >>> e = 7
1849
+ >>> args = primes + [e]
1850
+ >>> rsa_private_key(*args)
1851
+ (30030, 823)
1852
+
1853
+ See Also
1854
+ ========
1855
+
1856
+ rsa_public_key
1857
+ encipher_rsa
1858
+ decipher_rsa
1859
+
1860
+ References
1861
+ ==========
1862
+
1863
+ .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
1864
+
1865
+ .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
1866
+
1867
+ .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
1868
+
1869
+ .. [4] https://www.itiis.org/digital-library/manuscript/1381
1870
+ """
1871
+ return _rsa_key(*args, public=False, private=True, **kwargs)
1872
+
1873
+
1874
+ def _encipher_decipher_rsa(i, key, factors=None):
1875
+ n, d = key
1876
+ if not factors:
1877
+ return pow(i, d, n)
1878
+
1879
+ def _is_coprime_set(l):
1880
+ is_coprime_set = True
1881
+ for i in range(len(l)):
1882
+ for j in range(i+1, len(l)):
1883
+ if igcd(l[i], l[j]) != 1:
1884
+ is_coprime_set = False
1885
+ break
1886
+ return is_coprime_set
1887
+
1888
+ prod = reduce(lambda i, j: i*j, factors)
1889
+ if prod == n and _is_coprime_set(factors):
1890
+ return _decipher_rsa_crt(i, d, factors)
1891
+ return _encipher_decipher_rsa(i, key, factors=None)
1892
+
1893
+
1894
+ def encipher_rsa(i, key, factors=None):
1895
+ r"""Encrypt the plaintext with RSA.
1896
+
1897
+ Parameters
1898
+ ==========
1899
+
1900
+ i : integer
1901
+ The plaintext to be encrypted for.
1902
+
1903
+ key : (n, e) where n, e are integers
1904
+ `n` is the modulus of the key and `e` is the exponent of the
1905
+ key. The encryption is computed by `i^e \bmod n`.
1906
+
1907
+ The key can either be a public key or a private key, however,
1908
+ the message encrypted by a public key can only be decrypted by
1909
+ a private key, and vice versa, as RSA is an asymmetric
1910
+ cryptography system.
1911
+
1912
+ factors : list of coprime integers
1913
+ This is identical to the keyword ``factors`` in
1914
+ :meth:`decipher_rsa`.
1915
+
1916
+ Notes
1917
+ =====
1918
+
1919
+ Some specifications may make the RSA not cryptographically
1920
+ meaningful.
1921
+
1922
+ For example, `0`, `1` will remain always same after taking any
1923
+ number of exponentiation, thus, should be avoided.
1924
+
1925
+ Furthermore, if `i^e < n`, `i` may easily be figured out by taking
1926
+ `e` th root.
1927
+
1928
+ And also, specifying the exponent as `1` or in more generalized form
1929
+ as `1 + k \lambda(n)` where `k` is an nonnegative integer,
1930
+ `\lambda` is a carmichael totient, the RSA becomes an identity
1931
+ mapping.
1932
+
1933
+ Examples
1934
+ ========
1935
+
1936
+ >>> from sympy.crypto.crypto import encipher_rsa
1937
+ >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
1938
+
1939
+ Public Key Encryption:
1940
+
1941
+ >>> p, q, e = 3, 5, 7
1942
+ >>> puk = rsa_public_key(p, q, e)
1943
+ >>> msg = 12
1944
+ >>> encipher_rsa(msg, puk)
1945
+ 3
1946
+
1947
+ Private Key Encryption:
1948
+
1949
+ >>> p, q, e = 3, 5, 7
1950
+ >>> prk = rsa_private_key(p, q, e)
1951
+ >>> msg = 12
1952
+ >>> encipher_rsa(msg, prk)
1953
+ 3
1954
+
1955
+ Encryption using chinese remainder theorem:
1956
+
1957
+ >>> encipher_rsa(msg, prk, factors=[p, q])
1958
+ 3
1959
+ """
1960
+ return _encipher_decipher_rsa(i, key, factors=factors)
1961
+
1962
+
1963
+ def decipher_rsa(i, key, factors=None):
1964
+ r"""Decrypt the ciphertext with RSA.
1965
+
1966
+ Parameters
1967
+ ==========
1968
+
1969
+ i : integer
1970
+ The ciphertext to be decrypted for.
1971
+
1972
+ key : (n, d) where n, d are integers
1973
+ `n` is the modulus of the key and `d` is the exponent of the
1974
+ key. The decryption is computed by `i^d \bmod n`.
1975
+
1976
+ The key can either be a public key or a private key, however,
1977
+ the message encrypted by a public key can only be decrypted by
1978
+ a private key, and vice versa, as RSA is an asymmetric
1979
+ cryptography system.
1980
+
1981
+ factors : list of coprime integers
1982
+ As the modulus `n` created from RSA key generation is composed
1983
+ of arbitrary prime factors
1984
+ `n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
1985
+ `p_1, p_2, \dots, p_n` are distinct primes and
1986
+ `k_1, k_2, \dots, k_n` are positive integers, chinese remainder
1987
+ theorem can be used to compute `i^d \bmod n` from the
1988
+ fragmented modulo operations like
1989
+
1990
+ .. math::
1991
+ i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
1992
+ i^d \bmod {p_n}^{k_n}
1993
+
1994
+ or like
1995
+
1996
+ .. math::
1997
+ i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
1998
+ i^d \bmod {p_3}^{k_3}, \dots ,
1999
+ i^d \bmod {p_n}^{k_n}
2000
+
2001
+ as long as every moduli does not share any common divisor each
2002
+ other.
2003
+
2004
+ The raw primes used in generating the RSA key pair can be a good
2005
+ option.
2006
+
2007
+ Note that the speed advantage of using this is only viable for
2008
+ very large cases (Like 2048-bit RSA keys) since the
2009
+ overhead of using pure Python implementation of
2010
+ :meth:`sympy.ntheory.modular.crt` may overcompensate the
2011
+ theoretical speed advantage.
2012
+
2013
+ Notes
2014
+ =====
2015
+
2016
+ See the ``Notes`` section in the documentation of
2017
+ :meth:`encipher_rsa`
2018
+
2019
+ Examples
2020
+ ========
2021
+
2022
+ >>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
2023
+ >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
2024
+
2025
+ Public Key Encryption and Decryption:
2026
+
2027
+ >>> p, q, e = 3, 5, 7
2028
+ >>> prk = rsa_private_key(p, q, e)
2029
+ >>> puk = rsa_public_key(p, q, e)
2030
+ >>> msg = 12
2031
+ >>> new_msg = encipher_rsa(msg, prk)
2032
+ >>> new_msg
2033
+ 3
2034
+ >>> decipher_rsa(new_msg, puk)
2035
+ 12
2036
+
2037
+ Private Key Encryption and Decryption:
2038
+
2039
+ >>> p, q, e = 3, 5, 7
2040
+ >>> prk = rsa_private_key(p, q, e)
2041
+ >>> puk = rsa_public_key(p, q, e)
2042
+ >>> msg = 12
2043
+ >>> new_msg = encipher_rsa(msg, puk)
2044
+ >>> new_msg
2045
+ 3
2046
+ >>> decipher_rsa(new_msg, prk)
2047
+ 12
2048
+
2049
+ Decryption using chinese remainder theorem:
2050
+
2051
+ >>> decipher_rsa(new_msg, prk, factors=[p, q])
2052
+ 12
2053
+
2054
+ See Also
2055
+ ========
2056
+
2057
+ encipher_rsa
2058
+ """
2059
+ return _encipher_decipher_rsa(i, key, factors=factors)
2060
+
2061
+
2062
+ #################### kid krypto (kid RSA) #############################
2063
+
2064
+
2065
+ def kid_rsa_public_key(a, b, A, B):
2066
+ r"""
2067
+ Kid RSA is a version of RSA useful to teach grade school children
2068
+ since it does not involve exponentiation.
2069
+
2070
+ Explanation
2071
+ ===========
2072
+
2073
+ Alice wants to talk to Bob. Bob generates keys as follows.
2074
+ Key generation:
2075
+
2076
+ * Select positive integers `a, b, A, B` at random.
2077
+ * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
2078
+ `n = (e d - 1)//M`.
2079
+ * The *public key* is `(n, e)`. Bob sends these to Alice.
2080
+ * The *private key* is `(n, d)`, which Bob keeps secret.
2081
+
2082
+ Encryption: If `p` is the plaintext message then the
2083
+ ciphertext is `c = p e \pmod n`.
2084
+
2085
+ Decryption: If `c` is the ciphertext message then the
2086
+ plaintext is `p = c d \pmod n`.
2087
+
2088
+ Examples
2089
+ ========
2090
+
2091
+ >>> from sympy.crypto.crypto import kid_rsa_public_key
2092
+ >>> a, b, A, B = 3, 4, 5, 6
2093
+ >>> kid_rsa_public_key(a, b, A, B)
2094
+ (369, 58)
2095
+
2096
+ """
2097
+ M = a*b - 1
2098
+ e = A*M + a
2099
+ d = B*M + b
2100
+ n = (e*d - 1)//M
2101
+ return n, e
2102
+
2103
+
2104
+ def kid_rsa_private_key(a, b, A, B):
2105
+ """
2106
+ Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
2107
+ `n = (e d - 1) / M`. The *private key* is `d`, which Bob
2108
+ keeps secret.
2109
+
2110
+ Examples
2111
+ ========
2112
+
2113
+ >>> from sympy.crypto.crypto import kid_rsa_private_key
2114
+ >>> a, b, A, B = 3, 4, 5, 6
2115
+ >>> kid_rsa_private_key(a, b, A, B)
2116
+ (369, 70)
2117
+
2118
+ """
2119
+ M = a*b - 1
2120
+ e = A*M + a
2121
+ d = B*M + b
2122
+ n = (e*d - 1)//M
2123
+ return n, d
2124
+
2125
+
2126
+ def encipher_kid_rsa(msg, key):
2127
+ """
2128
+ Here ``msg`` is the plaintext and ``key`` is the public key.
2129
+
2130
+ Examples
2131
+ ========
2132
+
2133
+ >>> from sympy.crypto.crypto import (
2134
+ ... encipher_kid_rsa, kid_rsa_public_key)
2135
+ >>> msg = 200
2136
+ >>> a, b, A, B = 3, 4, 5, 6
2137
+ >>> key = kid_rsa_public_key(a, b, A, B)
2138
+ >>> encipher_kid_rsa(msg, key)
2139
+ 161
2140
+
2141
+ """
2142
+ n, e = key
2143
+ return (msg*e) % n
2144
+
2145
+
2146
+ def decipher_kid_rsa(msg, key):
2147
+ """
2148
+ Here ``msg`` is the plaintext and ``key`` is the private key.
2149
+
2150
+ Examples
2151
+ ========
2152
+
2153
+ >>> from sympy.crypto.crypto import (
2154
+ ... kid_rsa_public_key, kid_rsa_private_key,
2155
+ ... decipher_kid_rsa, encipher_kid_rsa)
2156
+ >>> a, b, A, B = 3, 4, 5, 6
2157
+ >>> d = kid_rsa_private_key(a, b, A, B)
2158
+ >>> msg = 200
2159
+ >>> pub = kid_rsa_public_key(a, b, A, B)
2160
+ >>> pri = kid_rsa_private_key(a, b, A, B)
2161
+ >>> ct = encipher_kid_rsa(msg, pub)
2162
+ >>> decipher_kid_rsa(ct, pri)
2163
+ 200
2164
+
2165
+ """
2166
+ n, d = key
2167
+ return (msg*d) % n
2168
+
2169
+
2170
+ #################### Morse Code ######################################
2171
+
2172
+ morse_char = {
2173
+ ".-": "A", "-...": "B",
2174
+ "-.-.": "C", "-..": "D",
2175
+ ".": "E", "..-.": "F",
2176
+ "--.": "G", "....": "H",
2177
+ "..": "I", ".---": "J",
2178
+ "-.-": "K", ".-..": "L",
2179
+ "--": "M", "-.": "N",
2180
+ "---": "O", ".--.": "P",
2181
+ "--.-": "Q", ".-.": "R",
2182
+ "...": "S", "-": "T",
2183
+ "..-": "U", "...-": "V",
2184
+ ".--": "W", "-..-": "X",
2185
+ "-.--": "Y", "--..": "Z",
2186
+ "-----": "0", ".----": "1",
2187
+ "..---": "2", "...--": "3",
2188
+ "....-": "4", ".....": "5",
2189
+ "-....": "6", "--...": "7",
2190
+ "---..": "8", "----.": "9",
2191
+ ".-.-.-": ".", "--..--": ",",
2192
+ "---...": ":", "-.-.-.": ";",
2193
+ "..--..": "?", "-....-": "-",
2194
+ "..--.-": "_", "-.--.": "(",
2195
+ "-.--.-": ")", ".----.": "'",
2196
+ "-...-": "=", ".-.-.": "+",
2197
+ "-..-.": "/", ".--.-.": "@",
2198
+ "...-..-": "$", "-.-.--": "!"}
2199
+ char_morse = {v: k for k, v in morse_char.items()}
2200
+
2201
+
2202
+ def encode_morse(msg, sep='|', mapping=None):
2203
+ """
2204
+ Encodes a plaintext into popular Morse Code with letters
2205
+ separated by ``sep`` and words by a double ``sep``.
2206
+
2207
+ Examples
2208
+ ========
2209
+
2210
+ >>> from sympy.crypto.crypto import encode_morse
2211
+ >>> msg = 'ATTACK RIGHT FLANK'
2212
+ >>> encode_morse(msg)
2213
+ '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
2214
+
2215
+ References
2216
+ ==========
2217
+
2218
+ .. [1] https://en.wikipedia.org/wiki/Morse_code
2219
+
2220
+ """
2221
+
2222
+ mapping = mapping or char_morse
2223
+ assert sep not in mapping
2224
+ word_sep = 2*sep
2225
+ mapping[" "] = word_sep
2226
+ suffix = msg and msg[-1] in whitespace
2227
+
2228
+ # normalize whitespace
2229
+ msg = (' ' if word_sep else '').join(msg.split())
2230
+ # omit unmapped chars
2231
+ chars = set(''.join(msg.split()))
2232
+ ok = set(mapping.keys())
2233
+ msg = translate(msg, None, ''.join(chars - ok))
2234
+
2235
+ morsestring = []
2236
+ words = msg.split()
2237
+ for word in words:
2238
+ morseword = []
2239
+ for letter in word:
2240
+ morseletter = mapping[letter]
2241
+ morseword.append(morseletter)
2242
+
2243
+ word = sep.join(morseword)
2244
+ morsestring.append(word)
2245
+
2246
+ return word_sep.join(morsestring) + (word_sep if suffix else '')
2247
+
2248
+
2249
+ def decode_morse(msg, sep='|', mapping=None):
2250
+ """
2251
+ Decodes a Morse Code with letters separated by ``sep``
2252
+ (default is '|') and words by `word_sep` (default is '||)
2253
+ into plaintext.
2254
+
2255
+ Examples
2256
+ ========
2257
+
2258
+ >>> from sympy.crypto.crypto import decode_morse
2259
+ >>> mc = '--|---|...-|.||.|.-|...|-'
2260
+ >>> decode_morse(mc)
2261
+ 'MOVE EAST'
2262
+
2263
+ References
2264
+ ==========
2265
+
2266
+ .. [1] https://en.wikipedia.org/wiki/Morse_code
2267
+
2268
+ """
2269
+
2270
+ mapping = mapping or morse_char
2271
+ word_sep = 2*sep
2272
+ characterstring = []
2273
+ words = msg.strip(word_sep).split(word_sep)
2274
+ for word in words:
2275
+ letters = word.split(sep)
2276
+ chars = [mapping[c] for c in letters]
2277
+ word = ''.join(chars)
2278
+ characterstring.append(word)
2279
+ rv = " ".join(characterstring)
2280
+ return rv
2281
+
2282
+
2283
+ #################### LFSRs ##########################################
2284
+
2285
+
2286
+ def lfsr_sequence(key, fill, n):
2287
+ r"""
2288
+ This function creates an LFSR sequence.
2289
+
2290
+ Parameters
2291
+ ==========
2292
+
2293
+ key : list
2294
+ A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
2295
+
2296
+ fill : list
2297
+ The list of the initial terms of the LFSR sequence,
2298
+ `[x_0, x_1, \ldots, x_k].`
2299
+
2300
+ n
2301
+ Number of terms of the sequence that the function returns.
2302
+
2303
+ Returns
2304
+ =======
2305
+
2306
+ L
2307
+ The LFSR sequence defined by
2308
+ `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
2309
+ `n \leq k`.
2310
+
2311
+ Notes
2312
+ =====
2313
+
2314
+ S. Golomb [G]_ gives a list of three statistical properties a
2315
+ sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
2316
+ `a_n \in \{0,1\}`, should display to be considered
2317
+ "random". Define the autocorrelation of `a` to be
2318
+
2319
+ .. math::
2320
+
2321
+ C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
2322
+
2323
+ In the case where `a` is periodic with period
2324
+ `P` then this reduces to
2325
+
2326
+ .. math::
2327
+
2328
+ C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
2329
+
2330
+ Assume `a` is periodic with period `P`.
2331
+
2332
+ - balance:
2333
+
2334
+ .. math::
2335
+
2336
+ \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
2337
+
2338
+ - low autocorrelation:
2339
+
2340
+ .. math::
2341
+
2342
+ C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
2343
+
2344
+ (For sequences satisfying these first two properties, it is known
2345
+ that `\epsilon = -1/P` must hold.)
2346
+
2347
+ - proportional runs property: In each period, half the runs have
2348
+ length `1`, one-fourth have length `2`, etc.
2349
+ Moreover, there are as many runs of `1`'s as there are of
2350
+ `0`'s.
2351
+
2352
+ Examples
2353
+ ========
2354
+
2355
+ >>> from sympy.crypto.crypto import lfsr_sequence
2356
+ >>> from sympy.polys.domains import FF
2357
+ >>> F = FF(2)
2358
+ >>> fill = [F(1), F(1), F(0), F(1)]
2359
+ >>> key = [F(1), F(0), F(0), F(1)]
2360
+ >>> lfsr_sequence(key, fill, 10)
2361
+ [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
2362
+ 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
2363
+
2364
+ References
2365
+ ==========
2366
+
2367
+ .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
2368
+ Laguna Hills, Ca, 1967
2369
+
2370
+ """
2371
+ if not isinstance(key, list):
2372
+ raise TypeError("key must be a list")
2373
+ if not isinstance(fill, list):
2374
+ raise TypeError("fill must be a list")
2375
+ p = key[0].mod
2376
+ F = FF(p)
2377
+ s = fill
2378
+ k = len(fill)
2379
+ L = []
2380
+ for i in range(n):
2381
+ s0 = s[:]
2382
+ L.append(s[0])
2383
+ s = s[1:k]
2384
+ x = sum([int(key[i]*s0[i]) for i in range(k)])
2385
+ s.append(F(x))
2386
+ return L # use [x.to_int() for x in L] for int version
2387
+
2388
+
2389
+ def lfsr_autocorrelation(L, P, k):
2390
+ """
2391
+ This function computes the LFSR autocorrelation function.
2392
+
2393
+ Parameters
2394
+ ==========
2395
+
2396
+ L
2397
+ A periodic sequence of elements of `GF(2)`.
2398
+ L must have length larger than P.
2399
+
2400
+ P
2401
+ The period of L.
2402
+
2403
+ k : int
2404
+ An integer `k` (`0 < k < P`).
2405
+
2406
+ Returns
2407
+ =======
2408
+
2409
+ autocorrelation
2410
+ The k-th value of the autocorrelation of the LFSR L.
2411
+
2412
+ Examples
2413
+ ========
2414
+
2415
+ >>> from sympy.crypto.crypto import (
2416
+ ... lfsr_sequence, lfsr_autocorrelation)
2417
+ >>> from sympy.polys.domains import FF
2418
+ >>> F = FF(2)
2419
+ >>> fill = [F(1), F(1), F(0), F(1)]
2420
+ >>> key = [F(1), F(0), F(0), F(1)]
2421
+ >>> s = lfsr_sequence(key, fill, 20)
2422
+ >>> lfsr_autocorrelation(s, 15, 7)
2423
+ -1/15
2424
+ >>> lfsr_autocorrelation(s, 15, 0)
2425
+ 1
2426
+
2427
+ """
2428
+ if not isinstance(L, list):
2429
+ raise TypeError("L (=%s) must be a list" % L)
2430
+ P = int(P)
2431
+ k = int(k)
2432
+ L0 = L[:P] # slices makes a copy
2433
+ L1 = L0 + L0[:k]
2434
+ L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)]
2435
+ tot = sum(L2)
2436
+ return Rational(tot, P)
2437
+
2438
+
2439
+ def lfsr_connection_polynomial(s):
2440
+ """
2441
+ This function computes the LFSR connection polynomial.
2442
+
2443
+ Parameters
2444
+ ==========
2445
+
2446
+ s
2447
+ A sequence of elements of even length, with entries in a finite
2448
+ field.
2449
+
2450
+ Returns
2451
+ =======
2452
+
2453
+ C(x)
2454
+ The connection polynomial of a minimal LFSR yielding s.
2455
+
2456
+ This implements the algorithm in section 3 of J. L. Massey's
2457
+ article [M]_.
2458
+
2459
+ Examples
2460
+ ========
2461
+
2462
+ >>> from sympy.crypto.crypto import (
2463
+ ... lfsr_sequence, lfsr_connection_polynomial)
2464
+ >>> from sympy.polys.domains import FF
2465
+ >>> F = FF(2)
2466
+ >>> fill = [F(1), F(1), F(0), F(1)]
2467
+ >>> key = [F(1), F(0), F(0), F(1)]
2468
+ >>> s = lfsr_sequence(key, fill, 20)
2469
+ >>> lfsr_connection_polynomial(s)
2470
+ x**4 + x + 1
2471
+ >>> fill = [F(1), F(0), F(0), F(1)]
2472
+ >>> key = [F(1), F(1), F(0), F(1)]
2473
+ >>> s = lfsr_sequence(key, fill, 20)
2474
+ >>> lfsr_connection_polynomial(s)
2475
+ x**3 + 1
2476
+ >>> fill = [F(1), F(0), F(1)]
2477
+ >>> key = [F(1), F(1), F(0)]
2478
+ >>> s = lfsr_sequence(key, fill, 20)
2479
+ >>> lfsr_connection_polynomial(s)
2480
+ x**3 + x**2 + 1
2481
+ >>> fill = [F(1), F(0), F(1)]
2482
+ >>> key = [F(1), F(0), F(1)]
2483
+ >>> s = lfsr_sequence(key, fill, 20)
2484
+ >>> lfsr_connection_polynomial(s)
2485
+ x**3 + x + 1
2486
+
2487
+ References
2488
+ ==========
2489
+
2490
+ .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
2491
+ IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
2492
+ Jan 1969.
2493
+
2494
+ """
2495
+ # Initialization:
2496
+ p = s[0].mod
2497
+ x = Symbol("x")
2498
+ C = 1*x**0
2499
+ B = 1*x**0
2500
+ m = 1
2501
+ b = 1*x**0
2502
+ L = 0
2503
+ N = 0
2504
+ while N < len(s):
2505
+ if L > 0:
2506
+ dC = Poly(C).degree()
2507
+ r = min(L + 1, dC + 1)
2508
+ coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
2509
+ for i in range(1, dC + 1)]
2510
+ d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int()
2511
+ for i in range(1, r)])) % p
2512
+ if L == 0:
2513
+ d = s[N].to_int()*x**0
2514
+ if d == 0:
2515
+ m += 1
2516
+ N += 1
2517
+ if d > 0:
2518
+ if 2*L > N:
2519
+ C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
2520
+ m += 1
2521
+ N += 1
2522
+ else:
2523
+ T = C
2524
+ C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
2525
+ L = N + 1 - L
2526
+ m = 1
2527
+ b = d
2528
+ B = T
2529
+ N += 1
2530
+ dC = Poly(C).degree()
2531
+ coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
2532
+ return sum([coeffsC[i] % p*x**i for i in range(dC + 1)
2533
+ if coeffsC[i] is not None])
2534
+
2535
+
2536
+ #################### ElGamal #############################
2537
+
2538
+
2539
+ def elgamal_private_key(digit=10, seed=None):
2540
+ r"""
2541
+ Return three number tuple as private key.
2542
+
2543
+ Explanation
2544
+ ===========
2545
+
2546
+ Elgamal encryption is based on the mathematical problem
2547
+ called the Discrete Logarithm Problem (DLP). For example,
2548
+
2549
+ `a^{b} \equiv c \pmod p`
2550
+
2551
+ In general, if ``a`` and ``b`` are known, ``ct`` is easily
2552
+ calculated. If ``b`` is unknown, it is hard to use
2553
+ ``a`` and ``ct`` to get ``b``.
2554
+
2555
+ Parameters
2556
+ ==========
2557
+
2558
+ digit : int
2559
+ Minimum number of binary digits for key.
2560
+
2561
+ Returns
2562
+ =======
2563
+
2564
+ tuple : (p, r, d)
2565
+ p = prime number.
2566
+
2567
+ r = primitive root.
2568
+
2569
+ d = random number.
2570
+
2571
+ Notes
2572
+ =====
2573
+
2574
+ For testing purposes, the ``seed`` parameter may be set to control
2575
+ the output of this routine. See sympy.core.random._randrange.
2576
+
2577
+ Examples
2578
+ ========
2579
+
2580
+ >>> from sympy.crypto.crypto import elgamal_private_key
2581
+ >>> from sympy.ntheory import is_primitive_root, isprime
2582
+ >>> a, b, _ = elgamal_private_key()
2583
+ >>> isprime(a)
2584
+ True
2585
+ >>> is_primitive_root(b, a)
2586
+ True
2587
+
2588
+ """
2589
+ randrange = _randrange(seed)
2590
+ p = nextprime(2**digit)
2591
+ return p, primitive_root(p), randrange(2, p)
2592
+
2593
+
2594
+ def elgamal_public_key(key):
2595
+ r"""
2596
+ Return three number tuple as public key.
2597
+
2598
+ Parameters
2599
+ ==========
2600
+
2601
+ key : (p, r, e)
2602
+ Tuple generated by ``elgamal_private_key``.
2603
+
2604
+ Returns
2605
+ =======
2606
+
2607
+ tuple : (p, r, e)
2608
+ `e = r**d \bmod p`
2609
+
2610
+ `d` is a random number in private key.
2611
+
2612
+ Examples
2613
+ ========
2614
+
2615
+ >>> from sympy.crypto.crypto import elgamal_public_key
2616
+ >>> elgamal_public_key((1031, 14, 636))
2617
+ (1031, 14, 212)
2618
+
2619
+ """
2620
+ p, r, e = key
2621
+ return p, r, pow(r, e, p)
2622
+
2623
+
2624
+ def encipher_elgamal(i, key, seed=None):
2625
+ r"""
2626
+ Encrypt message with public key.
2627
+
2628
+ Explanation
2629
+ ===========
2630
+
2631
+ ``i`` is a plaintext message expressed as an integer.
2632
+ ``key`` is public key (p, r, e). In order to encrypt
2633
+ a message, a random number ``a`` in ``range(2, p)``
2634
+ is generated and the encryped message is returned as
2635
+ `c_{1}` and `c_{2}` where:
2636
+
2637
+ `c_{1} \equiv r^{a} \pmod p`
2638
+
2639
+ `c_{2} \equiv m e^{a} \pmod p`
2640
+
2641
+ Parameters
2642
+ ==========
2643
+
2644
+ msg
2645
+ int of encoded message.
2646
+
2647
+ key
2648
+ Public key.
2649
+
2650
+ Returns
2651
+ =======
2652
+
2653
+ tuple : (c1, c2)
2654
+ Encipher into two number.
2655
+
2656
+ Notes
2657
+ =====
2658
+
2659
+ For testing purposes, the ``seed`` parameter may be set to control
2660
+ the output of this routine. See sympy.core.random._randrange.
2661
+
2662
+ Examples
2663
+ ========
2664
+
2665
+ >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
2666
+ >>> pri = elgamal_private_key(5, seed=[3]); pri
2667
+ (37, 2, 3)
2668
+ >>> pub = elgamal_public_key(pri); pub
2669
+ (37, 2, 8)
2670
+ >>> msg = 36
2671
+ >>> encipher_elgamal(msg, pub, seed=[3])
2672
+ (8, 6)
2673
+
2674
+ """
2675
+ p, r, e = key
2676
+ if i < 0 or i >= p:
2677
+ raise ValueError(
2678
+ 'Message (%s) should be in range(%s)' % (i, p))
2679
+ randrange = _randrange(seed)
2680
+ a = randrange(2, p)
2681
+ return pow(r, a, p), i*pow(e, a, p) % p
2682
+
2683
+
2684
+ def decipher_elgamal(msg, key):
2685
+ r"""
2686
+ Decrypt message with private key.
2687
+
2688
+ `msg = (c_{1}, c_{2})`
2689
+
2690
+ `key = (p, r, d)`
2691
+
2692
+ According to extended Eucliden theorem,
2693
+ `u c_{1}^{d} + p n = 1`
2694
+
2695
+ `u \equiv 1/{{c_{1}}^d} \pmod p`
2696
+
2697
+ `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
2698
+
2699
+ `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
2700
+
2701
+ Examples
2702
+ ========
2703
+
2704
+ >>> from sympy.crypto.crypto import decipher_elgamal
2705
+ >>> from sympy.crypto.crypto import encipher_elgamal
2706
+ >>> from sympy.crypto.crypto import elgamal_private_key
2707
+ >>> from sympy.crypto.crypto import elgamal_public_key
2708
+
2709
+ >>> pri = elgamal_private_key(5, seed=[3])
2710
+ >>> pub = elgamal_public_key(pri); pub
2711
+ (37, 2, 8)
2712
+ >>> msg = 17
2713
+ >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
2714
+ True
2715
+
2716
+ """
2717
+ p, _, d = key
2718
+ c1, c2 = msg
2719
+ u = igcdex(c1**d, p)[0]
2720
+ return u * c2 % p
2721
+
2722
+
2723
+ ################ Diffie-Hellman Key Exchange #########################
2724
+
2725
+ def dh_private_key(digit=10, seed=None):
2726
+ r"""
2727
+ Return three integer tuple as private key.
2728
+
2729
+ Explanation
2730
+ ===========
2731
+
2732
+ Diffie-Hellman key exchange is based on the mathematical problem
2733
+ called the Discrete Logarithm Problem (see ElGamal).
2734
+
2735
+ Diffie-Hellman key exchange is divided into the following steps:
2736
+
2737
+ * Alice and Bob agree on a base that consist of a prime ``p``
2738
+ and a primitive root of ``p`` called ``g``
2739
+ * Alice choses a number ``a`` and Bob choses a number ``b`` where
2740
+ ``a`` and ``b`` are random numbers in range `[2, p)`. These are
2741
+ their private keys.
2742
+ * Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
2743
+ Alice `g^{b} \pmod p`
2744
+ * They both raise the received value to their secretly chosen
2745
+ number (``a`` or ``b``) and now have both as their shared key
2746
+ `g^{ab} \pmod p`
2747
+
2748
+ Parameters
2749
+ ==========
2750
+
2751
+ digit
2752
+ Minimum number of binary digits required in key.
2753
+
2754
+ Returns
2755
+ =======
2756
+
2757
+ tuple : (p, g, a)
2758
+ p = prime number.
2759
+
2760
+ g = primitive root of p.
2761
+
2762
+ a = random number from 2 through p - 1.
2763
+
2764
+ Notes
2765
+ =====
2766
+
2767
+ For testing purposes, the ``seed`` parameter may be set to control
2768
+ the output of this routine. See sympy.core.random._randrange.
2769
+
2770
+ Examples
2771
+ ========
2772
+
2773
+ >>> from sympy.crypto.crypto import dh_private_key
2774
+ >>> from sympy.ntheory import isprime, is_primitive_root
2775
+ >>> p, g, _ = dh_private_key()
2776
+ >>> isprime(p)
2777
+ True
2778
+ >>> is_primitive_root(g, p)
2779
+ True
2780
+ >>> p, g, _ = dh_private_key(5)
2781
+ >>> isprime(p)
2782
+ True
2783
+ >>> is_primitive_root(g, p)
2784
+ True
2785
+
2786
+ """
2787
+ p = nextprime(2**digit)
2788
+ g = primitive_root(p)
2789
+ randrange = _randrange(seed)
2790
+ a = randrange(2, p)
2791
+ return p, g, a
2792
+
2793
+
2794
+ def dh_public_key(key):
2795
+ r"""
2796
+ Return three number tuple as public key.
2797
+
2798
+ This is the tuple that Alice sends to Bob.
2799
+
2800
+ Parameters
2801
+ ==========
2802
+
2803
+ key : (p, g, a)
2804
+ A tuple generated by ``dh_private_key``.
2805
+
2806
+ Returns
2807
+ =======
2808
+
2809
+ tuple : int, int, int
2810
+ A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
2811
+ parameters.s
2812
+
2813
+ Examples
2814
+ ========
2815
+
2816
+ >>> from sympy.crypto.crypto import dh_private_key, dh_public_key
2817
+ >>> p, g, a = dh_private_key();
2818
+ >>> _p, _g, x = dh_public_key((p, g, a))
2819
+ >>> p == _p and g == _g
2820
+ True
2821
+ >>> x == pow(g, a, p)
2822
+ True
2823
+
2824
+ """
2825
+ p, g, a = key
2826
+ return p, g, pow(g, a, p)
2827
+
2828
+
2829
+ def dh_shared_key(key, b):
2830
+ """
2831
+ Return an integer that is the shared key.
2832
+
2833
+ This is what Bob and Alice can both calculate using the public
2834
+ keys they received from each other and their private keys.
2835
+
2836
+ Parameters
2837
+ ==========
2838
+
2839
+ key : (p, g, x)
2840
+ Tuple `(p, g, x)` generated by ``dh_public_key``.
2841
+
2842
+ b
2843
+ Random number in the range of `2` to `p - 1`
2844
+ (Chosen by second key exchange member (Bob)).
2845
+
2846
+ Returns
2847
+ =======
2848
+
2849
+ int
2850
+ A shared key.
2851
+
2852
+ Examples
2853
+ ========
2854
+
2855
+ >>> from sympy.crypto.crypto import (
2856
+ ... dh_private_key, dh_public_key, dh_shared_key)
2857
+ >>> prk = dh_private_key();
2858
+ >>> p, g, x = dh_public_key(prk);
2859
+ >>> sk = dh_shared_key((p, g, x), 1000)
2860
+ >>> sk == pow(x, 1000, p)
2861
+ True
2862
+
2863
+ """
2864
+ p, _, x = key
2865
+ if 1 >= b or b >= p:
2866
+ raise ValueError(filldedent('''
2867
+ Value of b should be greater 1 and less
2868
+ than prime %s.''' % p))
2869
+
2870
+ return pow(x, b, p)
2871
+
2872
+
2873
+ ################ Goldwasser-Micali Encryption #########################
2874
+
2875
+
2876
+ def _legendre(a, p):
2877
+ """
2878
+ Returns the legendre symbol of a and p
2879
+ assuming that p is a prime.
2880
+
2881
+ i.e. 1 if a is a quadratic residue mod p
2882
+ -1 if a is not a quadratic residue mod p
2883
+ 0 if a is divisible by p
2884
+
2885
+ Parameters
2886
+ ==========
2887
+
2888
+ a : int
2889
+ The number to test.
2890
+
2891
+ p : prime
2892
+ The prime to test ``a`` against.
2893
+
2894
+ Returns
2895
+ =======
2896
+
2897
+ int
2898
+ Legendre symbol (a / p).
2899
+
2900
+ """
2901
+ sig = pow(a, (p - 1)//2, p)
2902
+ if sig == 1:
2903
+ return 1
2904
+ elif sig == 0:
2905
+ return 0
2906
+ else:
2907
+ return -1
2908
+
2909
+
2910
+ def _random_coprime_stream(n, seed=None):
2911
+ randrange = _randrange(seed)
2912
+ while True:
2913
+ y = randrange(n)
2914
+ if gcd(y, n) == 1:
2915
+ yield y
2916
+
2917
+
2918
+ def gm_private_key(p, q, a=None):
2919
+ r"""
2920
+ Check if ``p`` and ``q`` can be used as private keys for
2921
+ the Goldwasser-Micali encryption. The method works
2922
+ roughly as follows.
2923
+
2924
+ Explanation
2925
+ ===========
2926
+
2927
+ #. Pick two large primes $p$ and $q$.
2928
+ #. Call their product $N$.
2929
+ #. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
2930
+ #. For each $k$,
2931
+
2932
+ if $b_k = 0$:
2933
+ let $a_k$ be a random square
2934
+ (quadratic residue) modulo $p q$
2935
+ such that ``jacobi_symbol(a, p*q) = 1``
2936
+ if $b_k = 1$:
2937
+ let $a_k$ be a random non-square
2938
+ (non-quadratic residue) modulo $p q$
2939
+ such that ``jacobi_symbol(a, p*q) = 1``
2940
+
2941
+ returns $\left[a_1, a_2, \dots\right]$
2942
+
2943
+ $b_k$ can be recovered by checking whether or not
2944
+ $a_k$ is a residue. And from the $b_k$'s, the message
2945
+ can be reconstructed.
2946
+
2947
+ The idea is that, while ``jacobi_symbol(a, p*q)``
2948
+ can be easily computed (and when it is equal to $-1$ will
2949
+ tell you that $a$ is not a square mod $p q$), quadratic
2950
+ residuosity modulo a composite number is hard to compute
2951
+ without knowing its factorization.
2952
+
2953
+ Moreover, approximately half the numbers coprime to $p q$ have
2954
+ :func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
2955
+ are residues and approximately half are not. This maximizes the
2956
+ entropy of the code.
2957
+
2958
+ Parameters
2959
+ ==========
2960
+
2961
+ p, q, a
2962
+ Initialization variables.
2963
+
2964
+ Returns
2965
+ =======
2966
+
2967
+ tuple : (p, q)
2968
+ The input value ``p`` and ``q``.
2969
+
2970
+ Raises
2971
+ ======
2972
+
2973
+ ValueError
2974
+ If ``p`` and ``q`` are not distinct odd primes.
2975
+
2976
+ """
2977
+ if p == q:
2978
+ raise ValueError("expected distinct primes, "
2979
+ "got two copies of %i" % p)
2980
+ elif not isprime(p) or not isprime(q):
2981
+ raise ValueError("first two arguments must be prime, "
2982
+ "got %i of %i" % (p, q))
2983
+ elif p == 2 or q == 2:
2984
+ raise ValueError("first two arguments must not be even, "
2985
+ "got %i of %i" % (p, q))
2986
+ return p, q
2987
+
2988
+
2989
+ def gm_public_key(p, q, a=None, seed=None):
2990
+ """
2991
+ Compute public keys for ``p`` and ``q``.
2992
+ Note that in Goldwasser-Micali Encryption,
2993
+ public keys are randomly selected.
2994
+
2995
+ Parameters
2996
+ ==========
2997
+
2998
+ p, q, a : int, int, int
2999
+ Initialization variables.
3000
+
3001
+ Returns
3002
+ =======
3003
+
3004
+ tuple : (a, N)
3005
+ ``a`` is the input ``a`` if it is not ``None`` otherwise
3006
+ some random integer coprime to ``p`` and ``q``.
3007
+
3008
+ ``N`` is the product of ``p`` and ``q``.
3009
+
3010
+ """
3011
+
3012
+ p, q = gm_private_key(p, q)
3013
+ N = p * q
3014
+
3015
+ if a is None:
3016
+ randrange = _randrange(seed)
3017
+ while True:
3018
+ a = randrange(N)
3019
+ if _legendre(a, p) == _legendre(a, q) == -1:
3020
+ break
3021
+ else:
3022
+ if _legendre(a, p) != -1 or _legendre(a, q) != -1:
3023
+ return False
3024
+ return (a, N)
3025
+
3026
+
3027
+ def encipher_gm(i, key, seed=None):
3028
+ """
3029
+ Encrypt integer 'i' using public_key 'key'
3030
+ Note that gm uses random encryption.
3031
+
3032
+ Parameters
3033
+ ==========
3034
+
3035
+ i : int
3036
+ The message to encrypt.
3037
+
3038
+ key : (a, N)
3039
+ The public key.
3040
+
3041
+ Returns
3042
+ =======
3043
+
3044
+ list : list of int
3045
+ The randomized encrypted message.
3046
+
3047
+ """
3048
+ if i < 0:
3049
+ raise ValueError(
3050
+ "message must be a non-negative "
3051
+ "integer: got %d instead" % i)
3052
+ a, N = key
3053
+ bits = []
3054
+ while i > 0:
3055
+ bits.append(i % 2)
3056
+ i //= 2
3057
+
3058
+ gen = _random_coprime_stream(N, seed)
3059
+ rev = reversed(bits)
3060
+ encode = lambda b: next(gen)**2*pow(a, b) % N
3061
+ return [ encode(b) for b in rev ]
3062
+
3063
+
3064
+
3065
+ def decipher_gm(message, key):
3066
+ """
3067
+ Decrypt message 'message' using public_key 'key'.
3068
+
3069
+ Parameters
3070
+ ==========
3071
+
3072
+ message : list of int
3073
+ The randomized encrypted message.
3074
+
3075
+ key : (p, q)
3076
+ The private key.
3077
+
3078
+ Returns
3079
+ =======
3080
+
3081
+ int
3082
+ The encrypted message.
3083
+
3084
+ """
3085
+ p, q = key
3086
+ res = lambda m, p: _legendre(m, p) > 0
3087
+ bits = [res(m, p) * res(m, q) for m in message]
3088
+ m = 0
3089
+ for b in bits:
3090
+ m <<= 1
3091
+ m += not b
3092
+ return m
3093
+
3094
+
3095
+
3096
+ ########### RailFence Cipher #############
3097
+
3098
+ def encipher_railfence(message,rails):
3099
+ """
3100
+ Performs Railfence Encryption on plaintext and returns ciphertext
3101
+
3102
+ Examples
3103
+ ========
3104
+
3105
+ >>> from sympy.crypto.crypto import encipher_railfence
3106
+ >>> message = "hello world"
3107
+ >>> encipher_railfence(message,3)
3108
+ 'horel ollwd'
3109
+
3110
+ Parameters
3111
+ ==========
3112
+
3113
+ message : string, the message to encrypt.
3114
+ rails : int, the number of rails.
3115
+
3116
+ Returns
3117
+ =======
3118
+
3119
+ The Encrypted string message.
3120
+
3121
+ References
3122
+ ==========
3123
+ .. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
3124
+
3125
+ """
3126
+ r = list(range(rails))
3127
+ p = cycle(r + r[-2:0:-1])
3128
+ return ''.join(sorted(message, key=lambda i: next(p)))
3129
+
3130
+
3131
+ def decipher_railfence(ciphertext,rails):
3132
+ """
3133
+ Decrypt the message using the given rails
3134
+
3135
+ Examples
3136
+ ========
3137
+
3138
+ >>> from sympy.crypto.crypto import decipher_railfence
3139
+ >>> decipher_railfence("horel ollwd",3)
3140
+ 'hello world'
3141
+
3142
+ Parameters
3143
+ ==========
3144
+
3145
+ message : string, the message to encrypt.
3146
+ rails : int, the number of rails.
3147
+
3148
+ Returns
3149
+ =======
3150
+
3151
+ The Decrypted string message.
3152
+
3153
+ """
3154
+ r = list(range(rails))
3155
+ p = cycle(r + r[-2:0:-1])
3156
+
3157
+ idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
3158
+ res = [''] * len(ciphertext)
3159
+ for i, c in zip(idx, ciphertext):
3160
+ res[i] = c
3161
+ return ''.join(res)
3162
+
3163
+
3164
+ ################ Blum-Goldwasser cryptosystem #########################
3165
+
3166
+ def bg_private_key(p, q):
3167
+ """
3168
+ Check if p and q can be used as private keys for
3169
+ the Blum-Goldwasser cryptosystem.
3170
+
3171
+ Explanation
3172
+ ===========
3173
+
3174
+ The three necessary checks for p and q to pass
3175
+ so that they can be used as private keys:
3176
+
3177
+ 1. p and q must both be prime
3178
+ 2. p and q must be distinct
3179
+ 3. p and q must be congruent to 3 mod 4
3180
+
3181
+ Parameters
3182
+ ==========
3183
+
3184
+ p, q
3185
+ The keys to be checked.
3186
+
3187
+ Returns
3188
+ =======
3189
+
3190
+ p, q
3191
+ Input values.
3192
+
3193
+ Raises
3194
+ ======
3195
+
3196
+ ValueError
3197
+ If p and q do not pass the above conditions.
3198
+
3199
+ """
3200
+
3201
+ if not isprime(p) or not isprime(q):
3202
+ raise ValueError("the two arguments must be prime, "
3203
+ "got %i and %i" %(p, q))
3204
+ elif p == q:
3205
+ raise ValueError("the two arguments must be distinct, "
3206
+ "got two copies of %i. " %p)
3207
+ elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
3208
+ raise ValueError("the two arguments must be congruent to 3 mod 4, "
3209
+ "got %i and %i" %(p, q))
3210
+ return p, q
3211
+
3212
+ def bg_public_key(p, q):
3213
+ """
3214
+ Calculates public keys from private keys.
3215
+
3216
+ Explanation
3217
+ ===========
3218
+
3219
+ The function first checks the validity of
3220
+ private keys passed as arguments and
3221
+ then returns their product.
3222
+
3223
+ Parameters
3224
+ ==========
3225
+
3226
+ p, q
3227
+ The private keys.
3228
+
3229
+ Returns
3230
+ =======
3231
+
3232
+ N
3233
+ The public key.
3234
+
3235
+ """
3236
+ p, q = bg_private_key(p, q)
3237
+ N = p * q
3238
+ return N
3239
+
3240
+ def encipher_bg(i, key, seed=None):
3241
+ """
3242
+ Encrypts the message using public key and seed.
3243
+
3244
+ Explanation
3245
+ ===========
3246
+
3247
+ ALGORITHM:
3248
+ 1. Encodes i as a string of L bits, m.
3249
+ 2. Select a random element r, where 1 < r < key, and computes
3250
+ x = r^2 mod key.
3251
+ 3. Use BBS pseudo-random number generator to generate L random bits, b,
3252
+ using the initial seed as x.
3253
+ 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
3254
+ 5. x_L = x^(2^L) mod key.
3255
+ 6. Return (c, x_L)
3256
+
3257
+ Parameters
3258
+ ==========
3259
+
3260
+ i
3261
+ Message, a non-negative integer
3262
+
3263
+ key
3264
+ The public key
3265
+
3266
+ Returns
3267
+ =======
3268
+
3269
+ Tuple
3270
+ (encrypted_message, x_L)
3271
+
3272
+ Raises
3273
+ ======
3274
+
3275
+ ValueError
3276
+ If i is negative.
3277
+
3278
+ """
3279
+
3280
+ if i < 0:
3281
+ raise ValueError(
3282
+ "message must be a non-negative "
3283
+ "integer: got %d instead" % i)
3284
+
3285
+ enc_msg = []
3286
+ while i > 0:
3287
+ enc_msg.append(i % 2)
3288
+ i //= 2
3289
+ enc_msg.reverse()
3290
+ L = len(enc_msg)
3291
+
3292
+ r = _randint(seed)(2, key - 1)
3293
+ x = r**2 % key
3294
+ x_L = pow(int(x), int(2**L), int(key))
3295
+
3296
+ rand_bits = []
3297
+ for _ in range(L):
3298
+ rand_bits.append(x % 2)
3299
+ x = x**2 % key
3300
+
3301
+ encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
3302
+
3303
+ return (encrypt_msg, x_L)
3304
+
3305
+ def decipher_bg(message, key):
3306
+ """
3307
+ Decrypts the message using private keys.
3308
+
3309
+ Explanation
3310
+ ===========
3311
+
3312
+ ALGORITHM:
3313
+ 1. Let, c be the encrypted message, y the second number received,
3314
+ and p and q be the private keys.
3315
+ 2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
3316
+ r_q = y^((q+1)/4 ^ L) mod q.
3317
+ 3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
3318
+ 4. From, recompute the bits using the BBS generator, as in the
3319
+ encryption algorithm.
3320
+ 5. Compute original message by XORing c and b.
3321
+
3322
+ Parameters
3323
+ ==========
3324
+
3325
+ message
3326
+ Tuple of encrypted message and a non-negative integer.
3327
+
3328
+ key
3329
+ Tuple of private keys.
3330
+
3331
+ Returns
3332
+ =======
3333
+
3334
+ orig_msg
3335
+ The original message
3336
+
3337
+ """
3338
+
3339
+ p, q = key
3340
+ encrypt_msg, y = message
3341
+ public_key = p * q
3342
+ L = len(encrypt_msg)
3343
+ p_t = ((p + 1)/4)**L
3344
+ q_t = ((q + 1)/4)**L
3345
+ r_p = pow(int(y), int(p_t), int(p))
3346
+ r_q = pow(int(y), int(q_t), int(q))
3347
+
3348
+ x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key
3349
+
3350
+ orig_bits = []
3351
+ for _ in range(L):
3352
+ orig_bits.append(x % 2)
3353
+ x = x**2 % public_key
3354
+
3355
+ orig_msg = 0
3356
+ for (m, b) in zip(encrypt_msg, orig_bits):
3357
+ orig_msg = orig_msg * 2
3358
+ orig_msg += (m ^ b)
3359
+
3360
+ return orig_msg
llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (191 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import symbols
2
+ from sympy.crypto.crypto import (cycle_list,
3
+ encipher_shift, encipher_affine, encipher_substitution,
4
+ check_and_join, encipher_vigenere, decipher_vigenere,
5
+ encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6,
6
+ bifid5_square, bifid6_square, bifid5, bifid6,
7
+ decipher_bifid5, decipher_bifid6, encipher_kid_rsa,
8
+ decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key,
9
+ decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa,
10
+ lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence,
11
+ encode_morse, decode_morse, elgamal_private_key, elgamal_public_key,
12
+ encipher_elgamal, decipher_elgamal, dh_private_key, dh_public_key,
13
+ dh_shared_key, decipher_shift, decipher_affine, encipher_bifid,
14
+ decipher_bifid, bifid_square, padded_key, uniq, decipher_gm,
15
+ encipher_gm, gm_public_key, gm_private_key, encipher_bg, decipher_bg,
16
+ bg_private_key, bg_public_key, encipher_rot13, decipher_rot13,
17
+ encipher_atbash, decipher_atbash, NonInvertibleCipherWarning,
18
+ encipher_railfence, decipher_railfence)
19
+ from sympy.matrices import Matrix
20
+ from sympy.ntheory import isprime, is_primitive_root
21
+ from sympy.polys.domains import FF
22
+
23
+ from sympy.testing.pytest import raises, warns
24
+
25
+ from sympy.core.random import randrange
26
+
27
+ def test_encipher_railfence():
28
+ assert encipher_railfence("hello world",2) == "hlowrdel ol"
29
+ assert encipher_railfence("hello world",3) == "horel ollwd"
30
+ assert encipher_railfence("hello world",4) == "hwe olordll"
31
+
32
+ def test_decipher_railfence():
33
+ assert decipher_railfence("hlowrdel ol",2) == "hello world"
34
+ assert decipher_railfence("horel ollwd",3) == "hello world"
35
+ assert decipher_railfence("hwe olordll",4) == "hello world"
36
+
37
+
38
+ def test_cycle_list():
39
+ assert cycle_list(3, 4) == [3, 0, 1, 2]
40
+ assert cycle_list(-1, 4) == [3, 0, 1, 2]
41
+ assert cycle_list(1, 4) == [1, 2, 3, 0]
42
+
43
+
44
+ def test_encipher_shift():
45
+ assert encipher_shift("ABC", 0) == "ABC"
46
+ assert encipher_shift("ABC", 1) == "BCD"
47
+ assert encipher_shift("ABC", -1) == "ZAB"
48
+ assert decipher_shift("ZAB", -1) == "ABC"
49
+
50
+ def test_encipher_rot13():
51
+ assert encipher_rot13("ABC") == "NOP"
52
+ assert encipher_rot13("NOP") == "ABC"
53
+ assert decipher_rot13("ABC") == "NOP"
54
+ assert decipher_rot13("NOP") == "ABC"
55
+
56
+
57
+ def test_encipher_affine():
58
+ assert encipher_affine("ABC", (1, 0)) == "ABC"
59
+ assert encipher_affine("ABC", (1, 1)) == "BCD"
60
+ assert encipher_affine("ABC", (-1, 0)) == "AZY"
61
+ assert encipher_affine("ABC", (-1, 1), symbols="ABCD") == "BAD"
62
+ assert encipher_affine("123", (-1, 1), symbols="1234") == "214"
63
+ assert encipher_affine("ABC", (3, 16)) == "QTW"
64
+ assert decipher_affine("QTW", (3, 16)) == "ABC"
65
+
66
+ def test_encipher_atbash():
67
+ assert encipher_atbash("ABC") == "ZYX"
68
+ assert encipher_atbash("ZYX") == "ABC"
69
+ assert decipher_atbash("ABC") == "ZYX"
70
+ assert decipher_atbash("ZYX") == "ABC"
71
+
72
+ def test_encipher_substitution():
73
+ assert encipher_substitution("ABC", "BAC", "ABC") == "BAC"
74
+ assert encipher_substitution("123", "1243", "1234") == "124"
75
+
76
+
77
+ def test_check_and_join():
78
+ assert check_and_join("abc") == "abc"
79
+ assert check_and_join(uniq("aaabc")) == "abc"
80
+ assert check_and_join("ab c".split()) == "abc"
81
+ assert check_and_join("abc", "a", filter=True) == "a"
82
+ raises(ValueError, lambda: check_and_join('ab', 'a'))
83
+
84
+
85
+ def test_encipher_vigenere():
86
+ assert encipher_vigenere("ABC", "ABC") == "ACE"
87
+ assert encipher_vigenere("ABC", "ABC", symbols="ABCD") == "ACA"
88
+ assert encipher_vigenere("ABC", "AB", symbols="ABCD") == "ACC"
89
+ assert encipher_vigenere("AB", "ABC", symbols="ABCD") == "AC"
90
+ assert encipher_vigenere("A", "ABC", symbols="ABCD") == "A"
91
+
92
+
93
+ def test_decipher_vigenere():
94
+ assert decipher_vigenere("ABC", "ABC") == "AAA"
95
+ assert decipher_vigenere("ABC", "ABC", symbols="ABCD") == "AAA"
96
+ assert decipher_vigenere("ABC", "AB", symbols="ABCD") == "AAC"
97
+ assert decipher_vigenere("AB", "ABC", symbols="ABCD") == "AA"
98
+ assert decipher_vigenere("A", "ABC", symbols="ABCD") == "A"
99
+
100
+
101
+ def test_encipher_hill():
102
+ A = Matrix(2, 2, [1, 2, 3, 5])
103
+ assert encipher_hill("ABCD", A) == "CFIV"
104
+ A = Matrix(2, 2, [1, 0, 0, 1])
105
+ assert encipher_hill("ABCD", A) == "ABCD"
106
+ assert encipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
107
+ A = Matrix(2, 2, [1, 2, 3, 5])
108
+ assert encipher_hill("ABCD", A, symbols="ABCD") == "CBAB"
109
+ assert encipher_hill("AB", A, symbols="ABCD") == "CB"
110
+ # message length, n, does not need to be a multiple of k;
111
+ # it is padded
112
+ assert encipher_hill("ABA", A) == "CFGC"
113
+ assert encipher_hill("ABA", A, pad="Z") == "CFYV"
114
+
115
+
116
+ def test_decipher_hill():
117
+ A = Matrix(2, 2, [1, 2, 3, 5])
118
+ assert decipher_hill("CFIV", A) == "ABCD"
119
+ A = Matrix(2, 2, [1, 0, 0, 1])
120
+ assert decipher_hill("ABCD", A) == "ABCD"
121
+ assert decipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
122
+ A = Matrix(2, 2, [1, 2, 3, 5])
123
+ assert decipher_hill("CBAB", A, symbols="ABCD") == "ABCD"
124
+ assert decipher_hill("CB", A, symbols="ABCD") == "AB"
125
+ # n does not need to be a multiple of k
126
+ assert decipher_hill("CFA", A) == "ABAA"
127
+
128
+
129
+ def test_encipher_bifid5():
130
+ assert encipher_bifid5("AB", "AB") == "AB"
131
+ assert encipher_bifid5("AB", "CD") == "CO"
132
+ assert encipher_bifid5("ab", "c") == "CH"
133
+ assert encipher_bifid5("a bc", "b") == "BAC"
134
+
135
+
136
+ def test_bifid5_square():
137
+ A = bifid5
138
+ f = lambda i, j: symbols(A[5*i + j])
139
+ M = Matrix(5, 5, f)
140
+ assert bifid5_square("") == M
141
+
142
+
143
+ def test_decipher_bifid5():
144
+ assert decipher_bifid5("AB", "AB") == "AB"
145
+ assert decipher_bifid5("CO", "CD") == "AB"
146
+ assert decipher_bifid5("ch", "c") == "AB"
147
+ assert decipher_bifid5("b ac", "b") == "ABC"
148
+
149
+
150
+ def test_encipher_bifid6():
151
+ assert encipher_bifid6("AB", "AB") == "AB"
152
+ assert encipher_bifid6("AB", "CD") == "CP"
153
+ assert encipher_bifid6("ab", "c") == "CI"
154
+ assert encipher_bifid6("a bc", "b") == "BAC"
155
+
156
+
157
+ def test_decipher_bifid6():
158
+ assert decipher_bifid6("AB", "AB") == "AB"
159
+ assert decipher_bifid6("CP", "CD") == "AB"
160
+ assert decipher_bifid6("ci", "c") == "AB"
161
+ assert decipher_bifid6("b ac", "b") == "ABC"
162
+
163
+
164
+ def test_bifid6_square():
165
+ A = bifid6
166
+ f = lambda i, j: symbols(A[6*i + j])
167
+ M = Matrix(6, 6, f)
168
+ assert bifid6_square("") == M
169
+
170
+
171
+ def test_rsa_public_key():
172
+ assert rsa_public_key(2, 3, 1) == (6, 1)
173
+ assert rsa_public_key(5, 3, 3) == (15, 3)
174
+
175
+ with warns(NonInvertibleCipherWarning):
176
+ assert rsa_public_key(2, 2, 1) == (4, 1)
177
+ assert rsa_public_key(8, 8, 8) is False
178
+
179
+
180
+ def test_rsa_private_key():
181
+ assert rsa_private_key(2, 3, 1) == (6, 1)
182
+ assert rsa_private_key(5, 3, 3) == (15, 3)
183
+ assert rsa_private_key(23,29,5) == (667,493)
184
+
185
+ with warns(NonInvertibleCipherWarning):
186
+ assert rsa_private_key(2, 2, 1) == (4, 1)
187
+ assert rsa_private_key(8, 8, 8) is False
188
+
189
+
190
+ def test_rsa_large_key():
191
+ # Sample from
192
+ # http://www.herongyang.com/Cryptography/JCE-Public-Key-RSA-Private-Public-Key-Pair-Sample.html
193
+ p = int('101565610013301240713207239558950144682174355406589305284428666'\
194
+ '903702505233009')
195
+ q = int('894687191887545488935455605955948413812376003053143521429242133'\
196
+ '12069293984003')
197
+ e = int('65537')
198
+ d = int('893650581832704239530398858744759129594796235440844479456143566'\
199
+ '6999402846577625762582824202269399672579058991442587406384754958587'\
200
+ '400493169361356902030209')
201
+ assert rsa_public_key(p, q, e) == (p*q, e)
202
+ assert rsa_private_key(p, q, e) == (p*q, d)
203
+
204
+
205
+ def test_encipher_rsa():
206
+ puk = rsa_public_key(2, 3, 1)
207
+ assert encipher_rsa(2, puk) == 2
208
+ puk = rsa_public_key(5, 3, 3)
209
+ assert encipher_rsa(2, puk) == 8
210
+
211
+ with warns(NonInvertibleCipherWarning):
212
+ puk = rsa_public_key(2, 2, 1)
213
+ assert encipher_rsa(2, puk) == 2
214
+
215
+
216
+ def test_decipher_rsa():
217
+ prk = rsa_private_key(2, 3, 1)
218
+ assert decipher_rsa(2, prk) == 2
219
+ prk = rsa_private_key(5, 3, 3)
220
+ assert decipher_rsa(8, prk) == 2
221
+
222
+ with warns(NonInvertibleCipherWarning):
223
+ prk = rsa_private_key(2, 2, 1)
224
+ assert decipher_rsa(2, prk) == 2
225
+
226
+
227
+ def test_mutltiprime_rsa_full_example():
228
+ # Test example from
229
+ # https://iopscience.iop.org/article/10.1088/1742-6596/995/1/012030
230
+ puk = rsa_public_key(2, 3, 5, 7, 11, 13, 7)
231
+ prk = rsa_private_key(2, 3, 5, 7, 11, 13, 7)
232
+ assert puk == (30030, 7)
233
+ assert prk == (30030, 823)
234
+
235
+ msg = 10
236
+ encrypted = encipher_rsa(2 * msg - 15, puk)
237
+ assert encrypted == 18065
238
+ decrypted = (decipher_rsa(encrypted, prk) + 15) / 2
239
+ assert decrypted == msg
240
+
241
+ # Test example from
242
+ # https://www.scirp.org/pdf/JCC_2018032215502008.pdf
243
+ puk1 = rsa_public_key(53, 41, 43, 47, 41)
244
+ prk1 = rsa_private_key(53, 41, 43, 47, 41)
245
+ puk2 = rsa_public_key(53, 41, 43, 47, 97)
246
+ prk2 = rsa_private_key(53, 41, 43, 47, 97)
247
+
248
+ assert puk1 == (4391633, 41)
249
+ assert prk1 == (4391633, 294041)
250
+ assert puk2 == (4391633, 97)
251
+ assert prk2 == (4391633, 455713)
252
+
253
+ msg = 12321
254
+ encrypted = encipher_rsa(encipher_rsa(msg, puk1), puk2)
255
+ assert encrypted == 1081588
256
+ decrypted = decipher_rsa(decipher_rsa(encrypted, prk2), prk1)
257
+ assert decrypted == msg
258
+
259
+
260
+ def test_rsa_crt_extreme():
261
+ p = int(
262
+ '10177157607154245068023861503693082120906487143725062283406501' \
263
+ '54082258226204046999838297167140821364638180697194879500245557' \
264
+ '65445186962893346463841419427008800341257468600224049986260471' \
265
+ '92257248163014468841725476918639415726709736077813632961290911' \
266
+ '0256421232977833028677441206049309220354796014376698325101693')
267
+
268
+ q = int(
269
+ '28752342353095132872290181526607275886182793241660805077850801' \
270
+ '75689512797754286972952273553128181861830576836289738668745250' \
271
+ '34028199691128870676414118458442900035778874482624765513861643' \
272
+ '27966696316822188398336199002306588703902894100476186823849595' \
273
+ '103239410527279605442148285816149368667083114802852804976893')
274
+
275
+ r = int(
276
+ '17698229259868825776879500736350186838850961935956310134378261' \
277
+ '89771862186717463067541369694816245225291921138038800171125596' \
278
+ '07315449521981157084370187887650624061033066022458512942411841' \
279
+ '18747893789972315277160085086164119879536041875335384844820566' \
280
+ '0287479617671726408053319619892052000850883994343378882717849')
281
+
282
+ s = int(
283
+ '68925428438585431029269182233502611027091755064643742383515623' \
284
+ '64321310582896893395529367074942808353187138794422745718419645' \
285
+ '28291231865157212604266903677599180789896916456120289112752835' \
286
+ '98502265889669730331688206825220074713977607415178738015831030' \
287
+ '364290585369150502819743827343552098197095520550865360159439'
288
+ )
289
+
290
+ t = int(
291
+ '69035483433453632820551311892368908779778144568711455301541094' \
292
+ '31487047642322695357696860925747923189635033183069823820910521' \
293
+ '71172909106797748883261493224162414050106920442445896819806600' \
294
+ '15448444826108008217972129130625571421904893252804729877353352' \
295
+ '739420480574842850202181462656251626522910618936534699566291'
296
+ )
297
+
298
+ e = 65537
299
+ puk = rsa_public_key(p, q, r, s, t, e)
300
+ prk = rsa_private_key(p, q, r, s, t, e)
301
+
302
+ plaintext = 1000
303
+ ciphertext_1 = encipher_rsa(plaintext, puk)
304
+ ciphertext_2 = encipher_rsa(plaintext, puk, [p, q, r, s, t])
305
+ assert ciphertext_1 == ciphertext_2
306
+ assert decipher_rsa(ciphertext_1, prk) == \
307
+ decipher_rsa(ciphertext_1, prk, [p, q, r, s, t])
308
+
309
+
310
+ def test_rsa_exhaustive():
311
+ p, q = 61, 53
312
+ e = 17
313
+ puk = rsa_public_key(p, q, e, totient='Carmichael')
314
+ prk = rsa_private_key(p, q, e, totient='Carmichael')
315
+
316
+ for msg in range(puk[0]):
317
+ encrypted = encipher_rsa(msg, puk)
318
+ decrypted = decipher_rsa(encrypted, prk)
319
+ try:
320
+ assert decrypted == msg
321
+ except AssertionError:
322
+ raise AssertionError(
323
+ "The RSA is not correctly decrypted " \
324
+ "(Original : {}, Encrypted : {}, Decrypted : {})" \
325
+ .format(msg, encrypted, decrypted)
326
+ )
327
+
328
+
329
+ def test_rsa_multiprime_exhanstive():
330
+ primes = [3, 5, 7, 11]
331
+ e = 7
332
+ args = primes + [e]
333
+ puk = rsa_public_key(*args, totient='Carmichael')
334
+ prk = rsa_private_key(*args, totient='Carmichael')
335
+ n = puk[0]
336
+
337
+ for msg in range(n):
338
+ encrypted = encipher_rsa(msg, puk)
339
+ decrypted = decipher_rsa(encrypted, prk)
340
+ try:
341
+ assert decrypted == msg
342
+ except AssertionError:
343
+ raise AssertionError(
344
+ "The RSA is not correctly decrypted " \
345
+ "(Original : {}, Encrypted : {}, Decrypted : {})" \
346
+ .format(msg, encrypted, decrypted)
347
+ )
348
+
349
+
350
+ def test_rsa_multipower_exhanstive():
351
+ from sympy.core.numbers import igcd
352
+ primes = [5, 5, 7]
353
+ e = 7
354
+ args = primes + [e]
355
+ puk = rsa_public_key(*args, multipower=True)
356
+ prk = rsa_private_key(*args, multipower=True)
357
+ n = puk[0]
358
+
359
+ for msg in range(n):
360
+ if igcd(msg, n) != 1:
361
+ continue
362
+
363
+ encrypted = encipher_rsa(msg, puk)
364
+ decrypted = decipher_rsa(encrypted, prk)
365
+ try:
366
+ assert decrypted == msg
367
+ except AssertionError:
368
+ raise AssertionError(
369
+ "The RSA is not correctly decrypted " \
370
+ "(Original : {}, Encrypted : {}, Decrypted : {})" \
371
+ .format(msg, encrypted, decrypted)
372
+ )
373
+
374
+
375
+ def test_kid_rsa_public_key():
376
+ assert kid_rsa_public_key(1, 2, 1, 1) == (5, 2)
377
+ assert kid_rsa_public_key(1, 2, 2, 1) == (8, 3)
378
+ assert kid_rsa_public_key(1, 2, 1, 2) == (7, 2)
379
+
380
+
381
+ def test_kid_rsa_private_key():
382
+ assert kid_rsa_private_key(1, 2, 1, 1) == (5, 3)
383
+ assert kid_rsa_private_key(1, 2, 2, 1) == (8, 3)
384
+ assert kid_rsa_private_key(1, 2, 1, 2) == (7, 4)
385
+
386
+
387
+ def test_encipher_kid_rsa():
388
+ assert encipher_kid_rsa(1, (5, 2)) == 2
389
+ assert encipher_kid_rsa(1, (8, 3)) == 3
390
+ assert encipher_kid_rsa(1, (7, 2)) == 2
391
+
392
+
393
+ def test_decipher_kid_rsa():
394
+ assert decipher_kid_rsa(2, (5, 3)) == 1
395
+ assert decipher_kid_rsa(3, (8, 3)) == 1
396
+ assert decipher_kid_rsa(2, (7, 4)) == 1
397
+
398
+
399
+ def test_encode_morse():
400
+ assert encode_morse('ABC') == '.-|-...|-.-.'
401
+ assert encode_morse('SMS ') == '...|--|...||'
402
+ assert encode_morse('SMS\n') == '...|--|...||'
403
+ assert encode_morse('') == ''
404
+ assert encode_morse(' ') == '||'
405
+ assert encode_morse(' ', sep='`') == '``'
406
+ assert encode_morse(' ', sep='``') == '````'
407
+ assert encode_morse('!@#$%^&*()_+') == '-.-.--|.--.-.|...-..-|-.--.|-.--.-|..--.-|.-.-.'
408
+ assert encode_morse('12345') == '.----|..---|...--|....-|.....'
409
+ assert encode_morse('67890') == '-....|--...|---..|----.|-----'
410
+
411
+
412
+ def test_decode_morse():
413
+ assert decode_morse('-.-|.|-.--') == 'KEY'
414
+ assert decode_morse('.-.|..-|-.||') == 'RUN'
415
+ raises(KeyError, lambda: decode_morse('.....----'))
416
+
417
+
418
+ def test_lfsr_sequence():
419
+ raises(TypeError, lambda: lfsr_sequence(1, [1], 1))
420
+ raises(TypeError, lambda: lfsr_sequence([1], 1, 1))
421
+ F = FF(2)
422
+ assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
423
+ assert lfsr_sequence([F(0)], [F(1)], 2) == [F(1), F(0)]
424
+ F = FF(3)
425
+ assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
426
+ assert lfsr_sequence([F(0)], [F(2)], 2) == [F(2), F(0)]
427
+ assert lfsr_sequence([F(1)], [F(2)], 2) == [F(2), F(2)]
428
+
429
+
430
+ def test_lfsr_autocorrelation():
431
+ raises(TypeError, lambda: lfsr_autocorrelation(1, 2, 3))
432
+ F = FF(2)
433
+ s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
434
+ assert lfsr_autocorrelation(s, 2, 0) == 1
435
+ assert lfsr_autocorrelation(s, 2, 1) == -1
436
+
437
+
438
+ def test_lfsr_connection_polynomial():
439
+ F = FF(2)
440
+ x = symbols("x")
441
+ s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
442
+ assert lfsr_connection_polynomial(s) == x**2 + 1
443
+ s = lfsr_sequence([F(1), F(1)], [F(0), F(1)], 5)
444
+ assert lfsr_connection_polynomial(s) == x**2 + x + 1
445
+
446
+
447
+ def test_elgamal_private_key():
448
+ a, b, _ = elgamal_private_key(digit=100)
449
+ assert isprime(a)
450
+ assert is_primitive_root(b, a)
451
+ assert len(bin(a)) >= 102
452
+
453
+
454
+ def test_elgamal():
455
+ dk = elgamal_private_key(5)
456
+ ek = elgamal_public_key(dk)
457
+ P = ek[0]
458
+ assert P - 1 == decipher_elgamal(encipher_elgamal(P - 1, ek), dk)
459
+ raises(ValueError, lambda: encipher_elgamal(P, dk))
460
+ raises(ValueError, lambda: encipher_elgamal(-1, dk))
461
+
462
+
463
+ def test_dh_private_key():
464
+ p, g, _ = dh_private_key(digit = 100)
465
+ assert isprime(p)
466
+ assert is_primitive_root(g, p)
467
+ assert len(bin(p)) >= 102
468
+
469
+
470
+ def test_dh_public_key():
471
+ p1, g1, a = dh_private_key(digit = 100)
472
+ p2, g2, ga = dh_public_key((p1, g1, a))
473
+ assert p1 == p2
474
+ assert g1 == g2
475
+ assert ga == pow(g1, a, p1)
476
+
477
+
478
+ def test_dh_shared_key():
479
+ prk = dh_private_key(digit = 100)
480
+ p, _, ga = dh_public_key(prk)
481
+ b = randrange(2, p)
482
+ sk = dh_shared_key((p, _, ga), b)
483
+ assert sk == pow(ga, b, p)
484
+ raises(ValueError, lambda: dh_shared_key((1031, 14, 565), 2000))
485
+
486
+
487
+ def test_padded_key():
488
+ assert padded_key('b', 'ab') == 'ba'
489
+ raises(ValueError, lambda: padded_key('ab', 'ace'))
490
+ raises(ValueError, lambda: padded_key('ab', 'abba'))
491
+
492
+
493
+ def test_bifid():
494
+ raises(ValueError, lambda: encipher_bifid('abc', 'b', 'abcde'))
495
+ assert encipher_bifid('abc', 'b', 'abcd') == 'bdb'
496
+ raises(ValueError, lambda: decipher_bifid('bdb', 'b', 'abcde'))
497
+ assert encipher_bifid('bdb', 'b', 'abcd') == 'abc'
498
+ raises(ValueError, lambda: bifid_square('abcde'))
499
+ assert bifid5_square("B") == \
500
+ bifid5_square('BACDEFGHIKLMNOPQRSTUVWXYZ')
501
+ assert bifid6_square('B0') == \
502
+ bifid6_square('B0ACDEFGHIJKLMNOPQRSTUVWXYZ123456789')
503
+
504
+
505
+ def test_encipher_decipher_gm():
506
+ ps = [131, 137, 139, 149, 151, 157, 163, 167,
507
+ 173, 179, 181, 191, 193, 197, 199]
508
+ qs = [89, 97, 101, 103, 107, 109, 113, 127,
509
+ 131, 137, 139, 149, 151, 157, 47]
510
+ messages = [
511
+ 0, 32855, 34303, 14805, 1280, 75859, 38368,
512
+ 724, 60356, 51675, 76697, 61854, 18661,
513
+ ]
514
+ for p, q in zip(ps, qs):
515
+ pri = gm_private_key(p, q)
516
+ for msg in messages:
517
+ pub = gm_public_key(p, q)
518
+ enc = encipher_gm(msg, pub)
519
+ dec = decipher_gm(enc, pri)
520
+ assert dec == msg
521
+
522
+
523
+ def test_gm_private_key():
524
+ raises(ValueError, lambda: gm_public_key(13, 15))
525
+ raises(ValueError, lambda: gm_public_key(0, 0))
526
+ raises(ValueError, lambda: gm_public_key(0, 5))
527
+ assert 17, 19 == gm_public_key(17, 19)
528
+
529
+
530
+ def test_gm_public_key():
531
+ assert 323 == gm_public_key(17, 19)[1]
532
+ assert 15 == gm_public_key(3, 5)[1]
533
+ raises(ValueError, lambda: gm_public_key(15, 19))
534
+
535
+ def test_encipher_decipher_bg():
536
+ ps = [67, 7, 71, 103, 11, 43, 107, 47,
537
+ 79, 19, 83, 23, 59, 127, 31]
538
+ qs = qs = [7, 71, 103, 11, 43, 107, 47,
539
+ 79, 19, 83, 23, 59, 127, 31, 67]
540
+ messages = [
541
+ 0, 328, 343, 148, 1280, 758, 383,
542
+ 724, 603, 516, 766, 618, 186,
543
+ ]
544
+
545
+ for p, q in zip(ps, qs):
546
+ pri = bg_private_key(p, q)
547
+ for msg in messages:
548
+ pub = bg_public_key(p, q)
549
+ enc = encipher_bg(msg, pub)
550
+ dec = decipher_bg(enc, pri)
551
+ assert dec == msg
552
+
553
+ def test_bg_private_key():
554
+ raises(ValueError, lambda: bg_private_key(8, 16))
555
+ raises(ValueError, lambda: bg_private_key(8, 8))
556
+ raises(ValueError, lambda: bg_private_key(13, 17))
557
+ assert 23, 31 == bg_private_key(23, 31)
558
+
559
+ def test_bg_public_key():
560
+ assert 5293 == bg_public_key(67, 79)
561
+ assert 713 == bg_public_key(23, 31)
562
+ raises(ValueError, lambda: bg_private_key(13, 17))
llmeval-env/lib/python3.10/site-packages/sympy/polys/__init__.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Polynomial manipulation algorithms and algebraic objects. """
2
+
3
+ __all__ = [
4
+ 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree',
5
+ 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo',
6
+ 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert',
7
+ 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list',
8
+ 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content',
9
+ 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff',
10
+ 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor',
11
+ 'intervals', 'refine_root', 'count_roots', 'real_roots', 'nroots',
12
+ 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', 'groebner',
13
+ 'is_zero_dimensional', 'GroebnerBasis', 'poly',
14
+
15
+ 'symmetrize', 'horner', 'interpolate', 'rational_interpolate', 'viete',
16
+
17
+ 'together',
18
+
19
+ 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed',
20
+ 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed',
21
+ 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed',
22
+ 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible',
23
+ 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed',
24
+ 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed',
25
+ 'UnivariatePolynomialError', 'MultivariatePolynomialError',
26
+ 'PolificationFailed', 'OptionError', 'FlagError',
27
+
28
+ 'minpoly', 'minimal_polynomial', 'primitive_element', 'field_isomorphism',
29
+ 'to_number_field', 'isolate', 'round_two', 'prime_decomp',
30
+ 'prime_valuation', 'galois_group',
31
+
32
+ 'itermonomials', 'Monomial',
33
+
34
+ 'lex', 'grlex', 'grevlex', 'ilex', 'igrlex', 'igrevlex',
35
+
36
+ 'CRootOf', 'rootof', 'RootOf', 'ComplexRootOf', 'RootSum',
37
+
38
+ 'roots',
39
+
40
+ 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField',
41
+ 'ComplexField', 'PythonFiniteField', 'GMPYFiniteField',
42
+ 'PythonIntegerRing', 'GMPYIntegerRing', 'PythonRational',
43
+ 'GMPYRationalField', 'AlgebraicField', 'PolynomialRing', 'FractionField',
44
+ 'ExpressionDomain', 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy',
45
+ 'QQ_python', 'QQ_gmpy', 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR',
46
+ 'CC', 'EX', 'EXRAW',
47
+
48
+ 'construct_domain',
49
+
50
+ 'swinnerton_dyer_poly', 'cyclotomic_poly', 'symmetric_poly',
51
+ 'random_poly', 'interpolating_poly',
52
+
53
+ 'jacobi_poly', 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly',
54
+ 'hermite_prob_poly', 'legendre_poly', 'laguerre_poly',
55
+
56
+ 'bernoulli_poly', 'bernoulli_c_poly', 'genocchi_poly', 'euler_poly',
57
+ 'andre_poly',
58
+
59
+ 'apart', 'apart_list', 'assemble_partfrac_list',
60
+
61
+ 'Options',
62
+
63
+ 'ring', 'xring', 'vring', 'sring',
64
+
65
+ 'field', 'xfield', 'vfield', 'sfield'
66
+ ]
67
+
68
+ from .polytools import (Poly, PurePoly, poly_from_expr,
69
+ parallel_poly_from_expr, degree, total_degree, degree_list, LC, LM,
70
+ LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex,
71
+ invert, subresultants, resultant, discriminant, cofactors, gcd_list,
72
+ gcd, lcm_list, lcm, terms_gcd, trunc, monic, content, primitive,
73
+ compose, decompose, sturm, gff_list, gff, sqf_norm, sqf_part,
74
+ sqf_list, sqf, factor_list, factor, intervals, refine_root,
75
+ count_roots, real_roots, nroots, ground_roots, nth_power_roots_poly,
76
+ cancel, reduced, groebner, is_zero_dimensional, GroebnerBasis, poly)
77
+
78
+ from .polyfuncs import (symmetrize, horner, interpolate,
79
+ rational_interpolate, viete)
80
+
81
+ from .rationaltools import together
82
+
83
+ from .polyerrors import (BasePolynomialError, ExactQuotientFailed,
84
+ PolynomialDivisionFailed, OperationNotSupported, HeuristicGCDFailed,
85
+ HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
86
+ EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
87
+ NotReversible, NotAlgebraic, DomainError, PolynomialError,
88
+ UnificationFailed, GeneratorsError, GeneratorsNeeded,
89
+ ComputationFailed, UnivariatePolynomialError,
90
+ MultivariatePolynomialError, PolificationFailed, OptionError,
91
+ FlagError)
92
+
93
+ from .numberfields import (minpoly, minimal_polynomial, primitive_element,
94
+ field_isomorphism, to_number_field, isolate, round_two, prime_decomp,
95
+ prime_valuation, galois_group)
96
+
97
+ from .monomials import itermonomials, Monomial
98
+
99
+ from .orderings import lex, grlex, grevlex, ilex, igrlex, igrevlex
100
+
101
+ from .rootoftools import CRootOf, rootof, RootOf, ComplexRootOf, RootSum
102
+
103
+ from .polyroots import roots
104
+
105
+ from .domains import (Domain, FiniteField, IntegerRing, RationalField,
106
+ RealField, ComplexField, PythonFiniteField, GMPYFiniteField,
107
+ PythonIntegerRing, GMPYIntegerRing, PythonRational, GMPYRationalField,
108
+ AlgebraicField, PolynomialRing, FractionField, ExpressionDomain,
109
+ FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, QQ_gmpy, GF, FF,
110
+ ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW)
111
+
112
+ from .constructor import construct_domain
113
+
114
+ from .specialpolys import (swinnerton_dyer_poly, cyclotomic_poly,
115
+ symmetric_poly, random_poly, interpolating_poly)
116
+
117
+ from .orthopolys import (jacobi_poly, chebyshevt_poly, chebyshevu_poly,
118
+ hermite_poly, hermite_prob_poly, legendre_poly, laguerre_poly)
119
+
120
+ from .appellseqs import (bernoulli_poly, bernoulli_c_poly, genocchi_poly,
121
+ euler_poly, andre_poly)
122
+
123
+ from .partfrac import apart, apart_list, assemble_partfrac_list
124
+
125
+ from .polyoptions import Options
126
+
127
+ from .rings import ring, xring, vring, sring
128
+
129
+ from .fields import field, xfield, vfield, sfield
llmeval-env/lib/python3.10/site-packages/sympy/polys/appellseqs.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ Efficient functions for generating Appell sequences.
3
+
4
+ An Appell sequence is a zero-indexed sequence of polynomials `p_i(x)`
5
+ satisfying `p_{i+1}'(x)=(i+1)p_i(x)` for all `i`. This definition leads
6
+ to the following iterative algorithm:
7
+
8
+ .. math :: p_0(x) = c_0,\ p_i(x) = i \int_0^x p_{i-1}(t)\,dt + c_i
9
+
10
+ The constant coefficients `c_i` are usually determined from the
11
+ just-evaluated integral and `i`.
12
+
13
+ Appell sequences satisfy the following identity from umbral calculus:
14
+
15
+ .. math :: p_n(x+y) = \sum_{k=0}^n \binom{n}{k} p_k(x) y^{n-k}
16
+
17
+ References
18
+ ==========
19
+
20
+ .. [1] https://en.wikipedia.org/wiki/Appell_sequence
21
+ .. [2] Peter Luschny, "An introduction to the Bernoulli function",
22
+ https://arxiv.org/abs/2009.06743
23
+ """
24
+ from sympy.polys.densearith import dup_mul_ground, dup_sub_ground, dup_quo_ground
25
+ from sympy.polys.densetools import dup_eval, dup_integrate
26
+ from sympy.polys.domains import ZZ, QQ
27
+ from sympy.polys.polytools import named_poly
28
+ from sympy.utilities import public
29
+
30
+ def dup_bernoulli(n, K):
31
+ """Low-level implementation of Bernoulli polynomials."""
32
+ if n < 1:
33
+ return [K.one]
34
+ p = [K.one, K(-1,2)]
35
+ for i in range(2, n+1):
36
+ p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
37
+ if i % 2 == 0:
38
+ p = dup_sub_ground(p, dup_eval(p, K(1,2), K) * K(1<<(i-1), (1<<i)-1), K)
39
+ return p
40
+
41
+ @public
42
+ def bernoulli_poly(n, x=None, polys=False):
43
+ r"""Generates the Bernoulli polynomial `\operatorname{B}_n(x)`.
44
+
45
+ `\operatorname{B}_n(x)` is the unique polynomial satisfying
46
+
47
+ .. math :: \int_{x}^{x+1} \operatorname{B}_n(t) \,dt = x^n.
48
+
49
+ Based on this, we have for nonnegative integer `s` and integer
50
+ `a` and `b`
51
+
52
+ .. math :: \sum_{k=a}^{b} k^s = \frac{\operatorname{B}_{s+1}(b+1) -
53
+ \operatorname{B}_{s+1}(a)}{s+1}
54
+
55
+ which is related to Jakob Bernoulli's original motivation for introducing
56
+ the Bernoulli numbers, the values of these polynomials at `x = 1`.
57
+
58
+ Examples
59
+ ========
60
+
61
+ >>> from sympy import summation
62
+ >>> from sympy.abc import x
63
+ >>> from sympy.polys import bernoulli_poly
64
+ >>> bernoulli_poly(5, x)
65
+ x**5 - 5*x**4/2 + 5*x**3/3 - x/6
66
+
67
+ >>> def psum(p, a, b):
68
+ ... return (bernoulli_poly(p+1,b+1) - bernoulli_poly(p+1,a)) / (p+1)
69
+ >>> psum(4, -6, 27)
70
+ 3144337
71
+ >>> summation(x**4, (x, -6, 27))
72
+ 3144337
73
+
74
+ >>> psum(1, 1, x).factor()
75
+ x*(x + 1)/2
76
+ >>> psum(2, 1, x).factor()
77
+ x*(x + 1)*(2*x + 1)/6
78
+ >>> psum(3, 1, x).factor()
79
+ x**2*(x + 1)**2/4
80
+
81
+ Parameters
82
+ ==========
83
+
84
+ n : int
85
+ Degree of the polynomial.
86
+ x : optional
87
+ polys : bool, optional
88
+ If True, return a Poly, otherwise (default) return an expression.
89
+
90
+ See Also
91
+ ========
92
+
93
+ sympy.functions.combinatorial.numbers.bernoulli
94
+
95
+ References
96
+ ==========
97
+
98
+ .. [1] https://en.wikipedia.org/wiki/Bernoulli_polynomials
99
+ """
100
+ return named_poly(n, dup_bernoulli, QQ, "Bernoulli polynomial", (x,), polys)
101
+
102
+ def dup_bernoulli_c(n, K):
103
+ """Low-level implementation of central Bernoulli polynomials."""
104
+ p = [K.one]
105
+ for i in range(1, n+1):
106
+ p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
107
+ if i % 2 == 0:
108
+ p = dup_sub_ground(p, dup_eval(p, K.one, K) * K((1<<(i-1))-1, (1<<i)-1), K)
109
+ return p
110
+
111
+ @public
112
+ def bernoulli_c_poly(n, x=None, polys=False):
113
+ r"""Generates the central Bernoulli polynomial `\operatorname{B}_n^c(x)`.
114
+
115
+ These are scaled and shifted versions of the plain Bernoulli polynomials,
116
+ done in such a way that `\operatorname{B}_n^c(x)` is an even or odd function
117
+ for even or odd `n` respectively:
118
+
119
+ .. math :: \operatorname{B}_n^c(x) = 2^n \operatorname{B}_n
120
+ \left(\frac{x+1}{2}\right)
121
+
122
+ Parameters
123
+ ==========
124
+
125
+ n : int
126
+ Degree of the polynomial.
127
+ x : optional
128
+ polys : bool, optional
129
+ If True, return a Poly, otherwise (default) return an expression.
130
+ """
131
+ return named_poly(n, dup_bernoulli_c, QQ, "central Bernoulli polynomial", (x,), polys)
132
+
133
+ def dup_genocchi(n, K):
134
+ """Low-level implementation of Genocchi polynomials."""
135
+ if n < 1:
136
+ return [K.zero]
137
+ p = [-K.one]
138
+ for i in range(2, n+1):
139
+ p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
140
+ if i % 2 == 0:
141
+ p = dup_sub_ground(p, dup_eval(p, K.one, K) // K(2), K)
142
+ return p
143
+
144
+ @public
145
+ def genocchi_poly(n, x=None, polys=False):
146
+ r"""Generates the Genocchi polynomial `\operatorname{G}_n(x)`.
147
+
148
+ `\operatorname{G}_n(x)` is twice the difference between the plain and
149
+ central Bernoulli polynomials, so has degree `n-1`:
150
+
151
+ .. math :: \operatorname{G}_n(x) = 2 (\operatorname{B}_n(x) -
152
+ \operatorname{B}_n^c(x))
153
+
154
+ The factor of 2 in the definition endows `\operatorname{G}_n(x)` with
155
+ integer coefficients.
156
+
157
+ Parameters
158
+ ==========
159
+
160
+ n : int
161
+ Degree of the polynomial plus one.
162
+ x : optional
163
+ polys : bool, optional
164
+ If True, return a Poly, otherwise (default) return an expression.
165
+
166
+ See Also
167
+ ========
168
+
169
+ sympy.functions.combinatorial.numbers.genocchi
170
+ """
171
+ return named_poly(n, dup_genocchi, ZZ, "Genocchi polynomial", (x,), polys)
172
+
173
+ def dup_euler(n, K):
174
+ """Low-level implementation of Euler polynomials."""
175
+ return dup_quo_ground(dup_genocchi(n+1, ZZ), K(-n-1), K)
176
+
177
+ @public
178
+ def euler_poly(n, x=None, polys=False):
179
+ r"""Generates the Euler polynomial `\operatorname{E}_n(x)`.
180
+
181
+ These are scaled and reindexed versions of the Genocchi polynomials:
182
+
183
+ .. math :: \operatorname{E}_n(x) = -\frac{\operatorname{G}_{n+1}(x)}{n+1}
184
+
185
+ Parameters
186
+ ==========
187
+
188
+ n : int
189
+ Degree of the polynomial.
190
+ x : optional
191
+ polys : bool, optional
192
+ If True, return a Poly, otherwise (default) return an expression.
193
+
194
+ See Also
195
+ ========
196
+
197
+ sympy.functions.combinatorial.numbers.euler
198
+ """
199
+ return named_poly(n, dup_euler, QQ, "Euler polynomial", (x,), polys)
200
+
201
+ def dup_andre(n, K):
202
+ """Low-level implementation of Andre polynomials."""
203
+ p = [K.one]
204
+ for i in range(1, n+1):
205
+ p = dup_integrate(dup_mul_ground(p, K(i), K), 1, K)
206
+ if i % 2 == 0:
207
+ p = dup_sub_ground(p, dup_eval(p, K.one, K), K)
208
+ return p
209
+
210
+ @public
211
+ def andre_poly(n, x=None, polys=False):
212
+ r"""Generates the Andre polynomial `\mathcal{A}_n(x)`.
213
+
214
+ This is the Appell sequence where the constant coefficients form the sequence
215
+ of Euler numbers ``euler(n)``. As such they have integer coefficients
216
+ and parities matching the parity of `n`.
217
+
218
+ Luschny calls these the *Swiss-knife polynomials* because their values
219
+ at 0 and 1 can be simply transformed into both the Bernoulli and Euler
220
+ numbers. Here they are called the Andre polynomials because
221
+ `|\mathcal{A}_n(n\bmod 2)|` for `n \ge 0` generates what Luschny calls
222
+ the *Andre numbers*, A000111 in the OEIS.
223
+
224
+ Examples
225
+ ========
226
+
227
+ >>> from sympy import bernoulli, euler, genocchi
228
+ >>> from sympy.abc import x
229
+ >>> from sympy.polys import andre_poly
230
+ >>> andre_poly(9, x)
231
+ x**9 - 36*x**7 + 630*x**5 - 5124*x**3 + 12465*x
232
+
233
+ >>> [andre_poly(n, 0) for n in range(11)]
234
+ [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]
235
+ >>> [euler(n) for n in range(11)]
236
+ [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]
237
+ >>> [andre_poly(n-1, 1) * n / (4**n - 2**n) for n in range(1, 11)]
238
+ [1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
239
+ >>> [bernoulli(n) for n in range(1, 11)]
240
+ [1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
241
+ >>> [-andre_poly(n-1, -1) * n / (-2)**(n-1) for n in range(1, 11)]
242
+ [-1, -1, 0, 1, 0, -3, 0, 17, 0, -155]
243
+ >>> [genocchi(n) for n in range(1, 11)]
244
+ [-1, -1, 0, 1, 0, -3, 0, 17, 0, -155]
245
+
246
+ >>> [abs(andre_poly(n, n%2)) for n in range(11)]
247
+ [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
248
+
249
+ Parameters
250
+ ==========
251
+
252
+ n : int
253
+ Degree of the polynomial.
254
+ x : optional
255
+ polys : bool, optional
256
+ If True, return a Poly, otherwise (default) return an expression.
257
+
258
+ See Also
259
+ ========
260
+
261
+ sympy.functions.combinatorial.numbers.andre
262
+
263
+ References
264
+ ==========
265
+
266
+ .. [1] Peter Luschny, "An introduction to the Bernoulli function",
267
+ https://arxiv.org/abs/2009.06743
268
+ """
269
+ return named_poly(n, dup_andre, ZZ, "Andre polynomial", (x,), polys)
llmeval-env/lib/python3.10/site-packages/sympy/polys/compatibility.py ADDED
@@ -0,0 +1,1134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compatibility interface between dense and sparse polys. """
2
+
3
+
4
+ from sympy.polys.densearith import dup_add_term
5
+ from sympy.polys.densearith import dmp_add_term
6
+ from sympy.polys.densearith import dup_sub_term
7
+ from sympy.polys.densearith import dmp_sub_term
8
+ from sympy.polys.densearith import dup_mul_term
9
+ from sympy.polys.densearith import dmp_mul_term
10
+ from sympy.polys.densearith import dup_add_ground
11
+ from sympy.polys.densearith import dmp_add_ground
12
+ from sympy.polys.densearith import dup_sub_ground
13
+ from sympy.polys.densearith import dmp_sub_ground
14
+ from sympy.polys.densearith import dup_mul_ground
15
+ from sympy.polys.densearith import dmp_mul_ground
16
+ from sympy.polys.densearith import dup_quo_ground
17
+ from sympy.polys.densearith import dmp_quo_ground
18
+ from sympy.polys.densearith import dup_exquo_ground
19
+ from sympy.polys.densearith import dmp_exquo_ground
20
+ from sympy.polys.densearith import dup_lshift
21
+ from sympy.polys.densearith import dup_rshift
22
+ from sympy.polys.densearith import dup_abs
23
+ from sympy.polys.densearith import dmp_abs
24
+ from sympy.polys.densearith import dup_neg
25
+ from sympy.polys.densearith import dmp_neg
26
+ from sympy.polys.densearith import dup_add
27
+ from sympy.polys.densearith import dmp_add
28
+ from sympy.polys.densearith import dup_sub
29
+ from sympy.polys.densearith import dmp_sub
30
+ from sympy.polys.densearith import dup_add_mul
31
+ from sympy.polys.densearith import dmp_add_mul
32
+ from sympy.polys.densearith import dup_sub_mul
33
+ from sympy.polys.densearith import dmp_sub_mul
34
+ from sympy.polys.densearith import dup_mul
35
+ from sympy.polys.densearith import dmp_mul
36
+ from sympy.polys.densearith import dup_sqr
37
+ from sympy.polys.densearith import dmp_sqr
38
+ from sympy.polys.densearith import dup_pow
39
+ from sympy.polys.densearith import dmp_pow
40
+ from sympy.polys.densearith import dup_pdiv
41
+ from sympy.polys.densearith import dup_prem
42
+ from sympy.polys.densearith import dup_pquo
43
+ from sympy.polys.densearith import dup_pexquo
44
+ from sympy.polys.densearith import dmp_pdiv
45
+ from sympy.polys.densearith import dmp_prem
46
+ from sympy.polys.densearith import dmp_pquo
47
+ from sympy.polys.densearith import dmp_pexquo
48
+ from sympy.polys.densearith import dup_rr_div
49
+ from sympy.polys.densearith import dmp_rr_div
50
+ from sympy.polys.densearith import dup_ff_div
51
+ from sympy.polys.densearith import dmp_ff_div
52
+ from sympy.polys.densearith import dup_div
53
+ from sympy.polys.densearith import dup_rem
54
+ from sympy.polys.densearith import dup_quo
55
+ from sympy.polys.densearith import dup_exquo
56
+ from sympy.polys.densearith import dmp_div
57
+ from sympy.polys.densearith import dmp_rem
58
+ from sympy.polys.densearith import dmp_quo
59
+ from sympy.polys.densearith import dmp_exquo
60
+ from sympy.polys.densearith import dup_max_norm
61
+ from sympy.polys.densearith import dmp_max_norm
62
+ from sympy.polys.densearith import dup_l1_norm
63
+ from sympy.polys.densearith import dmp_l1_norm
64
+ from sympy.polys.densearith import dup_l2_norm_squared
65
+ from sympy.polys.densearith import dmp_l2_norm_squared
66
+ from sympy.polys.densearith import dup_expand
67
+ from sympy.polys.densearith import dmp_expand
68
+ from sympy.polys.densebasic import dup_LC
69
+ from sympy.polys.densebasic import dmp_LC
70
+ from sympy.polys.densebasic import dup_TC
71
+ from sympy.polys.densebasic import dmp_TC
72
+ from sympy.polys.densebasic import dmp_ground_LC
73
+ from sympy.polys.densebasic import dmp_ground_TC
74
+ from sympy.polys.densebasic import dup_degree
75
+ from sympy.polys.densebasic import dmp_degree
76
+ from sympy.polys.densebasic import dmp_degree_in
77
+ from sympy.polys.densebasic import dmp_to_dict
78
+ from sympy.polys.densetools import dup_integrate
79
+ from sympy.polys.densetools import dmp_integrate
80
+ from sympy.polys.densetools import dmp_integrate_in
81
+ from sympy.polys.densetools import dup_diff
82
+ from sympy.polys.densetools import dmp_diff
83
+ from sympy.polys.densetools import dmp_diff_in
84
+ from sympy.polys.densetools import dup_eval
85
+ from sympy.polys.densetools import dmp_eval
86
+ from sympy.polys.densetools import dmp_eval_in
87
+ from sympy.polys.densetools import dmp_eval_tail
88
+ from sympy.polys.densetools import dmp_diff_eval_in
89
+ from sympy.polys.densetools import dup_trunc
90
+ from sympy.polys.densetools import dmp_trunc
91
+ from sympy.polys.densetools import dmp_ground_trunc
92
+ from sympy.polys.densetools import dup_monic
93
+ from sympy.polys.densetools import dmp_ground_monic
94
+ from sympy.polys.densetools import dup_content
95
+ from sympy.polys.densetools import dmp_ground_content
96
+ from sympy.polys.densetools import dup_primitive
97
+ from sympy.polys.densetools import dmp_ground_primitive
98
+ from sympy.polys.densetools import dup_extract
99
+ from sympy.polys.densetools import dmp_ground_extract
100
+ from sympy.polys.densetools import dup_real_imag
101
+ from sympy.polys.densetools import dup_mirror
102
+ from sympy.polys.densetools import dup_scale
103
+ from sympy.polys.densetools import dup_shift
104
+ from sympy.polys.densetools import dup_transform
105
+ from sympy.polys.densetools import dup_compose
106
+ from sympy.polys.densetools import dmp_compose
107
+ from sympy.polys.densetools import dup_decompose
108
+ from sympy.polys.densetools import dmp_lift
109
+ from sympy.polys.densetools import dup_sign_variations
110
+ from sympy.polys.densetools import dup_clear_denoms
111
+ from sympy.polys.densetools import dmp_clear_denoms
112
+ from sympy.polys.densetools import dup_revert
113
+ from sympy.polys.euclidtools import dup_half_gcdex
114
+ from sympy.polys.euclidtools import dmp_half_gcdex
115
+ from sympy.polys.euclidtools import dup_gcdex
116
+ from sympy.polys.euclidtools import dmp_gcdex
117
+ from sympy.polys.euclidtools import dup_invert
118
+ from sympy.polys.euclidtools import dmp_invert
119
+ from sympy.polys.euclidtools import dup_euclidean_prs
120
+ from sympy.polys.euclidtools import dmp_euclidean_prs
121
+ from sympy.polys.euclidtools import dup_primitive_prs
122
+ from sympy.polys.euclidtools import dmp_primitive_prs
123
+ from sympy.polys.euclidtools import dup_inner_subresultants
124
+ from sympy.polys.euclidtools import dup_subresultants
125
+ from sympy.polys.euclidtools import dup_prs_resultant
126
+ from sympy.polys.euclidtools import dup_resultant
127
+ from sympy.polys.euclidtools import dmp_inner_subresultants
128
+ from sympy.polys.euclidtools import dmp_subresultants
129
+ from sympy.polys.euclidtools import dmp_prs_resultant
130
+ from sympy.polys.euclidtools import dmp_zz_modular_resultant
131
+ from sympy.polys.euclidtools import dmp_zz_collins_resultant
132
+ from sympy.polys.euclidtools import dmp_qq_collins_resultant
133
+ from sympy.polys.euclidtools import dmp_resultant
134
+ from sympy.polys.euclidtools import dup_discriminant
135
+ from sympy.polys.euclidtools import dmp_discriminant
136
+ from sympy.polys.euclidtools import dup_rr_prs_gcd
137
+ from sympy.polys.euclidtools import dup_ff_prs_gcd
138
+ from sympy.polys.euclidtools import dmp_rr_prs_gcd
139
+ from sympy.polys.euclidtools import dmp_ff_prs_gcd
140
+ from sympy.polys.euclidtools import dup_zz_heu_gcd
141
+ from sympy.polys.euclidtools import dmp_zz_heu_gcd
142
+ from sympy.polys.euclidtools import dup_qq_heu_gcd
143
+ from sympy.polys.euclidtools import dmp_qq_heu_gcd
144
+ from sympy.polys.euclidtools import dup_inner_gcd
145
+ from sympy.polys.euclidtools import dmp_inner_gcd
146
+ from sympy.polys.euclidtools import dup_gcd
147
+ from sympy.polys.euclidtools import dmp_gcd
148
+ from sympy.polys.euclidtools import dup_rr_lcm
149
+ from sympy.polys.euclidtools import dup_ff_lcm
150
+ from sympy.polys.euclidtools import dup_lcm
151
+ from sympy.polys.euclidtools import dmp_rr_lcm
152
+ from sympy.polys.euclidtools import dmp_ff_lcm
153
+ from sympy.polys.euclidtools import dmp_lcm
154
+ from sympy.polys.euclidtools import dmp_content
155
+ from sympy.polys.euclidtools import dmp_primitive
156
+ from sympy.polys.euclidtools import dup_cancel
157
+ from sympy.polys.euclidtools import dmp_cancel
158
+ from sympy.polys.factortools import dup_trial_division
159
+ from sympy.polys.factortools import dmp_trial_division
160
+ from sympy.polys.factortools import dup_zz_mignotte_bound
161
+ from sympy.polys.factortools import dmp_zz_mignotte_bound
162
+ from sympy.polys.factortools import dup_zz_hensel_step
163
+ from sympy.polys.factortools import dup_zz_hensel_lift
164
+ from sympy.polys.factortools import dup_zz_zassenhaus
165
+ from sympy.polys.factortools import dup_zz_irreducible_p
166
+ from sympy.polys.factortools import dup_cyclotomic_p
167
+ from sympy.polys.factortools import dup_zz_cyclotomic_poly
168
+ from sympy.polys.factortools import dup_zz_cyclotomic_factor
169
+ from sympy.polys.factortools import dup_zz_factor_sqf
170
+ from sympy.polys.factortools import dup_zz_factor
171
+ from sympy.polys.factortools import dmp_zz_wang_non_divisors
172
+ from sympy.polys.factortools import dmp_zz_wang_lead_coeffs
173
+ from sympy.polys.factortools import dup_zz_diophantine
174
+ from sympy.polys.factortools import dmp_zz_diophantine
175
+ from sympy.polys.factortools import dmp_zz_wang_hensel_lifting
176
+ from sympy.polys.factortools import dmp_zz_wang
177
+ from sympy.polys.factortools import dmp_zz_factor
178
+ from sympy.polys.factortools import dup_qq_i_factor
179
+ from sympy.polys.factortools import dup_zz_i_factor
180
+ from sympy.polys.factortools import dmp_qq_i_factor
181
+ from sympy.polys.factortools import dmp_zz_i_factor
182
+ from sympy.polys.factortools import dup_ext_factor
183
+ from sympy.polys.factortools import dmp_ext_factor
184
+ from sympy.polys.factortools import dup_gf_factor
185
+ from sympy.polys.factortools import dmp_gf_factor
186
+ from sympy.polys.factortools import dup_factor_list
187
+ from sympy.polys.factortools import dup_factor_list_include
188
+ from sympy.polys.factortools import dmp_factor_list
189
+ from sympy.polys.factortools import dmp_factor_list_include
190
+ from sympy.polys.factortools import dup_irreducible_p
191
+ from sympy.polys.factortools import dmp_irreducible_p
192
+ from sympy.polys.rootisolation import dup_sturm
193
+ from sympy.polys.rootisolation import dup_root_upper_bound
194
+ from sympy.polys.rootisolation import dup_root_lower_bound
195
+ from sympy.polys.rootisolation import dup_step_refine_real_root
196
+ from sympy.polys.rootisolation import dup_inner_refine_real_root
197
+ from sympy.polys.rootisolation import dup_outer_refine_real_root
198
+ from sympy.polys.rootisolation import dup_refine_real_root
199
+ from sympy.polys.rootisolation import dup_inner_isolate_real_roots
200
+ from sympy.polys.rootisolation import dup_inner_isolate_positive_roots
201
+ from sympy.polys.rootisolation import dup_inner_isolate_negative_roots
202
+ from sympy.polys.rootisolation import dup_isolate_real_roots_sqf
203
+ from sympy.polys.rootisolation import dup_isolate_real_roots
204
+ from sympy.polys.rootisolation import dup_isolate_real_roots_list
205
+ from sympy.polys.rootisolation import dup_count_real_roots
206
+ from sympy.polys.rootisolation import dup_count_complex_roots
207
+ from sympy.polys.rootisolation import dup_isolate_complex_roots_sqf
208
+ from sympy.polys.rootisolation import dup_isolate_all_roots_sqf
209
+ from sympy.polys.rootisolation import dup_isolate_all_roots
210
+
211
+ from sympy.polys.sqfreetools import (
212
+ dup_sqf_p, dmp_sqf_p, dup_sqf_norm, dmp_sqf_norm, dup_gf_sqf_part, dmp_gf_sqf_part,
213
+ dup_sqf_part, dmp_sqf_part, dup_gf_sqf_list, dmp_gf_sqf_list, dup_sqf_list,
214
+ dup_sqf_list_include, dmp_sqf_list, dmp_sqf_list_include, dup_gff_list, dmp_gff_list)
215
+
216
+ from sympy.polys.galoistools import (
217
+ gf_degree, gf_LC, gf_TC, gf_strip, gf_from_dict,
218
+ gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground,
219
+ gf_mul_ground, gf_quo_ground, gf_add, gf_sub, gf_mul, gf_sqr, gf_add_mul, gf_sub_mul,
220
+ gf_expand, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_pow, gf_pow_mod,
221
+ gf_gcd, gf_lcm, gf_cofactors, gf_gcdex, gf_monic, gf_diff, gf_eval, gf_multi_eval,
222
+ gf_compose, gf_compose_mod, gf_trace_map, gf_random, gf_irreducible, gf_irred_p_ben_or,
223
+ gf_irred_p_rabin, gf_irreducible_p, gf_sqf_p, gf_sqf_part, gf_Qmatrix,
224
+ gf_berlekamp, gf_ddf_zassenhaus, gf_edf_zassenhaus, gf_ddf_shoup, gf_edf_shoup,
225
+ gf_zassenhaus, gf_shoup, gf_factor_sqf, gf_factor)
226
+
227
+ from sympy.utilities import public
228
+
229
+ @public
230
+ class IPolys:
231
+ symbols = None
232
+ ngens = None
233
+ domain = None
234
+ order = None
235
+ gens = None
236
+
237
+ def drop(self, gen):
238
+ pass
239
+
240
+ def clone(self, symbols=None, domain=None, order=None):
241
+ pass
242
+
243
+ def to_ground(self):
244
+ pass
245
+
246
+ def ground_new(self, element):
247
+ pass
248
+
249
+ def domain_new(self, element):
250
+ pass
251
+
252
+ def from_dict(self, d):
253
+ pass
254
+
255
+ def wrap(self, element):
256
+ from sympy.polys.rings import PolyElement
257
+ if isinstance(element, PolyElement):
258
+ if element.ring == self:
259
+ return element
260
+ else:
261
+ raise NotImplementedError("domain conversions")
262
+ else:
263
+ return self.ground_new(element)
264
+
265
+ def to_dense(self, element):
266
+ return self.wrap(element).to_dense()
267
+
268
+ def from_dense(self, element):
269
+ return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain))
270
+
271
+ def dup_add_term(self, f, c, i):
272
+ return self.from_dense(dup_add_term(self.to_dense(f), c, i, self.domain))
273
+ def dmp_add_term(self, f, c, i):
274
+ return self.from_dense(dmp_add_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain))
275
+ def dup_sub_term(self, f, c, i):
276
+ return self.from_dense(dup_sub_term(self.to_dense(f), c, i, self.domain))
277
+ def dmp_sub_term(self, f, c, i):
278
+ return self.from_dense(dmp_sub_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain))
279
+ def dup_mul_term(self, f, c, i):
280
+ return self.from_dense(dup_mul_term(self.to_dense(f), c, i, self.domain))
281
+ def dmp_mul_term(self, f, c, i):
282
+ return self.from_dense(dmp_mul_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain))
283
+
284
+ def dup_add_ground(self, f, c):
285
+ return self.from_dense(dup_add_ground(self.to_dense(f), c, self.domain))
286
+ def dmp_add_ground(self, f, c):
287
+ return self.from_dense(dmp_add_ground(self.to_dense(f), c, self.ngens-1, self.domain))
288
+ def dup_sub_ground(self, f, c):
289
+ return self.from_dense(dup_sub_ground(self.to_dense(f), c, self.domain))
290
+ def dmp_sub_ground(self, f, c):
291
+ return self.from_dense(dmp_sub_ground(self.to_dense(f), c, self.ngens-1, self.domain))
292
+ def dup_mul_ground(self, f, c):
293
+ return self.from_dense(dup_mul_ground(self.to_dense(f), c, self.domain))
294
+ def dmp_mul_ground(self, f, c):
295
+ return self.from_dense(dmp_mul_ground(self.to_dense(f), c, self.ngens-1, self.domain))
296
+ def dup_quo_ground(self, f, c):
297
+ return self.from_dense(dup_quo_ground(self.to_dense(f), c, self.domain))
298
+ def dmp_quo_ground(self, f, c):
299
+ return self.from_dense(dmp_quo_ground(self.to_dense(f), c, self.ngens-1, self.domain))
300
+ def dup_exquo_ground(self, f, c):
301
+ return self.from_dense(dup_exquo_ground(self.to_dense(f), c, self.domain))
302
+ def dmp_exquo_ground(self, f, c):
303
+ return self.from_dense(dmp_exquo_ground(self.to_dense(f), c, self.ngens-1, self.domain))
304
+
305
+ def dup_lshift(self, f, n):
306
+ return self.from_dense(dup_lshift(self.to_dense(f), n, self.domain))
307
+ def dup_rshift(self, f, n):
308
+ return self.from_dense(dup_rshift(self.to_dense(f), n, self.domain))
309
+
310
+ def dup_abs(self, f):
311
+ return self.from_dense(dup_abs(self.to_dense(f), self.domain))
312
+ def dmp_abs(self, f):
313
+ return self.from_dense(dmp_abs(self.to_dense(f), self.ngens-1, self.domain))
314
+
315
+ def dup_neg(self, f):
316
+ return self.from_dense(dup_neg(self.to_dense(f), self.domain))
317
+ def dmp_neg(self, f):
318
+ return self.from_dense(dmp_neg(self.to_dense(f), self.ngens-1, self.domain))
319
+
320
+ def dup_add(self, f, g):
321
+ return self.from_dense(dup_add(self.to_dense(f), self.to_dense(g), self.domain))
322
+ def dmp_add(self, f, g):
323
+ return self.from_dense(dmp_add(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
324
+
325
+ def dup_sub(self, f, g):
326
+ return self.from_dense(dup_sub(self.to_dense(f), self.to_dense(g), self.domain))
327
+ def dmp_sub(self, f, g):
328
+ return self.from_dense(dmp_sub(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
329
+
330
+ def dup_add_mul(self, f, g, h):
331
+ return self.from_dense(dup_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain))
332
+ def dmp_add_mul(self, f, g, h):
333
+ return self.from_dense(dmp_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain))
334
+ def dup_sub_mul(self, f, g, h):
335
+ return self.from_dense(dup_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain))
336
+ def dmp_sub_mul(self, f, g, h):
337
+ return self.from_dense(dmp_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain))
338
+
339
+ def dup_mul(self, f, g):
340
+ return self.from_dense(dup_mul(self.to_dense(f), self.to_dense(g), self.domain))
341
+ def dmp_mul(self, f, g):
342
+ return self.from_dense(dmp_mul(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
343
+
344
+ def dup_sqr(self, f):
345
+ return self.from_dense(dup_sqr(self.to_dense(f), self.domain))
346
+ def dmp_sqr(self, f):
347
+ return self.from_dense(dmp_sqr(self.to_dense(f), self.ngens-1, self.domain))
348
+ def dup_pow(self, f, n):
349
+ return self.from_dense(dup_pow(self.to_dense(f), n, self.domain))
350
+ def dmp_pow(self, f, n):
351
+ return self.from_dense(dmp_pow(self.to_dense(f), n, self.ngens-1, self.domain))
352
+
353
+ def dup_pdiv(self, f, g):
354
+ q, r = dup_pdiv(self.to_dense(f), self.to_dense(g), self.domain)
355
+ return (self.from_dense(q), self.from_dense(r))
356
+ def dup_prem(self, f, g):
357
+ return self.from_dense(dup_prem(self.to_dense(f), self.to_dense(g), self.domain))
358
+ def dup_pquo(self, f, g):
359
+ return self.from_dense(dup_pquo(self.to_dense(f), self.to_dense(g), self.domain))
360
+ def dup_pexquo(self, f, g):
361
+ return self.from_dense(dup_pexquo(self.to_dense(f), self.to_dense(g), self.domain))
362
+
363
+ def dmp_pdiv(self, f, g):
364
+ q, r = dmp_pdiv(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
365
+ return (self.from_dense(q), self.from_dense(r))
366
+ def dmp_prem(self, f, g):
367
+ return self.from_dense(dmp_prem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
368
+ def dmp_pquo(self, f, g):
369
+ return self.from_dense(dmp_pquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
370
+ def dmp_pexquo(self, f, g):
371
+ return self.from_dense(dmp_pexquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
372
+
373
+ def dup_rr_div(self, f, g):
374
+ q, r = dup_rr_div(self.to_dense(f), self.to_dense(g), self.domain)
375
+ return (self.from_dense(q), self.from_dense(r))
376
+ def dmp_rr_div(self, f, g):
377
+ q, r = dmp_rr_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
378
+ return (self.from_dense(q), self.from_dense(r))
379
+ def dup_ff_div(self, f, g):
380
+ q, r = dup_ff_div(self.to_dense(f), self.to_dense(g), self.domain)
381
+ return (self.from_dense(q), self.from_dense(r))
382
+ def dmp_ff_div(self, f, g):
383
+ q, r = dmp_ff_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
384
+ return (self.from_dense(q), self.from_dense(r))
385
+
386
+ def dup_div(self, f, g):
387
+ q, r = dup_div(self.to_dense(f), self.to_dense(g), self.domain)
388
+ return (self.from_dense(q), self.from_dense(r))
389
+ def dup_rem(self, f, g):
390
+ return self.from_dense(dup_rem(self.to_dense(f), self.to_dense(g), self.domain))
391
+ def dup_quo(self, f, g):
392
+ return self.from_dense(dup_quo(self.to_dense(f), self.to_dense(g), self.domain))
393
+ def dup_exquo(self, f, g):
394
+ return self.from_dense(dup_exquo(self.to_dense(f), self.to_dense(g), self.domain))
395
+
396
+ def dmp_div(self, f, g):
397
+ q, r = dmp_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
398
+ return (self.from_dense(q), self.from_dense(r))
399
+ def dmp_rem(self, f, g):
400
+ return self.from_dense(dmp_rem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
401
+ def dmp_quo(self, f, g):
402
+ return self.from_dense(dmp_quo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
403
+ def dmp_exquo(self, f, g):
404
+ return self.from_dense(dmp_exquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
405
+
406
+ def dup_max_norm(self, f):
407
+ return dup_max_norm(self.to_dense(f), self.domain)
408
+ def dmp_max_norm(self, f):
409
+ return dmp_max_norm(self.to_dense(f), self.ngens-1, self.domain)
410
+
411
+ def dup_l1_norm(self, f):
412
+ return dup_l1_norm(self.to_dense(f), self.domain)
413
+ def dmp_l1_norm(self, f):
414
+ return dmp_l1_norm(self.to_dense(f), self.ngens-1, self.domain)
415
+
416
+ def dup_l2_norm_squared(self, f):
417
+ return dup_l2_norm_squared(self.to_dense(f), self.domain)
418
+ def dmp_l2_norm_squared(self, f):
419
+ return dmp_l2_norm_squared(self.to_dense(f), self.ngens-1, self.domain)
420
+
421
+ def dup_expand(self, polys):
422
+ return self.from_dense(dup_expand(list(map(self.to_dense, polys)), self.domain))
423
+ def dmp_expand(self, polys):
424
+ return self.from_dense(dmp_expand(list(map(self.to_dense, polys)), self.ngens-1, self.domain))
425
+
426
+ def dup_LC(self, f):
427
+ return dup_LC(self.to_dense(f), self.domain)
428
+ def dmp_LC(self, f):
429
+ LC = dmp_LC(self.to_dense(f), self.domain)
430
+ if isinstance(LC, list):
431
+ return self[1:].from_dense(LC)
432
+ else:
433
+ return LC
434
+ def dup_TC(self, f):
435
+ return dup_TC(self.to_dense(f), self.domain)
436
+ def dmp_TC(self, f):
437
+ TC = dmp_TC(self.to_dense(f), self.domain)
438
+ if isinstance(TC, list):
439
+ return self[1:].from_dense(TC)
440
+ else:
441
+ return TC
442
+
443
+ def dmp_ground_LC(self, f):
444
+ return dmp_ground_LC(self.to_dense(f), self.ngens-1, self.domain)
445
+ def dmp_ground_TC(self, f):
446
+ return dmp_ground_TC(self.to_dense(f), self.ngens-1, self.domain)
447
+
448
+ def dup_degree(self, f):
449
+ return dup_degree(self.to_dense(f))
450
+ def dmp_degree(self, f):
451
+ return dmp_degree(self.to_dense(f), self.ngens-1)
452
+ def dmp_degree_in(self, f, j):
453
+ return dmp_degree_in(self.to_dense(f), j, self.ngens-1)
454
+ def dup_integrate(self, f, m):
455
+ return self.from_dense(dup_integrate(self.to_dense(f), m, self.domain))
456
+ def dmp_integrate(self, f, m):
457
+ return self.from_dense(dmp_integrate(self.to_dense(f), m, self.ngens-1, self.domain))
458
+
459
+ def dup_diff(self, f, m):
460
+ return self.from_dense(dup_diff(self.to_dense(f), m, self.domain))
461
+ def dmp_diff(self, f, m):
462
+ return self.from_dense(dmp_diff(self.to_dense(f), m, self.ngens-1, self.domain))
463
+
464
+ def dmp_diff_in(self, f, m, j):
465
+ return self.from_dense(dmp_diff_in(self.to_dense(f), m, j, self.ngens-1, self.domain))
466
+ def dmp_integrate_in(self, f, m, j):
467
+ return self.from_dense(dmp_integrate_in(self.to_dense(f), m, j, self.ngens-1, self.domain))
468
+
469
+ def dup_eval(self, f, a):
470
+ return dup_eval(self.to_dense(f), a, self.domain)
471
+ def dmp_eval(self, f, a):
472
+ result = dmp_eval(self.to_dense(f), a, self.ngens-1, self.domain)
473
+ return self[1:].from_dense(result)
474
+
475
+ def dmp_eval_in(self, f, a, j):
476
+ result = dmp_eval_in(self.to_dense(f), a, j, self.ngens-1, self.domain)
477
+ return self.drop(j).from_dense(result)
478
+ def dmp_diff_eval_in(self, f, m, a, j):
479
+ result = dmp_diff_eval_in(self.to_dense(f), m, a, j, self.ngens-1, self.domain)
480
+ return self.drop(j).from_dense(result)
481
+
482
+ def dmp_eval_tail(self, f, A):
483
+ result = dmp_eval_tail(self.to_dense(f), A, self.ngens-1, self.domain)
484
+ if isinstance(result, list):
485
+ return self[:-len(A)].from_dense(result)
486
+ else:
487
+ return result
488
+
489
+ def dup_trunc(self, f, p):
490
+ return self.from_dense(dup_trunc(self.to_dense(f), p, self.domain))
491
+ def dmp_trunc(self, f, g):
492
+ return self.from_dense(dmp_trunc(self.to_dense(f), self[1:].to_dense(g), self.ngens-1, self.domain))
493
+ def dmp_ground_trunc(self, f, p):
494
+ return self.from_dense(dmp_ground_trunc(self.to_dense(f), p, self.ngens-1, self.domain))
495
+
496
+ def dup_monic(self, f):
497
+ return self.from_dense(dup_monic(self.to_dense(f), self.domain))
498
+ def dmp_ground_monic(self, f):
499
+ return self.from_dense(dmp_ground_monic(self.to_dense(f), self.ngens-1, self.domain))
500
+
501
+ def dup_extract(self, f, g):
502
+ c, F, G = dup_extract(self.to_dense(f), self.to_dense(g), self.domain)
503
+ return (c, self.from_dense(F), self.from_dense(G))
504
+ def dmp_ground_extract(self, f, g):
505
+ c, F, G = dmp_ground_extract(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
506
+ return (c, self.from_dense(F), self.from_dense(G))
507
+
508
+ def dup_real_imag(self, f):
509
+ p, q = dup_real_imag(self.wrap(f).drop(1).to_dense(), self.domain)
510
+ return (self.from_dense(p), self.from_dense(q))
511
+
512
+ def dup_mirror(self, f):
513
+ return self.from_dense(dup_mirror(self.to_dense(f), self.domain))
514
+ def dup_scale(self, f, a):
515
+ return self.from_dense(dup_scale(self.to_dense(f), a, self.domain))
516
+ def dup_shift(self, f, a):
517
+ return self.from_dense(dup_shift(self.to_dense(f), a, self.domain))
518
+ def dup_transform(self, f, p, q):
519
+ return self.from_dense(dup_transform(self.to_dense(f), self.to_dense(p), self.to_dense(q), self.domain))
520
+
521
+ def dup_compose(self, f, g):
522
+ return self.from_dense(dup_compose(self.to_dense(f), self.to_dense(g), self.domain))
523
+ def dmp_compose(self, f, g):
524
+ return self.from_dense(dmp_compose(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
525
+
526
+ def dup_decompose(self, f):
527
+ components = dup_decompose(self.to_dense(f), self.domain)
528
+ return list(map(self.from_dense, components))
529
+
530
+ def dmp_lift(self, f):
531
+ result = dmp_lift(self.to_dense(f), self.ngens-1, self.domain)
532
+ return self.to_ground().from_dense(result)
533
+
534
+ def dup_sign_variations(self, f):
535
+ return dup_sign_variations(self.to_dense(f), self.domain)
536
+
537
+ def dup_clear_denoms(self, f, convert=False):
538
+ c, F = dup_clear_denoms(self.to_dense(f), self.domain, convert=convert)
539
+ if convert:
540
+ ring = self.clone(domain=self.domain.get_ring())
541
+ else:
542
+ ring = self
543
+ return (c, ring.from_dense(F))
544
+ def dmp_clear_denoms(self, f, convert=False):
545
+ c, F = dmp_clear_denoms(self.to_dense(f), self.ngens-1, self.domain, convert=convert)
546
+ if convert:
547
+ ring = self.clone(domain=self.domain.get_ring())
548
+ else:
549
+ ring = self
550
+ return (c, ring.from_dense(F))
551
+
552
+ def dup_revert(self, f, n):
553
+ return self.from_dense(dup_revert(self.to_dense(f), n, self.domain))
554
+
555
+ def dup_half_gcdex(self, f, g):
556
+ s, h = dup_half_gcdex(self.to_dense(f), self.to_dense(g), self.domain)
557
+ return (self.from_dense(s), self.from_dense(h))
558
+ def dmp_half_gcdex(self, f, g):
559
+ s, h = dmp_half_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
560
+ return (self.from_dense(s), self.from_dense(h))
561
+ def dup_gcdex(self, f, g):
562
+ s, t, h = dup_gcdex(self.to_dense(f), self.to_dense(g), self.domain)
563
+ return (self.from_dense(s), self.from_dense(t), self.from_dense(h))
564
+ def dmp_gcdex(self, f, g):
565
+ s, t, h = dmp_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
566
+ return (self.from_dense(s), self.from_dense(t), self.from_dense(h))
567
+
568
+ def dup_invert(self, f, g):
569
+ return self.from_dense(dup_invert(self.to_dense(f), self.to_dense(g), self.domain))
570
+ def dmp_invert(self, f, g):
571
+ return self.from_dense(dmp_invert(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain))
572
+
573
+ def dup_euclidean_prs(self, f, g):
574
+ prs = dup_euclidean_prs(self.to_dense(f), self.to_dense(g), self.domain)
575
+ return list(map(self.from_dense, prs))
576
+ def dmp_euclidean_prs(self, f, g):
577
+ prs = dmp_euclidean_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
578
+ return list(map(self.from_dense, prs))
579
+ def dup_primitive_prs(self, f, g):
580
+ prs = dup_primitive_prs(self.to_dense(f), self.to_dense(g), self.domain)
581
+ return list(map(self.from_dense, prs))
582
+ def dmp_primitive_prs(self, f, g):
583
+ prs = dmp_primitive_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
584
+ return list(map(self.from_dense, prs))
585
+
586
+ def dup_inner_subresultants(self, f, g):
587
+ prs, sres = dup_inner_subresultants(self.to_dense(f), self.to_dense(g), self.domain)
588
+ return (list(map(self.from_dense, prs)), sres)
589
+ def dmp_inner_subresultants(self, f, g):
590
+ prs, sres = dmp_inner_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
591
+ return (list(map(self.from_dense, prs)), sres)
592
+
593
+ def dup_subresultants(self, f, g):
594
+ prs = dup_subresultants(self.to_dense(f), self.to_dense(g), self.domain)
595
+ return list(map(self.from_dense, prs))
596
+ def dmp_subresultants(self, f, g):
597
+ prs = dmp_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
598
+ return list(map(self.from_dense, prs))
599
+
600
+ def dup_prs_resultant(self, f, g):
601
+ res, prs = dup_prs_resultant(self.to_dense(f), self.to_dense(g), self.domain)
602
+ return (res, list(map(self.from_dense, prs)))
603
+ def dmp_prs_resultant(self, f, g):
604
+ res, prs = dmp_prs_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
605
+ return (self[1:].from_dense(res), list(map(self.from_dense, prs)))
606
+
607
+ def dmp_zz_modular_resultant(self, f, g, p):
608
+ res = dmp_zz_modular_resultant(self.to_dense(f), self.to_dense(g), self.domain_new(p), self.ngens-1, self.domain)
609
+ return self[1:].from_dense(res)
610
+ def dmp_zz_collins_resultant(self, f, g):
611
+ res = dmp_zz_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
612
+ return self[1:].from_dense(res)
613
+ def dmp_qq_collins_resultant(self, f, g):
614
+ res = dmp_qq_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
615
+ return self[1:].from_dense(res)
616
+
617
+ def dup_resultant(self, f, g): #, includePRS=False):
618
+ return dup_resultant(self.to_dense(f), self.to_dense(g), self.domain) #, includePRS=includePRS)
619
+ def dmp_resultant(self, f, g): #, includePRS=False):
620
+ res = dmp_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) #, includePRS=includePRS)
621
+ if isinstance(res, list):
622
+ return self[1:].from_dense(res)
623
+ else:
624
+ return res
625
+
626
+ def dup_discriminant(self, f):
627
+ return dup_discriminant(self.to_dense(f), self.domain)
628
+ def dmp_discriminant(self, f):
629
+ disc = dmp_discriminant(self.to_dense(f), self.ngens-1, self.domain)
630
+ if isinstance(disc, list):
631
+ return self[1:].from_dense(disc)
632
+ else:
633
+ return disc
634
+
635
+ def dup_rr_prs_gcd(self, f, g):
636
+ H, F, G = dup_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain)
637
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
638
+ def dup_ff_prs_gcd(self, f, g):
639
+ H, F, G = dup_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain)
640
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
641
+ def dmp_rr_prs_gcd(self, f, g):
642
+ H, F, G = dmp_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
643
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
644
+ def dmp_ff_prs_gcd(self, f, g):
645
+ H, F, G = dmp_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
646
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
647
+ def dup_zz_heu_gcd(self, f, g):
648
+ H, F, G = dup_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain)
649
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
650
+ def dmp_zz_heu_gcd(self, f, g):
651
+ H, F, G = dmp_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
652
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
653
+ def dup_qq_heu_gcd(self, f, g):
654
+ H, F, G = dup_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain)
655
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
656
+ def dmp_qq_heu_gcd(self, f, g):
657
+ H, F, G = dmp_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
658
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
659
+ def dup_inner_gcd(self, f, g):
660
+ H, F, G = dup_inner_gcd(self.to_dense(f), self.to_dense(g), self.domain)
661
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
662
+ def dmp_inner_gcd(self, f, g):
663
+ H, F, G = dmp_inner_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
664
+ return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
665
+ def dup_gcd(self, f, g):
666
+ H = dup_gcd(self.to_dense(f), self.to_dense(g), self.domain)
667
+ return self.from_dense(H)
668
+ def dmp_gcd(self, f, g):
669
+ H = dmp_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
670
+ return self.from_dense(H)
671
+ def dup_rr_lcm(self, f, g):
672
+ H = dup_rr_lcm(self.to_dense(f), self.to_dense(g), self.domain)
673
+ return self.from_dense(H)
674
+ def dup_ff_lcm(self, f, g):
675
+ H = dup_ff_lcm(self.to_dense(f), self.to_dense(g), self.domain)
676
+ return self.from_dense(H)
677
+ def dup_lcm(self, f, g):
678
+ H = dup_lcm(self.to_dense(f), self.to_dense(g), self.domain)
679
+ return self.from_dense(H)
680
+ def dmp_rr_lcm(self, f, g):
681
+ H = dmp_rr_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
682
+ return self.from_dense(H)
683
+ def dmp_ff_lcm(self, f, g):
684
+ H = dmp_ff_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
685
+ return self.from_dense(H)
686
+ def dmp_lcm(self, f, g):
687
+ H = dmp_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)
688
+ return self.from_dense(H)
689
+
690
+ def dup_content(self, f):
691
+ cont = dup_content(self.to_dense(f), self.domain)
692
+ return cont
693
+ def dup_primitive(self, f):
694
+ cont, prim = dup_primitive(self.to_dense(f), self.domain)
695
+ return cont, self.from_dense(prim)
696
+
697
+ def dmp_content(self, f):
698
+ cont = dmp_content(self.to_dense(f), self.ngens-1, self.domain)
699
+ if isinstance(cont, list):
700
+ return self[1:].from_dense(cont)
701
+ else:
702
+ return cont
703
+ def dmp_primitive(self, f):
704
+ cont, prim = dmp_primitive(self.to_dense(f), self.ngens-1, self.domain)
705
+ if isinstance(cont, list):
706
+ return (self[1:].from_dense(cont), self.from_dense(prim))
707
+ else:
708
+ return (cont, self.from_dense(prim))
709
+
710
+ def dmp_ground_content(self, f):
711
+ cont = dmp_ground_content(self.to_dense(f), self.ngens-1, self.domain)
712
+ return cont
713
+ def dmp_ground_primitive(self, f):
714
+ cont, prim = dmp_ground_primitive(self.to_dense(f), self.ngens-1, self.domain)
715
+ return (cont, self.from_dense(prim))
716
+
717
+ def dup_cancel(self, f, g, include=True):
718
+ result = dup_cancel(self.to_dense(f), self.to_dense(g), self.domain, include=include)
719
+ if not include:
720
+ cf, cg, F, G = result
721
+ return (cf, cg, self.from_dense(F), self.from_dense(G))
722
+ else:
723
+ F, G = result
724
+ return (self.from_dense(F), self.from_dense(G))
725
+ def dmp_cancel(self, f, g, include=True):
726
+ result = dmp_cancel(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain, include=include)
727
+ if not include:
728
+ cf, cg, F, G = result
729
+ return (cf, cg, self.from_dense(F), self.from_dense(G))
730
+ else:
731
+ F, G = result
732
+ return (self.from_dense(F), self.from_dense(G))
733
+
734
+ def dup_trial_division(self, f, factors):
735
+ factors = dup_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.domain)
736
+ return [ (self.from_dense(g), k) for g, k in factors ]
737
+ def dmp_trial_division(self, f, factors):
738
+ factors = dmp_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.ngens-1, self.domain)
739
+ return [ (self.from_dense(g), k) for g, k in factors ]
740
+
741
+ def dup_zz_mignotte_bound(self, f):
742
+ return dup_zz_mignotte_bound(self.to_dense(f), self.domain)
743
+ def dmp_zz_mignotte_bound(self, f):
744
+ return dmp_zz_mignotte_bound(self.to_dense(f), self.ngens-1, self.domain)
745
+
746
+ def dup_zz_hensel_step(self, m, f, g, h, s, t):
747
+ D = self.to_dense
748
+ G, H, S, T = dup_zz_hensel_step(m, D(f), D(g), D(h), D(s), D(t), self.domain)
749
+ return (self.from_dense(G), self.from_dense(H), self.from_dense(S), self.from_dense(T))
750
+ def dup_zz_hensel_lift(self, p, f, f_list, l):
751
+ D = self.to_dense
752
+ polys = dup_zz_hensel_lift(p, D(f), list(map(D, f_list)), l, self.domain)
753
+ return list(map(self.from_dense, polys))
754
+
755
+ def dup_zz_zassenhaus(self, f):
756
+ factors = dup_zz_zassenhaus(self.to_dense(f), self.domain)
757
+ return [ (self.from_dense(g), k) for g, k in factors ]
758
+
759
+ def dup_zz_irreducible_p(self, f):
760
+ return dup_zz_irreducible_p(self.to_dense(f), self.domain)
761
+ def dup_cyclotomic_p(self, f, irreducible=False):
762
+ return dup_cyclotomic_p(self.to_dense(f), self.domain, irreducible=irreducible)
763
+ def dup_zz_cyclotomic_poly(self, n):
764
+ F = dup_zz_cyclotomic_poly(n, self.domain)
765
+ return self.from_dense(F)
766
+ def dup_zz_cyclotomic_factor(self, f):
767
+ result = dup_zz_cyclotomic_factor(self.to_dense(f), self.domain)
768
+ if result is None:
769
+ return result
770
+ else:
771
+ return list(map(self.from_dense, result))
772
+
773
+ # E: List[ZZ], cs: ZZ, ct: ZZ
774
+ def dmp_zz_wang_non_divisors(self, E, cs, ct):
775
+ return dmp_zz_wang_non_divisors(E, cs, ct, self.domain)
776
+
777
+ # f: Poly, T: List[(Poly, int)], ct: ZZ, A: List[ZZ]
778
+ #def dmp_zz_wang_test_points(f, T, ct, A):
779
+ # dmp_zz_wang_test_points(self.to_dense(f), T, ct, A, self.ngens-1, self.domain)
780
+
781
+ # f: Poly, T: List[(Poly, int)], cs: ZZ, E: List[ZZ], H: List[Poly], A: List[ZZ]
782
+ def dmp_zz_wang_lead_coeffs(self, f, T, cs, E, H, A):
783
+ mv = self[1:]
784
+ T = [ (mv.to_dense(t), k) for t, k in T ]
785
+ uv = self[:1]
786
+ H = list(map(uv.to_dense, H))
787
+ f, HH, CC = dmp_zz_wang_lead_coeffs(self.to_dense(f), T, cs, E, H, A, self.ngens-1, self.domain)
788
+ return self.from_dense(f), list(map(uv.from_dense, HH)), list(map(mv.from_dense, CC))
789
+
790
+ # f: List[Poly], m: int, p: ZZ
791
+ def dup_zz_diophantine(self, F, m, p):
792
+ result = dup_zz_diophantine(list(map(self.to_dense, F)), m, p, self.domain)
793
+ return list(map(self.from_dense, result))
794
+
795
+ # f: List[Poly], c: List[Poly], A: List[ZZ], d: int, p: ZZ
796
+ def dmp_zz_diophantine(self, F, c, A, d, p):
797
+ result = dmp_zz_diophantine(list(map(self.to_dense, F)), self.to_dense(c), A, d, p, self.ngens-1, self.domain)
798
+ return list(map(self.from_dense, result))
799
+
800
+ # f: Poly, H: List[Poly], LC: List[Poly], A: List[ZZ], p: ZZ
801
+ def dmp_zz_wang_hensel_lifting(self, f, H, LC, A, p):
802
+ uv = self[:1]
803
+ mv = self[1:]
804
+ H = list(map(uv.to_dense, H))
805
+ LC = list(map(mv.to_dense, LC))
806
+ result = dmp_zz_wang_hensel_lifting(self.to_dense(f), H, LC, A, p, self.ngens-1, self.domain)
807
+ return list(map(self.from_dense, result))
808
+
809
+ def dmp_zz_wang(self, f, mod=None, seed=None):
810
+ factors = dmp_zz_wang(self.to_dense(f), self.ngens-1, self.domain, mod=mod, seed=seed)
811
+ return [ self.from_dense(g) for g in factors ]
812
+
813
+ def dup_zz_factor_sqf(self, f):
814
+ coeff, factors = dup_zz_factor_sqf(self.to_dense(f), self.domain)
815
+ return (coeff, [ self.from_dense(g) for g in factors ])
816
+
817
+ def dup_zz_factor(self, f):
818
+ coeff, factors = dup_zz_factor(self.to_dense(f), self.domain)
819
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
820
+ def dmp_zz_factor(self, f):
821
+ coeff, factors = dmp_zz_factor(self.to_dense(f), self.ngens-1, self.domain)
822
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
823
+
824
+ def dup_qq_i_factor(self, f):
825
+ coeff, factors = dup_qq_i_factor(self.to_dense(f), self.domain)
826
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
827
+ def dmp_qq_i_factor(self, f):
828
+ coeff, factors = dmp_qq_i_factor(self.to_dense(f), self.ngens-1, self.domain)
829
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
830
+
831
+ def dup_zz_i_factor(self, f):
832
+ coeff, factors = dup_zz_i_factor(self.to_dense(f), self.domain)
833
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
834
+ def dmp_zz_i_factor(self, f):
835
+ coeff, factors = dmp_zz_i_factor(self.to_dense(f), self.ngens-1, self.domain)
836
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
837
+
838
+ def dup_ext_factor(self, f):
839
+ coeff, factors = dup_ext_factor(self.to_dense(f), self.domain)
840
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
841
+ def dmp_ext_factor(self, f):
842
+ coeff, factors = dmp_ext_factor(self.to_dense(f), self.ngens-1, self.domain)
843
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
844
+
845
+ def dup_gf_factor(self, f):
846
+ coeff, factors = dup_gf_factor(self.to_dense(f), self.domain)
847
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
848
+ def dmp_gf_factor(self, f):
849
+ coeff, factors = dmp_gf_factor(self.to_dense(f), self.ngens-1, self.domain)
850
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
851
+
852
+ def dup_factor_list(self, f):
853
+ coeff, factors = dup_factor_list(self.to_dense(f), self.domain)
854
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
855
+ def dup_factor_list_include(self, f):
856
+ factors = dup_factor_list_include(self.to_dense(f), self.domain)
857
+ return [ (self.from_dense(g), k) for g, k in factors ]
858
+
859
+ def dmp_factor_list(self, f):
860
+ coeff, factors = dmp_factor_list(self.to_dense(f), self.ngens-1, self.domain)
861
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
862
+ def dmp_factor_list_include(self, f):
863
+ factors = dmp_factor_list_include(self.to_dense(f), self.ngens-1, self.domain)
864
+ return [ (self.from_dense(g), k) for g, k in factors ]
865
+
866
+ def dup_irreducible_p(self, f):
867
+ return dup_irreducible_p(self.to_dense(f), self.domain)
868
+ def dmp_irreducible_p(self, f):
869
+ return dmp_irreducible_p(self.to_dense(f), self.ngens-1, self.domain)
870
+
871
+ def dup_sturm(self, f):
872
+ seq = dup_sturm(self.to_dense(f), self.domain)
873
+ return list(map(self.from_dense, seq))
874
+
875
+ def dup_sqf_p(self, f):
876
+ return dup_sqf_p(self.to_dense(f), self.domain)
877
+ def dmp_sqf_p(self, f):
878
+ return dmp_sqf_p(self.to_dense(f), self.ngens-1, self.domain)
879
+
880
+ def dup_sqf_norm(self, f):
881
+ s, F, R = dup_sqf_norm(self.to_dense(f), self.domain)
882
+ return (s, self.from_dense(F), self.to_ground().from_dense(R))
883
+ def dmp_sqf_norm(self, f):
884
+ s, F, R = dmp_sqf_norm(self.to_dense(f), self.ngens-1, self.domain)
885
+ return (s, self.from_dense(F), self.to_ground().from_dense(R))
886
+
887
+ def dup_gf_sqf_part(self, f):
888
+ return self.from_dense(dup_gf_sqf_part(self.to_dense(f), self.domain))
889
+ def dmp_gf_sqf_part(self, f):
890
+ return self.from_dense(dmp_gf_sqf_part(self.to_dense(f), self.domain))
891
+ def dup_sqf_part(self, f):
892
+ return self.from_dense(dup_sqf_part(self.to_dense(f), self.domain))
893
+ def dmp_sqf_part(self, f):
894
+ return self.from_dense(dmp_sqf_part(self.to_dense(f), self.ngens-1, self.domain))
895
+
896
+ def dup_gf_sqf_list(self, f, all=False):
897
+ coeff, factors = dup_gf_sqf_list(self.to_dense(f), self.domain, all=all)
898
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
899
+ def dmp_gf_sqf_list(self, f, all=False):
900
+ coeff, factors = dmp_gf_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all)
901
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
902
+
903
+ def dup_sqf_list(self, f, all=False):
904
+ coeff, factors = dup_sqf_list(self.to_dense(f), self.domain, all=all)
905
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
906
+ def dup_sqf_list_include(self, f, all=False):
907
+ factors = dup_sqf_list_include(self.to_dense(f), self.domain, all=all)
908
+ return [ (self.from_dense(g), k) for g, k in factors ]
909
+ def dmp_sqf_list(self, f, all=False):
910
+ coeff, factors = dmp_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all)
911
+ return (coeff, [ (self.from_dense(g), k) for g, k in factors ])
912
+ def dmp_sqf_list_include(self, f, all=False):
913
+ factors = dmp_sqf_list_include(self.to_dense(f), self.ngens-1, self.domain, all=all)
914
+ return [ (self.from_dense(g), k) for g, k in factors ]
915
+
916
+ def dup_gff_list(self, f):
917
+ factors = dup_gff_list(self.to_dense(f), self.domain)
918
+ return [ (self.from_dense(g), k) for g, k in factors ]
919
+ def dmp_gff_list(self, f):
920
+ factors = dmp_gff_list(self.to_dense(f), self.ngens-1, self.domain)
921
+ return [ (self.from_dense(g), k) for g, k in factors ]
922
+
923
+ def dup_root_upper_bound(self, f):
924
+ return dup_root_upper_bound(self.to_dense(f), self.domain)
925
+ def dup_root_lower_bound(self, f):
926
+ return dup_root_lower_bound(self.to_dense(f), self.domain)
927
+
928
+ def dup_step_refine_real_root(self, f, M, fast=False):
929
+ return dup_step_refine_real_root(self.to_dense(f), M, self.domain, fast=fast)
930
+ def dup_inner_refine_real_root(self, f, M, eps=None, steps=None, disjoint=None, fast=False, mobius=False):
931
+ return dup_inner_refine_real_root(self.to_dense(f), M, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast, mobius=mobius)
932
+ def dup_outer_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False):
933
+ return dup_outer_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast)
934
+ def dup_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False):
935
+ return dup_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast)
936
+ def dup_inner_isolate_real_roots(self, f, eps=None, fast=False):
937
+ return dup_inner_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, fast=fast)
938
+ def dup_inner_isolate_positive_roots(self, f, eps=None, inf=None, sup=None, fast=False, mobius=False):
939
+ return dup_inner_isolate_positive_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, mobius=mobius)
940
+ def dup_inner_isolate_negative_roots(self, f, inf=None, sup=None, eps=None, fast=False, mobius=False):
941
+ return dup_inner_isolate_negative_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, eps=eps, fast=fast, mobius=mobius)
942
+ def dup_isolate_real_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False):
943
+ return dup_isolate_real_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox)
944
+ def dup_isolate_real_roots(self, f, eps=None, inf=None, sup=None, basis=False, fast=False):
945
+ return dup_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, basis=basis, fast=fast)
946
+ def dup_isolate_real_roots_list(self, polys, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False):
947
+ return dup_isolate_real_roots_list(list(map(self.to_dense, polys)), self.domain, eps=eps, inf=inf, sup=sup, strict=strict, basis=basis, fast=fast)
948
+ def dup_count_real_roots(self, f, inf=None, sup=None):
949
+ return dup_count_real_roots(self.to_dense(f), self.domain, inf=inf, sup=sup)
950
+ def dup_count_complex_roots(self, f, inf=None, sup=None, exclude=None):
951
+ return dup_count_complex_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, exclude=exclude)
952
+ def dup_isolate_complex_roots_sqf(self, f, eps=None, inf=None, sup=None, blackbox=False):
953
+ return dup_isolate_complex_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, blackbox=blackbox)
954
+ def dup_isolate_all_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False):
955
+ return dup_isolate_all_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox)
956
+ def dup_isolate_all_roots(self, f, eps=None, inf=None, sup=None, fast=False):
957
+ return dup_isolate_all_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast)
958
+
959
+ def fateman_poly_F_1(self):
960
+ from sympy.polys.specialpolys import dmp_fateman_poly_F_1
961
+ return tuple(map(self.from_dense, dmp_fateman_poly_F_1(self.ngens-1, self.domain)))
962
+ def fateman_poly_F_2(self):
963
+ from sympy.polys.specialpolys import dmp_fateman_poly_F_2
964
+ return tuple(map(self.from_dense, dmp_fateman_poly_F_2(self.ngens-1, self.domain)))
965
+ def fateman_poly_F_3(self):
966
+ from sympy.polys.specialpolys import dmp_fateman_poly_F_3
967
+ return tuple(map(self.from_dense, dmp_fateman_poly_F_3(self.ngens-1, self.domain)))
968
+
969
+ def to_gf_dense(self, element):
970
+ return gf_strip([ self.domain.dom.convert(c, self.domain) for c in self.wrap(element).to_dense() ])
971
+
972
+ def from_gf_dense(self, element):
973
+ return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain.dom))
974
+
975
+ def gf_degree(self, f):
976
+ return gf_degree(self.to_gf_dense(f))
977
+
978
+ def gf_LC(self, f):
979
+ return gf_LC(self.to_gf_dense(f), self.domain.dom)
980
+ def gf_TC(self, f):
981
+ return gf_TC(self.to_gf_dense(f), self.domain.dom)
982
+
983
+ def gf_strip(self, f):
984
+ return self.from_gf_dense(gf_strip(self.to_gf_dense(f)))
985
+ def gf_trunc(self, f):
986
+ return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod))
987
+ def gf_normal(self, f):
988
+ return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod, self.domain.dom))
989
+
990
+ def gf_from_dict(self, f):
991
+ return self.from_gf_dense(gf_from_dict(f, self.domain.mod, self.domain.dom))
992
+ def gf_to_dict(self, f, symmetric=True):
993
+ return gf_to_dict(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric)
994
+
995
+ def gf_from_int_poly(self, f):
996
+ return self.from_gf_dense(gf_from_int_poly(f, self.domain.mod))
997
+ def gf_to_int_poly(self, f, symmetric=True):
998
+ return gf_to_int_poly(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric)
999
+
1000
+ def gf_neg(self, f):
1001
+ return self.from_gf_dense(gf_neg(self.to_gf_dense(f), self.domain.mod, self.domain.dom))
1002
+
1003
+ def gf_add_ground(self, f, a):
1004
+ return self.from_gf_dense(gf_add_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom))
1005
+ def gf_sub_ground(self, f, a):
1006
+ return self.from_gf_dense(gf_sub_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom))
1007
+ def gf_mul_ground(self, f, a):
1008
+ return self.from_gf_dense(gf_mul_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom))
1009
+ def gf_quo_ground(self, f, a):
1010
+ return self.from_gf_dense(gf_quo_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom))
1011
+
1012
+ def gf_add(self, f, g):
1013
+ return self.from_gf_dense(gf_add(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1014
+ def gf_sub(self, f, g):
1015
+ return self.from_gf_dense(gf_sub(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1016
+ def gf_mul(self, f, g):
1017
+ return self.from_gf_dense(gf_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1018
+ def gf_sqr(self, f):
1019
+ return self.from_gf_dense(gf_sqr(self.to_gf_dense(f), self.domain.mod, self.domain.dom))
1020
+
1021
+ def gf_add_mul(self, f, g, h):
1022
+ return self.from_gf_dense(gf_add_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom))
1023
+ def gf_sub_mul(self, f, g, h):
1024
+ return self.from_gf_dense(gf_sub_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom))
1025
+
1026
+ def gf_expand(self, F):
1027
+ return self.from_gf_dense(gf_expand(list(map(self.to_gf_dense, F)), self.domain.mod, self.domain.dom))
1028
+
1029
+ def gf_div(self, f, g):
1030
+ q, r = gf_div(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)
1031
+ return self.from_gf_dense(q), self.from_gf_dense(r)
1032
+ def gf_rem(self, f, g):
1033
+ return self.from_gf_dense(gf_rem(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1034
+ def gf_quo(self, f, g):
1035
+ return self.from_gf_dense(gf_quo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1036
+ def gf_exquo(self, f, g):
1037
+ return self.from_gf_dense(gf_exquo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1038
+
1039
+ def gf_lshift(self, f, n):
1040
+ return self.from_gf_dense(gf_lshift(self.to_gf_dense(f), n, self.domain.dom))
1041
+ def gf_rshift(self, f, n):
1042
+ return self.from_gf_dense(gf_rshift(self.to_gf_dense(f), n, self.domain.dom))
1043
+
1044
+ def gf_pow(self, f, n):
1045
+ return self.from_gf_dense(gf_pow(self.to_gf_dense(f), n, self.domain.mod, self.domain.dom))
1046
+ def gf_pow_mod(self, f, n, g):
1047
+ return self.from_gf_dense(gf_pow_mod(self.to_gf_dense(f), n, self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1048
+
1049
+ def gf_cofactors(self, f, g):
1050
+ h, cff, cfg = gf_cofactors(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)
1051
+ return self.from_gf_dense(h), self.from_gf_dense(cff), self.from_gf_dense(cfg)
1052
+ def gf_gcd(self, f, g):
1053
+ return self.from_gf_dense(gf_gcd(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1054
+ def gf_lcm(self, f, g):
1055
+ return self.from_gf_dense(gf_lcm(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1056
+ def gf_gcdex(self, f, g):
1057
+ return self.from_gf_dense(gf_gcdex(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1058
+
1059
+ def gf_monic(self, f):
1060
+ return self.from_gf_dense(gf_monic(self.to_gf_dense(f), self.domain.mod, self.domain.dom))
1061
+ def gf_diff(self, f):
1062
+ return self.from_gf_dense(gf_diff(self.to_gf_dense(f), self.domain.mod, self.domain.dom))
1063
+
1064
+ def gf_eval(self, f, a):
1065
+ return gf_eval(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)
1066
+ def gf_multi_eval(self, f, A):
1067
+ return gf_multi_eval(self.to_gf_dense(f), A, self.domain.mod, self.domain.dom)
1068
+
1069
+ def gf_compose(self, f, g):
1070
+ return self.from_gf_dense(gf_compose(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom))
1071
+ def gf_compose_mod(self, g, h, f):
1072
+ return self.from_gf_dense(gf_compose_mod(self.to_gf_dense(g), self.to_gf_dense(h), self.to_gf_dense(f), self.domain.mod, self.domain.dom))
1073
+
1074
+ def gf_trace_map(self, a, b, c, n, f):
1075
+ a = self.to_gf_dense(a)
1076
+ b = self.to_gf_dense(b)
1077
+ c = self.to_gf_dense(c)
1078
+ f = self.to_gf_dense(f)
1079
+ U, V = gf_trace_map(a, b, c, n, f, self.domain.mod, self.domain.dom)
1080
+ return self.from_gf_dense(U), self.from_gf_dense(V)
1081
+
1082
+ def gf_random(self, n):
1083
+ return self.from_gf_dense(gf_random(n, self.domain.mod, self.domain.dom))
1084
+ def gf_irreducible(self, n):
1085
+ return self.from_gf_dense(gf_irreducible(n, self.domain.mod, self.domain.dom))
1086
+
1087
+ def gf_irred_p_ben_or(self, f):
1088
+ return gf_irred_p_ben_or(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1089
+ def gf_irred_p_rabin(self, f):
1090
+ return gf_irred_p_rabin(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1091
+ def gf_irreducible_p(self, f):
1092
+ return gf_irreducible_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1093
+ def gf_sqf_p(self, f):
1094
+ return gf_sqf_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1095
+
1096
+ def gf_sqf_part(self, f):
1097
+ return self.from_gf_dense(gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom))
1098
+ def gf_sqf_list(self, f, all=False):
1099
+ coeff, factors = gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1100
+ return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ]
1101
+
1102
+ def gf_Qmatrix(self, f):
1103
+ return gf_Qmatrix(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1104
+ def gf_berlekamp(self, f):
1105
+ factors = gf_berlekamp(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1106
+ return [ self.from_gf_dense(g) for g in factors ]
1107
+
1108
+ def gf_ddf_zassenhaus(self, f):
1109
+ factors = gf_ddf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1110
+ return [ (self.from_gf_dense(g), k) for g, k in factors ]
1111
+ def gf_edf_zassenhaus(self, f, n):
1112
+ factors = gf_edf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1113
+ return [ self.from_gf_dense(g) for g in factors ]
1114
+
1115
+ def gf_ddf_shoup(self, f):
1116
+ factors = gf_ddf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1117
+ return [ (self.from_gf_dense(g), k) for g, k in factors ]
1118
+ def gf_edf_shoup(self, f, n):
1119
+ factors = gf_edf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1120
+ return [ self.from_gf_dense(g) for g in factors ]
1121
+
1122
+ def gf_zassenhaus(self, f):
1123
+ factors = gf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1124
+ return [ self.from_gf_dense(g) for g in factors ]
1125
+ def gf_shoup(self, f):
1126
+ factors = gf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1127
+ return [ self.from_gf_dense(g) for g in factors ]
1128
+
1129
+ def gf_factor_sqf(self, f, method=None):
1130
+ coeff, factors = gf_factor_sqf(self.to_gf_dense(f), self.domain.mod, self.domain.dom, method=method)
1131
+ return coeff, [ self.from_gf_dense(g) for g in factors ]
1132
+ def gf_factor(self, f):
1133
+ coeff, factors = gf_factor(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
1134
+ return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ]
llmeval-env/lib/python3.10/site-packages/sympy/polys/constructor.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for constructing domains for expressions. """
2
+ from math import prod
3
+
4
+ from sympy.core import sympify
5
+ from sympy.core.evalf import pure_complex
6
+ from sympy.core.sorting import ordered
7
+ from sympy.polys.domains import ZZ, QQ, ZZ_I, QQ_I, EX
8
+ from sympy.polys.domains.complexfield import ComplexField
9
+ from sympy.polys.domains.realfield import RealField
10
+ from sympy.polys.polyoptions import build_options
11
+ from sympy.polys.polyutils import parallel_dict_from_basic
12
+ from sympy.utilities import public
13
+
14
+
15
+ def _construct_simple(coeffs, opt):
16
+ """Handle simple domains, e.g.: ZZ, QQ, RR and algebraic domains. """
17
+ rationals = floats = complexes = algebraics = False
18
+ float_numbers = []
19
+
20
+ if opt.extension is True:
21
+ is_algebraic = lambda coeff: coeff.is_number and coeff.is_algebraic
22
+ else:
23
+ is_algebraic = lambda coeff: False
24
+
25
+ for coeff in coeffs:
26
+ if coeff.is_Rational:
27
+ if not coeff.is_Integer:
28
+ rationals = True
29
+ elif coeff.is_Float:
30
+ if algebraics:
31
+ # there are both reals and algebraics -> EX
32
+ return False
33
+ else:
34
+ floats = True
35
+ float_numbers.append(coeff)
36
+ else:
37
+ is_complex = pure_complex(coeff)
38
+ if is_complex:
39
+ complexes = True
40
+ x, y = is_complex
41
+ if x.is_Rational and y.is_Rational:
42
+ if not (x.is_Integer and y.is_Integer):
43
+ rationals = True
44
+ continue
45
+ else:
46
+ floats = True
47
+ if x.is_Float:
48
+ float_numbers.append(x)
49
+ if y.is_Float:
50
+ float_numbers.append(y)
51
+ elif is_algebraic(coeff):
52
+ if floats:
53
+ # there are both algebraics and reals -> EX
54
+ return False
55
+ algebraics = True
56
+ else:
57
+ # this is a composite domain, e.g. ZZ[X], EX
58
+ return None
59
+
60
+ # Use the maximum precision of all coefficients for the RR or CC
61
+ # precision
62
+ max_prec = max(c._prec for c in float_numbers) if float_numbers else 53
63
+
64
+ if algebraics:
65
+ domain, result = _construct_algebraic(coeffs, opt)
66
+ else:
67
+ if floats and complexes:
68
+ domain = ComplexField(prec=max_prec)
69
+ elif floats:
70
+ domain = RealField(prec=max_prec)
71
+ elif rationals or opt.field:
72
+ domain = QQ_I if complexes else QQ
73
+ else:
74
+ domain = ZZ_I if complexes else ZZ
75
+
76
+ result = [domain.from_sympy(coeff) for coeff in coeffs]
77
+
78
+ return domain, result
79
+
80
+
81
+ def _construct_algebraic(coeffs, opt):
82
+ """We know that coefficients are algebraic so construct the extension. """
83
+ from sympy.polys.numberfields import primitive_element
84
+
85
+ exts = set()
86
+
87
+ def build_trees(args):
88
+ trees = []
89
+ for a in args:
90
+ if a.is_Rational:
91
+ tree = ('Q', QQ.from_sympy(a))
92
+ elif a.is_Add:
93
+ tree = ('+', build_trees(a.args))
94
+ elif a.is_Mul:
95
+ tree = ('*', build_trees(a.args))
96
+ else:
97
+ tree = ('e', a)
98
+ exts.add(a)
99
+ trees.append(tree)
100
+ return trees
101
+
102
+ trees = build_trees(coeffs)
103
+ exts = list(ordered(exts))
104
+
105
+ g, span, H = primitive_element(exts, ex=True, polys=True)
106
+ root = sum([ s*ext for s, ext in zip(span, exts) ])
107
+
108
+ domain, g = QQ.algebraic_field((g, root)), g.rep.rep
109
+
110
+ exts_dom = [domain.dtype.from_list(h, g, QQ) for h in H]
111
+ exts_map = dict(zip(exts, exts_dom))
112
+
113
+ def convert_tree(tree):
114
+ op, args = tree
115
+ if op == 'Q':
116
+ return domain.dtype.from_list([args], g, QQ)
117
+ elif op == '+':
118
+ return sum((convert_tree(a) for a in args), domain.zero)
119
+ elif op == '*':
120
+ return prod(convert_tree(a) for a in args)
121
+ elif op == 'e':
122
+ return exts_map[args]
123
+ else:
124
+ raise RuntimeError
125
+
126
+ result = [convert_tree(tree) for tree in trees]
127
+
128
+ return domain, result
129
+
130
+
131
+ def _construct_composite(coeffs, opt):
132
+ """Handle composite domains, e.g.: ZZ[X], QQ[X], ZZ(X), QQ(X). """
133
+ numers, denoms = [], []
134
+
135
+ for coeff in coeffs:
136
+ numer, denom = coeff.as_numer_denom()
137
+
138
+ numers.append(numer)
139
+ denoms.append(denom)
140
+
141
+ polys, gens = parallel_dict_from_basic(numers + denoms) # XXX: sorting
142
+ if not gens:
143
+ return None
144
+
145
+ if opt.composite is None:
146
+ if any(gen.is_number and gen.is_algebraic for gen in gens):
147
+ return None # generators are number-like so lets better use EX
148
+
149
+ all_symbols = set()
150
+
151
+ for gen in gens:
152
+ symbols = gen.free_symbols
153
+
154
+ if all_symbols & symbols:
155
+ return None # there could be algebraic relations between generators
156
+ else:
157
+ all_symbols |= symbols
158
+
159
+ n = len(gens)
160
+ k = len(polys)//2
161
+
162
+ numers = polys[:k]
163
+ denoms = polys[k:]
164
+
165
+ if opt.field:
166
+ fractions = True
167
+ else:
168
+ fractions, zeros = False, (0,)*n
169
+
170
+ for denom in denoms:
171
+ if len(denom) > 1 or zeros not in denom:
172
+ fractions = True
173
+ break
174
+
175
+ coeffs = set()
176
+
177
+ if not fractions:
178
+ for numer, denom in zip(numers, denoms):
179
+ denom = denom[zeros]
180
+
181
+ for monom, coeff in numer.items():
182
+ coeff /= denom
183
+ coeffs.add(coeff)
184
+ numer[monom] = coeff
185
+ else:
186
+ for numer, denom in zip(numers, denoms):
187
+ coeffs.update(list(numer.values()))
188
+ coeffs.update(list(denom.values()))
189
+
190
+ rationals = floats = complexes = False
191
+ float_numbers = []
192
+
193
+ for coeff in coeffs:
194
+ if coeff.is_Rational:
195
+ if not coeff.is_Integer:
196
+ rationals = True
197
+ elif coeff.is_Float:
198
+ floats = True
199
+ float_numbers.append(coeff)
200
+ else:
201
+ is_complex = pure_complex(coeff)
202
+ if is_complex is not None:
203
+ complexes = True
204
+ x, y = is_complex
205
+ if x.is_Rational and y.is_Rational:
206
+ if not (x.is_Integer and y.is_Integer):
207
+ rationals = True
208
+ else:
209
+ floats = True
210
+ if x.is_Float:
211
+ float_numbers.append(x)
212
+ if y.is_Float:
213
+ float_numbers.append(y)
214
+
215
+ max_prec = max(c._prec for c in float_numbers) if float_numbers else 53
216
+
217
+ if floats and complexes:
218
+ ground = ComplexField(prec=max_prec)
219
+ elif floats:
220
+ ground = RealField(prec=max_prec)
221
+ elif complexes:
222
+ if rationals:
223
+ ground = QQ_I
224
+ else:
225
+ ground = ZZ_I
226
+ elif rationals:
227
+ ground = QQ
228
+ else:
229
+ ground = ZZ
230
+
231
+ result = []
232
+
233
+ if not fractions:
234
+ domain = ground.poly_ring(*gens)
235
+
236
+ for numer in numers:
237
+ for monom, coeff in numer.items():
238
+ numer[monom] = ground.from_sympy(coeff)
239
+
240
+ result.append(domain(numer))
241
+ else:
242
+ domain = ground.frac_field(*gens)
243
+
244
+ for numer, denom in zip(numers, denoms):
245
+ for monom, coeff in numer.items():
246
+ numer[monom] = ground.from_sympy(coeff)
247
+
248
+ for monom, coeff in denom.items():
249
+ denom[monom] = ground.from_sympy(coeff)
250
+
251
+ result.append(domain((numer, denom)))
252
+
253
+ return domain, result
254
+
255
+
256
+ def _construct_expression(coeffs, opt):
257
+ """The last resort case, i.e. use the expression domain. """
258
+ domain, result = EX, []
259
+
260
+ for coeff in coeffs:
261
+ result.append(domain.from_sympy(coeff))
262
+
263
+ return domain, result
264
+
265
+
266
+ @public
267
+ def construct_domain(obj, **args):
268
+ """Construct a minimal domain for a list of expressions.
269
+
270
+ Explanation
271
+ ===========
272
+
273
+ Given a list of normal SymPy expressions (of type :py:class:`~.Expr`)
274
+ ``construct_domain`` will find a minimal :py:class:`~.Domain` that can
275
+ represent those expressions. The expressions will be converted to elements
276
+ of the domain and both the domain and the domain elements are returned.
277
+
278
+ Parameters
279
+ ==========
280
+
281
+ obj: list or dict
282
+ The expressions to build a domain for.
283
+
284
+ **args: keyword arguments
285
+ Options that affect the choice of domain.
286
+
287
+ Returns
288
+ =======
289
+
290
+ (K, elements): Domain and list of domain elements
291
+ The domain K that can represent the expressions and the list or dict
292
+ of domain elements representing the same expressions as elements of K.
293
+
294
+ Examples
295
+ ========
296
+
297
+ Given a list of :py:class:`~.Integer` ``construct_domain`` will return the
298
+ domain :ref:`ZZ` and a list of integers as elements of :ref:`ZZ`.
299
+
300
+ >>> from sympy import construct_domain, S
301
+ >>> expressions = [S(2), S(3), S(4)]
302
+ >>> K, elements = construct_domain(expressions)
303
+ >>> K
304
+ ZZ
305
+ >>> elements
306
+ [2, 3, 4]
307
+ >>> type(elements[0]) # doctest: +SKIP
308
+ <class 'int'>
309
+ >>> type(expressions[0])
310
+ <class 'sympy.core.numbers.Integer'>
311
+
312
+ If there are any :py:class:`~.Rational` then :ref:`QQ` is returned
313
+ instead.
314
+
315
+ >>> construct_domain([S(1)/2, S(3)/4])
316
+ (QQ, [1/2, 3/4])
317
+
318
+ If there are symbols then a polynomial ring :ref:`K[x]` is returned.
319
+
320
+ >>> from sympy import symbols
321
+ >>> x, y = symbols('x, y')
322
+ >>> construct_domain([2*x + 1, S(3)/4])
323
+ (QQ[x], [2*x + 1, 3/4])
324
+ >>> construct_domain([2*x + 1, y])
325
+ (ZZ[x,y], [2*x + 1, y])
326
+
327
+ If any symbols appear with negative powers then a rational function field
328
+ :ref:`K(x)` will be returned.
329
+
330
+ >>> construct_domain([y/x, x/(1 - y)])
331
+ (ZZ(x,y), [y/x, -x/(y - 1)])
332
+
333
+ Irrational algebraic numbers will result in the :ref:`EX` domain by
334
+ default. The keyword argument ``extension=True`` leads to the construction
335
+ of an algebraic number field :ref:`QQ(a)`.
336
+
337
+ >>> from sympy import sqrt
338
+ >>> construct_domain([sqrt(2)])
339
+ (EX, [EX(sqrt(2))])
340
+ >>> construct_domain([sqrt(2)], extension=True) # doctest: +SKIP
341
+ (QQ<sqrt(2)>, [ANP([1, 0], [1, 0, -2], QQ)])
342
+
343
+ See also
344
+ ========
345
+
346
+ Domain
347
+ Expr
348
+ """
349
+ opt = build_options(args)
350
+
351
+ if hasattr(obj, '__iter__'):
352
+ if isinstance(obj, dict):
353
+ if not obj:
354
+ monoms, coeffs = [], []
355
+ else:
356
+ monoms, coeffs = list(zip(*list(obj.items())))
357
+ else:
358
+ coeffs = obj
359
+ else:
360
+ coeffs = [obj]
361
+
362
+ coeffs = list(map(sympify, coeffs))
363
+ result = _construct_simple(coeffs, opt)
364
+
365
+ if result is not None:
366
+ if result is not False:
367
+ domain, coeffs = result
368
+ else:
369
+ domain, coeffs = _construct_expression(coeffs, opt)
370
+ else:
371
+ if opt.composite is False:
372
+ result = None
373
+ else:
374
+ result = _construct_composite(coeffs, opt)
375
+
376
+ if result is not None:
377
+ domain, coeffs = result
378
+ else:
379
+ domain, coeffs = _construct_expression(coeffs, opt)
380
+
381
+ if hasattr(obj, '__iter__'):
382
+ if isinstance(obj, dict):
383
+ return domain, dict(list(zip(monoms, coeffs)))
384
+ else:
385
+ return domain, coeffs
386
+ else:
387
+ return domain, coeffs[0]
llmeval-env/lib/python3.10/site-packages/sympy/polys/densearith.py ADDED
@@ -0,0 +1,1875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Arithmetics for dense recursive polynomials in ``K[x]`` or ``K[X]``. """
2
+
3
+
4
+ from sympy.polys.densebasic import (
5
+ dup_slice,
6
+ dup_LC, dmp_LC,
7
+ dup_degree, dmp_degree,
8
+ dup_strip, dmp_strip,
9
+ dmp_zero_p, dmp_zero,
10
+ dmp_one_p, dmp_one,
11
+ dmp_ground, dmp_zeros)
12
+ from sympy.polys.polyerrors import (ExactQuotientFailed, PolynomialDivisionFailed)
13
+
14
+ def dup_add_term(f, c, i, K):
15
+ """
16
+ Add ``c*x**i`` to ``f`` in ``K[x]``.
17
+
18
+ Examples
19
+ ========
20
+
21
+ >>> from sympy.polys import ring, ZZ
22
+ >>> R, x = ring("x", ZZ)
23
+
24
+ >>> R.dup_add_term(x**2 - 1, ZZ(2), 4)
25
+ 2*x**4 + x**2 - 1
26
+
27
+ """
28
+ if not c:
29
+ return f
30
+
31
+ n = len(f)
32
+ m = n - i - 1
33
+
34
+ if i == n - 1:
35
+ return dup_strip([f[0] + c] + f[1:])
36
+ else:
37
+ if i >= n:
38
+ return [c] + [K.zero]*(i - n) + f
39
+ else:
40
+ return f[:m] + [f[m] + c] + f[m + 1:]
41
+
42
+
43
+ def dmp_add_term(f, c, i, u, K):
44
+ """
45
+ Add ``c(x_2..x_u)*x_0**i`` to ``f`` in ``K[X]``.
46
+
47
+ Examples
48
+ ========
49
+
50
+ >>> from sympy.polys import ring, ZZ
51
+ >>> R, x,y = ring("x,y", ZZ)
52
+
53
+ >>> R.dmp_add_term(x*y + 1, 2, 2)
54
+ 2*x**2 + x*y + 1
55
+
56
+ """
57
+ if not u:
58
+ return dup_add_term(f, c, i, K)
59
+
60
+ v = u - 1
61
+
62
+ if dmp_zero_p(c, v):
63
+ return f
64
+
65
+ n = len(f)
66
+ m = n - i - 1
67
+
68
+ if i == n - 1:
69
+ return dmp_strip([dmp_add(f[0], c, v, K)] + f[1:], u)
70
+ else:
71
+ if i >= n:
72
+ return [c] + dmp_zeros(i - n, v, K) + f
73
+ else:
74
+ return f[:m] + [dmp_add(f[m], c, v, K)] + f[m + 1:]
75
+
76
+
77
+ def dup_sub_term(f, c, i, K):
78
+ """
79
+ Subtract ``c*x**i`` from ``f`` in ``K[x]``.
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy.polys import ring, ZZ
85
+ >>> R, x = ring("x", ZZ)
86
+
87
+ >>> R.dup_sub_term(2*x**4 + x**2 - 1, ZZ(2), 4)
88
+ x**2 - 1
89
+
90
+ """
91
+ if not c:
92
+ return f
93
+
94
+ n = len(f)
95
+ m = n - i - 1
96
+
97
+ if i == n - 1:
98
+ return dup_strip([f[0] - c] + f[1:])
99
+ else:
100
+ if i >= n:
101
+ return [-c] + [K.zero]*(i - n) + f
102
+ else:
103
+ return f[:m] + [f[m] - c] + f[m + 1:]
104
+
105
+
106
+ def dmp_sub_term(f, c, i, u, K):
107
+ """
108
+ Subtract ``c(x_2..x_u)*x_0**i`` from ``f`` in ``K[X]``.
109
+
110
+ Examples
111
+ ========
112
+
113
+ >>> from sympy.polys import ring, ZZ
114
+ >>> R, x,y = ring("x,y", ZZ)
115
+
116
+ >>> R.dmp_sub_term(2*x**2 + x*y + 1, 2, 2)
117
+ x*y + 1
118
+
119
+ """
120
+ if not u:
121
+ return dup_add_term(f, -c, i, K)
122
+
123
+ v = u - 1
124
+
125
+ if dmp_zero_p(c, v):
126
+ return f
127
+
128
+ n = len(f)
129
+ m = n - i - 1
130
+
131
+ if i == n - 1:
132
+ return dmp_strip([dmp_sub(f[0], c, v, K)] + f[1:], u)
133
+ else:
134
+ if i >= n:
135
+ return [dmp_neg(c, v, K)] + dmp_zeros(i - n, v, K) + f
136
+ else:
137
+ return f[:m] + [dmp_sub(f[m], c, v, K)] + f[m + 1:]
138
+
139
+
140
+ def dup_mul_term(f, c, i, K):
141
+ """
142
+ Multiply ``f`` by ``c*x**i`` in ``K[x]``.
143
+
144
+ Examples
145
+ ========
146
+
147
+ >>> from sympy.polys import ring, ZZ
148
+ >>> R, x = ring("x", ZZ)
149
+
150
+ >>> R.dup_mul_term(x**2 - 1, ZZ(3), 2)
151
+ 3*x**4 - 3*x**2
152
+
153
+ """
154
+ if not c or not f:
155
+ return []
156
+ else:
157
+ return [ cf * c for cf in f ] + [K.zero]*i
158
+
159
+
160
+ def dmp_mul_term(f, c, i, u, K):
161
+ """
162
+ Multiply ``f`` by ``c(x_2..x_u)*x_0**i`` in ``K[X]``.
163
+
164
+ Examples
165
+ ========
166
+
167
+ >>> from sympy.polys import ring, ZZ
168
+ >>> R, x,y = ring("x,y", ZZ)
169
+
170
+ >>> R.dmp_mul_term(x**2*y + x, 3*y, 2)
171
+ 3*x**4*y**2 + 3*x**3*y
172
+
173
+ """
174
+ if not u:
175
+ return dup_mul_term(f, c, i, K)
176
+
177
+ v = u - 1
178
+
179
+ if dmp_zero_p(f, u):
180
+ return f
181
+ if dmp_zero_p(c, v):
182
+ return dmp_zero(u)
183
+ else:
184
+ return [ dmp_mul(cf, c, v, K) for cf in f ] + dmp_zeros(i, v, K)
185
+
186
+
187
+ def dup_add_ground(f, c, K):
188
+ """
189
+ Add an element of the ground domain to ``f``.
190
+
191
+ Examples
192
+ ========
193
+
194
+ >>> from sympy.polys import ring, ZZ
195
+ >>> R, x = ring("x", ZZ)
196
+
197
+ >>> R.dup_add_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4))
198
+ x**3 + 2*x**2 + 3*x + 8
199
+
200
+ """
201
+ return dup_add_term(f, c, 0, K)
202
+
203
+
204
+ def dmp_add_ground(f, c, u, K):
205
+ """
206
+ Add an element of the ground domain to ``f``.
207
+
208
+ Examples
209
+ ========
210
+
211
+ >>> from sympy.polys import ring, ZZ
212
+ >>> R, x,y = ring("x,y", ZZ)
213
+
214
+ >>> R.dmp_add_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4))
215
+ x**3 + 2*x**2 + 3*x + 8
216
+
217
+ """
218
+ return dmp_add_term(f, dmp_ground(c, u - 1), 0, u, K)
219
+
220
+
221
+ def dup_sub_ground(f, c, K):
222
+ """
223
+ Subtract an element of the ground domain from ``f``.
224
+
225
+ Examples
226
+ ========
227
+
228
+ >>> from sympy.polys import ring, ZZ
229
+ >>> R, x = ring("x", ZZ)
230
+
231
+ >>> R.dup_sub_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4))
232
+ x**3 + 2*x**2 + 3*x
233
+
234
+ """
235
+ return dup_sub_term(f, c, 0, K)
236
+
237
+
238
+ def dmp_sub_ground(f, c, u, K):
239
+ """
240
+ Subtract an element of the ground domain from ``f``.
241
+
242
+ Examples
243
+ ========
244
+
245
+ >>> from sympy.polys import ring, ZZ
246
+ >>> R, x,y = ring("x,y", ZZ)
247
+
248
+ >>> R.dmp_sub_ground(x**3 + 2*x**2 + 3*x + 4, ZZ(4))
249
+ x**3 + 2*x**2 + 3*x
250
+
251
+ """
252
+ return dmp_sub_term(f, dmp_ground(c, u - 1), 0, u, K)
253
+
254
+
255
+ def dup_mul_ground(f, c, K):
256
+ """
257
+ Multiply ``f`` by a constant value in ``K[x]``.
258
+
259
+ Examples
260
+ ========
261
+
262
+ >>> from sympy.polys import ring, ZZ
263
+ >>> R, x = ring("x", ZZ)
264
+
265
+ >>> R.dup_mul_ground(x**2 + 2*x - 1, ZZ(3))
266
+ 3*x**2 + 6*x - 3
267
+
268
+ """
269
+ if not c or not f:
270
+ return []
271
+ else:
272
+ return [ cf * c for cf in f ]
273
+
274
+
275
+ def dmp_mul_ground(f, c, u, K):
276
+ """
277
+ Multiply ``f`` by a constant value in ``K[X]``.
278
+
279
+ Examples
280
+ ========
281
+
282
+ >>> from sympy.polys import ring, ZZ
283
+ >>> R, x,y = ring("x,y", ZZ)
284
+
285
+ >>> R.dmp_mul_ground(2*x + 2*y, ZZ(3))
286
+ 6*x + 6*y
287
+
288
+ """
289
+ if not u:
290
+ return dup_mul_ground(f, c, K)
291
+
292
+ v = u - 1
293
+
294
+ return [ dmp_mul_ground(cf, c, v, K) for cf in f ]
295
+
296
+
297
+ def dup_quo_ground(f, c, K):
298
+ """
299
+ Quotient by a constant in ``K[x]``.
300
+
301
+ Examples
302
+ ========
303
+
304
+ >>> from sympy.polys import ring, ZZ, QQ
305
+
306
+ >>> R, x = ring("x", ZZ)
307
+ >>> R.dup_quo_ground(3*x**2 + 2, ZZ(2))
308
+ x**2 + 1
309
+
310
+ >>> R, x = ring("x", QQ)
311
+ >>> R.dup_quo_ground(3*x**2 + 2, QQ(2))
312
+ 3/2*x**2 + 1
313
+
314
+ """
315
+ if not c:
316
+ raise ZeroDivisionError('polynomial division')
317
+ if not f:
318
+ return f
319
+
320
+ if K.is_Field:
321
+ return [ K.quo(cf, c) for cf in f ]
322
+ else:
323
+ return [ cf // c for cf in f ]
324
+
325
+
326
+ def dmp_quo_ground(f, c, u, K):
327
+ """
328
+ Quotient by a constant in ``K[X]``.
329
+
330
+ Examples
331
+ ========
332
+
333
+ >>> from sympy.polys import ring, ZZ, QQ
334
+
335
+ >>> R, x,y = ring("x,y", ZZ)
336
+ >>> R.dmp_quo_ground(2*x**2*y + 3*x, ZZ(2))
337
+ x**2*y + x
338
+
339
+ >>> R, x,y = ring("x,y", QQ)
340
+ >>> R.dmp_quo_ground(2*x**2*y + 3*x, QQ(2))
341
+ x**2*y + 3/2*x
342
+
343
+ """
344
+ if not u:
345
+ return dup_quo_ground(f, c, K)
346
+
347
+ v = u - 1
348
+
349
+ return [ dmp_quo_ground(cf, c, v, K) for cf in f ]
350
+
351
+
352
+ def dup_exquo_ground(f, c, K):
353
+ """
354
+ Exact quotient by a constant in ``K[x]``.
355
+
356
+ Examples
357
+ ========
358
+
359
+ >>> from sympy.polys import ring, QQ
360
+ >>> R, x = ring("x", QQ)
361
+
362
+ >>> R.dup_exquo_ground(x**2 + 2, QQ(2))
363
+ 1/2*x**2 + 1
364
+
365
+ """
366
+ if not c:
367
+ raise ZeroDivisionError('polynomial division')
368
+ if not f:
369
+ return f
370
+
371
+ return [ K.exquo(cf, c) for cf in f ]
372
+
373
+
374
+ def dmp_exquo_ground(f, c, u, K):
375
+ """
376
+ Exact quotient by a constant in ``K[X]``.
377
+
378
+ Examples
379
+ ========
380
+
381
+ >>> from sympy.polys import ring, QQ
382
+ >>> R, x,y = ring("x,y", QQ)
383
+
384
+ >>> R.dmp_exquo_ground(x**2*y + 2*x, QQ(2))
385
+ 1/2*x**2*y + x
386
+
387
+ """
388
+ if not u:
389
+ return dup_exquo_ground(f, c, K)
390
+
391
+ v = u - 1
392
+
393
+ return [ dmp_exquo_ground(cf, c, v, K) for cf in f ]
394
+
395
+
396
+ def dup_lshift(f, n, K):
397
+ """
398
+ Efficiently multiply ``f`` by ``x**n`` in ``K[x]``.
399
+
400
+ Examples
401
+ ========
402
+
403
+ >>> from sympy.polys import ring, ZZ
404
+ >>> R, x = ring("x", ZZ)
405
+
406
+ >>> R.dup_lshift(x**2 + 1, 2)
407
+ x**4 + x**2
408
+
409
+ """
410
+ if not f:
411
+ return f
412
+ else:
413
+ return f + [K.zero]*n
414
+
415
+
416
+ def dup_rshift(f, n, K):
417
+ """
418
+ Efficiently divide ``f`` by ``x**n`` in ``K[x]``.
419
+
420
+ Examples
421
+ ========
422
+
423
+ >>> from sympy.polys import ring, ZZ
424
+ >>> R, x = ring("x", ZZ)
425
+
426
+ >>> R.dup_rshift(x**4 + x**2, 2)
427
+ x**2 + 1
428
+ >>> R.dup_rshift(x**4 + x**2 + 2, 2)
429
+ x**2 + 1
430
+
431
+ """
432
+ return f[:-n]
433
+
434
+
435
+ def dup_abs(f, K):
436
+ """
437
+ Make all coefficients positive in ``K[x]``.
438
+
439
+ Examples
440
+ ========
441
+
442
+ >>> from sympy.polys import ring, ZZ
443
+ >>> R, x = ring("x", ZZ)
444
+
445
+ >>> R.dup_abs(x**2 - 1)
446
+ x**2 + 1
447
+
448
+ """
449
+ return [ K.abs(coeff) for coeff in f ]
450
+
451
+
452
+ def dmp_abs(f, u, K):
453
+ """
454
+ Make all coefficients positive in ``K[X]``.
455
+
456
+ Examples
457
+ ========
458
+
459
+ >>> from sympy.polys import ring, ZZ
460
+ >>> R, x,y = ring("x,y", ZZ)
461
+
462
+ >>> R.dmp_abs(x**2*y - x)
463
+ x**2*y + x
464
+
465
+ """
466
+ if not u:
467
+ return dup_abs(f, K)
468
+
469
+ v = u - 1
470
+
471
+ return [ dmp_abs(cf, v, K) for cf in f ]
472
+
473
+
474
+ def dup_neg(f, K):
475
+ """
476
+ Negate a polynomial in ``K[x]``.
477
+
478
+ Examples
479
+ ========
480
+
481
+ >>> from sympy.polys import ring, ZZ
482
+ >>> R, x = ring("x", ZZ)
483
+
484
+ >>> R.dup_neg(x**2 - 1)
485
+ -x**2 + 1
486
+
487
+ """
488
+ return [ -coeff for coeff in f ]
489
+
490
+
491
+ def dmp_neg(f, u, K):
492
+ """
493
+ Negate a polynomial in ``K[X]``.
494
+
495
+ Examples
496
+ ========
497
+
498
+ >>> from sympy.polys import ring, ZZ
499
+ >>> R, x,y = ring("x,y", ZZ)
500
+
501
+ >>> R.dmp_neg(x**2*y - x)
502
+ -x**2*y + x
503
+
504
+ """
505
+ if not u:
506
+ return dup_neg(f, K)
507
+
508
+ v = u - 1
509
+
510
+ return [ dmp_neg(cf, v, K) for cf in f ]
511
+
512
+
513
+ def dup_add(f, g, K):
514
+ """
515
+ Add dense polynomials in ``K[x]``.
516
+
517
+ Examples
518
+ ========
519
+
520
+ >>> from sympy.polys import ring, ZZ
521
+ >>> R, x = ring("x", ZZ)
522
+
523
+ >>> R.dup_add(x**2 - 1, x - 2)
524
+ x**2 + x - 3
525
+
526
+ """
527
+ if not f:
528
+ return g
529
+ if not g:
530
+ return f
531
+
532
+ df = dup_degree(f)
533
+ dg = dup_degree(g)
534
+
535
+ if df == dg:
536
+ return dup_strip([ a + b for a, b in zip(f, g) ])
537
+ else:
538
+ k = abs(df - dg)
539
+
540
+ if df > dg:
541
+ h, f = f[:k], f[k:]
542
+ else:
543
+ h, g = g[:k], g[k:]
544
+
545
+ return h + [ a + b for a, b in zip(f, g) ]
546
+
547
+
548
+ def dmp_add(f, g, u, K):
549
+ """
550
+ Add dense polynomials in ``K[X]``.
551
+
552
+ Examples
553
+ ========
554
+
555
+ >>> from sympy.polys import ring, ZZ
556
+ >>> R, x,y = ring("x,y", ZZ)
557
+
558
+ >>> R.dmp_add(x**2 + y, x**2*y + x)
559
+ x**2*y + x**2 + x + y
560
+
561
+ """
562
+ if not u:
563
+ return dup_add(f, g, K)
564
+
565
+ df = dmp_degree(f, u)
566
+
567
+ if df < 0:
568
+ return g
569
+
570
+ dg = dmp_degree(g, u)
571
+
572
+ if dg < 0:
573
+ return f
574
+
575
+ v = u - 1
576
+
577
+ if df == dg:
578
+ return dmp_strip([ dmp_add(a, b, v, K) for a, b in zip(f, g) ], u)
579
+ else:
580
+ k = abs(df - dg)
581
+
582
+ if df > dg:
583
+ h, f = f[:k], f[k:]
584
+ else:
585
+ h, g = g[:k], g[k:]
586
+
587
+ return h + [ dmp_add(a, b, v, K) for a, b in zip(f, g) ]
588
+
589
+
590
+ def dup_sub(f, g, K):
591
+ """
592
+ Subtract dense polynomials in ``K[x]``.
593
+
594
+ Examples
595
+ ========
596
+
597
+ >>> from sympy.polys import ring, ZZ
598
+ >>> R, x = ring("x", ZZ)
599
+
600
+ >>> R.dup_sub(x**2 - 1, x - 2)
601
+ x**2 - x + 1
602
+
603
+ """
604
+ if not f:
605
+ return dup_neg(g, K)
606
+ if not g:
607
+ return f
608
+
609
+ df = dup_degree(f)
610
+ dg = dup_degree(g)
611
+
612
+ if df == dg:
613
+ return dup_strip([ a - b for a, b in zip(f, g) ])
614
+ else:
615
+ k = abs(df - dg)
616
+
617
+ if df > dg:
618
+ h, f = f[:k], f[k:]
619
+ else:
620
+ h, g = dup_neg(g[:k], K), g[k:]
621
+
622
+ return h + [ a - b for a, b in zip(f, g) ]
623
+
624
+
625
+ def dmp_sub(f, g, u, K):
626
+ """
627
+ Subtract dense polynomials in ``K[X]``.
628
+
629
+ Examples
630
+ ========
631
+
632
+ >>> from sympy.polys import ring, ZZ
633
+ >>> R, x,y = ring("x,y", ZZ)
634
+
635
+ >>> R.dmp_sub(x**2 + y, x**2*y + x)
636
+ -x**2*y + x**2 - x + y
637
+
638
+ """
639
+ if not u:
640
+ return dup_sub(f, g, K)
641
+
642
+ df = dmp_degree(f, u)
643
+
644
+ if df < 0:
645
+ return dmp_neg(g, u, K)
646
+
647
+ dg = dmp_degree(g, u)
648
+
649
+ if dg < 0:
650
+ return f
651
+
652
+ v = u - 1
653
+
654
+ if df == dg:
655
+ return dmp_strip([ dmp_sub(a, b, v, K) for a, b in zip(f, g) ], u)
656
+ else:
657
+ k = abs(df - dg)
658
+
659
+ if df > dg:
660
+ h, f = f[:k], f[k:]
661
+ else:
662
+ h, g = dmp_neg(g[:k], u, K), g[k:]
663
+
664
+ return h + [ dmp_sub(a, b, v, K) for a, b in zip(f, g) ]
665
+
666
+
667
+ def dup_add_mul(f, g, h, K):
668
+ """
669
+ Returns ``f + g*h`` where ``f, g, h`` are in ``K[x]``.
670
+
671
+ Examples
672
+ ========
673
+
674
+ >>> from sympy.polys import ring, ZZ
675
+ >>> R, x = ring("x", ZZ)
676
+
677
+ >>> R.dup_add_mul(x**2 - 1, x - 2, x + 2)
678
+ 2*x**2 - 5
679
+
680
+ """
681
+ return dup_add(f, dup_mul(g, h, K), K)
682
+
683
+
684
+ def dmp_add_mul(f, g, h, u, K):
685
+ """
686
+ Returns ``f + g*h`` where ``f, g, h`` are in ``K[X]``.
687
+
688
+ Examples
689
+ ========
690
+
691
+ >>> from sympy.polys import ring, ZZ
692
+ >>> R, x,y = ring("x,y", ZZ)
693
+
694
+ >>> R.dmp_add_mul(x**2 + y, x, x + 2)
695
+ 2*x**2 + 2*x + y
696
+
697
+ """
698
+ return dmp_add(f, dmp_mul(g, h, u, K), u, K)
699
+
700
+
701
+ def dup_sub_mul(f, g, h, K):
702
+ """
703
+ Returns ``f - g*h`` where ``f, g, h`` are in ``K[x]``.
704
+
705
+ Examples
706
+ ========
707
+
708
+ >>> from sympy.polys import ring, ZZ
709
+ >>> R, x = ring("x", ZZ)
710
+
711
+ >>> R.dup_sub_mul(x**2 - 1, x - 2, x + 2)
712
+ 3
713
+
714
+ """
715
+ return dup_sub(f, dup_mul(g, h, K), K)
716
+
717
+
718
+ def dmp_sub_mul(f, g, h, u, K):
719
+ """
720
+ Returns ``f - g*h`` where ``f, g, h`` are in ``K[X]``.
721
+
722
+ Examples
723
+ ========
724
+
725
+ >>> from sympy.polys import ring, ZZ
726
+ >>> R, x,y = ring("x,y", ZZ)
727
+
728
+ >>> R.dmp_sub_mul(x**2 + y, x, x + 2)
729
+ -2*x + y
730
+
731
+ """
732
+ return dmp_sub(f, dmp_mul(g, h, u, K), u, K)
733
+
734
+
735
+ def dup_mul(f, g, K):
736
+ """
737
+ Multiply dense polynomials in ``K[x]``.
738
+
739
+ Examples
740
+ ========
741
+
742
+ >>> from sympy.polys import ring, ZZ
743
+ >>> R, x = ring("x", ZZ)
744
+
745
+ >>> R.dup_mul(x - 2, x + 2)
746
+ x**2 - 4
747
+
748
+ """
749
+ if f == g:
750
+ return dup_sqr(f, K)
751
+
752
+ if not (f and g):
753
+ return []
754
+
755
+ df = dup_degree(f)
756
+ dg = dup_degree(g)
757
+
758
+ n = max(df, dg) + 1
759
+
760
+ if n < 100:
761
+ h = []
762
+
763
+ for i in range(0, df + dg + 1):
764
+ coeff = K.zero
765
+
766
+ for j in range(max(0, i - dg), min(df, i) + 1):
767
+ coeff += f[j]*g[i - j]
768
+
769
+ h.append(coeff)
770
+
771
+ return dup_strip(h)
772
+ else:
773
+ # Use Karatsuba's algorithm (divide and conquer), see e.g.:
774
+ # Joris van der Hoeven, Relax But Don't Be Too Lazy,
775
+ # J. Symbolic Computation, 11 (2002), section 3.1.1.
776
+ n2 = n//2
777
+
778
+ fl, gl = dup_slice(f, 0, n2, K), dup_slice(g, 0, n2, K)
779
+
780
+ fh = dup_rshift(dup_slice(f, n2, n, K), n2, K)
781
+ gh = dup_rshift(dup_slice(g, n2, n, K), n2, K)
782
+
783
+ lo, hi = dup_mul(fl, gl, K), dup_mul(fh, gh, K)
784
+
785
+ mid = dup_mul(dup_add(fl, fh, K), dup_add(gl, gh, K), K)
786
+ mid = dup_sub(mid, dup_add(lo, hi, K), K)
787
+
788
+ return dup_add(dup_add(lo, dup_lshift(mid, n2, K), K),
789
+ dup_lshift(hi, 2*n2, K), K)
790
+
791
+
792
+ def dmp_mul(f, g, u, K):
793
+ """
794
+ Multiply dense polynomials in ``K[X]``.
795
+
796
+ Examples
797
+ ========
798
+
799
+ >>> from sympy.polys import ring, ZZ
800
+ >>> R, x,y = ring("x,y", ZZ)
801
+
802
+ >>> R.dmp_mul(x*y + 1, x)
803
+ x**2*y + x
804
+
805
+ """
806
+ if not u:
807
+ return dup_mul(f, g, K)
808
+
809
+ if f == g:
810
+ return dmp_sqr(f, u, K)
811
+
812
+ df = dmp_degree(f, u)
813
+
814
+ if df < 0:
815
+ return f
816
+
817
+ dg = dmp_degree(g, u)
818
+
819
+ if dg < 0:
820
+ return g
821
+
822
+ h, v = [], u - 1
823
+
824
+ for i in range(0, df + dg + 1):
825
+ coeff = dmp_zero(v)
826
+
827
+ for j in range(max(0, i - dg), min(df, i) + 1):
828
+ coeff = dmp_add(coeff, dmp_mul(f[j], g[i - j], v, K), v, K)
829
+
830
+ h.append(coeff)
831
+
832
+ return dmp_strip(h, u)
833
+
834
+
835
+ def dup_sqr(f, K):
836
+ """
837
+ Square dense polynomials in ``K[x]``.
838
+
839
+ Examples
840
+ ========
841
+
842
+ >>> from sympy.polys import ring, ZZ
843
+ >>> R, x = ring("x", ZZ)
844
+
845
+ >>> R.dup_sqr(x**2 + 1)
846
+ x**4 + 2*x**2 + 1
847
+
848
+ """
849
+ df, h = len(f) - 1, []
850
+
851
+ for i in range(0, 2*df + 1):
852
+ c = K.zero
853
+
854
+ jmin = max(0, i - df)
855
+ jmax = min(i, df)
856
+
857
+ n = jmax - jmin + 1
858
+
859
+ jmax = jmin + n // 2 - 1
860
+
861
+ for j in range(jmin, jmax + 1):
862
+ c += f[j]*f[i - j]
863
+
864
+ c += c
865
+
866
+ if n & 1:
867
+ elem = f[jmax + 1]
868
+ c += elem**2
869
+
870
+ h.append(c)
871
+
872
+ return dup_strip(h)
873
+
874
+
875
+ def dmp_sqr(f, u, K):
876
+ """
877
+ Square dense polynomials in ``K[X]``.
878
+
879
+ Examples
880
+ ========
881
+
882
+ >>> from sympy.polys import ring, ZZ
883
+ >>> R, x,y = ring("x,y", ZZ)
884
+
885
+ >>> R.dmp_sqr(x**2 + x*y + y**2)
886
+ x**4 + 2*x**3*y + 3*x**2*y**2 + 2*x*y**3 + y**4
887
+
888
+ """
889
+ if not u:
890
+ return dup_sqr(f, K)
891
+
892
+ df = dmp_degree(f, u)
893
+
894
+ if df < 0:
895
+ return f
896
+
897
+ h, v = [], u - 1
898
+
899
+ for i in range(0, 2*df + 1):
900
+ c = dmp_zero(v)
901
+
902
+ jmin = max(0, i - df)
903
+ jmax = min(i, df)
904
+
905
+ n = jmax - jmin + 1
906
+
907
+ jmax = jmin + n // 2 - 1
908
+
909
+ for j in range(jmin, jmax + 1):
910
+ c = dmp_add(c, dmp_mul(f[j], f[i - j], v, K), v, K)
911
+
912
+ c = dmp_mul_ground(c, K(2), v, K)
913
+
914
+ if n & 1:
915
+ elem = dmp_sqr(f[jmax + 1], v, K)
916
+ c = dmp_add(c, elem, v, K)
917
+
918
+ h.append(c)
919
+
920
+ return dmp_strip(h, u)
921
+
922
+
923
+ def dup_pow(f, n, K):
924
+ """
925
+ Raise ``f`` to the ``n``-th power in ``K[x]``.
926
+
927
+ Examples
928
+ ========
929
+
930
+ >>> from sympy.polys import ring, ZZ
931
+ >>> R, x = ring("x", ZZ)
932
+
933
+ >>> R.dup_pow(x - 2, 3)
934
+ x**3 - 6*x**2 + 12*x - 8
935
+
936
+ """
937
+ if not n:
938
+ return [K.one]
939
+ if n < 0:
940
+ raise ValueError("Cannot raise polynomial to a negative power")
941
+ if n == 1 or not f or f == [K.one]:
942
+ return f
943
+
944
+ g = [K.one]
945
+
946
+ while True:
947
+ n, m = n//2, n
948
+
949
+ if m % 2:
950
+ g = dup_mul(g, f, K)
951
+
952
+ if not n:
953
+ break
954
+
955
+ f = dup_sqr(f, K)
956
+
957
+ return g
958
+
959
+
960
+ def dmp_pow(f, n, u, K):
961
+ """
962
+ Raise ``f`` to the ``n``-th power in ``K[X]``.
963
+
964
+ Examples
965
+ ========
966
+
967
+ >>> from sympy.polys import ring, ZZ
968
+ >>> R, x,y = ring("x,y", ZZ)
969
+
970
+ >>> R.dmp_pow(x*y + 1, 3)
971
+ x**3*y**3 + 3*x**2*y**2 + 3*x*y + 1
972
+
973
+ """
974
+ if not u:
975
+ return dup_pow(f, n, K)
976
+
977
+ if not n:
978
+ return dmp_one(u, K)
979
+ if n < 0:
980
+ raise ValueError("Cannot raise polynomial to a negative power")
981
+ if n == 1 or dmp_zero_p(f, u) or dmp_one_p(f, u, K):
982
+ return f
983
+
984
+ g = dmp_one(u, K)
985
+
986
+ while True:
987
+ n, m = n//2, n
988
+
989
+ if m & 1:
990
+ g = dmp_mul(g, f, u, K)
991
+
992
+ if not n:
993
+ break
994
+
995
+ f = dmp_sqr(f, u, K)
996
+
997
+ return g
998
+
999
+
1000
+ def dup_pdiv(f, g, K):
1001
+ """
1002
+ Polynomial pseudo-division in ``K[x]``.
1003
+
1004
+ Examples
1005
+ ========
1006
+
1007
+ >>> from sympy.polys import ring, ZZ
1008
+ >>> R, x = ring("x", ZZ)
1009
+
1010
+ >>> R.dup_pdiv(x**2 + 1, 2*x - 4)
1011
+ (2*x + 4, 20)
1012
+
1013
+ """
1014
+ df = dup_degree(f)
1015
+ dg = dup_degree(g)
1016
+
1017
+ q, r, dr = [], f, df
1018
+
1019
+ if not g:
1020
+ raise ZeroDivisionError("polynomial division")
1021
+ elif df < dg:
1022
+ return q, r
1023
+
1024
+ N = df - dg + 1
1025
+ lc_g = dup_LC(g, K)
1026
+
1027
+ while True:
1028
+ lc_r = dup_LC(r, K)
1029
+ j, N = dr - dg, N - 1
1030
+
1031
+ Q = dup_mul_ground(q, lc_g, K)
1032
+ q = dup_add_term(Q, lc_r, j, K)
1033
+
1034
+ R = dup_mul_ground(r, lc_g, K)
1035
+ G = dup_mul_term(g, lc_r, j, K)
1036
+ r = dup_sub(R, G, K)
1037
+
1038
+ _dr, dr = dr, dup_degree(r)
1039
+
1040
+ if dr < dg:
1041
+ break
1042
+ elif not (dr < _dr):
1043
+ raise PolynomialDivisionFailed(f, g, K)
1044
+
1045
+ c = lc_g**N
1046
+
1047
+ q = dup_mul_ground(q, c, K)
1048
+ r = dup_mul_ground(r, c, K)
1049
+
1050
+ return q, r
1051
+
1052
+
1053
+ def dup_prem(f, g, K):
1054
+ """
1055
+ Polynomial pseudo-remainder in ``K[x]``.
1056
+
1057
+ Examples
1058
+ ========
1059
+
1060
+ >>> from sympy.polys import ring, ZZ
1061
+ >>> R, x = ring("x", ZZ)
1062
+
1063
+ >>> R.dup_prem(x**2 + 1, 2*x - 4)
1064
+ 20
1065
+
1066
+ """
1067
+ df = dup_degree(f)
1068
+ dg = dup_degree(g)
1069
+
1070
+ r, dr = f, df
1071
+
1072
+ if not g:
1073
+ raise ZeroDivisionError("polynomial division")
1074
+ elif df < dg:
1075
+ return r
1076
+
1077
+ N = df - dg + 1
1078
+ lc_g = dup_LC(g, K)
1079
+
1080
+ while True:
1081
+ lc_r = dup_LC(r, K)
1082
+ j, N = dr - dg, N - 1
1083
+
1084
+ R = dup_mul_ground(r, lc_g, K)
1085
+ G = dup_mul_term(g, lc_r, j, K)
1086
+ r = dup_sub(R, G, K)
1087
+
1088
+ _dr, dr = dr, dup_degree(r)
1089
+
1090
+ if dr < dg:
1091
+ break
1092
+ elif not (dr < _dr):
1093
+ raise PolynomialDivisionFailed(f, g, K)
1094
+
1095
+ return dup_mul_ground(r, lc_g**N, K)
1096
+
1097
+
1098
+ def dup_pquo(f, g, K):
1099
+ """
1100
+ Polynomial exact pseudo-quotient in ``K[X]``.
1101
+
1102
+ Examples
1103
+ ========
1104
+
1105
+ >>> from sympy.polys import ring, ZZ
1106
+ >>> R, x = ring("x", ZZ)
1107
+
1108
+ >>> R.dup_pquo(x**2 - 1, 2*x - 2)
1109
+ 2*x + 2
1110
+
1111
+ >>> R.dup_pquo(x**2 + 1, 2*x - 4)
1112
+ 2*x + 4
1113
+
1114
+ """
1115
+ return dup_pdiv(f, g, K)[0]
1116
+
1117
+
1118
+ def dup_pexquo(f, g, K):
1119
+ """
1120
+ Polynomial pseudo-quotient in ``K[x]``.
1121
+
1122
+ Examples
1123
+ ========
1124
+
1125
+ >>> from sympy.polys import ring, ZZ
1126
+ >>> R, x = ring("x", ZZ)
1127
+
1128
+ >>> R.dup_pexquo(x**2 - 1, 2*x - 2)
1129
+ 2*x + 2
1130
+
1131
+ >>> R.dup_pexquo(x**2 + 1, 2*x - 4)
1132
+ Traceback (most recent call last):
1133
+ ...
1134
+ ExactQuotientFailed: [2, -4] does not divide [1, 0, 1]
1135
+
1136
+ """
1137
+ q, r = dup_pdiv(f, g, K)
1138
+
1139
+ if not r:
1140
+ return q
1141
+ else:
1142
+ raise ExactQuotientFailed(f, g)
1143
+
1144
+
1145
+ def dmp_pdiv(f, g, u, K):
1146
+ """
1147
+ Polynomial pseudo-division in ``K[X]``.
1148
+
1149
+ Examples
1150
+ ========
1151
+
1152
+ >>> from sympy.polys import ring, ZZ
1153
+ >>> R, x,y = ring("x,y", ZZ)
1154
+
1155
+ >>> R.dmp_pdiv(x**2 + x*y, 2*x + 2)
1156
+ (2*x + 2*y - 2, -4*y + 4)
1157
+
1158
+ """
1159
+ if not u:
1160
+ return dup_pdiv(f, g, K)
1161
+
1162
+ df = dmp_degree(f, u)
1163
+ dg = dmp_degree(g, u)
1164
+
1165
+ if dg < 0:
1166
+ raise ZeroDivisionError("polynomial division")
1167
+
1168
+ q, r, dr = dmp_zero(u), f, df
1169
+
1170
+ if df < dg:
1171
+ return q, r
1172
+
1173
+ N = df - dg + 1
1174
+ lc_g = dmp_LC(g, K)
1175
+
1176
+ while True:
1177
+ lc_r = dmp_LC(r, K)
1178
+ j, N = dr - dg, N - 1
1179
+
1180
+ Q = dmp_mul_term(q, lc_g, 0, u, K)
1181
+ q = dmp_add_term(Q, lc_r, j, u, K)
1182
+
1183
+ R = dmp_mul_term(r, lc_g, 0, u, K)
1184
+ G = dmp_mul_term(g, lc_r, j, u, K)
1185
+ r = dmp_sub(R, G, u, K)
1186
+
1187
+ _dr, dr = dr, dmp_degree(r, u)
1188
+
1189
+ if dr < dg:
1190
+ break
1191
+ elif not (dr < _dr):
1192
+ raise PolynomialDivisionFailed(f, g, K)
1193
+
1194
+ c = dmp_pow(lc_g, N, u - 1, K)
1195
+
1196
+ q = dmp_mul_term(q, c, 0, u, K)
1197
+ r = dmp_mul_term(r, c, 0, u, K)
1198
+
1199
+ return q, r
1200
+
1201
+
1202
+ def dmp_prem(f, g, u, K):
1203
+ """
1204
+ Polynomial pseudo-remainder in ``K[X]``.
1205
+
1206
+ Examples
1207
+ ========
1208
+
1209
+ >>> from sympy.polys import ring, ZZ
1210
+ >>> R, x,y = ring("x,y", ZZ)
1211
+
1212
+ >>> R.dmp_prem(x**2 + x*y, 2*x + 2)
1213
+ -4*y + 4
1214
+
1215
+ """
1216
+ if not u:
1217
+ return dup_prem(f, g, K)
1218
+
1219
+ df = dmp_degree(f, u)
1220
+ dg = dmp_degree(g, u)
1221
+
1222
+ if dg < 0:
1223
+ raise ZeroDivisionError("polynomial division")
1224
+
1225
+ r, dr = f, df
1226
+
1227
+ if df < dg:
1228
+ return r
1229
+
1230
+ N = df - dg + 1
1231
+ lc_g = dmp_LC(g, K)
1232
+
1233
+ while True:
1234
+ lc_r = dmp_LC(r, K)
1235
+ j, N = dr - dg, N - 1
1236
+
1237
+ R = dmp_mul_term(r, lc_g, 0, u, K)
1238
+ G = dmp_mul_term(g, lc_r, j, u, K)
1239
+ r = dmp_sub(R, G, u, K)
1240
+
1241
+ _dr, dr = dr, dmp_degree(r, u)
1242
+
1243
+ if dr < dg:
1244
+ break
1245
+ elif not (dr < _dr):
1246
+ raise PolynomialDivisionFailed(f, g, K)
1247
+
1248
+ c = dmp_pow(lc_g, N, u - 1, K)
1249
+
1250
+ return dmp_mul_term(r, c, 0, u, K)
1251
+
1252
+
1253
+ def dmp_pquo(f, g, u, K):
1254
+ """
1255
+ Polynomial exact pseudo-quotient in ``K[X]``.
1256
+
1257
+ Examples
1258
+ ========
1259
+
1260
+ >>> from sympy.polys import ring, ZZ
1261
+ >>> R, x,y = ring("x,y", ZZ)
1262
+
1263
+ >>> f = x**2 + x*y
1264
+ >>> g = 2*x + 2*y
1265
+ >>> h = 2*x + 2
1266
+
1267
+ >>> R.dmp_pquo(f, g)
1268
+ 2*x
1269
+
1270
+ >>> R.dmp_pquo(f, h)
1271
+ 2*x + 2*y - 2
1272
+
1273
+ """
1274
+ return dmp_pdiv(f, g, u, K)[0]
1275
+
1276
+
1277
+ def dmp_pexquo(f, g, u, K):
1278
+ """
1279
+ Polynomial pseudo-quotient in ``K[X]``.
1280
+
1281
+ Examples
1282
+ ========
1283
+
1284
+ >>> from sympy.polys import ring, ZZ
1285
+ >>> R, x,y = ring("x,y", ZZ)
1286
+
1287
+ >>> f = x**2 + x*y
1288
+ >>> g = 2*x + 2*y
1289
+ >>> h = 2*x + 2
1290
+
1291
+ >>> R.dmp_pexquo(f, g)
1292
+ 2*x
1293
+
1294
+ >>> R.dmp_pexquo(f, h)
1295
+ Traceback (most recent call last):
1296
+ ...
1297
+ ExactQuotientFailed: [[2], [2]] does not divide [[1], [1, 0], []]
1298
+
1299
+ """
1300
+ q, r = dmp_pdiv(f, g, u, K)
1301
+
1302
+ if dmp_zero_p(r, u):
1303
+ return q
1304
+ else:
1305
+ raise ExactQuotientFailed(f, g)
1306
+
1307
+
1308
+ def dup_rr_div(f, g, K):
1309
+ """
1310
+ Univariate division with remainder over a ring.
1311
+
1312
+ Examples
1313
+ ========
1314
+
1315
+ >>> from sympy.polys import ring, ZZ
1316
+ >>> R, x = ring("x", ZZ)
1317
+
1318
+ >>> R.dup_rr_div(x**2 + 1, 2*x - 4)
1319
+ (0, x**2 + 1)
1320
+
1321
+ """
1322
+ df = dup_degree(f)
1323
+ dg = dup_degree(g)
1324
+
1325
+ q, r, dr = [], f, df
1326
+
1327
+ if not g:
1328
+ raise ZeroDivisionError("polynomial division")
1329
+ elif df < dg:
1330
+ return q, r
1331
+
1332
+ lc_g = dup_LC(g, K)
1333
+
1334
+ while True:
1335
+ lc_r = dup_LC(r, K)
1336
+
1337
+ if lc_r % lc_g:
1338
+ break
1339
+
1340
+ c = K.exquo(lc_r, lc_g)
1341
+ j = dr - dg
1342
+
1343
+ q = dup_add_term(q, c, j, K)
1344
+ h = dup_mul_term(g, c, j, K)
1345
+ r = dup_sub(r, h, K)
1346
+
1347
+ _dr, dr = dr, dup_degree(r)
1348
+
1349
+ if dr < dg:
1350
+ break
1351
+ elif not (dr < _dr):
1352
+ raise PolynomialDivisionFailed(f, g, K)
1353
+
1354
+ return q, r
1355
+
1356
+
1357
+ def dmp_rr_div(f, g, u, K):
1358
+ """
1359
+ Multivariate division with remainder over a ring.
1360
+
1361
+ Examples
1362
+ ========
1363
+
1364
+ >>> from sympy.polys import ring, ZZ
1365
+ >>> R, x,y = ring("x,y", ZZ)
1366
+
1367
+ >>> R.dmp_rr_div(x**2 + x*y, 2*x + 2)
1368
+ (0, x**2 + x*y)
1369
+
1370
+ """
1371
+ if not u:
1372
+ return dup_rr_div(f, g, K)
1373
+
1374
+ df = dmp_degree(f, u)
1375
+ dg = dmp_degree(g, u)
1376
+
1377
+ if dg < 0:
1378
+ raise ZeroDivisionError("polynomial division")
1379
+
1380
+ q, r, dr = dmp_zero(u), f, df
1381
+
1382
+ if df < dg:
1383
+ return q, r
1384
+
1385
+ lc_g, v = dmp_LC(g, K), u - 1
1386
+
1387
+ while True:
1388
+ lc_r = dmp_LC(r, K)
1389
+ c, R = dmp_rr_div(lc_r, lc_g, v, K)
1390
+
1391
+ if not dmp_zero_p(R, v):
1392
+ break
1393
+
1394
+ j = dr - dg
1395
+
1396
+ q = dmp_add_term(q, c, j, u, K)
1397
+ h = dmp_mul_term(g, c, j, u, K)
1398
+ r = dmp_sub(r, h, u, K)
1399
+
1400
+ _dr, dr = dr, dmp_degree(r, u)
1401
+
1402
+ if dr < dg:
1403
+ break
1404
+ elif not (dr < _dr):
1405
+ raise PolynomialDivisionFailed(f, g, K)
1406
+
1407
+ return q, r
1408
+
1409
+
1410
+ def dup_ff_div(f, g, K):
1411
+ """
1412
+ Polynomial division with remainder over a field.
1413
+
1414
+ Examples
1415
+ ========
1416
+
1417
+ >>> from sympy.polys import ring, QQ
1418
+ >>> R, x = ring("x", QQ)
1419
+
1420
+ >>> R.dup_ff_div(x**2 + 1, 2*x - 4)
1421
+ (1/2*x + 1, 5)
1422
+
1423
+ """
1424
+ df = dup_degree(f)
1425
+ dg = dup_degree(g)
1426
+
1427
+ q, r, dr = [], f, df
1428
+
1429
+ if not g:
1430
+ raise ZeroDivisionError("polynomial division")
1431
+ elif df < dg:
1432
+ return q, r
1433
+
1434
+ lc_g = dup_LC(g, K)
1435
+
1436
+ while True:
1437
+ lc_r = dup_LC(r, K)
1438
+
1439
+ c = K.exquo(lc_r, lc_g)
1440
+ j = dr - dg
1441
+
1442
+ q = dup_add_term(q, c, j, K)
1443
+ h = dup_mul_term(g, c, j, K)
1444
+ r = dup_sub(r, h, K)
1445
+
1446
+ _dr, dr = dr, dup_degree(r)
1447
+
1448
+ if dr < dg:
1449
+ break
1450
+ elif dr == _dr and not K.is_Exact:
1451
+ # remove leading term created by rounding error
1452
+ r = dup_strip(r[1:])
1453
+ dr = dup_degree(r)
1454
+ if dr < dg:
1455
+ break
1456
+ elif not (dr < _dr):
1457
+ raise PolynomialDivisionFailed(f, g, K)
1458
+
1459
+ return q, r
1460
+
1461
+
1462
+ def dmp_ff_div(f, g, u, K):
1463
+ """
1464
+ Polynomial division with remainder over a field.
1465
+
1466
+ Examples
1467
+ ========
1468
+
1469
+ >>> from sympy.polys import ring, QQ
1470
+ >>> R, x,y = ring("x,y", QQ)
1471
+
1472
+ >>> R.dmp_ff_div(x**2 + x*y, 2*x + 2)
1473
+ (1/2*x + 1/2*y - 1/2, -y + 1)
1474
+
1475
+ """
1476
+ if not u:
1477
+ return dup_ff_div(f, g, K)
1478
+
1479
+ df = dmp_degree(f, u)
1480
+ dg = dmp_degree(g, u)
1481
+
1482
+ if dg < 0:
1483
+ raise ZeroDivisionError("polynomial division")
1484
+
1485
+ q, r, dr = dmp_zero(u), f, df
1486
+
1487
+ if df < dg:
1488
+ return q, r
1489
+
1490
+ lc_g, v = dmp_LC(g, K), u - 1
1491
+
1492
+ while True:
1493
+ lc_r = dmp_LC(r, K)
1494
+ c, R = dmp_ff_div(lc_r, lc_g, v, K)
1495
+
1496
+ if not dmp_zero_p(R, v):
1497
+ break
1498
+
1499
+ j = dr - dg
1500
+
1501
+ q = dmp_add_term(q, c, j, u, K)
1502
+ h = dmp_mul_term(g, c, j, u, K)
1503
+ r = dmp_sub(r, h, u, K)
1504
+
1505
+ _dr, dr = dr, dmp_degree(r, u)
1506
+
1507
+ if dr < dg:
1508
+ break
1509
+ elif not (dr < _dr):
1510
+ raise PolynomialDivisionFailed(f, g, K)
1511
+
1512
+ return q, r
1513
+
1514
+
1515
+ def dup_div(f, g, K):
1516
+ """
1517
+ Polynomial division with remainder in ``K[x]``.
1518
+
1519
+ Examples
1520
+ ========
1521
+
1522
+ >>> from sympy.polys import ring, ZZ, QQ
1523
+
1524
+ >>> R, x = ring("x", ZZ)
1525
+ >>> R.dup_div(x**2 + 1, 2*x - 4)
1526
+ (0, x**2 + 1)
1527
+
1528
+ >>> R, x = ring("x", QQ)
1529
+ >>> R.dup_div(x**2 + 1, 2*x - 4)
1530
+ (1/2*x + 1, 5)
1531
+
1532
+ """
1533
+ if K.is_Field:
1534
+ return dup_ff_div(f, g, K)
1535
+ else:
1536
+ return dup_rr_div(f, g, K)
1537
+
1538
+
1539
+ def dup_rem(f, g, K):
1540
+ """
1541
+ Returns polynomial remainder in ``K[x]``.
1542
+
1543
+ Examples
1544
+ ========
1545
+
1546
+ >>> from sympy.polys import ring, ZZ, QQ
1547
+
1548
+ >>> R, x = ring("x", ZZ)
1549
+ >>> R.dup_rem(x**2 + 1, 2*x - 4)
1550
+ x**2 + 1
1551
+
1552
+ >>> R, x = ring("x", QQ)
1553
+ >>> R.dup_rem(x**2 + 1, 2*x - 4)
1554
+ 5
1555
+
1556
+ """
1557
+ return dup_div(f, g, K)[1]
1558
+
1559
+
1560
+ def dup_quo(f, g, K):
1561
+ """
1562
+ Returns exact polynomial quotient in ``K[x]``.
1563
+
1564
+ Examples
1565
+ ========
1566
+
1567
+ >>> from sympy.polys import ring, ZZ, QQ
1568
+
1569
+ >>> R, x = ring("x", ZZ)
1570
+ >>> R.dup_quo(x**2 + 1, 2*x - 4)
1571
+ 0
1572
+
1573
+ >>> R, x = ring("x", QQ)
1574
+ >>> R.dup_quo(x**2 + 1, 2*x - 4)
1575
+ 1/2*x + 1
1576
+
1577
+ """
1578
+ return dup_div(f, g, K)[0]
1579
+
1580
+
1581
+ def dup_exquo(f, g, K):
1582
+ """
1583
+ Returns polynomial quotient in ``K[x]``.
1584
+
1585
+ Examples
1586
+ ========
1587
+
1588
+ >>> from sympy.polys import ring, ZZ
1589
+ >>> R, x = ring("x", ZZ)
1590
+
1591
+ >>> R.dup_exquo(x**2 - 1, x - 1)
1592
+ x + 1
1593
+
1594
+ >>> R.dup_exquo(x**2 + 1, 2*x - 4)
1595
+ Traceback (most recent call last):
1596
+ ...
1597
+ ExactQuotientFailed: [2, -4] does not divide [1, 0, 1]
1598
+
1599
+ """
1600
+ q, r = dup_div(f, g, K)
1601
+
1602
+ if not r:
1603
+ return q
1604
+ else:
1605
+ raise ExactQuotientFailed(f, g)
1606
+
1607
+
1608
+ def dmp_div(f, g, u, K):
1609
+ """
1610
+ Polynomial division with remainder in ``K[X]``.
1611
+
1612
+ Examples
1613
+ ========
1614
+
1615
+ >>> from sympy.polys import ring, ZZ, QQ
1616
+
1617
+ >>> R, x,y = ring("x,y", ZZ)
1618
+ >>> R.dmp_div(x**2 + x*y, 2*x + 2)
1619
+ (0, x**2 + x*y)
1620
+
1621
+ >>> R, x,y = ring("x,y", QQ)
1622
+ >>> R.dmp_div(x**2 + x*y, 2*x + 2)
1623
+ (1/2*x + 1/2*y - 1/2, -y + 1)
1624
+
1625
+ """
1626
+ if K.is_Field:
1627
+ return dmp_ff_div(f, g, u, K)
1628
+ else:
1629
+ return dmp_rr_div(f, g, u, K)
1630
+
1631
+
1632
+ def dmp_rem(f, g, u, K):
1633
+ """
1634
+ Returns polynomial remainder in ``K[X]``.
1635
+
1636
+ Examples
1637
+ ========
1638
+
1639
+ >>> from sympy.polys import ring, ZZ, QQ
1640
+
1641
+ >>> R, x,y = ring("x,y", ZZ)
1642
+ >>> R.dmp_rem(x**2 + x*y, 2*x + 2)
1643
+ x**2 + x*y
1644
+
1645
+ >>> R, x,y = ring("x,y", QQ)
1646
+ >>> R.dmp_rem(x**2 + x*y, 2*x + 2)
1647
+ -y + 1
1648
+
1649
+ """
1650
+ return dmp_div(f, g, u, K)[1]
1651
+
1652
+
1653
+ def dmp_quo(f, g, u, K):
1654
+ """
1655
+ Returns exact polynomial quotient in ``K[X]``.
1656
+
1657
+ Examples
1658
+ ========
1659
+
1660
+ >>> from sympy.polys import ring, ZZ, QQ
1661
+
1662
+ >>> R, x,y = ring("x,y", ZZ)
1663
+ >>> R.dmp_quo(x**2 + x*y, 2*x + 2)
1664
+ 0
1665
+
1666
+ >>> R, x,y = ring("x,y", QQ)
1667
+ >>> R.dmp_quo(x**2 + x*y, 2*x + 2)
1668
+ 1/2*x + 1/2*y - 1/2
1669
+
1670
+ """
1671
+ return dmp_div(f, g, u, K)[0]
1672
+
1673
+
1674
+ def dmp_exquo(f, g, u, K):
1675
+ """
1676
+ Returns polynomial quotient in ``K[X]``.
1677
+
1678
+ Examples
1679
+ ========
1680
+
1681
+ >>> from sympy.polys import ring, ZZ
1682
+ >>> R, x,y = ring("x,y", ZZ)
1683
+
1684
+ >>> f = x**2 + x*y
1685
+ >>> g = x + y
1686
+ >>> h = 2*x + 2
1687
+
1688
+ >>> R.dmp_exquo(f, g)
1689
+ x
1690
+
1691
+ >>> R.dmp_exquo(f, h)
1692
+ Traceback (most recent call last):
1693
+ ...
1694
+ ExactQuotientFailed: [[2], [2]] does not divide [[1], [1, 0], []]
1695
+
1696
+ """
1697
+ q, r = dmp_div(f, g, u, K)
1698
+
1699
+ if dmp_zero_p(r, u):
1700
+ return q
1701
+ else:
1702
+ raise ExactQuotientFailed(f, g)
1703
+
1704
+
1705
+ def dup_max_norm(f, K):
1706
+ """
1707
+ Returns maximum norm of a polynomial in ``K[x]``.
1708
+
1709
+ Examples
1710
+ ========
1711
+
1712
+ >>> from sympy.polys import ring, ZZ
1713
+ >>> R, x = ring("x", ZZ)
1714
+
1715
+ >>> R.dup_max_norm(-x**2 + 2*x - 3)
1716
+ 3
1717
+
1718
+ """
1719
+ if not f:
1720
+ return K.zero
1721
+ else:
1722
+ return max(dup_abs(f, K))
1723
+
1724
+
1725
+ def dmp_max_norm(f, u, K):
1726
+ """
1727
+ Returns maximum norm of a polynomial in ``K[X]``.
1728
+
1729
+ Examples
1730
+ ========
1731
+
1732
+ >>> from sympy.polys import ring, ZZ
1733
+ >>> R, x,y = ring("x,y", ZZ)
1734
+
1735
+ >>> R.dmp_max_norm(2*x*y - x - 3)
1736
+ 3
1737
+
1738
+ """
1739
+ if not u:
1740
+ return dup_max_norm(f, K)
1741
+
1742
+ v = u - 1
1743
+
1744
+ return max([ dmp_max_norm(c, v, K) for c in f ])
1745
+
1746
+
1747
+ def dup_l1_norm(f, K):
1748
+ """
1749
+ Returns l1 norm of a polynomial in ``K[x]``.
1750
+
1751
+ Examples
1752
+ ========
1753
+
1754
+ >>> from sympy.polys import ring, ZZ
1755
+ >>> R, x = ring("x", ZZ)
1756
+
1757
+ >>> R.dup_l1_norm(2*x**3 - 3*x**2 + 1)
1758
+ 6
1759
+
1760
+ """
1761
+ if not f:
1762
+ return K.zero
1763
+ else:
1764
+ return sum(dup_abs(f, K))
1765
+
1766
+
1767
+ def dmp_l1_norm(f, u, K):
1768
+ """
1769
+ Returns l1 norm of a polynomial in ``K[X]``.
1770
+
1771
+ Examples
1772
+ ========
1773
+
1774
+ >>> from sympy.polys import ring, ZZ
1775
+ >>> R, x,y = ring("x,y", ZZ)
1776
+
1777
+ >>> R.dmp_l1_norm(2*x*y - x - 3)
1778
+ 6
1779
+
1780
+ """
1781
+ if not u:
1782
+ return dup_l1_norm(f, K)
1783
+
1784
+ v = u - 1
1785
+
1786
+ return sum([ dmp_l1_norm(c, v, K) for c in f ])
1787
+
1788
+
1789
+ def dup_l2_norm_squared(f, K):
1790
+ """
1791
+ Returns squared l2 norm of a polynomial in ``K[x]``.
1792
+
1793
+ Examples
1794
+ ========
1795
+
1796
+ >>> from sympy.polys import ring, ZZ
1797
+ >>> R, x = ring("x", ZZ)
1798
+
1799
+ >>> R.dup_l2_norm_squared(2*x**3 - 3*x**2 + 1)
1800
+ 14
1801
+
1802
+ """
1803
+ return sum([coeff**2 for coeff in f], K.zero)
1804
+
1805
+
1806
+ def dmp_l2_norm_squared(f, u, K):
1807
+ """
1808
+ Returns squared l2 norm of a polynomial in ``K[X]``.
1809
+
1810
+ Examples
1811
+ ========
1812
+
1813
+ >>> from sympy.polys import ring, ZZ
1814
+ >>> R, x,y = ring("x,y", ZZ)
1815
+
1816
+ >>> R.dmp_l2_norm_squared(2*x*y - x - 3)
1817
+ 14
1818
+
1819
+ """
1820
+ if not u:
1821
+ return dup_l2_norm_squared(f, K)
1822
+
1823
+ v = u - 1
1824
+
1825
+ return sum([ dmp_l2_norm_squared(c, v, K) for c in f ])
1826
+
1827
+
1828
+ def dup_expand(polys, K):
1829
+ """
1830
+ Multiply together several polynomials in ``K[x]``.
1831
+
1832
+ Examples
1833
+ ========
1834
+
1835
+ >>> from sympy.polys import ring, ZZ
1836
+ >>> R, x = ring("x", ZZ)
1837
+
1838
+ >>> R.dup_expand([x**2 - 1, x, 2])
1839
+ 2*x**3 - 2*x
1840
+
1841
+ """
1842
+ if not polys:
1843
+ return [K.one]
1844
+
1845
+ f = polys[0]
1846
+
1847
+ for g in polys[1:]:
1848
+ f = dup_mul(f, g, K)
1849
+
1850
+ return f
1851
+
1852
+
1853
+ def dmp_expand(polys, u, K):
1854
+ """
1855
+ Multiply together several polynomials in ``K[X]``.
1856
+
1857
+ Examples
1858
+ ========
1859
+
1860
+ >>> from sympy.polys import ring, ZZ
1861
+ >>> R, x,y = ring("x,y", ZZ)
1862
+
1863
+ >>> R.dmp_expand([x**2 + y**2, x + 1])
1864
+ x**3 + x**2 + x*y**2 + y**2
1865
+
1866
+ """
1867
+ if not polys:
1868
+ return dmp_one(u, K)
1869
+
1870
+ f = polys[0]
1871
+
1872
+ for g in polys[1:]:
1873
+ f = dmp_mul(f, g, u, K)
1874
+
1875
+ return f
llmeval-env/lib/python3.10/site-packages/sympy/polys/densebasic.py ADDED
@@ -0,0 +1,1881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Basic tools for dense recursive polynomials in ``K[x]`` or ``K[X]``. """
2
+
3
+
4
+ from sympy.core.numbers import oo
5
+ from sympy.core import igcd
6
+ from sympy.polys.monomials import monomial_min, monomial_div
7
+ from sympy.polys.orderings import monomial_key
8
+
9
+ import random
10
+
11
+ def poly_LC(f, K):
12
+ """
13
+ Return leading coefficient of ``f``.
14
+
15
+ Examples
16
+ ========
17
+
18
+ >>> from sympy.polys.domains import ZZ
19
+ >>> from sympy.polys.densebasic import poly_LC
20
+
21
+ >>> poly_LC([], ZZ)
22
+ 0
23
+ >>> poly_LC([ZZ(1), ZZ(2), ZZ(3)], ZZ)
24
+ 1
25
+
26
+ """
27
+ if not f:
28
+ return K.zero
29
+ else:
30
+ return f[0]
31
+
32
+
33
+ def poly_TC(f, K):
34
+ """
35
+ Return trailing coefficient of ``f``.
36
+
37
+ Examples
38
+ ========
39
+
40
+ >>> from sympy.polys.domains import ZZ
41
+ >>> from sympy.polys.densebasic import poly_TC
42
+
43
+ >>> poly_TC([], ZZ)
44
+ 0
45
+ >>> poly_TC([ZZ(1), ZZ(2), ZZ(3)], ZZ)
46
+ 3
47
+
48
+ """
49
+ if not f:
50
+ return K.zero
51
+ else:
52
+ return f[-1]
53
+
54
+ dup_LC = dmp_LC = poly_LC
55
+ dup_TC = dmp_TC = poly_TC
56
+
57
+
58
+ def dmp_ground_LC(f, u, K):
59
+ """
60
+ Return the ground leading coefficient.
61
+
62
+ Examples
63
+ ========
64
+
65
+ >>> from sympy.polys.domains import ZZ
66
+ >>> from sympy.polys.densebasic import dmp_ground_LC
67
+
68
+ >>> f = ZZ.map([[[1], [2, 3]]])
69
+
70
+ >>> dmp_ground_LC(f, 2, ZZ)
71
+ 1
72
+
73
+ """
74
+ while u:
75
+ f = dmp_LC(f, K)
76
+ u -= 1
77
+
78
+ return dup_LC(f, K)
79
+
80
+
81
+ def dmp_ground_TC(f, u, K):
82
+ """
83
+ Return the ground trailing coefficient.
84
+
85
+ Examples
86
+ ========
87
+
88
+ >>> from sympy.polys.domains import ZZ
89
+ >>> from sympy.polys.densebasic import dmp_ground_TC
90
+
91
+ >>> f = ZZ.map([[[1], [2, 3]]])
92
+
93
+ >>> dmp_ground_TC(f, 2, ZZ)
94
+ 3
95
+
96
+ """
97
+ while u:
98
+ f = dmp_TC(f, K)
99
+ u -= 1
100
+
101
+ return dup_TC(f, K)
102
+
103
+
104
+ def dmp_true_LT(f, u, K):
105
+ """
106
+ Return the leading term ``c * x_1**n_1 ... x_k**n_k``.
107
+
108
+ Examples
109
+ ========
110
+
111
+ >>> from sympy.polys.domains import ZZ
112
+ >>> from sympy.polys.densebasic import dmp_true_LT
113
+
114
+ >>> f = ZZ.map([[4], [2, 0], [3, 0, 0]])
115
+
116
+ >>> dmp_true_LT(f, 1, ZZ)
117
+ ((2, 0), 4)
118
+
119
+ """
120
+ monom = []
121
+
122
+ while u:
123
+ monom.append(len(f) - 1)
124
+ f, u = f[0], u - 1
125
+
126
+ if not f:
127
+ monom.append(0)
128
+ else:
129
+ monom.append(len(f) - 1)
130
+
131
+ return tuple(monom), dup_LC(f, K)
132
+
133
+
134
+ def dup_degree(f):
135
+ """
136
+ Return the leading degree of ``f`` in ``K[x]``.
137
+
138
+ Note that the degree of 0 is negative infinity (the SymPy object -oo).
139
+
140
+ Examples
141
+ ========
142
+
143
+ >>> from sympy.polys.domains import ZZ
144
+ >>> from sympy.polys.densebasic import dup_degree
145
+
146
+ >>> f = ZZ.map([1, 2, 0, 3])
147
+
148
+ >>> dup_degree(f)
149
+ 3
150
+
151
+ """
152
+ if not f:
153
+ return -oo
154
+ return len(f) - 1
155
+
156
+
157
+ def dmp_degree(f, u):
158
+ """
159
+ Return the leading degree of ``f`` in ``x_0`` in ``K[X]``.
160
+
161
+ Note that the degree of 0 is negative infinity (the SymPy object -oo).
162
+
163
+ Examples
164
+ ========
165
+
166
+ >>> from sympy.polys.domains import ZZ
167
+ >>> from sympy.polys.densebasic import dmp_degree
168
+
169
+ >>> dmp_degree([[[]]], 2)
170
+ -oo
171
+
172
+ >>> f = ZZ.map([[2], [1, 2, 3]])
173
+
174
+ >>> dmp_degree(f, 1)
175
+ 1
176
+
177
+ """
178
+ if dmp_zero_p(f, u):
179
+ return -oo
180
+ else:
181
+ return len(f) - 1
182
+
183
+
184
+ def _rec_degree_in(g, v, i, j):
185
+ """Recursive helper function for :func:`dmp_degree_in`."""
186
+ if i == j:
187
+ return dmp_degree(g, v)
188
+
189
+ v, i = v - 1, i + 1
190
+
191
+ return max([ _rec_degree_in(c, v, i, j) for c in g ])
192
+
193
+
194
+ def dmp_degree_in(f, j, u):
195
+ """
196
+ Return the leading degree of ``f`` in ``x_j`` in ``K[X]``.
197
+
198
+ Examples
199
+ ========
200
+
201
+ >>> from sympy.polys.domains import ZZ
202
+ >>> from sympy.polys.densebasic import dmp_degree_in
203
+
204
+ >>> f = ZZ.map([[2], [1, 2, 3]])
205
+
206
+ >>> dmp_degree_in(f, 0, 1)
207
+ 1
208
+ >>> dmp_degree_in(f, 1, 1)
209
+ 2
210
+
211
+ """
212
+ if not j:
213
+ return dmp_degree(f, u)
214
+ if j < 0 or j > u:
215
+ raise IndexError("0 <= j <= %s expected, got %s" % (u, j))
216
+
217
+ return _rec_degree_in(f, u, 0, j)
218
+
219
+
220
+ def _rec_degree_list(g, v, i, degs):
221
+ """Recursive helper for :func:`dmp_degree_list`."""
222
+ degs[i] = max(degs[i], dmp_degree(g, v))
223
+
224
+ if v > 0:
225
+ v, i = v - 1, i + 1
226
+
227
+ for c in g:
228
+ _rec_degree_list(c, v, i, degs)
229
+
230
+
231
+ def dmp_degree_list(f, u):
232
+ """
233
+ Return a list of degrees of ``f`` in ``K[X]``.
234
+
235
+ Examples
236
+ ========
237
+
238
+ >>> from sympy.polys.domains import ZZ
239
+ >>> from sympy.polys.densebasic import dmp_degree_list
240
+
241
+ >>> f = ZZ.map([[1], [1, 2, 3]])
242
+
243
+ >>> dmp_degree_list(f, 1)
244
+ (1, 2)
245
+
246
+ """
247
+ degs = [-oo]*(u + 1)
248
+ _rec_degree_list(f, u, 0, degs)
249
+ return tuple(degs)
250
+
251
+
252
+ def dup_strip(f):
253
+ """
254
+ Remove leading zeros from ``f`` in ``K[x]``.
255
+
256
+ Examples
257
+ ========
258
+
259
+ >>> from sympy.polys.densebasic import dup_strip
260
+
261
+ >>> dup_strip([0, 0, 1, 2, 3, 0])
262
+ [1, 2, 3, 0]
263
+
264
+ """
265
+ if not f or f[0]:
266
+ return f
267
+
268
+ i = 0
269
+
270
+ for cf in f:
271
+ if cf:
272
+ break
273
+ else:
274
+ i += 1
275
+
276
+ return f[i:]
277
+
278
+
279
+ def dmp_strip(f, u):
280
+ """
281
+ Remove leading zeros from ``f`` in ``K[X]``.
282
+
283
+ Examples
284
+ ========
285
+
286
+ >>> from sympy.polys.densebasic import dmp_strip
287
+
288
+ >>> dmp_strip([[], [0, 1, 2], [1]], 1)
289
+ [[0, 1, 2], [1]]
290
+
291
+ """
292
+ if not u:
293
+ return dup_strip(f)
294
+
295
+ if dmp_zero_p(f, u):
296
+ return f
297
+
298
+ i, v = 0, u - 1
299
+
300
+ for c in f:
301
+ if not dmp_zero_p(c, v):
302
+ break
303
+ else:
304
+ i += 1
305
+
306
+ if i == len(f):
307
+ return dmp_zero(u)
308
+ else:
309
+ return f[i:]
310
+
311
+
312
+ def _rec_validate(f, g, i, K):
313
+ """Recursive helper for :func:`dmp_validate`."""
314
+ if not isinstance(g, list):
315
+ if K is not None and not K.of_type(g):
316
+ raise TypeError("%s in %s in not of type %s" % (g, f, K.dtype))
317
+
318
+ return {i - 1}
319
+ elif not g:
320
+ return {i}
321
+ else:
322
+ levels = set()
323
+
324
+ for c in g:
325
+ levels |= _rec_validate(f, c, i + 1, K)
326
+
327
+ return levels
328
+
329
+
330
+ def _rec_strip(g, v):
331
+ """Recursive helper for :func:`_rec_strip`."""
332
+ if not v:
333
+ return dup_strip(g)
334
+
335
+ w = v - 1
336
+
337
+ return dmp_strip([ _rec_strip(c, w) for c in g ], v)
338
+
339
+
340
+ def dmp_validate(f, K=None):
341
+ """
342
+ Return the number of levels in ``f`` and recursively strip it.
343
+
344
+ Examples
345
+ ========
346
+
347
+ >>> from sympy.polys.densebasic import dmp_validate
348
+
349
+ >>> dmp_validate([[], [0, 1, 2], [1]])
350
+ ([[1, 2], [1]], 1)
351
+
352
+ >>> dmp_validate([[1], 1])
353
+ Traceback (most recent call last):
354
+ ...
355
+ ValueError: invalid data structure for a multivariate polynomial
356
+
357
+ """
358
+ levels = _rec_validate(f, f, 0, K)
359
+
360
+ u = levels.pop()
361
+
362
+ if not levels:
363
+ return _rec_strip(f, u), u
364
+ else:
365
+ raise ValueError(
366
+ "invalid data structure for a multivariate polynomial")
367
+
368
+
369
+ def dup_reverse(f):
370
+ """
371
+ Compute ``x**n * f(1/x)``, i.e.: reverse ``f`` in ``K[x]``.
372
+
373
+ Examples
374
+ ========
375
+
376
+ >>> from sympy.polys.domains import ZZ
377
+ >>> from sympy.polys.densebasic import dup_reverse
378
+
379
+ >>> f = ZZ.map([1, 2, 3, 0])
380
+
381
+ >>> dup_reverse(f)
382
+ [3, 2, 1]
383
+
384
+ """
385
+ return dup_strip(list(reversed(f)))
386
+
387
+
388
+ def dup_copy(f):
389
+ """
390
+ Create a new copy of a polynomial ``f`` in ``K[x]``.
391
+
392
+ Examples
393
+ ========
394
+
395
+ >>> from sympy.polys.domains import ZZ
396
+ >>> from sympy.polys.densebasic import dup_copy
397
+
398
+ >>> f = ZZ.map([1, 2, 3, 0])
399
+
400
+ >>> dup_copy([1, 2, 3, 0])
401
+ [1, 2, 3, 0]
402
+
403
+ """
404
+ return list(f)
405
+
406
+
407
+ def dmp_copy(f, u):
408
+ """
409
+ Create a new copy of a polynomial ``f`` in ``K[X]``.
410
+
411
+ Examples
412
+ ========
413
+
414
+ >>> from sympy.polys.domains import ZZ
415
+ >>> from sympy.polys.densebasic import dmp_copy
416
+
417
+ >>> f = ZZ.map([[1], [1, 2]])
418
+
419
+ >>> dmp_copy(f, 1)
420
+ [[1], [1, 2]]
421
+
422
+ """
423
+ if not u:
424
+ return list(f)
425
+
426
+ v = u - 1
427
+
428
+ return [ dmp_copy(c, v) for c in f ]
429
+
430
+
431
+ def dup_to_tuple(f):
432
+ """
433
+ Convert `f` into a tuple.
434
+
435
+ This is needed for hashing. This is similar to dup_copy().
436
+
437
+ Examples
438
+ ========
439
+
440
+ >>> from sympy.polys.domains import ZZ
441
+ >>> from sympy.polys.densebasic import dup_copy
442
+
443
+ >>> f = ZZ.map([1, 2, 3, 0])
444
+
445
+ >>> dup_copy([1, 2, 3, 0])
446
+ [1, 2, 3, 0]
447
+
448
+ """
449
+ return tuple(f)
450
+
451
+
452
+ def dmp_to_tuple(f, u):
453
+ """
454
+ Convert `f` into a nested tuple of tuples.
455
+
456
+ This is needed for hashing. This is similar to dmp_copy().
457
+
458
+ Examples
459
+ ========
460
+
461
+ >>> from sympy.polys.domains import ZZ
462
+ >>> from sympy.polys.densebasic import dmp_to_tuple
463
+
464
+ >>> f = ZZ.map([[1], [1, 2]])
465
+
466
+ >>> dmp_to_tuple(f, 1)
467
+ ((1,), (1, 2))
468
+
469
+ """
470
+ if not u:
471
+ return tuple(f)
472
+ v = u - 1
473
+
474
+ return tuple(dmp_to_tuple(c, v) for c in f)
475
+
476
+
477
+ def dup_normal(f, K):
478
+ """
479
+ Normalize univariate polynomial in the given domain.
480
+
481
+ Examples
482
+ ========
483
+
484
+ >>> from sympy.polys.domains import ZZ
485
+ >>> from sympy.polys.densebasic import dup_normal
486
+
487
+ >>> dup_normal([0, 1.5, 2, 3], ZZ)
488
+ [1, 2, 3]
489
+
490
+ """
491
+ return dup_strip([ K.normal(c) for c in f ])
492
+
493
+
494
+ def dmp_normal(f, u, K):
495
+ """
496
+ Normalize a multivariate polynomial in the given domain.
497
+
498
+ Examples
499
+ ========
500
+
501
+ >>> from sympy.polys.domains import ZZ
502
+ >>> from sympy.polys.densebasic import dmp_normal
503
+
504
+ >>> dmp_normal([[], [0, 1.5, 2]], 1, ZZ)
505
+ [[1, 2]]
506
+
507
+ """
508
+ if not u:
509
+ return dup_normal(f, K)
510
+
511
+ v = u - 1
512
+
513
+ return dmp_strip([ dmp_normal(c, v, K) for c in f ], u)
514
+
515
+
516
+ def dup_convert(f, K0, K1):
517
+ """
518
+ Convert the ground domain of ``f`` from ``K0`` to ``K1``.
519
+
520
+ Examples
521
+ ========
522
+
523
+ >>> from sympy.polys.rings import ring
524
+ >>> from sympy.polys.domains import ZZ
525
+ >>> from sympy.polys.densebasic import dup_convert
526
+
527
+ >>> R, x = ring("x", ZZ)
528
+
529
+ >>> dup_convert([R(1), R(2)], R.to_domain(), ZZ)
530
+ [1, 2]
531
+ >>> dup_convert([ZZ(1), ZZ(2)], ZZ, R.to_domain())
532
+ [1, 2]
533
+
534
+ """
535
+ if K0 is not None and K0 == K1:
536
+ return f
537
+ else:
538
+ return dup_strip([ K1.convert(c, K0) for c in f ])
539
+
540
+
541
+ def dmp_convert(f, u, K0, K1):
542
+ """
543
+ Convert the ground domain of ``f`` from ``K0`` to ``K1``.
544
+
545
+ Examples
546
+ ========
547
+
548
+ >>> from sympy.polys.rings import ring
549
+ >>> from sympy.polys.domains import ZZ
550
+ >>> from sympy.polys.densebasic import dmp_convert
551
+
552
+ >>> R, x = ring("x", ZZ)
553
+
554
+ >>> dmp_convert([[R(1)], [R(2)]], 1, R.to_domain(), ZZ)
555
+ [[1], [2]]
556
+ >>> dmp_convert([[ZZ(1)], [ZZ(2)]], 1, ZZ, R.to_domain())
557
+ [[1], [2]]
558
+
559
+ """
560
+ if not u:
561
+ return dup_convert(f, K0, K1)
562
+ if K0 is not None and K0 == K1:
563
+ return f
564
+
565
+ v = u - 1
566
+
567
+ return dmp_strip([ dmp_convert(c, v, K0, K1) for c in f ], u)
568
+
569
+
570
+ def dup_from_sympy(f, K):
571
+ """
572
+ Convert the ground domain of ``f`` from SymPy to ``K``.
573
+
574
+ Examples
575
+ ========
576
+
577
+ >>> from sympy import S
578
+ >>> from sympy.polys.domains import ZZ
579
+ >>> from sympy.polys.densebasic import dup_from_sympy
580
+
581
+ >>> dup_from_sympy([S(1), S(2)], ZZ) == [ZZ(1), ZZ(2)]
582
+ True
583
+
584
+ """
585
+ return dup_strip([ K.from_sympy(c) for c in f ])
586
+
587
+
588
+ def dmp_from_sympy(f, u, K):
589
+ """
590
+ Convert the ground domain of ``f`` from SymPy to ``K``.
591
+
592
+ Examples
593
+ ========
594
+
595
+ >>> from sympy import S
596
+ >>> from sympy.polys.domains import ZZ
597
+ >>> from sympy.polys.densebasic import dmp_from_sympy
598
+
599
+ >>> dmp_from_sympy([[S(1)], [S(2)]], 1, ZZ) == [[ZZ(1)], [ZZ(2)]]
600
+ True
601
+
602
+ """
603
+ if not u:
604
+ return dup_from_sympy(f, K)
605
+
606
+ v = u - 1
607
+
608
+ return dmp_strip([ dmp_from_sympy(c, v, K) for c in f ], u)
609
+
610
+
611
+ def dup_nth(f, n, K):
612
+ """
613
+ Return the ``n``-th coefficient of ``f`` in ``K[x]``.
614
+
615
+ Examples
616
+ ========
617
+
618
+ >>> from sympy.polys.domains import ZZ
619
+ >>> from sympy.polys.densebasic import dup_nth
620
+
621
+ >>> f = ZZ.map([1, 2, 3])
622
+
623
+ >>> dup_nth(f, 0, ZZ)
624
+ 3
625
+ >>> dup_nth(f, 4, ZZ)
626
+ 0
627
+
628
+ """
629
+ if n < 0:
630
+ raise IndexError("'n' must be non-negative, got %i" % n)
631
+ elif n >= len(f):
632
+ return K.zero
633
+ else:
634
+ return f[dup_degree(f) - n]
635
+
636
+
637
+ def dmp_nth(f, n, u, K):
638
+ """
639
+ Return the ``n``-th coefficient of ``f`` in ``K[x]``.
640
+
641
+ Examples
642
+ ========
643
+
644
+ >>> from sympy.polys.domains import ZZ
645
+ >>> from sympy.polys.densebasic import dmp_nth
646
+
647
+ >>> f = ZZ.map([[1], [2], [3]])
648
+
649
+ >>> dmp_nth(f, 0, 1, ZZ)
650
+ [3]
651
+ >>> dmp_nth(f, 4, 1, ZZ)
652
+ []
653
+
654
+ """
655
+ if n < 0:
656
+ raise IndexError("'n' must be non-negative, got %i" % n)
657
+ elif n >= len(f):
658
+ return dmp_zero(u - 1)
659
+ else:
660
+ return f[dmp_degree(f, u) - n]
661
+
662
+
663
+ def dmp_ground_nth(f, N, u, K):
664
+ """
665
+ Return the ground ``n``-th coefficient of ``f`` in ``K[x]``.
666
+
667
+ Examples
668
+ ========
669
+
670
+ >>> from sympy.polys.domains import ZZ
671
+ >>> from sympy.polys.densebasic import dmp_ground_nth
672
+
673
+ >>> f = ZZ.map([[1], [2, 3]])
674
+
675
+ >>> dmp_ground_nth(f, (0, 1), 1, ZZ)
676
+ 2
677
+
678
+ """
679
+ v = u
680
+
681
+ for n in N:
682
+ if n < 0:
683
+ raise IndexError("`n` must be non-negative, got %i" % n)
684
+ elif n >= len(f):
685
+ return K.zero
686
+ else:
687
+ d = dmp_degree(f, v)
688
+ if d == -oo:
689
+ d = -1
690
+ f, v = f[d - n], v - 1
691
+
692
+ return f
693
+
694
+
695
+ def dmp_zero_p(f, u):
696
+ """
697
+ Return ``True`` if ``f`` is zero in ``K[X]``.
698
+
699
+ Examples
700
+ ========
701
+
702
+ >>> from sympy.polys.densebasic import dmp_zero_p
703
+
704
+ >>> dmp_zero_p([[[[[]]]]], 4)
705
+ True
706
+ >>> dmp_zero_p([[[[[1]]]]], 4)
707
+ False
708
+
709
+ """
710
+ while u:
711
+ if len(f) != 1:
712
+ return False
713
+
714
+ f = f[0]
715
+ u -= 1
716
+
717
+ return not f
718
+
719
+
720
+ def dmp_zero(u):
721
+ """
722
+ Return a multivariate zero.
723
+
724
+ Examples
725
+ ========
726
+
727
+ >>> from sympy.polys.densebasic import dmp_zero
728
+
729
+ >>> dmp_zero(4)
730
+ [[[[[]]]]]
731
+
732
+ """
733
+ r = []
734
+
735
+ for i in range(u):
736
+ r = [r]
737
+
738
+ return r
739
+
740
+
741
+ def dmp_one_p(f, u, K):
742
+ """
743
+ Return ``True`` if ``f`` is one in ``K[X]``.
744
+
745
+ Examples
746
+ ========
747
+
748
+ >>> from sympy.polys.domains import ZZ
749
+ >>> from sympy.polys.densebasic import dmp_one_p
750
+
751
+ >>> dmp_one_p([[[ZZ(1)]]], 2, ZZ)
752
+ True
753
+
754
+ """
755
+ return dmp_ground_p(f, K.one, u)
756
+
757
+
758
+ def dmp_one(u, K):
759
+ """
760
+ Return a multivariate one over ``K``.
761
+
762
+ Examples
763
+ ========
764
+
765
+ >>> from sympy.polys.domains import ZZ
766
+ >>> from sympy.polys.densebasic import dmp_one
767
+
768
+ >>> dmp_one(2, ZZ)
769
+ [[[1]]]
770
+
771
+ """
772
+ return dmp_ground(K.one, u)
773
+
774
+
775
+ def dmp_ground_p(f, c, u):
776
+ """
777
+ Return True if ``f`` is constant in ``K[X]``.
778
+
779
+ Examples
780
+ ========
781
+
782
+ >>> from sympy.polys.densebasic import dmp_ground_p
783
+
784
+ >>> dmp_ground_p([[[3]]], 3, 2)
785
+ True
786
+ >>> dmp_ground_p([[[4]]], None, 2)
787
+ True
788
+
789
+ """
790
+ if c is not None and not c:
791
+ return dmp_zero_p(f, u)
792
+
793
+ while u:
794
+ if len(f) != 1:
795
+ return False
796
+ f = f[0]
797
+ u -= 1
798
+
799
+ if c is None:
800
+ return len(f) <= 1
801
+ else:
802
+ return f == [c]
803
+
804
+
805
+ def dmp_ground(c, u):
806
+ """
807
+ Return a multivariate constant.
808
+
809
+ Examples
810
+ ========
811
+
812
+ >>> from sympy.polys.densebasic import dmp_ground
813
+
814
+ >>> dmp_ground(3, 5)
815
+ [[[[[[3]]]]]]
816
+ >>> dmp_ground(1, -1)
817
+ 1
818
+
819
+ """
820
+ if not c:
821
+ return dmp_zero(u)
822
+
823
+ for i in range(u + 1):
824
+ c = [c]
825
+
826
+ return c
827
+
828
+
829
+ def dmp_zeros(n, u, K):
830
+ """
831
+ Return a list of multivariate zeros.
832
+
833
+ Examples
834
+ ========
835
+
836
+ >>> from sympy.polys.domains import ZZ
837
+ >>> from sympy.polys.densebasic import dmp_zeros
838
+
839
+ >>> dmp_zeros(3, 2, ZZ)
840
+ [[[[]]], [[[]]], [[[]]]]
841
+ >>> dmp_zeros(3, -1, ZZ)
842
+ [0, 0, 0]
843
+
844
+ """
845
+ if not n:
846
+ return []
847
+
848
+ if u < 0:
849
+ return [K.zero]*n
850
+ else:
851
+ return [ dmp_zero(u) for i in range(n) ]
852
+
853
+
854
+ def dmp_grounds(c, n, u):
855
+ """
856
+ Return a list of multivariate constants.
857
+
858
+ Examples
859
+ ========
860
+
861
+ >>> from sympy.polys.domains import ZZ
862
+ >>> from sympy.polys.densebasic import dmp_grounds
863
+
864
+ >>> dmp_grounds(ZZ(4), 3, 2)
865
+ [[[[4]]], [[[4]]], [[[4]]]]
866
+ >>> dmp_grounds(ZZ(4), 3, -1)
867
+ [4, 4, 4]
868
+
869
+ """
870
+ if not n:
871
+ return []
872
+
873
+ if u < 0:
874
+ return [c]*n
875
+ else:
876
+ return [ dmp_ground(c, u) for i in range(n) ]
877
+
878
+
879
+ def dmp_negative_p(f, u, K):
880
+ """
881
+ Return ``True`` if ``LC(f)`` is negative.
882
+
883
+ Examples
884
+ ========
885
+
886
+ >>> from sympy.polys.domains import ZZ
887
+ >>> from sympy.polys.densebasic import dmp_negative_p
888
+
889
+ >>> dmp_negative_p([[ZZ(1)], [-ZZ(1)]], 1, ZZ)
890
+ False
891
+ >>> dmp_negative_p([[-ZZ(1)], [ZZ(1)]], 1, ZZ)
892
+ True
893
+
894
+ """
895
+ return K.is_negative(dmp_ground_LC(f, u, K))
896
+
897
+
898
+ def dmp_positive_p(f, u, K):
899
+ """
900
+ Return ``True`` if ``LC(f)`` is positive.
901
+
902
+ Examples
903
+ ========
904
+
905
+ >>> from sympy.polys.domains import ZZ
906
+ >>> from sympy.polys.densebasic import dmp_positive_p
907
+
908
+ >>> dmp_positive_p([[ZZ(1)], [-ZZ(1)]], 1, ZZ)
909
+ True
910
+ >>> dmp_positive_p([[-ZZ(1)], [ZZ(1)]], 1, ZZ)
911
+ False
912
+
913
+ """
914
+ return K.is_positive(dmp_ground_LC(f, u, K))
915
+
916
+
917
+ def dup_from_dict(f, K):
918
+ """
919
+ Create a ``K[x]`` polynomial from a ``dict``.
920
+
921
+ Examples
922
+ ========
923
+
924
+ >>> from sympy.polys.domains import ZZ
925
+ >>> from sympy.polys.densebasic import dup_from_dict
926
+
927
+ >>> dup_from_dict({(0,): ZZ(7), (2,): ZZ(5), (4,): ZZ(1)}, ZZ)
928
+ [1, 0, 5, 0, 7]
929
+ >>> dup_from_dict({}, ZZ)
930
+ []
931
+
932
+ """
933
+ if not f:
934
+ return []
935
+
936
+ n, h = max(f.keys()), []
937
+
938
+ if isinstance(n, int):
939
+ for k in range(n, -1, -1):
940
+ h.append(f.get(k, K.zero))
941
+ else:
942
+ (n,) = n
943
+
944
+ for k in range(n, -1, -1):
945
+ h.append(f.get((k,), K.zero))
946
+
947
+ return dup_strip(h)
948
+
949
+
950
+ def dup_from_raw_dict(f, K):
951
+ """
952
+ Create a ``K[x]`` polynomial from a raw ``dict``.
953
+
954
+ Examples
955
+ ========
956
+
957
+ >>> from sympy.polys.domains import ZZ
958
+ >>> from sympy.polys.densebasic import dup_from_raw_dict
959
+
960
+ >>> dup_from_raw_dict({0: ZZ(7), 2: ZZ(5), 4: ZZ(1)}, ZZ)
961
+ [1, 0, 5, 0, 7]
962
+
963
+ """
964
+ if not f:
965
+ return []
966
+
967
+ n, h = max(f.keys()), []
968
+
969
+ for k in range(n, -1, -1):
970
+ h.append(f.get(k, K.zero))
971
+
972
+ return dup_strip(h)
973
+
974
+
975
+ def dmp_from_dict(f, u, K):
976
+ """
977
+ Create a ``K[X]`` polynomial from a ``dict``.
978
+
979
+ Examples
980
+ ========
981
+
982
+ >>> from sympy.polys.domains import ZZ
983
+ >>> from sympy.polys.densebasic import dmp_from_dict
984
+
985
+ >>> dmp_from_dict({(0, 0): ZZ(3), (0, 1): ZZ(2), (2, 1): ZZ(1)}, 1, ZZ)
986
+ [[1, 0], [], [2, 3]]
987
+ >>> dmp_from_dict({}, 0, ZZ)
988
+ []
989
+
990
+ """
991
+ if not u:
992
+ return dup_from_dict(f, K)
993
+ if not f:
994
+ return dmp_zero(u)
995
+
996
+ coeffs = {}
997
+
998
+ for monom, coeff in f.items():
999
+ head, tail = monom[0], monom[1:]
1000
+
1001
+ if head in coeffs:
1002
+ coeffs[head][tail] = coeff
1003
+ else:
1004
+ coeffs[head] = { tail: coeff }
1005
+
1006
+ n, v, h = max(coeffs.keys()), u - 1, []
1007
+
1008
+ for k in range(n, -1, -1):
1009
+ coeff = coeffs.get(k)
1010
+
1011
+ if coeff is not None:
1012
+ h.append(dmp_from_dict(coeff, v, K))
1013
+ else:
1014
+ h.append(dmp_zero(v))
1015
+
1016
+ return dmp_strip(h, u)
1017
+
1018
+
1019
+ def dup_to_dict(f, K=None, zero=False):
1020
+ """
1021
+ Convert ``K[x]`` polynomial to a ``dict``.
1022
+
1023
+ Examples
1024
+ ========
1025
+
1026
+ >>> from sympy.polys.densebasic import dup_to_dict
1027
+
1028
+ >>> dup_to_dict([1, 0, 5, 0, 7])
1029
+ {(0,): 7, (2,): 5, (4,): 1}
1030
+ >>> dup_to_dict([])
1031
+ {}
1032
+
1033
+ """
1034
+ if not f and zero:
1035
+ return {(0,): K.zero}
1036
+
1037
+ n, result = len(f) - 1, {}
1038
+
1039
+ for k in range(0, n + 1):
1040
+ if f[n - k]:
1041
+ result[(k,)] = f[n - k]
1042
+
1043
+ return result
1044
+
1045
+
1046
+ def dup_to_raw_dict(f, K=None, zero=False):
1047
+ """
1048
+ Convert a ``K[x]`` polynomial to a raw ``dict``.
1049
+
1050
+ Examples
1051
+ ========
1052
+
1053
+ >>> from sympy.polys.densebasic import dup_to_raw_dict
1054
+
1055
+ >>> dup_to_raw_dict([1, 0, 5, 0, 7])
1056
+ {0: 7, 2: 5, 4: 1}
1057
+
1058
+ """
1059
+ if not f and zero:
1060
+ return {0: K.zero}
1061
+
1062
+ n, result = len(f) - 1, {}
1063
+
1064
+ for k in range(0, n + 1):
1065
+ if f[n - k]:
1066
+ result[k] = f[n - k]
1067
+
1068
+ return result
1069
+
1070
+
1071
+ def dmp_to_dict(f, u, K=None, zero=False):
1072
+ """
1073
+ Convert a ``K[X]`` polynomial to a ``dict````.
1074
+
1075
+ Examples
1076
+ ========
1077
+
1078
+ >>> from sympy.polys.densebasic import dmp_to_dict
1079
+
1080
+ >>> dmp_to_dict([[1, 0], [], [2, 3]], 1)
1081
+ {(0, 0): 3, (0, 1): 2, (2, 1): 1}
1082
+ >>> dmp_to_dict([], 0)
1083
+ {}
1084
+
1085
+ """
1086
+ if not u:
1087
+ return dup_to_dict(f, K, zero=zero)
1088
+
1089
+ if dmp_zero_p(f, u) and zero:
1090
+ return {(0,)*(u + 1): K.zero}
1091
+
1092
+ n, v, result = dmp_degree(f, u), u - 1, {}
1093
+
1094
+ if n == -oo:
1095
+ n = -1
1096
+
1097
+ for k in range(0, n + 1):
1098
+ h = dmp_to_dict(f[n - k], v)
1099
+
1100
+ for exp, coeff in h.items():
1101
+ result[(k,) + exp] = coeff
1102
+
1103
+ return result
1104
+
1105
+
1106
+ def dmp_swap(f, i, j, u, K):
1107
+ """
1108
+ Transform ``K[..x_i..x_j..]`` to ``K[..x_j..x_i..]``.
1109
+
1110
+ Examples
1111
+ ========
1112
+
1113
+ >>> from sympy.polys.domains import ZZ
1114
+ >>> from sympy.polys.densebasic import dmp_swap
1115
+
1116
+ >>> f = ZZ.map([[[2], [1, 0]], []])
1117
+
1118
+ >>> dmp_swap(f, 0, 1, 2, ZZ)
1119
+ [[[2], []], [[1, 0], []]]
1120
+ >>> dmp_swap(f, 1, 2, 2, ZZ)
1121
+ [[[1], [2, 0]], [[]]]
1122
+ >>> dmp_swap(f, 0, 2, 2, ZZ)
1123
+ [[[1, 0]], [[2, 0], []]]
1124
+
1125
+ """
1126
+ if i < 0 or j < 0 or i > u or j > u:
1127
+ raise IndexError("0 <= i < j <= %s expected" % u)
1128
+ elif i == j:
1129
+ return f
1130
+
1131
+ F, H = dmp_to_dict(f, u), {}
1132
+
1133
+ for exp, coeff in F.items():
1134
+ H[exp[:i] + (exp[j],) +
1135
+ exp[i + 1:j] +
1136
+ (exp[i],) + exp[j + 1:]] = coeff
1137
+
1138
+ return dmp_from_dict(H, u, K)
1139
+
1140
+
1141
+ def dmp_permute(f, P, u, K):
1142
+ """
1143
+ Return a polynomial in ``K[x_{P(1)},..,x_{P(n)}]``.
1144
+
1145
+ Examples
1146
+ ========
1147
+
1148
+ >>> from sympy.polys.domains import ZZ
1149
+ >>> from sympy.polys.densebasic import dmp_permute
1150
+
1151
+ >>> f = ZZ.map([[[2], [1, 0]], []])
1152
+
1153
+ >>> dmp_permute(f, [1, 0, 2], 2, ZZ)
1154
+ [[[2], []], [[1, 0], []]]
1155
+ >>> dmp_permute(f, [1, 2, 0], 2, ZZ)
1156
+ [[[1], []], [[2, 0], []]]
1157
+
1158
+ """
1159
+ F, H = dmp_to_dict(f, u), {}
1160
+
1161
+ for exp, coeff in F.items():
1162
+ new_exp = [0]*len(exp)
1163
+
1164
+ for e, p in zip(exp, P):
1165
+ new_exp[p] = e
1166
+
1167
+ H[tuple(new_exp)] = coeff
1168
+
1169
+ return dmp_from_dict(H, u, K)
1170
+
1171
+
1172
+ def dmp_nest(f, l, K):
1173
+ """
1174
+ Return a multivariate value nested ``l``-levels.
1175
+
1176
+ Examples
1177
+ ========
1178
+
1179
+ >>> from sympy.polys.domains import ZZ
1180
+ >>> from sympy.polys.densebasic import dmp_nest
1181
+
1182
+ >>> dmp_nest([[ZZ(1)]], 2, ZZ)
1183
+ [[[[1]]]]
1184
+
1185
+ """
1186
+ if not isinstance(f, list):
1187
+ return dmp_ground(f, l)
1188
+
1189
+ for i in range(l):
1190
+ f = [f]
1191
+
1192
+ return f
1193
+
1194
+
1195
+ def dmp_raise(f, l, u, K):
1196
+ """
1197
+ Return a multivariate polynomial raised ``l``-levels.
1198
+
1199
+ Examples
1200
+ ========
1201
+
1202
+ >>> from sympy.polys.domains import ZZ
1203
+ >>> from sympy.polys.densebasic import dmp_raise
1204
+
1205
+ >>> f = ZZ.map([[], [1, 2]])
1206
+
1207
+ >>> dmp_raise(f, 2, 1, ZZ)
1208
+ [[[[]]], [[[1]], [[2]]]]
1209
+
1210
+ """
1211
+ if not l:
1212
+ return f
1213
+
1214
+ if not u:
1215
+ if not f:
1216
+ return dmp_zero(l)
1217
+
1218
+ k = l - 1
1219
+
1220
+ return [ dmp_ground(c, k) for c in f ]
1221
+
1222
+ v = u - 1
1223
+
1224
+ return [ dmp_raise(c, l, v, K) for c in f ]
1225
+
1226
+
1227
+ def dup_deflate(f, K):
1228
+ """
1229
+ Map ``x**m`` to ``y`` in a polynomial in ``K[x]``.
1230
+
1231
+ Examples
1232
+ ========
1233
+
1234
+ >>> from sympy.polys.domains import ZZ
1235
+ >>> from sympy.polys.densebasic import dup_deflate
1236
+
1237
+ >>> f = ZZ.map([1, 0, 0, 1, 0, 0, 1])
1238
+
1239
+ >>> dup_deflate(f, ZZ)
1240
+ (3, [1, 1, 1])
1241
+
1242
+ """
1243
+ if dup_degree(f) <= 0:
1244
+ return 1, f
1245
+
1246
+ g = 0
1247
+
1248
+ for i in range(len(f)):
1249
+ if not f[-i - 1]:
1250
+ continue
1251
+
1252
+ g = igcd(g, i)
1253
+
1254
+ if g == 1:
1255
+ return 1, f
1256
+
1257
+ return g, f[::g]
1258
+
1259
+
1260
+ def dmp_deflate(f, u, K):
1261
+ """
1262
+ Map ``x_i**m_i`` to ``y_i`` in a polynomial in ``K[X]``.
1263
+
1264
+ Examples
1265
+ ========
1266
+
1267
+ >>> from sympy.polys.domains import ZZ
1268
+ >>> from sympy.polys.densebasic import dmp_deflate
1269
+
1270
+ >>> f = ZZ.map([[1, 0, 0, 2], [], [3, 0, 0, 4]])
1271
+
1272
+ >>> dmp_deflate(f, 1, ZZ)
1273
+ ((2, 3), [[1, 2], [3, 4]])
1274
+
1275
+ """
1276
+ if dmp_zero_p(f, u):
1277
+ return (1,)*(u + 1), f
1278
+
1279
+ F = dmp_to_dict(f, u)
1280
+ B = [0]*(u + 1)
1281
+
1282
+ for M in F.keys():
1283
+ for i, m in enumerate(M):
1284
+ B[i] = igcd(B[i], m)
1285
+
1286
+ for i, b in enumerate(B):
1287
+ if not b:
1288
+ B[i] = 1
1289
+
1290
+ B = tuple(B)
1291
+
1292
+ if all(b == 1 for b in B):
1293
+ return B, f
1294
+
1295
+ H = {}
1296
+
1297
+ for A, coeff in F.items():
1298
+ N = [ a // b for a, b in zip(A, B) ]
1299
+ H[tuple(N)] = coeff
1300
+
1301
+ return B, dmp_from_dict(H, u, K)
1302
+
1303
+
1304
+ def dup_multi_deflate(polys, K):
1305
+ """
1306
+ Map ``x**m`` to ``y`` in a set of polynomials in ``K[x]``.
1307
+
1308
+ Examples
1309
+ ========
1310
+
1311
+ >>> from sympy.polys.domains import ZZ
1312
+ >>> from sympy.polys.densebasic import dup_multi_deflate
1313
+
1314
+ >>> f = ZZ.map([1, 0, 2, 0, 3])
1315
+ >>> g = ZZ.map([4, 0, 0])
1316
+
1317
+ >>> dup_multi_deflate((f, g), ZZ)
1318
+ (2, ([1, 2, 3], [4, 0]))
1319
+
1320
+ """
1321
+ G = 0
1322
+
1323
+ for p in polys:
1324
+ if dup_degree(p) <= 0:
1325
+ return 1, polys
1326
+
1327
+ g = 0
1328
+
1329
+ for i in range(len(p)):
1330
+ if not p[-i - 1]:
1331
+ continue
1332
+
1333
+ g = igcd(g, i)
1334
+
1335
+ if g == 1:
1336
+ return 1, polys
1337
+
1338
+ G = igcd(G, g)
1339
+
1340
+ return G, tuple([ p[::G] for p in polys ])
1341
+
1342
+
1343
+ def dmp_multi_deflate(polys, u, K):
1344
+ """
1345
+ Map ``x_i**m_i`` to ``y_i`` in a set of polynomials in ``K[X]``.
1346
+
1347
+ Examples
1348
+ ========
1349
+
1350
+ >>> from sympy.polys.domains import ZZ
1351
+ >>> from sympy.polys.densebasic import dmp_multi_deflate
1352
+
1353
+ >>> f = ZZ.map([[1, 0, 0, 2], [], [3, 0, 0, 4]])
1354
+ >>> g = ZZ.map([[1, 0, 2], [], [3, 0, 4]])
1355
+
1356
+ >>> dmp_multi_deflate((f, g), 1, ZZ)
1357
+ ((2, 1), ([[1, 0, 0, 2], [3, 0, 0, 4]], [[1, 0, 2], [3, 0, 4]]))
1358
+
1359
+ """
1360
+ if not u:
1361
+ M, H = dup_multi_deflate(polys, K)
1362
+ return (M,), H
1363
+
1364
+ F, B = [], [0]*(u + 1)
1365
+
1366
+ for p in polys:
1367
+ f = dmp_to_dict(p, u)
1368
+
1369
+ if not dmp_zero_p(p, u):
1370
+ for M in f.keys():
1371
+ for i, m in enumerate(M):
1372
+ B[i] = igcd(B[i], m)
1373
+
1374
+ F.append(f)
1375
+
1376
+ for i, b in enumerate(B):
1377
+ if not b:
1378
+ B[i] = 1
1379
+
1380
+ B = tuple(B)
1381
+
1382
+ if all(b == 1 for b in B):
1383
+ return B, polys
1384
+
1385
+ H = []
1386
+
1387
+ for f in F:
1388
+ h = {}
1389
+
1390
+ for A, coeff in f.items():
1391
+ N = [ a // b for a, b in zip(A, B) ]
1392
+ h[tuple(N)] = coeff
1393
+
1394
+ H.append(dmp_from_dict(h, u, K))
1395
+
1396
+ return B, tuple(H)
1397
+
1398
+
1399
+ def dup_inflate(f, m, K):
1400
+ """
1401
+ Map ``y`` to ``x**m`` in a polynomial in ``K[x]``.
1402
+
1403
+ Examples
1404
+ ========
1405
+
1406
+ >>> from sympy.polys.domains import ZZ
1407
+ >>> from sympy.polys.densebasic import dup_inflate
1408
+
1409
+ >>> f = ZZ.map([1, 1, 1])
1410
+
1411
+ >>> dup_inflate(f, 3, ZZ)
1412
+ [1, 0, 0, 1, 0, 0, 1]
1413
+
1414
+ """
1415
+ if m <= 0:
1416
+ raise IndexError("'m' must be positive, got %s" % m)
1417
+ if m == 1 or not f:
1418
+ return f
1419
+
1420
+ result = [f[0]]
1421
+
1422
+ for coeff in f[1:]:
1423
+ result.extend([K.zero]*(m - 1))
1424
+ result.append(coeff)
1425
+
1426
+ return result
1427
+
1428
+
1429
+ def _rec_inflate(g, M, v, i, K):
1430
+ """Recursive helper for :func:`dmp_inflate`."""
1431
+ if not v:
1432
+ return dup_inflate(g, M[i], K)
1433
+ if M[i] <= 0:
1434
+ raise IndexError("all M[i] must be positive, got %s" % M[i])
1435
+
1436
+ w, j = v - 1, i + 1
1437
+
1438
+ g = [ _rec_inflate(c, M, w, j, K) for c in g ]
1439
+
1440
+ result = [g[0]]
1441
+
1442
+ for coeff in g[1:]:
1443
+ for _ in range(1, M[i]):
1444
+ result.append(dmp_zero(w))
1445
+
1446
+ result.append(coeff)
1447
+
1448
+ return result
1449
+
1450
+
1451
+ def dmp_inflate(f, M, u, K):
1452
+ """
1453
+ Map ``y_i`` to ``x_i**k_i`` in a polynomial in ``K[X]``.
1454
+
1455
+ Examples
1456
+ ========
1457
+
1458
+ >>> from sympy.polys.domains import ZZ
1459
+ >>> from sympy.polys.densebasic import dmp_inflate
1460
+
1461
+ >>> f = ZZ.map([[1, 2], [3, 4]])
1462
+
1463
+ >>> dmp_inflate(f, (2, 3), 1, ZZ)
1464
+ [[1, 0, 0, 2], [], [3, 0, 0, 4]]
1465
+
1466
+ """
1467
+ if not u:
1468
+ return dup_inflate(f, M[0], K)
1469
+
1470
+ if all(m == 1 for m in M):
1471
+ return f
1472
+ else:
1473
+ return _rec_inflate(f, M, u, 0, K)
1474
+
1475
+
1476
+ def dmp_exclude(f, u, K):
1477
+ """
1478
+ Exclude useless levels from ``f``.
1479
+
1480
+ Return the levels excluded, the new excluded ``f``, and the new ``u``.
1481
+
1482
+ Examples
1483
+ ========
1484
+
1485
+ >>> from sympy.polys.domains import ZZ
1486
+ >>> from sympy.polys.densebasic import dmp_exclude
1487
+
1488
+ >>> f = ZZ.map([[[1]], [[1], [2]]])
1489
+
1490
+ >>> dmp_exclude(f, 2, ZZ)
1491
+ ([2], [[1], [1, 2]], 1)
1492
+
1493
+ """
1494
+ if not u or dmp_ground_p(f, None, u):
1495
+ return [], f, u
1496
+
1497
+ J, F = [], dmp_to_dict(f, u)
1498
+
1499
+ for j in range(0, u + 1):
1500
+ for monom in F.keys():
1501
+ if monom[j]:
1502
+ break
1503
+ else:
1504
+ J.append(j)
1505
+
1506
+ if not J:
1507
+ return [], f, u
1508
+
1509
+ f = {}
1510
+
1511
+ for monom, coeff in F.items():
1512
+ monom = list(monom)
1513
+
1514
+ for j in reversed(J):
1515
+ del monom[j]
1516
+
1517
+ f[tuple(monom)] = coeff
1518
+
1519
+ u -= len(J)
1520
+
1521
+ return J, dmp_from_dict(f, u, K), u
1522
+
1523
+
1524
+ def dmp_include(f, J, u, K):
1525
+ """
1526
+ Include useless levels in ``f``.
1527
+
1528
+ Examples
1529
+ ========
1530
+
1531
+ >>> from sympy.polys.domains import ZZ
1532
+ >>> from sympy.polys.densebasic import dmp_include
1533
+
1534
+ >>> f = ZZ.map([[1], [1, 2]])
1535
+
1536
+ >>> dmp_include(f, [2], 1, ZZ)
1537
+ [[[1]], [[1], [2]]]
1538
+
1539
+ """
1540
+ if not J:
1541
+ return f
1542
+
1543
+ F, f = dmp_to_dict(f, u), {}
1544
+
1545
+ for monom, coeff in F.items():
1546
+ monom = list(monom)
1547
+
1548
+ for j in J:
1549
+ monom.insert(j, 0)
1550
+
1551
+ f[tuple(monom)] = coeff
1552
+
1553
+ u += len(J)
1554
+
1555
+ return dmp_from_dict(f, u, K)
1556
+
1557
+
1558
+ def dmp_inject(f, u, K, front=False):
1559
+ """
1560
+ Convert ``f`` from ``K[X][Y]`` to ``K[X,Y]``.
1561
+
1562
+ Examples
1563
+ ========
1564
+
1565
+ >>> from sympy.polys.rings import ring
1566
+ >>> from sympy.polys.domains import ZZ
1567
+ >>> from sympy.polys.densebasic import dmp_inject
1568
+
1569
+ >>> R, x,y = ring("x,y", ZZ)
1570
+
1571
+ >>> dmp_inject([R(1), x + 2], 0, R.to_domain())
1572
+ ([[[1]], [[1], [2]]], 2)
1573
+ >>> dmp_inject([R(1), x + 2], 0, R.to_domain(), front=True)
1574
+ ([[[1]], [[1, 2]]], 2)
1575
+
1576
+ """
1577
+ f, h = dmp_to_dict(f, u), {}
1578
+
1579
+ v = K.ngens - 1
1580
+
1581
+ for f_monom, g in f.items():
1582
+ g = g.to_dict()
1583
+
1584
+ for g_monom, c in g.items():
1585
+ if front:
1586
+ h[g_monom + f_monom] = c
1587
+ else:
1588
+ h[f_monom + g_monom] = c
1589
+
1590
+ w = u + v + 1
1591
+
1592
+ return dmp_from_dict(h, w, K.dom), w
1593
+
1594
+
1595
+ def dmp_eject(f, u, K, front=False):
1596
+ """
1597
+ Convert ``f`` from ``K[X,Y]`` to ``K[X][Y]``.
1598
+
1599
+ Examples
1600
+ ========
1601
+
1602
+ >>> from sympy.polys.domains import ZZ
1603
+ >>> from sympy.polys.densebasic import dmp_eject
1604
+
1605
+ >>> dmp_eject([[[1]], [[1], [2]]], 2, ZZ['x', 'y'])
1606
+ [1, x + 2]
1607
+
1608
+ """
1609
+ f, h = dmp_to_dict(f, u), {}
1610
+
1611
+ n = K.ngens
1612
+ v = u - K.ngens + 1
1613
+
1614
+ for monom, c in f.items():
1615
+ if front:
1616
+ g_monom, f_monom = monom[:n], monom[n:]
1617
+ else:
1618
+ g_monom, f_monom = monom[-n:], monom[:-n]
1619
+
1620
+ if f_monom in h:
1621
+ h[f_monom][g_monom] = c
1622
+ else:
1623
+ h[f_monom] = {g_monom: c}
1624
+
1625
+ for monom, c in h.items():
1626
+ h[monom] = K(c)
1627
+
1628
+ return dmp_from_dict(h, v - 1, K)
1629
+
1630
+
1631
+ def dup_terms_gcd(f, K):
1632
+ """
1633
+ Remove GCD of terms from ``f`` in ``K[x]``.
1634
+
1635
+ Examples
1636
+ ========
1637
+
1638
+ >>> from sympy.polys.domains import ZZ
1639
+ >>> from sympy.polys.densebasic import dup_terms_gcd
1640
+
1641
+ >>> f = ZZ.map([1, 0, 1, 0, 0])
1642
+
1643
+ >>> dup_terms_gcd(f, ZZ)
1644
+ (2, [1, 0, 1])
1645
+
1646
+ """
1647
+ if dup_TC(f, K) or not f:
1648
+ return 0, f
1649
+
1650
+ i = 0
1651
+
1652
+ for c in reversed(f):
1653
+ if not c:
1654
+ i += 1
1655
+ else:
1656
+ break
1657
+
1658
+ return i, f[:-i]
1659
+
1660
+
1661
+ def dmp_terms_gcd(f, u, K):
1662
+ """
1663
+ Remove GCD of terms from ``f`` in ``K[X]``.
1664
+
1665
+ Examples
1666
+ ========
1667
+
1668
+ >>> from sympy.polys.domains import ZZ
1669
+ >>> from sympy.polys.densebasic import dmp_terms_gcd
1670
+
1671
+ >>> f = ZZ.map([[1, 0], [1, 0, 0], [], []])
1672
+
1673
+ >>> dmp_terms_gcd(f, 1, ZZ)
1674
+ ((2, 1), [[1], [1, 0]])
1675
+
1676
+ """
1677
+ if dmp_ground_TC(f, u, K) or dmp_zero_p(f, u):
1678
+ return (0,)*(u + 1), f
1679
+
1680
+ F = dmp_to_dict(f, u)
1681
+ G = monomial_min(*list(F.keys()))
1682
+
1683
+ if all(g == 0 for g in G):
1684
+ return G, f
1685
+
1686
+ f = {}
1687
+
1688
+ for monom, coeff in F.items():
1689
+ f[monomial_div(monom, G)] = coeff
1690
+
1691
+ return G, dmp_from_dict(f, u, K)
1692
+
1693
+
1694
+ def _rec_list_terms(g, v, monom):
1695
+ """Recursive helper for :func:`dmp_list_terms`."""
1696
+ d, terms = dmp_degree(g, v), []
1697
+
1698
+ if not v:
1699
+ for i, c in enumerate(g):
1700
+ if not c:
1701
+ continue
1702
+
1703
+ terms.append((monom + (d - i,), c))
1704
+ else:
1705
+ w = v - 1
1706
+
1707
+ for i, c in enumerate(g):
1708
+ terms.extend(_rec_list_terms(c, w, monom + (d - i,)))
1709
+
1710
+ return terms
1711
+
1712
+
1713
+ def dmp_list_terms(f, u, K, order=None):
1714
+ """
1715
+ List all non-zero terms from ``f`` in the given order ``order``.
1716
+
1717
+ Examples
1718
+ ========
1719
+
1720
+ >>> from sympy.polys.domains import ZZ
1721
+ >>> from sympy.polys.densebasic import dmp_list_terms
1722
+
1723
+ >>> f = ZZ.map([[1, 1], [2, 3]])
1724
+
1725
+ >>> dmp_list_terms(f, 1, ZZ)
1726
+ [((1, 1), 1), ((1, 0), 1), ((0, 1), 2), ((0, 0), 3)]
1727
+ >>> dmp_list_terms(f, 1, ZZ, order='grevlex')
1728
+ [((1, 1), 1), ((1, 0), 1), ((0, 1), 2), ((0, 0), 3)]
1729
+
1730
+ """
1731
+ def sort(terms, O):
1732
+ return sorted(terms, key=lambda term: O(term[0]), reverse=True)
1733
+
1734
+ terms = _rec_list_terms(f, u, ())
1735
+
1736
+ if not terms:
1737
+ return [((0,)*(u + 1), K.zero)]
1738
+
1739
+ if order is None:
1740
+ return terms
1741
+ else:
1742
+ return sort(terms, monomial_key(order))
1743
+
1744
+
1745
+ def dup_apply_pairs(f, g, h, args, K):
1746
+ """
1747
+ Apply ``h`` to pairs of coefficients of ``f`` and ``g``.
1748
+
1749
+ Examples
1750
+ ========
1751
+
1752
+ >>> from sympy.polys.domains import ZZ
1753
+ >>> from sympy.polys.densebasic import dup_apply_pairs
1754
+
1755
+ >>> h = lambda x, y, z: 2*x + y - z
1756
+
1757
+ >>> dup_apply_pairs([1, 2, 3], [3, 2, 1], h, (1,), ZZ)
1758
+ [4, 5, 6]
1759
+
1760
+ """
1761
+ n, m = len(f), len(g)
1762
+
1763
+ if n != m:
1764
+ if n > m:
1765
+ g = [K.zero]*(n - m) + g
1766
+ else:
1767
+ f = [K.zero]*(m - n) + f
1768
+
1769
+ result = []
1770
+
1771
+ for a, b in zip(f, g):
1772
+ result.append(h(a, b, *args))
1773
+
1774
+ return dup_strip(result)
1775
+
1776
+
1777
+ def dmp_apply_pairs(f, g, h, args, u, K):
1778
+ """
1779
+ Apply ``h`` to pairs of coefficients of ``f`` and ``g``.
1780
+
1781
+ Examples
1782
+ ========
1783
+
1784
+ >>> from sympy.polys.domains import ZZ
1785
+ >>> from sympy.polys.densebasic import dmp_apply_pairs
1786
+
1787
+ >>> h = lambda x, y, z: 2*x + y - z
1788
+
1789
+ >>> dmp_apply_pairs([[1], [2, 3]], [[3], [2, 1]], h, (1,), 1, ZZ)
1790
+ [[4], [5, 6]]
1791
+
1792
+ """
1793
+ if not u:
1794
+ return dup_apply_pairs(f, g, h, args, K)
1795
+
1796
+ n, m, v = len(f), len(g), u - 1
1797
+
1798
+ if n != m:
1799
+ if n > m:
1800
+ g = dmp_zeros(n - m, v, K) + g
1801
+ else:
1802
+ f = dmp_zeros(m - n, v, K) + f
1803
+
1804
+ result = []
1805
+
1806
+ for a, b in zip(f, g):
1807
+ result.append(dmp_apply_pairs(a, b, h, args, v, K))
1808
+
1809
+ return dmp_strip(result, u)
1810
+
1811
+
1812
+ def dup_slice(f, m, n, K):
1813
+ """Take a continuous subsequence of terms of ``f`` in ``K[x]``. """
1814
+ k = len(f)
1815
+
1816
+ if k >= m:
1817
+ M = k - m
1818
+ else:
1819
+ M = 0
1820
+ if k >= n:
1821
+ N = k - n
1822
+ else:
1823
+ N = 0
1824
+
1825
+ f = f[N:M]
1826
+
1827
+ if not f:
1828
+ return []
1829
+ else:
1830
+ return f + [K.zero]*m
1831
+
1832
+
1833
+ def dmp_slice(f, m, n, u, K):
1834
+ """Take a continuous subsequence of terms of ``f`` in ``K[X]``. """
1835
+ return dmp_slice_in(f, m, n, 0, u, K)
1836
+
1837
+
1838
+ def dmp_slice_in(f, m, n, j, u, K):
1839
+ """Take a continuous subsequence of terms of ``f`` in ``x_j`` in ``K[X]``. """
1840
+ if j < 0 or j > u:
1841
+ raise IndexError("-%s <= j < %s expected, got %s" % (u, u, j))
1842
+
1843
+ if not u:
1844
+ return dup_slice(f, m, n, K)
1845
+
1846
+ f, g = dmp_to_dict(f, u), {}
1847
+
1848
+ for monom, coeff in f.items():
1849
+ k = monom[j]
1850
+
1851
+ if k < m or k >= n:
1852
+ monom = monom[:j] + (0,) + monom[j + 1:]
1853
+
1854
+ if monom in g:
1855
+ g[monom] += coeff
1856
+ else:
1857
+ g[monom] = coeff
1858
+
1859
+ return dmp_from_dict(g, u, K)
1860
+
1861
+
1862
+ def dup_random(n, a, b, K):
1863
+ """
1864
+ Return a polynomial of degree ``n`` with coefficients in ``[a, b]``.
1865
+
1866
+ Examples
1867
+ ========
1868
+
1869
+ >>> from sympy.polys.domains import ZZ
1870
+ >>> from sympy.polys.densebasic import dup_random
1871
+
1872
+ >>> dup_random(3, -10, 10, ZZ) #doctest: +SKIP
1873
+ [-2, -8, 9, -4]
1874
+
1875
+ """
1876
+ f = [ K.convert(random.randint(a, b)) for _ in range(0, n + 1) ]
1877
+
1878
+ while not f[0]:
1879
+ f[0] = K.convert(random.randint(a, b))
1880
+
1881
+ return f
llmeval-env/lib/python3.10/site-packages/sympy/polys/densetools.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Advanced tools for dense recursive polynomials in ``K[x]`` or ``K[X]``. """
2
+
3
+
4
+ from sympy.polys.densearith import (
5
+ dup_add_term, dmp_add_term,
6
+ dup_lshift,
7
+ dup_add, dmp_add,
8
+ dup_sub, dmp_sub,
9
+ dup_mul, dmp_mul,
10
+ dup_sqr,
11
+ dup_div,
12
+ dup_rem, dmp_rem,
13
+ dmp_expand,
14
+ dup_mul_ground, dmp_mul_ground,
15
+ dup_quo_ground, dmp_quo_ground,
16
+ dup_exquo_ground, dmp_exquo_ground,
17
+ )
18
+ from sympy.polys.densebasic import (
19
+ dup_strip, dmp_strip,
20
+ dup_convert, dmp_convert,
21
+ dup_degree, dmp_degree,
22
+ dmp_to_dict,
23
+ dmp_from_dict,
24
+ dup_LC, dmp_LC, dmp_ground_LC,
25
+ dup_TC, dmp_TC,
26
+ dmp_zero, dmp_ground,
27
+ dmp_zero_p,
28
+ dup_to_raw_dict, dup_from_raw_dict,
29
+ dmp_zeros
30
+ )
31
+ from sympy.polys.polyerrors import (
32
+ MultivariatePolynomialError,
33
+ DomainError
34
+ )
35
+ from sympy.utilities import variations
36
+
37
+ from math import ceil as _ceil, log as _log
38
+
39
+ def dup_integrate(f, m, K):
40
+ """
41
+ Computes the indefinite integral of ``f`` in ``K[x]``.
42
+
43
+ Examples
44
+ ========
45
+
46
+ >>> from sympy.polys import ring, QQ
47
+ >>> R, x = ring("x", QQ)
48
+
49
+ >>> R.dup_integrate(x**2 + 2*x, 1)
50
+ 1/3*x**3 + x**2
51
+ >>> R.dup_integrate(x**2 + 2*x, 2)
52
+ 1/12*x**4 + 1/3*x**3
53
+
54
+ """
55
+ if m <= 0 or not f:
56
+ return f
57
+
58
+ g = [K.zero]*m
59
+
60
+ for i, c in enumerate(reversed(f)):
61
+ n = i + 1
62
+
63
+ for j in range(1, m):
64
+ n *= i + j + 1
65
+
66
+ g.insert(0, K.exquo(c, K(n)))
67
+
68
+ return g
69
+
70
+
71
+ def dmp_integrate(f, m, u, K):
72
+ """
73
+ Computes the indefinite integral of ``f`` in ``x_0`` in ``K[X]``.
74
+
75
+ Examples
76
+ ========
77
+
78
+ >>> from sympy.polys import ring, QQ
79
+ >>> R, x,y = ring("x,y", QQ)
80
+
81
+ >>> R.dmp_integrate(x + 2*y, 1)
82
+ 1/2*x**2 + 2*x*y
83
+ >>> R.dmp_integrate(x + 2*y, 2)
84
+ 1/6*x**3 + x**2*y
85
+
86
+ """
87
+ if not u:
88
+ return dup_integrate(f, m, K)
89
+
90
+ if m <= 0 or dmp_zero_p(f, u):
91
+ return f
92
+
93
+ g, v = dmp_zeros(m, u - 1, K), u - 1
94
+
95
+ for i, c in enumerate(reversed(f)):
96
+ n = i + 1
97
+
98
+ for j in range(1, m):
99
+ n *= i + j + 1
100
+
101
+ g.insert(0, dmp_quo_ground(c, K(n), v, K))
102
+
103
+ return g
104
+
105
+
106
+ def _rec_integrate_in(g, m, v, i, j, K):
107
+ """Recursive helper for :func:`dmp_integrate_in`."""
108
+ if i == j:
109
+ return dmp_integrate(g, m, v, K)
110
+
111
+ w, i = v - 1, i + 1
112
+
113
+ return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c in g ], v)
114
+
115
+
116
+ def dmp_integrate_in(f, m, j, u, K):
117
+ """
118
+ Computes the indefinite integral of ``f`` in ``x_j`` in ``K[X]``.
119
+
120
+ Examples
121
+ ========
122
+
123
+ >>> from sympy.polys import ring, QQ
124
+ >>> R, x,y = ring("x,y", QQ)
125
+
126
+ >>> R.dmp_integrate_in(x + 2*y, 1, 0)
127
+ 1/2*x**2 + 2*x*y
128
+ >>> R.dmp_integrate_in(x + 2*y, 1, 1)
129
+ x*y + y**2
130
+
131
+ """
132
+ if j < 0 or j > u:
133
+ raise IndexError("0 <= j <= u expected, got u = %d, j = %d" % (u, j))
134
+
135
+ return _rec_integrate_in(f, m, u, 0, j, K)
136
+
137
+
138
+ def dup_diff(f, m, K):
139
+ """
140
+ ``m``-th order derivative of a polynomial in ``K[x]``.
141
+
142
+ Examples
143
+ ========
144
+
145
+ >>> from sympy.polys import ring, ZZ
146
+ >>> R, x = ring("x", ZZ)
147
+
148
+ >>> R.dup_diff(x**3 + 2*x**2 + 3*x + 4, 1)
149
+ 3*x**2 + 4*x + 3
150
+ >>> R.dup_diff(x**3 + 2*x**2 + 3*x + 4, 2)
151
+ 6*x + 4
152
+
153
+ """
154
+ if m <= 0:
155
+ return f
156
+
157
+ n = dup_degree(f)
158
+
159
+ if n < m:
160
+ return []
161
+
162
+ deriv = []
163
+
164
+ if m == 1:
165
+ for coeff in f[:-m]:
166
+ deriv.append(K(n)*coeff)
167
+ n -= 1
168
+ else:
169
+ for coeff in f[:-m]:
170
+ k = n
171
+
172
+ for i in range(n - 1, n - m, -1):
173
+ k *= i
174
+
175
+ deriv.append(K(k)*coeff)
176
+ n -= 1
177
+
178
+ return dup_strip(deriv)
179
+
180
+
181
+ def dmp_diff(f, m, u, K):
182
+ """
183
+ ``m``-th order derivative in ``x_0`` of a polynomial in ``K[X]``.
184
+
185
+ Examples
186
+ ========
187
+
188
+ >>> from sympy.polys import ring, ZZ
189
+ >>> R, x,y = ring("x,y", ZZ)
190
+
191
+ >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1
192
+
193
+ >>> R.dmp_diff(f, 1)
194
+ y**2 + 2*y + 3
195
+ >>> R.dmp_diff(f, 2)
196
+ 0
197
+
198
+ """
199
+ if not u:
200
+ return dup_diff(f, m, K)
201
+ if m <= 0:
202
+ return f
203
+
204
+ n = dmp_degree(f, u)
205
+
206
+ if n < m:
207
+ return dmp_zero(u)
208
+
209
+ deriv, v = [], u - 1
210
+
211
+ if m == 1:
212
+ for coeff in f[:-m]:
213
+ deriv.append(dmp_mul_ground(coeff, K(n), v, K))
214
+ n -= 1
215
+ else:
216
+ for coeff in f[:-m]:
217
+ k = n
218
+
219
+ for i in range(n - 1, n - m, -1):
220
+ k *= i
221
+
222
+ deriv.append(dmp_mul_ground(coeff, K(k), v, K))
223
+ n -= 1
224
+
225
+ return dmp_strip(deriv, u)
226
+
227
+
228
+ def _rec_diff_in(g, m, v, i, j, K):
229
+ """Recursive helper for :func:`dmp_diff_in`."""
230
+ if i == j:
231
+ return dmp_diff(g, m, v, K)
232
+
233
+ w, i = v - 1, i + 1
234
+
235
+ return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c in g ], v)
236
+
237
+
238
+ def dmp_diff_in(f, m, j, u, K):
239
+ """
240
+ ``m``-th order derivative in ``x_j`` of a polynomial in ``K[X]``.
241
+
242
+ Examples
243
+ ========
244
+
245
+ >>> from sympy.polys import ring, ZZ
246
+ >>> R, x,y = ring("x,y", ZZ)
247
+
248
+ >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1
249
+
250
+ >>> R.dmp_diff_in(f, 1, 0)
251
+ y**2 + 2*y + 3
252
+ >>> R.dmp_diff_in(f, 1, 1)
253
+ 2*x*y + 2*x + 4*y + 3
254
+
255
+ """
256
+ if j < 0 or j > u:
257
+ raise IndexError("0 <= j <= %s expected, got %s" % (u, j))
258
+
259
+ return _rec_diff_in(f, m, u, 0, j, K)
260
+
261
+
262
+ def dup_eval(f, a, K):
263
+ """
264
+ Evaluate a polynomial at ``x = a`` in ``K[x]`` using Horner scheme.
265
+
266
+ Examples
267
+ ========
268
+
269
+ >>> from sympy.polys import ring, ZZ
270
+ >>> R, x = ring("x", ZZ)
271
+
272
+ >>> R.dup_eval(x**2 + 2*x + 3, 2)
273
+ 11
274
+
275
+ """
276
+ if not a:
277
+ return K.convert(dup_TC(f, K))
278
+
279
+ result = K.zero
280
+
281
+ for c in f:
282
+ result *= a
283
+ result += c
284
+
285
+ return result
286
+
287
+
288
+ def dmp_eval(f, a, u, K):
289
+ """
290
+ Evaluate a polynomial at ``x_0 = a`` in ``K[X]`` using the Horner scheme.
291
+
292
+ Examples
293
+ ========
294
+
295
+ >>> from sympy.polys import ring, ZZ
296
+ >>> R, x,y = ring("x,y", ZZ)
297
+
298
+ >>> R.dmp_eval(2*x*y + 3*x + y + 2, 2)
299
+ 5*y + 8
300
+
301
+ """
302
+ if not u:
303
+ return dup_eval(f, a, K)
304
+
305
+ if not a:
306
+ return dmp_TC(f, K)
307
+
308
+ result, v = dmp_LC(f, K), u - 1
309
+
310
+ for coeff in f[1:]:
311
+ result = dmp_mul_ground(result, a, v, K)
312
+ result = dmp_add(result, coeff, v, K)
313
+
314
+ return result
315
+
316
+
317
+ def _rec_eval_in(g, a, v, i, j, K):
318
+ """Recursive helper for :func:`dmp_eval_in`."""
319
+ if i == j:
320
+ return dmp_eval(g, a, v, K)
321
+
322
+ v, i = v - 1, i + 1
323
+
324
+ return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ], v)
325
+
326
+
327
+ def dmp_eval_in(f, a, j, u, K):
328
+ """
329
+ Evaluate a polynomial at ``x_j = a`` in ``K[X]`` using the Horner scheme.
330
+
331
+ Examples
332
+ ========
333
+
334
+ >>> from sympy.polys import ring, ZZ
335
+ >>> R, x,y = ring("x,y", ZZ)
336
+
337
+ >>> f = 2*x*y + 3*x + y + 2
338
+
339
+ >>> R.dmp_eval_in(f, 2, 0)
340
+ 5*y + 8
341
+ >>> R.dmp_eval_in(f, 2, 1)
342
+ 7*x + 4
343
+
344
+ """
345
+ if j < 0 or j > u:
346
+ raise IndexError("0 <= j <= %s expected, got %s" % (u, j))
347
+
348
+ return _rec_eval_in(f, a, u, 0, j, K)
349
+
350
+
351
+ def _rec_eval_tail(g, i, A, u, K):
352
+ """Recursive helper for :func:`dmp_eval_tail`."""
353
+ if i == u:
354
+ return dup_eval(g, A[-1], K)
355
+ else:
356
+ h = [ _rec_eval_tail(c, i + 1, A, u, K) for c in g ]
357
+
358
+ if i < u - len(A) + 1:
359
+ return h
360
+ else:
361
+ return dup_eval(h, A[-u + i - 1], K)
362
+
363
+
364
+ def dmp_eval_tail(f, A, u, K):
365
+ """
366
+ Evaluate a polynomial at ``x_j = a_j, ...`` in ``K[X]``.
367
+
368
+ Examples
369
+ ========
370
+
371
+ >>> from sympy.polys import ring, ZZ
372
+ >>> R, x,y = ring("x,y", ZZ)
373
+
374
+ >>> f = 2*x*y + 3*x + y + 2
375
+
376
+ >>> R.dmp_eval_tail(f, [2])
377
+ 7*x + 4
378
+ >>> R.dmp_eval_tail(f, [2, 2])
379
+ 18
380
+
381
+ """
382
+ if not A:
383
+ return f
384
+
385
+ if dmp_zero_p(f, u):
386
+ return dmp_zero(u - len(A))
387
+
388
+ e = _rec_eval_tail(f, 0, A, u, K)
389
+
390
+ if u == len(A) - 1:
391
+ return e
392
+ else:
393
+ return dmp_strip(e, u - len(A))
394
+
395
+
396
+ def _rec_diff_eval(g, m, a, v, i, j, K):
397
+ """Recursive helper for :func:`dmp_diff_eval`."""
398
+ if i == j:
399
+ return dmp_eval(dmp_diff(g, m, v, K), a, v, K)
400
+
401
+ v, i = v - 1, i + 1
402
+
403
+ return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in g ], v)
404
+
405
+
406
+ def dmp_diff_eval_in(f, m, a, j, u, K):
407
+ """
408
+ Differentiate and evaluate a polynomial in ``x_j`` at ``a`` in ``K[X]``.
409
+
410
+ Examples
411
+ ========
412
+
413
+ >>> from sympy.polys import ring, ZZ
414
+ >>> R, x,y = ring("x,y", ZZ)
415
+
416
+ >>> f = x*y**2 + 2*x*y + 3*x + 2*y**2 + 3*y + 1
417
+
418
+ >>> R.dmp_diff_eval_in(f, 1, 2, 0)
419
+ y**2 + 2*y + 3
420
+ >>> R.dmp_diff_eval_in(f, 1, 2, 1)
421
+ 6*x + 11
422
+
423
+ """
424
+ if j > u:
425
+ raise IndexError("-%s <= j < %s expected, got %s" % (u, u, j))
426
+ if not j:
427
+ return dmp_eval(dmp_diff(f, m, u, K), a, u, K)
428
+
429
+ return _rec_diff_eval(f, m, a, u, 0, j, K)
430
+
431
+
432
+ def dup_trunc(f, p, K):
433
+ """
434
+ Reduce a ``K[x]`` polynomial modulo a constant ``p`` in ``K``.
435
+
436
+ Examples
437
+ ========
438
+
439
+ >>> from sympy.polys import ring, ZZ
440
+ >>> R, x = ring("x", ZZ)
441
+
442
+ >>> R.dup_trunc(2*x**3 + 3*x**2 + 5*x + 7, ZZ(3))
443
+ -x**3 - x + 1
444
+
445
+ """
446
+ if K.is_ZZ:
447
+ g = []
448
+
449
+ for c in f:
450
+ c = c % p
451
+
452
+ if c > p // 2:
453
+ g.append(c - p)
454
+ else:
455
+ g.append(c)
456
+ else:
457
+ g = [ c % p for c in f ]
458
+
459
+ return dup_strip(g)
460
+
461
+
462
+ def dmp_trunc(f, p, u, K):
463
+ """
464
+ Reduce a ``K[X]`` polynomial modulo a polynomial ``p`` in ``K[Y]``.
465
+
466
+ Examples
467
+ ========
468
+
469
+ >>> from sympy.polys import ring, ZZ
470
+ >>> R, x,y = ring("x,y", ZZ)
471
+
472
+ >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3
473
+ >>> g = (y - 1).drop(x)
474
+
475
+ >>> R.dmp_trunc(f, g)
476
+ 11*x**2 + 11*x + 5
477
+
478
+ """
479
+ return dmp_strip([ dmp_rem(c, p, u - 1, K) for c in f ], u)
480
+
481
+
482
+ def dmp_ground_trunc(f, p, u, K):
483
+ """
484
+ Reduce a ``K[X]`` polynomial modulo a constant ``p`` in ``K``.
485
+
486
+ Examples
487
+ ========
488
+
489
+ >>> from sympy.polys import ring, ZZ
490
+ >>> R, x,y = ring("x,y", ZZ)
491
+
492
+ >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3
493
+
494
+ >>> R.dmp_ground_trunc(f, ZZ(3))
495
+ -x**2 - x*y - y
496
+
497
+ """
498
+ if not u:
499
+ return dup_trunc(f, p, K)
500
+
501
+ v = u - 1
502
+
503
+ return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f ], u)
504
+
505
+
506
+ def dup_monic(f, K):
507
+ """
508
+ Divide all coefficients by ``LC(f)`` in ``K[x]``.
509
+
510
+ Examples
511
+ ========
512
+
513
+ >>> from sympy.polys import ring, ZZ, QQ
514
+
515
+ >>> R, x = ring("x", ZZ)
516
+ >>> R.dup_monic(3*x**2 + 6*x + 9)
517
+ x**2 + 2*x + 3
518
+
519
+ >>> R, x = ring("x", QQ)
520
+ >>> R.dup_monic(3*x**2 + 4*x + 2)
521
+ x**2 + 4/3*x + 2/3
522
+
523
+ """
524
+ if not f:
525
+ return f
526
+
527
+ lc = dup_LC(f, K)
528
+
529
+ if K.is_one(lc):
530
+ return f
531
+ else:
532
+ return dup_exquo_ground(f, lc, K)
533
+
534
+
535
+ def dmp_ground_monic(f, u, K):
536
+ """
537
+ Divide all coefficients by ``LC(f)`` in ``K[X]``.
538
+
539
+ Examples
540
+ ========
541
+
542
+ >>> from sympy.polys import ring, ZZ, QQ
543
+
544
+ >>> R, x,y = ring("x,y", ZZ)
545
+ >>> f = 3*x**2*y + 6*x**2 + 3*x*y + 9*y + 3
546
+
547
+ >>> R.dmp_ground_monic(f)
548
+ x**2*y + 2*x**2 + x*y + 3*y + 1
549
+
550
+ >>> R, x,y = ring("x,y", QQ)
551
+ >>> f = 3*x**2*y + 8*x**2 + 5*x*y + 6*x + 2*y + 3
552
+
553
+ >>> R.dmp_ground_monic(f)
554
+ x**2*y + 8/3*x**2 + 5/3*x*y + 2*x + 2/3*y + 1
555
+
556
+ """
557
+ if not u:
558
+ return dup_monic(f, K)
559
+
560
+ if dmp_zero_p(f, u):
561
+ return f
562
+
563
+ lc = dmp_ground_LC(f, u, K)
564
+
565
+ if K.is_one(lc):
566
+ return f
567
+ else:
568
+ return dmp_exquo_ground(f, lc, u, K)
569
+
570
+
571
+ def dup_content(f, K):
572
+ """
573
+ Compute the GCD of coefficients of ``f`` in ``K[x]``.
574
+
575
+ Examples
576
+ ========
577
+
578
+ >>> from sympy.polys import ring, ZZ, QQ
579
+
580
+ >>> R, x = ring("x", ZZ)
581
+ >>> f = 6*x**2 + 8*x + 12
582
+
583
+ >>> R.dup_content(f)
584
+ 2
585
+
586
+ >>> R, x = ring("x", QQ)
587
+ >>> f = 6*x**2 + 8*x + 12
588
+
589
+ >>> R.dup_content(f)
590
+ 2
591
+
592
+ """
593
+ from sympy.polys.domains import QQ
594
+
595
+ if not f:
596
+ return K.zero
597
+
598
+ cont = K.zero
599
+
600
+ if K == QQ:
601
+ for c in f:
602
+ cont = K.gcd(cont, c)
603
+ else:
604
+ for c in f:
605
+ cont = K.gcd(cont, c)
606
+
607
+ if K.is_one(cont):
608
+ break
609
+
610
+ return cont
611
+
612
+
613
+ def dmp_ground_content(f, u, K):
614
+ """
615
+ Compute the GCD of coefficients of ``f`` in ``K[X]``.
616
+
617
+ Examples
618
+ ========
619
+
620
+ >>> from sympy.polys import ring, ZZ, QQ
621
+
622
+ >>> R, x,y = ring("x,y", ZZ)
623
+ >>> f = 2*x*y + 6*x + 4*y + 12
624
+
625
+ >>> R.dmp_ground_content(f)
626
+ 2
627
+
628
+ >>> R, x,y = ring("x,y", QQ)
629
+ >>> f = 2*x*y + 6*x + 4*y + 12
630
+
631
+ >>> R.dmp_ground_content(f)
632
+ 2
633
+
634
+ """
635
+ from sympy.polys.domains import QQ
636
+
637
+ if not u:
638
+ return dup_content(f, K)
639
+
640
+ if dmp_zero_p(f, u):
641
+ return K.zero
642
+
643
+ cont, v = K.zero, u - 1
644
+
645
+ if K == QQ:
646
+ for c in f:
647
+ cont = K.gcd(cont, dmp_ground_content(c, v, K))
648
+ else:
649
+ for c in f:
650
+ cont = K.gcd(cont, dmp_ground_content(c, v, K))
651
+
652
+ if K.is_one(cont):
653
+ break
654
+
655
+ return cont
656
+
657
+
658
+ def dup_primitive(f, K):
659
+ """
660
+ Compute content and the primitive form of ``f`` in ``K[x]``.
661
+
662
+ Examples
663
+ ========
664
+
665
+ >>> from sympy.polys import ring, ZZ, QQ
666
+
667
+ >>> R, x = ring("x", ZZ)
668
+ >>> f = 6*x**2 + 8*x + 12
669
+
670
+ >>> R.dup_primitive(f)
671
+ (2, 3*x**2 + 4*x + 6)
672
+
673
+ >>> R, x = ring("x", QQ)
674
+ >>> f = 6*x**2 + 8*x + 12
675
+
676
+ >>> R.dup_primitive(f)
677
+ (2, 3*x**2 + 4*x + 6)
678
+
679
+ """
680
+ if not f:
681
+ return K.zero, f
682
+
683
+ cont = dup_content(f, K)
684
+
685
+ if K.is_one(cont):
686
+ return cont, f
687
+ else:
688
+ return cont, dup_quo_ground(f, cont, K)
689
+
690
+
691
+ def dmp_ground_primitive(f, u, K):
692
+ """
693
+ Compute content and the primitive form of ``f`` in ``K[X]``.
694
+
695
+ Examples
696
+ ========
697
+
698
+ >>> from sympy.polys import ring, ZZ, QQ
699
+
700
+ >>> R, x,y = ring("x,y", ZZ)
701
+ >>> f = 2*x*y + 6*x + 4*y + 12
702
+
703
+ >>> R.dmp_ground_primitive(f)
704
+ (2, x*y + 3*x + 2*y + 6)
705
+
706
+ >>> R, x,y = ring("x,y", QQ)
707
+ >>> f = 2*x*y + 6*x + 4*y + 12
708
+
709
+ >>> R.dmp_ground_primitive(f)
710
+ (2, x*y + 3*x + 2*y + 6)
711
+
712
+ """
713
+ if not u:
714
+ return dup_primitive(f, K)
715
+
716
+ if dmp_zero_p(f, u):
717
+ return K.zero, f
718
+
719
+ cont = dmp_ground_content(f, u, K)
720
+
721
+ if K.is_one(cont):
722
+ return cont, f
723
+ else:
724
+ return cont, dmp_quo_ground(f, cont, u, K)
725
+
726
+
727
+ def dup_extract(f, g, K):
728
+ """
729
+ Extract common content from a pair of polynomials in ``K[x]``.
730
+
731
+ Examples
732
+ ========
733
+
734
+ >>> from sympy.polys import ring, ZZ
735
+ >>> R, x = ring("x", ZZ)
736
+
737
+ >>> R.dup_extract(6*x**2 + 12*x + 18, 4*x**2 + 8*x + 12)
738
+ (2, 3*x**2 + 6*x + 9, 2*x**2 + 4*x + 6)
739
+
740
+ """
741
+ fc = dup_content(f, K)
742
+ gc = dup_content(g, K)
743
+
744
+ gcd = K.gcd(fc, gc)
745
+
746
+ if not K.is_one(gcd):
747
+ f = dup_quo_ground(f, gcd, K)
748
+ g = dup_quo_ground(g, gcd, K)
749
+
750
+ return gcd, f, g
751
+
752
+
753
+ def dmp_ground_extract(f, g, u, K):
754
+ """
755
+ Extract common content from a pair of polynomials in ``K[X]``.
756
+
757
+ Examples
758
+ ========
759
+
760
+ >>> from sympy.polys import ring, ZZ
761
+ >>> R, x,y = ring("x,y", ZZ)
762
+
763
+ >>> R.dmp_ground_extract(6*x*y + 12*x + 18, 4*x*y + 8*x + 12)
764
+ (2, 3*x*y + 6*x + 9, 2*x*y + 4*x + 6)
765
+
766
+ """
767
+ fc = dmp_ground_content(f, u, K)
768
+ gc = dmp_ground_content(g, u, K)
769
+
770
+ gcd = K.gcd(fc, gc)
771
+
772
+ if not K.is_one(gcd):
773
+ f = dmp_quo_ground(f, gcd, u, K)
774
+ g = dmp_quo_ground(g, gcd, u, K)
775
+
776
+ return gcd, f, g
777
+
778
+
779
+ def dup_real_imag(f, K):
780
+ """
781
+ Return bivariate polynomials ``f1`` and ``f2``, such that ``f = f1 + f2*I``.
782
+
783
+ Examples
784
+ ========
785
+
786
+ >>> from sympy.polys import ring, ZZ
787
+ >>> R, x,y = ring("x,y", ZZ)
788
+
789
+ >>> R.dup_real_imag(x**3 + x**2 + x + 1)
790
+ (x**3 + x**2 - 3*x*y**2 + x - y**2 + 1, 3*x**2*y + 2*x*y - y**3 + y)
791
+
792
+ """
793
+ if not K.is_ZZ and not K.is_QQ:
794
+ raise DomainError("computing real and imaginary parts is not supported over %s" % K)
795
+
796
+ f1 = dmp_zero(1)
797
+ f2 = dmp_zero(1)
798
+
799
+ if not f:
800
+ return f1, f2
801
+
802
+ g = [[[K.one, K.zero]], [[K.one], []]]
803
+ h = dmp_ground(f[0], 2)
804
+
805
+ for c in f[1:]:
806
+ h = dmp_mul(h, g, 2, K)
807
+ h = dmp_add_term(h, dmp_ground(c, 1), 0, 2, K)
808
+
809
+ H = dup_to_raw_dict(h)
810
+
811
+ for k, h in H.items():
812
+ m = k % 4
813
+
814
+ if not m:
815
+ f1 = dmp_add(f1, h, 1, K)
816
+ elif m == 1:
817
+ f2 = dmp_add(f2, h, 1, K)
818
+ elif m == 2:
819
+ f1 = dmp_sub(f1, h, 1, K)
820
+ else:
821
+ f2 = dmp_sub(f2, h, 1, K)
822
+
823
+ return f1, f2
824
+
825
+
826
+ def dup_mirror(f, K):
827
+ """
828
+ Evaluate efficiently the composition ``f(-x)`` in ``K[x]``.
829
+
830
+ Examples
831
+ ========
832
+
833
+ >>> from sympy.polys import ring, ZZ
834
+ >>> R, x = ring("x", ZZ)
835
+
836
+ >>> R.dup_mirror(x**3 + 2*x**2 - 4*x + 2)
837
+ -x**3 + 2*x**2 + 4*x + 2
838
+
839
+ """
840
+ f = list(f)
841
+
842
+ for i in range(len(f) - 2, -1, -2):
843
+ f[i] = -f[i]
844
+
845
+ return f
846
+
847
+
848
+ def dup_scale(f, a, K):
849
+ """
850
+ Evaluate efficiently composition ``f(a*x)`` in ``K[x]``.
851
+
852
+ Examples
853
+ ========
854
+
855
+ >>> from sympy.polys import ring, ZZ
856
+ >>> R, x = ring("x", ZZ)
857
+
858
+ >>> R.dup_scale(x**2 - 2*x + 1, ZZ(2))
859
+ 4*x**2 - 4*x + 1
860
+
861
+ """
862
+ f, n, b = list(f), len(f) - 1, a
863
+
864
+ for i in range(n - 1, -1, -1):
865
+ f[i], b = b*f[i], b*a
866
+
867
+ return f
868
+
869
+
870
+ def dup_shift(f, a, K):
871
+ """
872
+ Evaluate efficiently Taylor shift ``f(x + a)`` in ``K[x]``.
873
+
874
+ Examples
875
+ ========
876
+
877
+ >>> from sympy.polys import ring, ZZ
878
+ >>> R, x = ring("x", ZZ)
879
+
880
+ >>> R.dup_shift(x**2 - 2*x + 1, ZZ(2))
881
+ x**2 + 2*x + 1
882
+
883
+ """
884
+ f, n = list(f), len(f) - 1
885
+
886
+ for i in range(n, 0, -1):
887
+ for j in range(0, i):
888
+ f[j + 1] += a*f[j]
889
+
890
+ return f
891
+
892
+
893
+ def dup_transform(f, p, q, K):
894
+ """
895
+ Evaluate functional transformation ``q**n * f(p/q)`` in ``K[x]``.
896
+
897
+ Examples
898
+ ========
899
+
900
+ >>> from sympy.polys import ring, ZZ
901
+ >>> R, x = ring("x", ZZ)
902
+
903
+ >>> R.dup_transform(x**2 - 2*x + 1, x**2 + 1, x - 1)
904
+ x**4 - 2*x**3 + 5*x**2 - 4*x + 4
905
+
906
+ """
907
+ if not f:
908
+ return []
909
+
910
+ n = len(f) - 1
911
+ h, Q = [f[0]], [[K.one]]
912
+
913
+ for i in range(0, n):
914
+ Q.append(dup_mul(Q[-1], q, K))
915
+
916
+ for c, q in zip(f[1:], Q[1:]):
917
+ h = dup_mul(h, p, K)
918
+ q = dup_mul_ground(q, c, K)
919
+ h = dup_add(h, q, K)
920
+
921
+ return h
922
+
923
+
924
+ def dup_compose(f, g, K):
925
+ """
926
+ Evaluate functional composition ``f(g)`` in ``K[x]``.
927
+
928
+ Examples
929
+ ========
930
+
931
+ >>> from sympy.polys import ring, ZZ
932
+ >>> R, x = ring("x", ZZ)
933
+
934
+ >>> R.dup_compose(x**2 + x, x - 1)
935
+ x**2 - x
936
+
937
+ """
938
+ if len(g) <= 1:
939
+ return dup_strip([dup_eval(f, dup_LC(g, K), K)])
940
+
941
+ if not f:
942
+ return []
943
+
944
+ h = [f[0]]
945
+
946
+ for c in f[1:]:
947
+ h = dup_mul(h, g, K)
948
+ h = dup_add_term(h, c, 0, K)
949
+
950
+ return h
951
+
952
+
953
+ def dmp_compose(f, g, u, K):
954
+ """
955
+ Evaluate functional composition ``f(g)`` in ``K[X]``.
956
+
957
+ Examples
958
+ ========
959
+
960
+ >>> from sympy.polys import ring, ZZ
961
+ >>> R, x,y = ring("x,y", ZZ)
962
+
963
+ >>> R.dmp_compose(x*y + 2*x + y, y)
964
+ y**2 + 3*y
965
+
966
+ """
967
+ if not u:
968
+ return dup_compose(f, g, K)
969
+
970
+ if dmp_zero_p(f, u):
971
+ return f
972
+
973
+ h = [f[0]]
974
+
975
+ for c in f[1:]:
976
+ h = dmp_mul(h, g, u, K)
977
+ h = dmp_add_term(h, c, 0, u, K)
978
+
979
+ return h
980
+
981
+
982
+ def _dup_right_decompose(f, s, K):
983
+ """Helper function for :func:`_dup_decompose`."""
984
+ n = len(f) - 1
985
+ lc = dup_LC(f, K)
986
+
987
+ f = dup_to_raw_dict(f)
988
+ g = { s: K.one }
989
+
990
+ r = n // s
991
+
992
+ for i in range(1, s):
993
+ coeff = K.zero
994
+
995
+ for j in range(0, i):
996
+ if not n + j - i in f:
997
+ continue
998
+
999
+ if not s - j in g:
1000
+ continue
1001
+
1002
+ fc, gc = f[n + j - i], g[s - j]
1003
+ coeff += (i - r*j)*fc*gc
1004
+
1005
+ g[s - i] = K.quo(coeff, i*r*lc)
1006
+
1007
+ return dup_from_raw_dict(g, K)
1008
+
1009
+
1010
+ def _dup_left_decompose(f, h, K):
1011
+ """Helper function for :func:`_dup_decompose`."""
1012
+ g, i = {}, 0
1013
+
1014
+ while f:
1015
+ q, r = dup_div(f, h, K)
1016
+
1017
+ if dup_degree(r) > 0:
1018
+ return None
1019
+ else:
1020
+ g[i] = dup_LC(r, K)
1021
+ f, i = q, i + 1
1022
+
1023
+ return dup_from_raw_dict(g, K)
1024
+
1025
+
1026
+ def _dup_decompose(f, K):
1027
+ """Helper function for :func:`dup_decompose`."""
1028
+ df = len(f) - 1
1029
+
1030
+ for s in range(2, df):
1031
+ if df % s != 0:
1032
+ continue
1033
+
1034
+ h = _dup_right_decompose(f, s, K)
1035
+
1036
+ if h is not None:
1037
+ g = _dup_left_decompose(f, h, K)
1038
+
1039
+ if g is not None:
1040
+ return g, h
1041
+
1042
+ return None
1043
+
1044
+
1045
+ def dup_decompose(f, K):
1046
+ """
1047
+ Computes functional decomposition of ``f`` in ``K[x]``.
1048
+
1049
+ Given a univariate polynomial ``f`` with coefficients in a field of
1050
+ characteristic zero, returns list ``[f_1, f_2, ..., f_n]``, where::
1051
+
1052
+ f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n))
1053
+
1054
+ and ``f_2, ..., f_n`` are monic and homogeneous polynomials of at
1055
+ least second degree.
1056
+
1057
+ Unlike factorization, complete functional decompositions of
1058
+ polynomials are not unique, consider examples:
1059
+
1060
+ 1. ``f o g = f(x + b) o (g - b)``
1061
+ 2. ``x**n o x**m = x**m o x**n``
1062
+ 3. ``T_n o T_m = T_m o T_n``
1063
+
1064
+ where ``T_n`` and ``T_m`` are Chebyshev polynomials.
1065
+
1066
+ Examples
1067
+ ========
1068
+
1069
+ >>> from sympy.polys import ring, ZZ
1070
+ >>> R, x = ring("x", ZZ)
1071
+
1072
+ >>> R.dup_decompose(x**4 - 2*x**3 + x**2)
1073
+ [x**2, x**2 - x]
1074
+
1075
+ References
1076
+ ==========
1077
+
1078
+ .. [1] [Kozen89]_
1079
+
1080
+ """
1081
+ F = []
1082
+
1083
+ while True:
1084
+ result = _dup_decompose(f, K)
1085
+
1086
+ if result is not None:
1087
+ f, h = result
1088
+ F = [h] + F
1089
+ else:
1090
+ break
1091
+
1092
+ return [f] + F
1093
+
1094
+
1095
+ def dmp_lift(f, u, K):
1096
+ """
1097
+ Convert algebraic coefficients to integers in ``K[X]``.
1098
+
1099
+ Examples
1100
+ ========
1101
+
1102
+ >>> from sympy.polys import ring, QQ
1103
+ >>> from sympy import I
1104
+
1105
+ >>> K = QQ.algebraic_field(I)
1106
+ >>> R, x = ring("x", K)
1107
+
1108
+ >>> f = x**2 + K([QQ(1), QQ(0)])*x + K([QQ(2), QQ(0)])
1109
+
1110
+ >>> R.dmp_lift(f)
1111
+ x**8 + 2*x**6 + 9*x**4 - 8*x**2 + 16
1112
+
1113
+ """
1114
+ if K.is_GaussianField:
1115
+ K1 = K.as_AlgebraicField()
1116
+ f = dmp_convert(f, u, K, K1)
1117
+ K = K1
1118
+
1119
+ if not K.is_Algebraic:
1120
+ raise DomainError(
1121
+ 'computation can be done only in an algebraic domain')
1122
+
1123
+ F, monoms, polys = dmp_to_dict(f, u), [], []
1124
+
1125
+ for monom, coeff in F.items():
1126
+ if not coeff.is_ground:
1127
+ monoms.append(monom)
1128
+
1129
+ perms = variations([-1, 1], len(monoms), repetition=True)
1130
+
1131
+ for perm in perms:
1132
+ G = dict(F)
1133
+
1134
+ for sign, monom in zip(perm, monoms):
1135
+ if sign == -1:
1136
+ G[monom] = -G[monom]
1137
+
1138
+ polys.append(dmp_from_dict(G, u, K))
1139
+
1140
+ return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom)
1141
+
1142
+
1143
+ def dup_sign_variations(f, K):
1144
+ """
1145
+ Compute the number of sign variations of ``f`` in ``K[x]``.
1146
+
1147
+ Examples
1148
+ ========
1149
+
1150
+ >>> from sympy.polys import ring, ZZ
1151
+ >>> R, x = ring("x", ZZ)
1152
+
1153
+ >>> R.dup_sign_variations(x**4 - x**2 - x + 1)
1154
+ 2
1155
+
1156
+ """
1157
+ prev, k = K.zero, 0
1158
+
1159
+ for coeff in f:
1160
+ if K.is_negative(coeff*prev):
1161
+ k += 1
1162
+
1163
+ if coeff:
1164
+ prev = coeff
1165
+
1166
+ return k
1167
+
1168
+
1169
+ def dup_clear_denoms(f, K0, K1=None, convert=False):
1170
+ """
1171
+ Clear denominators, i.e. transform ``K_0`` to ``K_1``.
1172
+
1173
+ Examples
1174
+ ========
1175
+
1176
+ >>> from sympy.polys import ring, QQ
1177
+ >>> R, x = ring("x", QQ)
1178
+
1179
+ >>> f = QQ(1,2)*x + QQ(1,3)
1180
+
1181
+ >>> R.dup_clear_denoms(f, convert=False)
1182
+ (6, 3*x + 2)
1183
+ >>> R.dup_clear_denoms(f, convert=True)
1184
+ (6, 3*x + 2)
1185
+
1186
+ """
1187
+ if K1 is None:
1188
+ if K0.has_assoc_Ring:
1189
+ K1 = K0.get_ring()
1190
+ else:
1191
+ K1 = K0
1192
+
1193
+ common = K1.one
1194
+
1195
+ for c in f:
1196
+ common = K1.lcm(common, K0.denom(c))
1197
+
1198
+ if not K1.is_one(common):
1199
+ f = dup_mul_ground(f, common, K0)
1200
+
1201
+ if not convert:
1202
+ return common, f
1203
+ else:
1204
+ return common, dup_convert(f, K0, K1)
1205
+
1206
+
1207
+ def _rec_clear_denoms(g, v, K0, K1):
1208
+ """Recursive helper for :func:`dmp_clear_denoms`."""
1209
+ common = K1.one
1210
+
1211
+ if not v:
1212
+ for c in g:
1213
+ common = K1.lcm(common, K0.denom(c))
1214
+ else:
1215
+ w = v - 1
1216
+
1217
+ for c in g:
1218
+ common = K1.lcm(common, _rec_clear_denoms(c, w, K0, K1))
1219
+
1220
+ return common
1221
+
1222
+
1223
+ def dmp_clear_denoms(f, u, K0, K1=None, convert=False):
1224
+ """
1225
+ Clear denominators, i.e. transform ``K_0`` to ``K_1``.
1226
+
1227
+ Examples
1228
+ ========
1229
+
1230
+ >>> from sympy.polys import ring, QQ
1231
+ >>> R, x,y = ring("x,y", QQ)
1232
+
1233
+ >>> f = QQ(1,2)*x + QQ(1,3)*y + 1
1234
+
1235
+ >>> R.dmp_clear_denoms(f, convert=False)
1236
+ (6, 3*x + 2*y + 6)
1237
+ >>> R.dmp_clear_denoms(f, convert=True)
1238
+ (6, 3*x + 2*y + 6)
1239
+
1240
+ """
1241
+ if not u:
1242
+ return dup_clear_denoms(f, K0, K1, convert=convert)
1243
+
1244
+ if K1 is None:
1245
+ if K0.has_assoc_Ring:
1246
+ K1 = K0.get_ring()
1247
+ else:
1248
+ K1 = K0
1249
+
1250
+ common = _rec_clear_denoms(f, u, K0, K1)
1251
+
1252
+ if not K1.is_one(common):
1253
+ f = dmp_mul_ground(f, common, u, K0)
1254
+
1255
+ if not convert:
1256
+ return common, f
1257
+ else:
1258
+ return common, dmp_convert(f, u, K0, K1)
1259
+
1260
+
1261
+ def dup_revert(f, n, K):
1262
+ """
1263
+ Compute ``f**(-1)`` mod ``x**n`` using Newton iteration.
1264
+
1265
+ This function computes first ``2**n`` terms of a polynomial that
1266
+ is a result of inversion of a polynomial modulo ``x**n``. This is
1267
+ useful to efficiently compute series expansion of ``1/f``.
1268
+
1269
+ Examples
1270
+ ========
1271
+
1272
+ >>> from sympy.polys import ring, QQ
1273
+ >>> R, x = ring("x", QQ)
1274
+
1275
+ >>> f = -QQ(1,720)*x**6 + QQ(1,24)*x**4 - QQ(1,2)*x**2 + 1
1276
+
1277
+ >>> R.dup_revert(f, 8)
1278
+ 61/720*x**6 + 5/24*x**4 + 1/2*x**2 + 1
1279
+
1280
+ """
1281
+ g = [K.revert(dup_TC(f, K))]
1282
+ h = [K.one, K.zero, K.zero]
1283
+
1284
+ N = int(_ceil(_log(n, 2)))
1285
+
1286
+ for i in range(1, N + 1):
1287
+ a = dup_mul_ground(g, K(2), K)
1288
+ b = dup_mul(f, dup_sqr(g, K), K)
1289
+ g = dup_rem(dup_sub(a, b, K), h, K)
1290
+ h = dup_lshift(h, dup_degree(h), K)
1291
+
1292
+ return g
1293
+
1294
+
1295
+ def dmp_revert(f, g, u, K):
1296
+ """
1297
+ Compute ``f**(-1)`` mod ``x**n`` using Newton iteration.
1298
+
1299
+ Examples
1300
+ ========
1301
+
1302
+ >>> from sympy.polys import ring, QQ
1303
+ >>> R, x,y = ring("x,y", QQ)
1304
+
1305
+ """
1306
+ if not u:
1307
+ return dup_revert(f, g, K)
1308
+ else:
1309
+ raise MultivariatePolynomialError(f, g)
llmeval-env/lib/python3.10/site-packages/sympy/polys/dispersion.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S
2
+ from sympy.polys import Poly
3
+
4
+
5
+ def dispersionset(p, q=None, *gens, **args):
6
+ r"""Compute the *dispersion set* of two polynomials.
7
+
8
+ For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
9
+ and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as:
10
+
11
+ .. math::
12
+ \operatorname{J}(f, g)
13
+ & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\
14
+ & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\}
15
+
16
+ For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`.
17
+
18
+ Examples
19
+ ========
20
+
21
+ >>> from sympy import poly
22
+ >>> from sympy.polys.dispersion import dispersion, dispersionset
23
+ >>> from sympy.abc import x
24
+
25
+ Dispersion set and dispersion of a simple polynomial:
26
+
27
+ >>> fp = poly((x - 3)*(x + 3), x)
28
+ >>> sorted(dispersionset(fp))
29
+ [0, 6]
30
+ >>> dispersion(fp)
31
+ 6
32
+
33
+ Note that the definition of the dispersion is not symmetric:
34
+
35
+ >>> fp = poly(x**4 - 3*x**2 + 1, x)
36
+ >>> gp = fp.shift(-3)
37
+ >>> sorted(dispersionset(fp, gp))
38
+ [2, 3, 4]
39
+ >>> dispersion(fp, gp)
40
+ 4
41
+ >>> sorted(dispersionset(gp, fp))
42
+ []
43
+ >>> dispersion(gp, fp)
44
+ -oo
45
+
46
+ Computing the dispersion also works over field extensions:
47
+
48
+ >>> from sympy import sqrt
49
+ >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
50
+ >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
51
+ >>> sorted(dispersionset(fp, gp))
52
+ [2]
53
+ >>> sorted(dispersionset(gp, fp))
54
+ [1, 4]
55
+
56
+ We can even perform the computations for polynomials
57
+ having symbolic coefficients:
58
+
59
+ >>> from sympy.abc import a
60
+ >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
61
+ >>> sorted(dispersionset(fp))
62
+ [0, 1]
63
+
64
+ See Also
65
+ ========
66
+
67
+ dispersion
68
+
69
+ References
70
+ ==========
71
+
72
+ .. [1] [ManWright94]_
73
+ .. [2] [Koepf98]_
74
+ .. [3] [Abramov71]_
75
+ .. [4] [Man93]_
76
+ """
77
+ # Check for valid input
78
+ same = False if q is not None else True
79
+ if same:
80
+ q = p
81
+
82
+ p = Poly(p, *gens, **args)
83
+ q = Poly(q, *gens, **args)
84
+
85
+ if not p.is_univariate or not q.is_univariate:
86
+ raise ValueError("Polynomials need to be univariate")
87
+
88
+ # The generator
89
+ if not p.gen == q.gen:
90
+ raise ValueError("Polynomials must have the same generator")
91
+ gen = p.gen
92
+
93
+ # We define the dispersion of constant polynomials to be zero
94
+ if p.degree() < 1 or q.degree() < 1:
95
+ return {0}
96
+
97
+ # Factor p and q over the rationals
98
+ fp = p.factor_list()
99
+ fq = q.factor_list() if not same else fp
100
+
101
+ # Iterate over all pairs of factors
102
+ J = set()
103
+ for s, unused in fp[1]:
104
+ for t, unused in fq[1]:
105
+ m = s.degree()
106
+ n = t.degree()
107
+ if n != m:
108
+ continue
109
+ an = s.LC()
110
+ bn = t.LC()
111
+ if not (an - bn).is_zero:
112
+ continue
113
+ # Note that the roles of `s` and `t` below are switched
114
+ # w.r.t. the original paper. This is for consistency
115
+ # with the description in the book of W. Koepf.
116
+ anm1 = s.coeff_monomial(gen**(m-1))
117
+ bnm1 = t.coeff_monomial(gen**(n-1))
118
+ alpha = (anm1 - bnm1) / S(n*bn)
119
+ if not alpha.is_integer:
120
+ continue
121
+ if alpha < 0 or alpha in J:
122
+ continue
123
+ if n > 1 and not (s - t.shift(alpha)).is_zero:
124
+ continue
125
+ J.add(alpha)
126
+
127
+ return J
128
+
129
+
130
+ def dispersion(p, q=None, *gens, **args):
131
+ r"""Compute the *dispersion* of polynomials.
132
+
133
+ For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
134
+ and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as:
135
+
136
+ .. math::
137
+ \operatorname{dis}(f, g)
138
+ & := \max\{ J(f,g) \cup \{0\} \} \\
139
+ & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \}
140
+
141
+ and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`.
142
+ Note that we make the definition `\max\{\} := -\infty`.
143
+
144
+ Examples
145
+ ========
146
+
147
+ >>> from sympy import poly
148
+ >>> from sympy.polys.dispersion import dispersion, dispersionset
149
+ >>> from sympy.abc import x
150
+
151
+ Dispersion set and dispersion of a simple polynomial:
152
+
153
+ >>> fp = poly((x - 3)*(x + 3), x)
154
+ >>> sorted(dispersionset(fp))
155
+ [0, 6]
156
+ >>> dispersion(fp)
157
+ 6
158
+
159
+ Note that the definition of the dispersion is not symmetric:
160
+
161
+ >>> fp = poly(x**4 - 3*x**2 + 1, x)
162
+ >>> gp = fp.shift(-3)
163
+ >>> sorted(dispersionset(fp, gp))
164
+ [2, 3, 4]
165
+ >>> dispersion(fp, gp)
166
+ 4
167
+ >>> sorted(dispersionset(gp, fp))
168
+ []
169
+ >>> dispersion(gp, fp)
170
+ -oo
171
+
172
+ The maximum of an empty set is defined to be `-\infty`
173
+ as seen in this example.
174
+
175
+ Computing the dispersion also works over field extensions:
176
+
177
+ >>> from sympy import sqrt
178
+ >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
179
+ >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
180
+ >>> sorted(dispersionset(fp, gp))
181
+ [2]
182
+ >>> sorted(dispersionset(gp, fp))
183
+ [1, 4]
184
+
185
+ We can even perform the computations for polynomials
186
+ having symbolic coefficients:
187
+
188
+ >>> from sympy.abc import a
189
+ >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
190
+ >>> sorted(dispersionset(fp))
191
+ [0, 1]
192
+
193
+ See Also
194
+ ========
195
+
196
+ dispersionset
197
+
198
+ References
199
+ ==========
200
+
201
+ .. [1] [ManWright94]_
202
+ .. [2] [Koepf98]_
203
+ .. [3] [Abramov71]_
204
+ .. [4] [Man93]_
205
+ """
206
+ J = dispersionset(p, q, *gens, **args)
207
+ if not J:
208
+ # Definition for maximum of empty set
209
+ j = S.NegativeInfinity
210
+ else:
211
+ j = max(J)
212
+ return j
llmeval-env/lib/python3.10/site-packages/sympy/polys/distributedmodules.py ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ Sparse distributed elements of free modules over multivariate (generalized)
3
+ polynomial rings.
4
+
5
+ This code and its data structures are very much like the distributed
6
+ polynomials, except that the first "exponent" of the monomial is
7
+ a module generator index. That is, the multi-exponent ``(i, e_1, ..., e_n)``
8
+ represents the "monomial" `x_1^{e_1} \cdots x_n^{e_n} f_i` of the free module
9
+ `F` generated by `f_1, \ldots, f_r` over (a localization of) the ring
10
+ `K[x_1, \ldots, x_n]`. A module element is simply stored as a list of terms
11
+ ordered by the monomial order. Here a term is a pair of a multi-exponent and a
12
+ coefficient. In general, this coefficient should never be zero (since it can
13
+ then be omitted). The zero module element is stored as an empty list.
14
+
15
+ The main routines are ``sdm_nf_mora`` and ``sdm_groebner`` which can be used
16
+ to compute, respectively, weak normal forms and standard bases. They work with
17
+ arbitrary (not necessarily global) monomial orders.
18
+
19
+ In general, product orders have to be used to construct valid monomial orders
20
+ for modules. However, ``lex`` can be used as-is.
21
+
22
+ Note that the "level" (number of variables, i.e. parameter u+1 in
23
+ distributedpolys.py) is never needed in this code.
24
+
25
+ The main reference for this file is [SCA],
26
+ "A Singular Introduction to Commutative Algebra".
27
+ """
28
+
29
+
30
+ from itertools import permutations
31
+
32
+ from sympy.polys.monomials import (
33
+ monomial_mul, monomial_lcm, monomial_div, monomial_deg
34
+ )
35
+
36
+ from sympy.polys.polytools import Poly
37
+ from sympy.polys.polyutils import parallel_dict_from_expr
38
+ from sympy.core.singleton import S
39
+ from sympy.core.sympify import sympify
40
+
41
+ # Additional monomial tools.
42
+
43
+
44
+ def sdm_monomial_mul(M, X):
45
+ """
46
+ Multiply tuple ``X`` representing a monomial of `K[X]` into the tuple
47
+ ``M`` representing a monomial of `F`.
48
+
49
+ Examples
50
+ ========
51
+
52
+ Multiplying `xy^3` into `x f_1` yields `x^2 y^3 f_1`:
53
+
54
+ >>> from sympy.polys.distributedmodules import sdm_monomial_mul
55
+ >>> sdm_monomial_mul((1, 1, 0), (1, 3))
56
+ (1, 2, 3)
57
+ """
58
+ return (M[0],) + monomial_mul(X, M[1:])
59
+
60
+
61
+ def sdm_monomial_deg(M):
62
+ """
63
+ Return the total degree of ``M``.
64
+
65
+ Examples
66
+ ========
67
+
68
+ For example, the total degree of `x^2 y f_5` is 3:
69
+
70
+ >>> from sympy.polys.distributedmodules import sdm_monomial_deg
71
+ >>> sdm_monomial_deg((5, 2, 1))
72
+ 3
73
+ """
74
+ return monomial_deg(M[1:])
75
+
76
+
77
+ def sdm_monomial_lcm(A, B):
78
+ r"""
79
+ Return the "least common multiple" of ``A`` and ``B``.
80
+
81
+ IF `A = M e_j` and `B = N e_j`, where `M` and `N` are polynomial monomials,
82
+ this returns `\lcm(M, N) e_j`. Note that ``A`` and ``B`` involve distinct
83
+ monomials.
84
+
85
+ Otherwise the result is undefined.
86
+
87
+ Examples
88
+ ========
89
+
90
+ >>> from sympy.polys.distributedmodules import sdm_monomial_lcm
91
+ >>> sdm_monomial_lcm((1, 2, 3), (1, 0, 5))
92
+ (1, 2, 5)
93
+ """
94
+ return (A[0],) + monomial_lcm(A[1:], B[1:])
95
+
96
+
97
+ def sdm_monomial_divides(A, B):
98
+ """
99
+ Does there exist a (polynomial) monomial X such that XA = B?
100
+
101
+ Examples
102
+ ========
103
+
104
+ Positive examples:
105
+
106
+ In the following examples, the monomial is given in terms of x, y and the
107
+ generator(s), f_1, f_2 etc. The tuple form of that monomial is used in
108
+ the call to sdm_monomial_divides.
109
+ Note: the generator appears last in the expression but first in the tuple
110
+ and other factors appear in the same order that they appear in the monomial
111
+ expression.
112
+
113
+ `A = f_1` divides `B = f_1`
114
+
115
+ >>> from sympy.polys.distributedmodules import sdm_monomial_divides
116
+ >>> sdm_monomial_divides((1, 0, 0), (1, 0, 0))
117
+ True
118
+
119
+ `A = f_1` divides `B = x^2 y f_1`
120
+
121
+ >>> sdm_monomial_divides((1, 0, 0), (1, 2, 1))
122
+ True
123
+
124
+ `A = xy f_5` divides `B = x^2 y f_5`
125
+
126
+ >>> sdm_monomial_divides((5, 1, 1), (5, 2, 1))
127
+ True
128
+
129
+ Negative examples:
130
+
131
+ `A = f_1` does not divide `B = f_2`
132
+
133
+ >>> sdm_monomial_divides((1, 0, 0), (2, 0, 0))
134
+ False
135
+
136
+ `A = x f_1` does not divide `B = f_1`
137
+
138
+ >>> sdm_monomial_divides((1, 1, 0), (1, 0, 0))
139
+ False
140
+
141
+ `A = xy^2 f_5` does not divide `B = y f_5`
142
+
143
+ >>> sdm_monomial_divides((5, 1, 2), (5, 0, 1))
144
+ False
145
+ """
146
+ return A[0] == B[0] and all(a <= b for a, b in zip(A[1:], B[1:]))
147
+
148
+
149
+ # The actual distributed modules code.
150
+
151
+ def sdm_LC(f, K):
152
+ """Returns the leading coefficient of ``f``. """
153
+ if not f:
154
+ return K.zero
155
+ else:
156
+ return f[0][1]
157
+
158
+
159
+ def sdm_to_dict(f):
160
+ """Make a dictionary from a distributed polynomial. """
161
+ return dict(f)
162
+
163
+
164
+ def sdm_from_dict(d, O):
165
+ """
166
+ Create an sdm from a dictionary.
167
+
168
+ Here ``O`` is the monomial order to use.
169
+
170
+ Examples
171
+ ========
172
+
173
+ >>> from sympy.polys.distributedmodules import sdm_from_dict
174
+ >>> from sympy.polys import QQ, lex
175
+ >>> dic = {(1, 1, 0): QQ(1), (1, 0, 0): QQ(2), (0, 1, 0): QQ(0)}
176
+ >>> sdm_from_dict(dic, lex)
177
+ [((1, 1, 0), 1), ((1, 0, 0), 2)]
178
+ """
179
+ return sdm_strip(sdm_sort(list(d.items()), O))
180
+
181
+
182
+ def sdm_sort(f, O):
183
+ """Sort terms in ``f`` using the given monomial order ``O``. """
184
+ return sorted(f, key=lambda term: O(term[0]), reverse=True)
185
+
186
+
187
+ def sdm_strip(f):
188
+ """Remove terms with zero coefficients from ``f`` in ``K[X]``. """
189
+ return [ (monom, coeff) for monom, coeff in f if coeff ]
190
+
191
+
192
+ def sdm_add(f, g, O, K):
193
+ """
194
+ Add two module elements ``f``, ``g``.
195
+
196
+ Addition is done over the ground field ``K``, monomials are ordered
197
+ according to ``O``.
198
+
199
+ Examples
200
+ ========
201
+
202
+ All examples use lexicographic order.
203
+
204
+ `(xy f_1) + (f_2) = f_2 + xy f_1`
205
+
206
+ >>> from sympy.polys.distributedmodules import sdm_add
207
+ >>> from sympy.polys import lex, QQ
208
+ >>> sdm_add([((1, 1, 1), QQ(1))], [((2, 0, 0), QQ(1))], lex, QQ)
209
+ [((2, 0, 0), 1), ((1, 1, 1), 1)]
210
+
211
+ `(xy f_1) + (-xy f_1)` = 0`
212
+
213
+ >>> sdm_add([((1, 1, 1), QQ(1))], [((1, 1, 1), QQ(-1))], lex, QQ)
214
+ []
215
+
216
+ `(f_1) + (2f_1) = 3f_1`
217
+
218
+ >>> sdm_add([((1, 0, 0), QQ(1))], [((1, 0, 0), QQ(2))], lex, QQ)
219
+ [((1, 0, 0), 3)]
220
+
221
+ `(yf_1) + (xf_1) = xf_1 + yf_1`
222
+
223
+ >>> sdm_add([((1, 0, 1), QQ(1))], [((1, 1, 0), QQ(1))], lex, QQ)
224
+ [((1, 1, 0), 1), ((1, 0, 1), 1)]
225
+ """
226
+ h = dict(f)
227
+
228
+ for monom, c in g:
229
+ if monom in h:
230
+ coeff = h[monom] + c
231
+
232
+ if not coeff:
233
+ del h[monom]
234
+ else:
235
+ h[monom] = coeff
236
+ else:
237
+ h[monom] = c
238
+
239
+ return sdm_from_dict(h, O)
240
+
241
+
242
+ def sdm_LM(f):
243
+ r"""
244
+ Returns the leading monomial of ``f``.
245
+
246
+ Only valid if `f \ne 0`.
247
+
248
+ Examples
249
+ ========
250
+
251
+ >>> from sympy.polys.distributedmodules import sdm_LM, sdm_from_dict
252
+ >>> from sympy.polys import QQ, lex
253
+ >>> dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(1), (4, 0, 1): QQ(1)}
254
+ >>> sdm_LM(sdm_from_dict(dic, lex))
255
+ (4, 0, 1)
256
+ """
257
+ return f[0][0]
258
+
259
+
260
+ def sdm_LT(f):
261
+ r"""
262
+ Returns the leading term of ``f``.
263
+
264
+ Only valid if `f \ne 0`.
265
+
266
+ Examples
267
+ ========
268
+
269
+ >>> from sympy.polys.distributedmodules import sdm_LT, sdm_from_dict
270
+ >>> from sympy.polys import QQ, lex
271
+ >>> dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(2), (4, 0, 1): QQ(3)}
272
+ >>> sdm_LT(sdm_from_dict(dic, lex))
273
+ ((4, 0, 1), 3)
274
+ """
275
+ return f[0]
276
+
277
+
278
+ def sdm_mul_term(f, term, O, K):
279
+ """
280
+ Multiply a distributed module element ``f`` by a (polynomial) term ``term``.
281
+
282
+ Multiplication of coefficients is done over the ground field ``K``, and
283
+ monomials are ordered according to ``O``.
284
+
285
+ Examples
286
+ ========
287
+
288
+ `0 f_1 = 0`
289
+
290
+ >>> from sympy.polys.distributedmodules import sdm_mul_term
291
+ >>> from sympy.polys import lex, QQ
292
+ >>> sdm_mul_term([((1, 0, 0), QQ(1))], ((0, 0), QQ(0)), lex, QQ)
293
+ []
294
+
295
+ `x 0 = 0`
296
+
297
+ >>> sdm_mul_term([], ((1, 0), QQ(1)), lex, QQ)
298
+ []
299
+
300
+ `(x) (f_1) = xf_1`
301
+
302
+ >>> sdm_mul_term([((1, 0, 0), QQ(1))], ((1, 0), QQ(1)), lex, QQ)
303
+ [((1, 1, 0), 1)]
304
+
305
+ `(2xy) (3x f_1 + 4y f_2) = 8xy^2 f_2 + 6x^2y f_1`
306
+
307
+ >>> f = [((2, 0, 1), QQ(4)), ((1, 1, 0), QQ(3))]
308
+ >>> sdm_mul_term(f, ((1, 1), QQ(2)), lex, QQ)
309
+ [((2, 1, 2), 8), ((1, 2, 1), 6)]
310
+ """
311
+ X, c = term
312
+
313
+ if not f or not c:
314
+ return []
315
+ else:
316
+ if K.is_one(c):
317
+ return [ (sdm_monomial_mul(f_M, X), f_c) for f_M, f_c in f ]
318
+ else:
319
+ return [ (sdm_monomial_mul(f_M, X), f_c * c) for f_M, f_c in f ]
320
+
321
+
322
+ def sdm_zero():
323
+ """Return the zero module element."""
324
+ return []
325
+
326
+
327
+ def sdm_deg(f):
328
+ """
329
+ Degree of ``f``.
330
+
331
+ This is the maximum of the degrees of all its monomials.
332
+ Invalid if ``f`` is zero.
333
+
334
+ Examples
335
+ ========
336
+
337
+ >>> from sympy.polys.distributedmodules import sdm_deg
338
+ >>> sdm_deg([((1, 2, 3), 1), ((10, 0, 1), 1), ((2, 3, 4), 4)])
339
+ 7
340
+ """
341
+ return max(sdm_monomial_deg(M[0]) for M in f)
342
+
343
+
344
+ # Conversion
345
+
346
+ def sdm_from_vector(vec, O, K, **opts):
347
+ """
348
+ Create an sdm from an iterable of expressions.
349
+
350
+ Coefficients are created in the ground field ``K``, and terms are ordered
351
+ according to monomial order ``O``. Named arguments are passed on to the
352
+ polys conversion code and can be used to specify for example generators.
353
+
354
+ Examples
355
+ ========
356
+
357
+ >>> from sympy.polys.distributedmodules import sdm_from_vector
358
+ >>> from sympy.abc import x, y, z
359
+ >>> from sympy.polys import QQ, lex
360
+ >>> sdm_from_vector([x**2+y**2, 2*z], lex, QQ)
361
+ [((1, 0, 0, 1), 2), ((0, 2, 0, 0), 1), ((0, 0, 2, 0), 1)]
362
+ """
363
+ dics, gens = parallel_dict_from_expr(sympify(vec), **opts)
364
+ dic = {}
365
+ for i, d in enumerate(dics):
366
+ for k, v in d.items():
367
+ dic[(i,) + k] = K.convert(v)
368
+ return sdm_from_dict(dic, O)
369
+
370
+
371
+ def sdm_to_vector(f, gens, K, n=None):
372
+ """
373
+ Convert sdm ``f`` into a list of polynomial expressions.
374
+
375
+ The generators for the polynomial ring are specified via ``gens``. The rank
376
+ of the module is guessed, or passed via ``n``. The ground field is assumed
377
+ to be ``K``.
378
+
379
+ Examples
380
+ ========
381
+
382
+ >>> from sympy.polys.distributedmodules import sdm_to_vector
383
+ >>> from sympy.abc import x, y, z
384
+ >>> from sympy.polys import QQ
385
+ >>> f = [((1, 0, 0, 1), QQ(2)), ((0, 2, 0, 0), QQ(1)), ((0, 0, 2, 0), QQ(1))]
386
+ >>> sdm_to_vector(f, [x, y, z], QQ)
387
+ [x**2 + y**2, 2*z]
388
+ """
389
+ dic = sdm_to_dict(f)
390
+ dics = {}
391
+ for k, v in dic.items():
392
+ dics.setdefault(k[0], []).append((k[1:], v))
393
+ n = n or len(dics)
394
+ res = []
395
+ for k in range(n):
396
+ if k in dics:
397
+ res.append(Poly(dict(dics[k]), gens=gens, domain=K).as_expr())
398
+ else:
399
+ res.append(S.Zero)
400
+ return res
401
+
402
+ # Algorithms.
403
+
404
+
405
+ def sdm_spoly(f, g, O, K, phantom=None):
406
+ """
407
+ Compute the generalized s-polynomial of ``f`` and ``g``.
408
+
409
+ The ground field is assumed to be ``K``, and monomials ordered according to
410
+ ``O``.
411
+
412
+ This is invalid if either of ``f`` or ``g`` is zero.
413
+
414
+ If the leading terms of `f` and `g` involve different basis elements of
415
+ `F`, their s-poly is defined to be zero. Otherwise it is a certain linear
416
+ combination of `f` and `g` in which the leading terms cancel.
417
+ See [SCA, defn 2.3.6] for details.
418
+
419
+ If ``phantom`` is not ``None``, it should be a pair of module elements on
420
+ which to perform the same operation(s) as on ``f`` and ``g``. The in this
421
+ case both results are returned.
422
+
423
+ Examples
424
+ ========
425
+
426
+ >>> from sympy.polys.distributedmodules import sdm_spoly
427
+ >>> from sympy.polys import QQ, lex
428
+ >>> f = [((2, 1, 1), QQ(1)), ((1, 0, 1), QQ(1))]
429
+ >>> g = [((2, 3, 0), QQ(1))]
430
+ >>> h = [((1, 2, 3), QQ(1))]
431
+ >>> sdm_spoly(f, h, lex, QQ)
432
+ []
433
+ >>> sdm_spoly(f, g, lex, QQ)
434
+ [((1, 2, 1), 1)]
435
+ """
436
+ if not f or not g:
437
+ return sdm_zero()
438
+ LM1 = sdm_LM(f)
439
+ LM2 = sdm_LM(g)
440
+ if LM1[0] != LM2[0]:
441
+ return sdm_zero()
442
+ LM1 = LM1[1:]
443
+ LM2 = LM2[1:]
444
+ lcm = monomial_lcm(LM1, LM2)
445
+ m1 = monomial_div(lcm, LM1)
446
+ m2 = monomial_div(lcm, LM2)
447
+ c = K.quo(-sdm_LC(f, K), sdm_LC(g, K))
448
+ r1 = sdm_add(sdm_mul_term(f, (m1, K.one), O, K),
449
+ sdm_mul_term(g, (m2, c), O, K), O, K)
450
+ if phantom is None:
451
+ return r1
452
+ r2 = sdm_add(sdm_mul_term(phantom[0], (m1, K.one), O, K),
453
+ sdm_mul_term(phantom[1], (m2, c), O, K), O, K)
454
+ return r1, r2
455
+
456
+
457
+ def sdm_ecart(f):
458
+ """
459
+ Compute the ecart of ``f``.
460
+
461
+ This is defined to be the difference of the total degree of `f` and the
462
+ total degree of the leading monomial of `f` [SCA, defn 2.3.7].
463
+
464
+ Invalid if f is zero.
465
+
466
+ Examples
467
+ ========
468
+
469
+ >>> from sympy.polys.distributedmodules import sdm_ecart
470
+ >>> sdm_ecart([((1, 2, 3), 1), ((1, 0, 1), 1)])
471
+ 0
472
+ >>> sdm_ecart([((2, 2, 1), 1), ((1, 5, 1), 1)])
473
+ 3
474
+ """
475
+ return sdm_deg(f) - sdm_monomial_deg(sdm_LM(f))
476
+
477
+
478
+ def sdm_nf_mora(f, G, O, K, phantom=None):
479
+ r"""
480
+ Compute a weak normal form of ``f`` with respect to ``G`` and order ``O``.
481
+
482
+ The ground field is assumed to be ``K``, and monomials ordered according to
483
+ ``O``.
484
+
485
+ Weak normal forms are defined in [SCA, defn 2.3.3]. They are not unique.
486
+ This function deterministically computes a weak normal form, depending on
487
+ the order of `G`.
488
+
489
+ The most important property of a weak normal form is the following: if
490
+ `R` is the ring associated with the monomial ordering (if the ordering is
491
+ global, we just have `R = K[x_1, \ldots, x_n]`, otherwise it is a certain
492
+ localization thereof), `I` any ideal of `R` and `G` a standard basis for
493
+ `I`, then for any `f \in R`, we have `f \in I` if and only if
494
+ `NF(f | G) = 0`.
495
+
496
+ This is the generalized Mora algorithm for computing weak normal forms with
497
+ respect to arbitrary monomial orders [SCA, algorithm 2.3.9].
498
+
499
+ If ``phantom`` is not ``None``, it should be a pair of "phantom" arguments
500
+ on which to perform the same computations as on ``f``, ``G``, both results
501
+ are then returned.
502
+ """
503
+ from itertools import repeat
504
+ h = f
505
+ T = list(G)
506
+ if phantom is not None:
507
+ # "phantom" variables with suffix p
508
+ hp = phantom[0]
509
+ Tp = list(phantom[1])
510
+ phantom = True
511
+ else:
512
+ Tp = repeat([])
513
+ phantom = False
514
+ while h:
515
+ # TODO better data structure!!!
516
+ Th = [(g, sdm_ecart(g), gp) for g, gp in zip(T, Tp)
517
+ if sdm_monomial_divides(sdm_LM(g), sdm_LM(h))]
518
+ if not Th:
519
+ break
520
+ g, _, gp = min(Th, key=lambda x: x[1])
521
+ if sdm_ecart(g) > sdm_ecart(h):
522
+ T.append(h)
523
+ if phantom:
524
+ Tp.append(hp)
525
+ if phantom:
526
+ h, hp = sdm_spoly(h, g, O, K, phantom=(hp, gp))
527
+ else:
528
+ h = sdm_spoly(h, g, O, K)
529
+ if phantom:
530
+ return h, hp
531
+ return h
532
+
533
+
534
+ def sdm_nf_buchberger(f, G, O, K, phantom=None):
535
+ r"""
536
+ Compute a weak normal form of ``f`` with respect to ``G`` and order ``O``.
537
+
538
+ The ground field is assumed to be ``K``, and monomials ordered according to
539
+ ``O``.
540
+
541
+ This is the standard Buchberger algorithm for computing weak normal forms with
542
+ respect to *global* monomial orders [SCA, algorithm 1.6.10].
543
+
544
+ If ``phantom`` is not ``None``, it should be a pair of "phantom" arguments
545
+ on which to perform the same computations as on ``f``, ``G``, both results
546
+ are then returned.
547
+ """
548
+ from itertools import repeat
549
+ h = f
550
+ T = list(G)
551
+ if phantom is not None:
552
+ # "phantom" variables with suffix p
553
+ hp = phantom[0]
554
+ Tp = list(phantom[1])
555
+ phantom = True
556
+ else:
557
+ Tp = repeat([])
558
+ phantom = False
559
+ while h:
560
+ try:
561
+ g, gp = next((g, gp) for g, gp in zip(T, Tp)
562
+ if sdm_monomial_divides(sdm_LM(g), sdm_LM(h)))
563
+ except StopIteration:
564
+ break
565
+ if phantom:
566
+ h, hp = sdm_spoly(h, g, O, K, phantom=(hp, gp))
567
+ else:
568
+ h = sdm_spoly(h, g, O, K)
569
+ if phantom:
570
+ return h, hp
571
+ return h
572
+
573
+
574
+ def sdm_nf_buchberger_reduced(f, G, O, K):
575
+ r"""
576
+ Compute a reduced normal form of ``f`` with respect to ``G`` and order ``O``.
577
+
578
+ The ground field is assumed to be ``K``, and monomials ordered according to
579
+ ``O``.
580
+
581
+ In contrast to weak normal forms, reduced normal forms *are* unique, but
582
+ their computation is more expensive.
583
+
584
+ This is the standard Buchberger algorithm for computing reduced normal forms
585
+ with respect to *global* monomial orders [SCA, algorithm 1.6.11].
586
+
587
+ The ``pantom`` option is not supported, so this normal form cannot be used
588
+ as a normal form for the "extended" groebner algorithm.
589
+ """
590
+ h = sdm_zero()
591
+ g = f
592
+ while g:
593
+ g = sdm_nf_buchberger(g, G, O, K)
594
+ if g:
595
+ h = sdm_add(h, [sdm_LT(g)], O, K)
596
+ g = g[1:]
597
+ return h
598
+
599
+
600
+ def sdm_groebner(G, NF, O, K, extended=False):
601
+ """
602
+ Compute a minimal standard basis of ``G`` with respect to order ``O``.
603
+
604
+ The algorithm uses a normal form ``NF``, for example ``sdm_nf_mora``.
605
+ The ground field is assumed to be ``K``, and monomials ordered according
606
+ to ``O``.
607
+
608
+ Let `N` denote the submodule generated by elements of `G`. A standard
609
+ basis for `N` is a subset `S` of `N`, such that `in(S) = in(N)`, where for
610
+ any subset `X` of `F`, `in(X)` denotes the submodule generated by the
611
+ initial forms of elements of `X`. [SCA, defn 2.3.2]
612
+
613
+ A standard basis is called minimal if no subset of it is a standard basis.
614
+
615
+ One may show that standard bases are always generating sets.
616
+
617
+ Minimal standard bases are not unique. This algorithm computes a
618
+ deterministic result, depending on the particular order of `G`.
619
+
620
+ If ``extended=True``, also compute the transition matrix from the initial
621
+ generators to the groebner basis. That is, return a list of coefficient
622
+ vectors, expressing the elements of the groebner basis in terms of the
623
+ elements of ``G``.
624
+
625
+ This functions implements the "sugar" strategy, see
626
+
627
+ Giovini et al: "One sugar cube, please" OR Selection strategies in
628
+ Buchberger algorithm.
629
+ """
630
+
631
+ # The critical pair set.
632
+ # A critical pair is stored as (i, j, s, t) where (i, j) defines the pair
633
+ # (by indexing S), s is the sugar of the pair, and t is the lcm of their
634
+ # leading monomials.
635
+ P = []
636
+
637
+ # The eventual standard basis.
638
+ S = []
639
+ Sugars = []
640
+
641
+ def Ssugar(i, j):
642
+ """Compute the sugar of the S-poly corresponding to (i, j)."""
643
+ LMi = sdm_LM(S[i])
644
+ LMj = sdm_LM(S[j])
645
+ return max(Sugars[i] - sdm_monomial_deg(LMi),
646
+ Sugars[j] - sdm_monomial_deg(LMj)) \
647
+ + sdm_monomial_deg(sdm_monomial_lcm(LMi, LMj))
648
+
649
+ ourkey = lambda p: (p[2], O(p[3]), p[1])
650
+
651
+ def update(f, sugar, P):
652
+ """Add f with sugar ``sugar`` to S, update P."""
653
+ if not f:
654
+ return P
655
+ k = len(S)
656
+ S.append(f)
657
+ Sugars.append(sugar)
658
+
659
+ LMf = sdm_LM(f)
660
+
661
+ def removethis(pair):
662
+ i, j, s, t = pair
663
+ if LMf[0] != t[0]:
664
+ return False
665
+ tik = sdm_monomial_lcm(LMf, sdm_LM(S[i]))
666
+ tjk = sdm_monomial_lcm(LMf, sdm_LM(S[j]))
667
+ return tik != t and tjk != t and sdm_monomial_divides(tik, t) and \
668
+ sdm_monomial_divides(tjk, t)
669
+ # apply the chain criterion
670
+ P = [p for p in P if not removethis(p)]
671
+
672
+ # new-pair set
673
+ N = [(i, k, Ssugar(i, k), sdm_monomial_lcm(LMf, sdm_LM(S[i])))
674
+ for i in range(k) if LMf[0] == sdm_LM(S[i])[0]]
675
+ # TODO apply the product criterion?
676
+ N.sort(key=ourkey)
677
+ remove = set()
678
+ for i, p in enumerate(N):
679
+ for j in range(i + 1, len(N)):
680
+ if sdm_monomial_divides(p[3], N[j][3]):
681
+ remove.add(j)
682
+
683
+ # TODO mergesort?
684
+ P.extend(reversed([p for i, p in enumerate(N) if i not in remove]))
685
+ P.sort(key=ourkey, reverse=True)
686
+ # NOTE reverse-sort, because we want to pop from the end
687
+ return P
688
+
689
+ # Figure out the number of generators in the ground ring.
690
+ try:
691
+ # NOTE: we look for the first non-zero vector, take its first monomial
692
+ # the number of generators in the ring is one less than the length
693
+ # (since the zeroth entry is for the module generators)
694
+ numgens = len(next(x[0] for x in G if x)[0]) - 1
695
+ except StopIteration:
696
+ # No non-zero elements in G ...
697
+ if extended:
698
+ return [], []
699
+ return []
700
+
701
+ # This list will store expressions of the elements of S in terms of the
702
+ # initial generators
703
+ coefficients = []
704
+
705
+ # First add all the elements of G to S
706
+ for i, f in enumerate(G):
707
+ P = update(f, sdm_deg(f), P)
708
+ if extended and f:
709
+ coefficients.append(sdm_from_dict({(i,) + (0,)*numgens: K(1)}, O))
710
+
711
+ # Now carry out the buchberger algorithm.
712
+ while P:
713
+ i, j, s, t = P.pop()
714
+ f, g = S[i], S[j]
715
+ if extended:
716
+ sp, coeff = sdm_spoly(f, g, O, K,
717
+ phantom=(coefficients[i], coefficients[j]))
718
+ h, hcoeff = NF(sp, S, O, K, phantom=(coeff, coefficients))
719
+ if h:
720
+ coefficients.append(hcoeff)
721
+ else:
722
+ h = NF(sdm_spoly(f, g, O, K), S, O, K)
723
+ P = update(h, Ssugar(i, j), P)
724
+
725
+ # Finally interreduce the standard basis.
726
+ # (TODO again, better data structures)
727
+ S = {(tuple(f), i) for i, f in enumerate(S)}
728
+ for (a, ai), (b, bi) in permutations(S, 2):
729
+ A = sdm_LM(a)
730
+ B = sdm_LM(b)
731
+ if sdm_monomial_divides(A, B) and (b, bi) in S and (a, ai) in S:
732
+ S.remove((b, bi))
733
+
734
+ L = sorted(((list(f), i) for f, i in S), key=lambda p: O(sdm_LM(p[0])),
735
+ reverse=True)
736
+ res = [x[0] for x in L]
737
+ if extended:
738
+ return res, [coefficients[i] for _, i in L]
739
+ return res
llmeval-env/lib/python3.10/site-packages/sympy/polys/domainmatrix.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stub module to expose DomainMatrix which has now moved to
3
+ sympy.polys.matrices package. It should now be imported as:
4
+
5
+ >>> from sympy.polys.matrices import DomainMatrix
6
+
7
+ This module might be removed in future.
8
+ """
9
+
10
+ from sympy.polys.matrices.domainmatrix import DomainMatrix
11
+
12
+ __all__ = ['DomainMatrix']
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/algebraicfield.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`AlgebraicField` class. """
2
+
3
+
4
+ from sympy.core.add import Add
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.singleton import S
7
+ from sympy.polys.domains.characteristiczero import CharacteristicZero
8
+ from sympy.polys.domains.field import Field
9
+ from sympy.polys.domains.simpledomain import SimpleDomain
10
+ from sympy.polys.polyclasses import ANP
11
+ from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed
12
+ from sympy.utilities import public
13
+
14
+ @public
15
+ class AlgebraicField(Field, CharacteristicZero, SimpleDomain):
16
+ r"""Algebraic number field :ref:`QQ(a)`
17
+
18
+ A :ref:`QQ(a)` domain represents an `algebraic number field`_
19
+ `\mathbb{Q}(a)` as a :py:class:`~.Domain` in the domain system (see
20
+ :ref:`polys-domainsintro`).
21
+
22
+ A :py:class:`~.Poly` created from an expression involving `algebraic
23
+ numbers`_ will treat the algebraic numbers as generators if the generators
24
+ argument is not specified.
25
+
26
+ >>> from sympy import Poly, Symbol, sqrt
27
+ >>> x = Symbol('x')
28
+ >>> Poly(x**2 + sqrt(2))
29
+ Poly(x**2 + (sqrt(2)), x, sqrt(2), domain='ZZ')
30
+
31
+ That is a multivariate polynomial with ``sqrt(2)`` treated as one of the
32
+ generators (variables). If the generators are explicitly specified then
33
+ ``sqrt(2)`` will be considered to be a coefficient but by default the
34
+ :ref:`EX` domain is used. To make a :py:class:`~.Poly` with a :ref:`QQ(a)`
35
+ domain the argument ``extension=True`` can be given.
36
+
37
+ >>> Poly(x**2 + sqrt(2), x)
38
+ Poly(x**2 + sqrt(2), x, domain='EX')
39
+ >>> Poly(x**2 + sqrt(2), x, extension=True)
40
+ Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2)>')
41
+
42
+ A generator of the algebraic field extension can also be specified
43
+ explicitly which is particularly useful if the coefficients are all
44
+ rational but an extension field is needed (e.g. to factor the
45
+ polynomial).
46
+
47
+ >>> Poly(x**2 + 1)
48
+ Poly(x**2 + 1, x, domain='ZZ')
49
+ >>> Poly(x**2 + 1, extension=sqrt(2))
50
+ Poly(x**2 + 1, x, domain='QQ<sqrt(2)>')
51
+
52
+ It is possible to factorise a polynomial over a :ref:`QQ(a)` domain using
53
+ the ``extension`` argument to :py:func:`~.factor` or by specifying the domain
54
+ explicitly.
55
+
56
+ >>> from sympy import factor, QQ
57
+ >>> factor(x**2 - 2)
58
+ x**2 - 2
59
+ >>> factor(x**2 - 2, extension=sqrt(2))
60
+ (x - sqrt(2))*(x + sqrt(2))
61
+ >>> factor(x**2 - 2, domain='QQ<sqrt(2)>')
62
+ (x - sqrt(2))*(x + sqrt(2))
63
+ >>> factor(x**2 - 2, domain=QQ.algebraic_field(sqrt(2)))
64
+ (x - sqrt(2))*(x + sqrt(2))
65
+
66
+ The ``extension=True`` argument can be used but will only create an
67
+ extension that contains the coefficients which is usually not enough to
68
+ factorise the polynomial.
69
+
70
+ >>> p = x**3 + sqrt(2)*x**2 - 2*x - 2*sqrt(2)
71
+ >>> factor(p) # treats sqrt(2) as a symbol
72
+ (x + sqrt(2))*(x**2 - 2)
73
+ >>> factor(p, extension=True)
74
+ (x - sqrt(2))*(x + sqrt(2))**2
75
+ >>> factor(x**2 - 2, extension=True) # all rational coefficients
76
+ x**2 - 2
77
+
78
+ It is also possible to use :ref:`QQ(a)` with the :py:func:`~.cancel`
79
+ and :py:func:`~.gcd` functions.
80
+
81
+ >>> from sympy import cancel, gcd
82
+ >>> cancel((x**2 - 2)/(x - sqrt(2)))
83
+ (x**2 - 2)/(x - sqrt(2))
84
+ >>> cancel((x**2 - 2)/(x - sqrt(2)), extension=sqrt(2))
85
+ x + sqrt(2)
86
+ >>> gcd(x**2 - 2, x - sqrt(2))
87
+ 1
88
+ >>> gcd(x**2 - 2, x - sqrt(2), extension=sqrt(2))
89
+ x - sqrt(2)
90
+
91
+ When using the domain directly :ref:`QQ(a)` can be used as a constructor
92
+ to create instances which then support the operations ``+,-,*,**,/``. The
93
+ :py:meth:`~.Domain.algebraic_field` method is used to construct a
94
+ particular :ref:`QQ(a)` domain. The :py:meth:`~.Domain.from_sympy` method
95
+ can be used to create domain elements from normal SymPy expressions.
96
+
97
+ >>> K = QQ.algebraic_field(sqrt(2))
98
+ >>> K
99
+ QQ<sqrt(2)>
100
+ >>> xk = K.from_sympy(3 + 4*sqrt(2))
101
+ >>> xk # doctest: +SKIP
102
+ ANP([4, 3], [1, 0, -2], QQ)
103
+
104
+ Elements of :ref:`QQ(a)` are instances of :py:class:`~.ANP` which have
105
+ limited printing support. The raw display shows the internal
106
+ representation of the element as the list ``[4, 3]`` representing the
107
+ coefficients of ``1`` and ``sqrt(2)`` for this element in the form
108
+ ``a * sqrt(2) + b * 1`` where ``a`` and ``b`` are elements of :ref:`QQ`.
109
+ The minimal polynomial for the generator ``(x**2 - 2)`` is also shown in
110
+ the :ref:`dup-representation` as the list ``[1, 0, -2]``. We can use
111
+ :py:meth:`~.Domain.to_sympy` to get a better printed form for the
112
+ elements and to see the results of operations.
113
+
114
+ >>> xk = K.from_sympy(3 + 4*sqrt(2))
115
+ >>> yk = K.from_sympy(2 + 3*sqrt(2))
116
+ >>> xk * yk # doctest: +SKIP
117
+ ANP([17, 30], [1, 0, -2], QQ)
118
+ >>> K.to_sympy(xk * yk)
119
+ 17*sqrt(2) + 30
120
+ >>> K.to_sympy(xk + yk)
121
+ 5 + 7*sqrt(2)
122
+ >>> K.to_sympy(xk ** 2)
123
+ 24*sqrt(2) + 41
124
+ >>> K.to_sympy(xk / yk)
125
+ sqrt(2)/14 + 9/7
126
+
127
+ Any expression representing an algebraic number can be used to generate
128
+ a :ref:`QQ(a)` domain provided its `minimal polynomial`_ can be computed.
129
+ The function :py:func:`~.minpoly` function is used for this.
130
+
131
+ >>> from sympy import exp, I, pi, minpoly
132
+ >>> g = exp(2*I*pi/3)
133
+ >>> g
134
+ exp(2*I*pi/3)
135
+ >>> g.is_algebraic
136
+ True
137
+ >>> minpoly(g, x)
138
+ x**2 + x + 1
139
+ >>> factor(x**3 - 1, extension=g)
140
+ (x - 1)*(x - exp(2*I*pi/3))*(x + 1 + exp(2*I*pi/3))
141
+
142
+ It is also possible to make an algebraic field from multiple extension
143
+ elements.
144
+
145
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
146
+ >>> K
147
+ QQ<sqrt(2) + sqrt(3)>
148
+ >>> p = x**4 - 5*x**2 + 6
149
+ >>> factor(p)
150
+ (x**2 - 3)*(x**2 - 2)
151
+ >>> factor(p, domain=K)
152
+ (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))
153
+ >>> factor(p, extension=[sqrt(2), sqrt(3)])
154
+ (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))
155
+
156
+ Multiple extension elements are always combined together to make a single
157
+ `primitive element`_. In the case of ``[sqrt(2), sqrt(3)]`` the primitive
158
+ element chosen is ``sqrt(2) + sqrt(3)`` which is why the domain displays
159
+ as ``QQ<sqrt(2) + sqrt(3)>``. The minimal polynomial for the primitive
160
+ element is computed using the :py:func:`~.primitive_element` function.
161
+
162
+ >>> from sympy import primitive_element
163
+ >>> primitive_element([sqrt(2), sqrt(3)], x)
164
+ (x**4 - 10*x**2 + 1, [1, 1])
165
+ >>> minpoly(sqrt(2) + sqrt(3), x)
166
+ x**4 - 10*x**2 + 1
167
+
168
+ The extension elements that generate the domain can be accessed from the
169
+ domain using the :py:attr:`~.ext` and :py:attr:`~.orig_ext` attributes as
170
+ instances of :py:class:`~.AlgebraicNumber`. The minimal polynomial for
171
+ the primitive element as a :py:class:`~.DMP` instance is available as
172
+ :py:attr:`~.mod`.
173
+
174
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
175
+ >>> K
176
+ QQ<sqrt(2) + sqrt(3)>
177
+ >>> K.ext
178
+ sqrt(2) + sqrt(3)
179
+ >>> K.orig_ext
180
+ (sqrt(2), sqrt(3))
181
+ >>> K.mod
182
+ DMP([1, 0, -10, 0, 1], QQ, None)
183
+
184
+ The `discriminant`_ of the field can be obtained from the
185
+ :py:meth:`~.discriminant` method, and an `integral basis`_ from the
186
+ :py:meth:`~.integral_basis` method. The latter returns a list of
187
+ :py:class:`~.ANP` instances by default, but can be made to return instances
188
+ of :py:class:`~.Expr` or :py:class:`~.AlgebraicNumber` by passing a ``fmt``
189
+ argument. The maximal order, or ring of integers, of the field can also be
190
+ obtained from the :py:meth:`~.maximal_order` method, as a
191
+ :py:class:`~sympy.polys.numberfields.modules.Submodule`.
192
+
193
+ >>> zeta5 = exp(2*I*pi/5)
194
+ >>> K = QQ.algebraic_field(zeta5)
195
+ >>> K
196
+ QQ<exp(2*I*pi/5)>
197
+ >>> K.discriminant()
198
+ 125
199
+ >>> K = QQ.algebraic_field(sqrt(5))
200
+ >>> K
201
+ QQ<sqrt(5)>
202
+ >>> K.integral_basis(fmt='sympy')
203
+ [1, 1/2 + sqrt(5)/2]
204
+ >>> K.maximal_order()
205
+ Submodule[[2, 0], [1, 1]]/2
206
+
207
+ The factorization of a rational prime into prime ideals of the field is
208
+ computed by the :py:meth:`~.primes_above` method, which returns a list
209
+ of :py:class:`~sympy.polys.numberfields.primes.PrimeIdeal` instances.
210
+
211
+ >>> zeta7 = exp(2*I*pi/7)
212
+ >>> K = QQ.algebraic_field(zeta7)
213
+ >>> K
214
+ QQ<exp(2*I*pi/7)>
215
+ >>> K.primes_above(11)
216
+ [(11, _x**3 + 5*_x**2 + 4*_x - 1), (11, _x**3 - 4*_x**2 - 5*_x - 1)]
217
+
218
+ The Galois group of the Galois closure of the field can be computed (when
219
+ the minimal polynomial of the field is of sufficiently small degree).
220
+
221
+ >>> K.galois_group(by_name=True)[0]
222
+ S6TransitiveSubgroups.C6
223
+
224
+ Notes
225
+ =====
226
+
227
+ It is not currently possible to generate an algebraic extension over any
228
+ domain other than :ref:`QQ`. Ideally it would be possible to generate
229
+ extensions like ``QQ(x)(sqrt(x**2 - 2))``. This is equivalent to the
230
+ quotient ring ``QQ(x)[y]/(y**2 - x**2 + 2)`` and there are two
231
+ implementations of this kind of quotient ring/extension in the
232
+ :py:class:`~.QuotientRing` and :py:class:`~.MonogenicFiniteExtension`
233
+ classes. Each of those implementations needs some work to make them fully
234
+ usable though.
235
+
236
+ .. _algebraic number field: https://en.wikipedia.org/wiki/Algebraic_number_field
237
+ .. _algebraic numbers: https://en.wikipedia.org/wiki/Algebraic_number
238
+ .. _discriminant: https://en.wikipedia.org/wiki/Discriminant_of_an_algebraic_number_field
239
+ .. _integral basis: https://en.wikipedia.org/wiki/Algebraic_number_field#Integral_basis
240
+ .. _minimal polynomial: https://en.wikipedia.org/wiki/Minimal_polynomial_(field_theory)
241
+ .. _primitive element: https://en.wikipedia.org/wiki/Primitive_element_theorem
242
+ """
243
+
244
+ dtype = ANP
245
+
246
+ is_AlgebraicField = is_Algebraic = True
247
+ is_Numerical = True
248
+
249
+ has_assoc_Ring = False
250
+ has_assoc_Field = True
251
+
252
+ def __init__(self, dom, *ext, alias=None):
253
+ r"""
254
+ Parameters
255
+ ==========
256
+
257
+ dom : :py:class:`~.Domain`
258
+ The base field over which this is an extension field.
259
+ Currently only :ref:`QQ` is accepted.
260
+
261
+ *ext : One or more :py:class:`~.Expr`
262
+ Generators of the extension. These should be expressions that are
263
+ algebraic over `\mathbb{Q}`.
264
+
265
+ alias : str, :py:class:`~.Symbol`, None, optional (default=None)
266
+ If provided, this will be used as the alias symbol for the
267
+ primitive element of the :py:class:`~.AlgebraicField`.
268
+ If ``None``, while ``ext`` consists of exactly one
269
+ :py:class:`~.AlgebraicNumber`, its alias (if any) will be used.
270
+ """
271
+ if not dom.is_QQ:
272
+ raise DomainError("ground domain must be a rational field")
273
+
274
+ from sympy.polys.numberfields import to_number_field
275
+ if len(ext) == 1 and isinstance(ext[0], tuple):
276
+ orig_ext = ext[0][1:]
277
+ else:
278
+ orig_ext = ext
279
+
280
+ if alias is None and len(ext) == 1:
281
+ alias = getattr(ext[0], 'alias', None)
282
+
283
+ self.orig_ext = orig_ext
284
+ """
285
+ Original elements given to generate the extension.
286
+
287
+ >>> from sympy import QQ, sqrt
288
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
289
+ >>> K.orig_ext
290
+ (sqrt(2), sqrt(3))
291
+ """
292
+
293
+ self.ext = to_number_field(ext, alias=alias)
294
+ """
295
+ Primitive element used for the extension.
296
+
297
+ >>> from sympy import QQ, sqrt
298
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
299
+ >>> K.ext
300
+ sqrt(2) + sqrt(3)
301
+ """
302
+
303
+ self.mod = self.ext.minpoly.rep
304
+ """
305
+ Minimal polynomial for the primitive element of the extension.
306
+
307
+ >>> from sympy import QQ, sqrt
308
+ >>> K = QQ.algebraic_field(sqrt(2))
309
+ >>> K.mod
310
+ DMP([1, 0, -2], QQ, None)
311
+ """
312
+
313
+ self.domain = self.dom = dom
314
+
315
+ self.ngens = 1
316
+ self.symbols = self.gens = (self.ext,)
317
+ self.unit = self([dom(1), dom(0)])
318
+
319
+ self.zero = self.dtype.zero(self.mod.rep, dom)
320
+ self.one = self.dtype.one(self.mod.rep, dom)
321
+
322
+ self._maximal_order = None
323
+ self._discriminant = None
324
+ self._nilradicals_mod_p = {}
325
+
326
+ def new(self, element):
327
+ return self.dtype(element, self.mod.rep, self.dom)
328
+
329
+ def __str__(self):
330
+ return str(self.dom) + '<' + str(self.ext) + '>'
331
+
332
+ def __hash__(self):
333
+ return hash((self.__class__.__name__, self.dtype, self.dom, self.ext))
334
+
335
+ def __eq__(self, other):
336
+ """Returns ``True`` if two domains are equivalent. """
337
+ return isinstance(other, AlgebraicField) and \
338
+ self.dtype == other.dtype and self.ext == other.ext
339
+
340
+ def algebraic_field(self, *extension, alias=None):
341
+ r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """
342
+ return AlgebraicField(self.dom, *((self.ext,) + extension), alias=alias)
343
+
344
+ def to_alg_num(self, a):
345
+ """Convert ``a`` of ``dtype`` to an :py:class:`~.AlgebraicNumber`. """
346
+ return self.ext.field_element(a)
347
+
348
+ def to_sympy(self, a):
349
+ """Convert ``a`` of ``dtype`` to a SymPy object. """
350
+ # Precompute a converter to be reused:
351
+ if not hasattr(self, '_converter'):
352
+ self._converter = _make_converter(self)
353
+
354
+ return self._converter(a)
355
+
356
+ def from_sympy(self, a):
357
+ """Convert SymPy's expression to ``dtype``. """
358
+ try:
359
+ return self([self.dom.from_sympy(a)])
360
+ except CoercionFailed:
361
+ pass
362
+
363
+ from sympy.polys.numberfields import to_number_field
364
+
365
+ try:
366
+ return self(to_number_field(a, self.ext).native_coeffs())
367
+ except (NotAlgebraic, IsomorphismFailed):
368
+ raise CoercionFailed(
369
+ "%s is not a valid algebraic number in %s" % (a, self))
370
+
371
+ def from_ZZ(K1, a, K0):
372
+ """Convert a Python ``int`` object to ``dtype``. """
373
+ return K1(K1.dom.convert(a, K0))
374
+
375
+ def from_ZZ_python(K1, a, K0):
376
+ """Convert a Python ``int`` object to ``dtype``. """
377
+ return K1(K1.dom.convert(a, K0))
378
+
379
+ def from_QQ(K1, a, K0):
380
+ """Convert a Python ``Fraction`` object to ``dtype``. """
381
+ return K1(K1.dom.convert(a, K0))
382
+
383
+ def from_QQ_python(K1, a, K0):
384
+ """Convert a Python ``Fraction`` object to ``dtype``. """
385
+ return K1(K1.dom.convert(a, K0))
386
+
387
+ def from_ZZ_gmpy(K1, a, K0):
388
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
389
+ return K1(K1.dom.convert(a, K0))
390
+
391
+ def from_QQ_gmpy(K1, a, K0):
392
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
393
+ return K1(K1.dom.convert(a, K0))
394
+
395
+ def from_RealField(K1, a, K0):
396
+ """Convert a mpmath ``mpf`` object to ``dtype``. """
397
+ return K1(K1.dom.convert(a, K0))
398
+
399
+ def get_ring(self):
400
+ """Returns a ring associated with ``self``. """
401
+ raise DomainError('there is no ring associated with %s' % self)
402
+
403
+ def is_positive(self, a):
404
+ """Returns True if ``a`` is positive. """
405
+ return self.dom.is_positive(a.LC())
406
+
407
+ def is_negative(self, a):
408
+ """Returns True if ``a`` is negative. """
409
+ return self.dom.is_negative(a.LC())
410
+
411
+ def is_nonpositive(self, a):
412
+ """Returns True if ``a`` is non-positive. """
413
+ return self.dom.is_nonpositive(a.LC())
414
+
415
+ def is_nonnegative(self, a):
416
+ """Returns True if ``a`` is non-negative. """
417
+ return self.dom.is_nonnegative(a.LC())
418
+
419
+ def numer(self, a):
420
+ """Returns numerator of ``a``. """
421
+ return a
422
+
423
+ def denom(self, a):
424
+ """Returns denominator of ``a``. """
425
+ return self.one
426
+
427
+ def from_AlgebraicField(K1, a, K0):
428
+ """Convert AlgebraicField element 'a' to another AlgebraicField """
429
+ return K1.from_sympy(K0.to_sympy(a))
430
+
431
+ def from_GaussianIntegerRing(K1, a, K0):
432
+ """Convert a GaussianInteger element 'a' to ``dtype``. """
433
+ return K1.from_sympy(K0.to_sympy(a))
434
+
435
+ def from_GaussianRationalField(K1, a, K0):
436
+ """Convert a GaussianRational element 'a' to ``dtype``. """
437
+ return K1.from_sympy(K0.to_sympy(a))
438
+
439
+ def _do_round_two(self):
440
+ from sympy.polys.numberfields.basis import round_two
441
+ ZK, dK = round_two(self, radicals=self._nilradicals_mod_p)
442
+ self._maximal_order = ZK
443
+ self._discriminant = dK
444
+
445
+ def maximal_order(self):
446
+ """
447
+ Compute the maximal order, or ring of integers, of the field.
448
+
449
+ Returns
450
+ =======
451
+
452
+ :py:class:`~sympy.polys.numberfields.modules.Submodule`.
453
+
454
+ See Also
455
+ ========
456
+
457
+ integral_basis
458
+
459
+ """
460
+ if self._maximal_order is None:
461
+ self._do_round_two()
462
+ return self._maximal_order
463
+
464
+ def integral_basis(self, fmt=None):
465
+ r"""
466
+ Get an integral basis for the field.
467
+
468
+ Parameters
469
+ ==========
470
+
471
+ fmt : str, None, optional (default=None)
472
+ If ``None``, return a list of :py:class:`~.ANP` instances.
473
+ If ``"sympy"``, convert each element of the list to an
474
+ :py:class:`~.Expr`, using ``self.to_sympy()``.
475
+ If ``"alg"``, convert each element of the list to an
476
+ :py:class:`~.AlgebraicNumber`, using ``self.to_alg_num()``.
477
+
478
+ Examples
479
+ ========
480
+
481
+ >>> from sympy import QQ, AlgebraicNumber, sqrt
482
+ >>> alpha = AlgebraicNumber(sqrt(5), alias='alpha')
483
+ >>> k = QQ.algebraic_field(alpha)
484
+ >>> B0 = k.integral_basis()
485
+ >>> B1 = k.integral_basis(fmt='sympy')
486
+ >>> B2 = k.integral_basis(fmt='alg')
487
+ >>> print(B0[1]) # doctest: +SKIP
488
+ ANP([mpq(1,2), mpq(1,2)], [mpq(1,1), mpq(0,1), mpq(-5,1)], QQ)
489
+ >>> print(B1[1])
490
+ 1/2 + alpha/2
491
+ >>> print(B2[1])
492
+ alpha/2 + 1/2
493
+
494
+ In the last two cases we get legible expressions, which print somewhat
495
+ differently because of the different types involved:
496
+
497
+ >>> print(type(B1[1]))
498
+ <class 'sympy.core.add.Add'>
499
+ >>> print(type(B2[1]))
500
+ <class 'sympy.core.numbers.AlgebraicNumber'>
501
+
502
+ See Also
503
+ ========
504
+
505
+ to_sympy
506
+ to_alg_num
507
+ maximal_order
508
+ """
509
+ ZK = self.maximal_order()
510
+ M = ZK.QQ_matrix
511
+ n = M.shape[1]
512
+ B = [self.new(list(reversed(M[:, j].flat()))) for j in range(n)]
513
+ if fmt == 'sympy':
514
+ return [self.to_sympy(b) for b in B]
515
+ elif fmt == 'alg':
516
+ return [self.to_alg_num(b) for b in B]
517
+ return B
518
+
519
+ def discriminant(self):
520
+ """Get the discriminant of the field."""
521
+ if self._discriminant is None:
522
+ self._do_round_two()
523
+ return self._discriminant
524
+
525
+ def primes_above(self, p):
526
+ """Compute the prime ideals lying above a given rational prime *p*."""
527
+ from sympy.polys.numberfields.primes import prime_decomp
528
+ ZK = self.maximal_order()
529
+ dK = self.discriminant()
530
+ rad = self._nilradicals_mod_p.get(p)
531
+ return prime_decomp(p, ZK=ZK, dK=dK, radical=rad)
532
+
533
+ def galois_group(self, by_name=False, max_tries=30, randomize=False):
534
+ """
535
+ Compute the Galois group of the Galois closure of this field.
536
+
537
+ Examples
538
+ ========
539
+
540
+ If the field is Galois, the order of the group will equal the degree
541
+ of the field:
542
+
543
+ >>> from sympy import QQ
544
+ >>> from sympy.abc import x
545
+ >>> k = QQ.alg_field_from_poly(x**4 + 1)
546
+ >>> G, _ = k.galois_group()
547
+ >>> G.order()
548
+ 4
549
+
550
+ If the field is not Galois, then its Galois closure is a proper
551
+ extension, and the order of the Galois group will be greater than the
552
+ degree of the field:
553
+
554
+ >>> k = QQ.alg_field_from_poly(x**4 - 2)
555
+ >>> G, _ = k.galois_group()
556
+ >>> G.order()
557
+ 8
558
+
559
+ See Also
560
+ ========
561
+
562
+ sympy.polys.numberfields.galoisgroups.galois_group
563
+
564
+ """
565
+ return self.ext.minpoly_of_element().galois_group(
566
+ by_name=by_name, max_tries=max_tries, randomize=randomize)
567
+
568
+
569
+ def _make_converter(K):
570
+ """Construct the converter to convert back to Expr"""
571
+ # Precompute the effect of converting to SymPy and expanding expressions
572
+ # like (sqrt(2) + sqrt(3))**2. Asking Expr to do the expansion on every
573
+ # conversion from K to Expr is slow. Here we compute the expansions for
574
+ # each power of the generator and collect together the resulting algebraic
575
+ # terms and the rational coefficients into a matrix.
576
+
577
+ gen = K.ext.as_expr()
578
+ todom = K.dom.from_sympy
579
+
580
+ # We'll let Expr compute the expansions. We won't make any presumptions
581
+ # about what this results in except that it is QQ-linear in some terms
582
+ # that we will call algebraics. The final result will be expressed in
583
+ # terms of those.
584
+ powers = [S.One, gen]
585
+ for n in range(2, K.mod.degree()):
586
+ powers.append((gen * powers[-1]).expand())
587
+
588
+ # Collect the rational coefficients and algebraic Expr that can
589
+ # map the ANP coefficients into an expanded SymPy expression
590
+ terms = [dict(t.as_coeff_Mul()[::-1] for t in Add.make_args(p)) for p in powers]
591
+ algebraics = set().union(*terms)
592
+ matrix = [[todom(t.get(a, S.Zero)) for t in terms] for a in algebraics]
593
+
594
+ # Create a function to do the conversion efficiently:
595
+
596
+ def converter(a):
597
+ """Convert a to Expr using converter"""
598
+ ai = a.rep[::-1]
599
+ tosympy = K.dom.to_sympy
600
+ coeffs_dom = [sum(mij*aj for mij, aj in zip(mi, ai)) for mi in matrix]
601
+ coeffs_sympy = [tosympy(c) for c in coeffs_dom]
602
+ res = Add(*(Mul(c, a) for c, a in zip(coeffs_sympy, algebraics)))
603
+ return res
604
+
605
+ return converter
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/complexfield.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`ComplexField` class. """
2
+
3
+
4
+ from sympy.core.numbers import Float, I
5
+ from sympy.polys.domains.characteristiczero import CharacteristicZero
6
+ from sympy.polys.domains.field import Field
7
+ from sympy.polys.domains.mpelements import MPContext
8
+ from sympy.polys.domains.simpledomain import SimpleDomain
9
+ from sympy.polys.polyerrors import DomainError, CoercionFailed
10
+ from sympy.utilities import public
11
+
12
+ @public
13
+ class ComplexField(Field, CharacteristicZero, SimpleDomain):
14
+ """Complex numbers up to the given precision. """
15
+
16
+ rep = 'CC'
17
+
18
+ is_ComplexField = is_CC = True
19
+
20
+ is_Exact = False
21
+ is_Numerical = True
22
+
23
+ has_assoc_Ring = False
24
+ has_assoc_Field = True
25
+
26
+ _default_precision = 53
27
+
28
+ @property
29
+ def has_default_precision(self):
30
+ return self.precision == self._default_precision
31
+
32
+ @property
33
+ def precision(self):
34
+ return self._context.prec
35
+
36
+ @property
37
+ def dps(self):
38
+ return self._context.dps
39
+
40
+ @property
41
+ def tolerance(self):
42
+ return self._context.tolerance
43
+
44
+ def __init__(self, prec=_default_precision, dps=None, tol=None):
45
+ context = MPContext(prec, dps, tol, False)
46
+ context._parent = self
47
+ self._context = context
48
+
49
+ self.dtype = context.mpc
50
+ self.zero = self.dtype(0)
51
+ self.one = self.dtype(1)
52
+
53
+ def __eq__(self, other):
54
+ return (isinstance(other, ComplexField)
55
+ and self.precision == other.precision
56
+ and self.tolerance == other.tolerance)
57
+
58
+ def __hash__(self):
59
+ return hash((self.__class__.__name__, self.dtype, self.precision, self.tolerance))
60
+
61
+ def to_sympy(self, element):
62
+ """Convert ``element`` to SymPy number. """
63
+ return Float(element.real, self.dps) + I*Float(element.imag, self.dps)
64
+
65
+ def from_sympy(self, expr):
66
+ """Convert SymPy's number to ``dtype``. """
67
+ number = expr.evalf(n=self.dps)
68
+ real, imag = number.as_real_imag()
69
+
70
+ if real.is_Number and imag.is_Number:
71
+ return self.dtype(real, imag)
72
+ else:
73
+ raise CoercionFailed("expected complex number, got %s" % expr)
74
+
75
+ def from_ZZ(self, element, base):
76
+ return self.dtype(element)
77
+
78
+ def from_QQ(self, element, base):
79
+ return self.dtype(int(element.numerator)) / int(element.denominator)
80
+
81
+ def from_ZZ_python(self, element, base):
82
+ return self.dtype(element)
83
+
84
+ def from_QQ_python(self, element, base):
85
+ return self.dtype(element.numerator) / element.denominator
86
+
87
+ def from_ZZ_gmpy(self, element, base):
88
+ return self.dtype(int(element))
89
+
90
+ def from_QQ_gmpy(self, element, base):
91
+ return self.dtype(int(element.numerator)) / int(element.denominator)
92
+
93
+ def from_GaussianIntegerRing(self, element, base):
94
+ return self.dtype(int(element.x), int(element.y))
95
+
96
+ def from_GaussianRationalField(self, element, base):
97
+ x = element.x
98
+ y = element.y
99
+ return (self.dtype(int(x.numerator)) / int(x.denominator) +
100
+ self.dtype(0, int(y.numerator)) / int(y.denominator))
101
+
102
+ def from_AlgebraicField(self, element, base):
103
+ return self.from_sympy(base.to_sympy(element).evalf(self.dps))
104
+
105
+ def from_RealField(self, element, base):
106
+ return self.dtype(element)
107
+
108
+ def from_ComplexField(self, element, base):
109
+ if self == base:
110
+ return element
111
+ else:
112
+ return self.dtype(element)
113
+
114
+ def get_ring(self):
115
+ """Returns a ring associated with ``self``. """
116
+ raise DomainError("there is no ring associated with %s" % self)
117
+
118
+ def get_exact(self):
119
+ """Returns an exact domain associated with ``self``. """
120
+ raise DomainError("there is no exact domain associated with %s" % self)
121
+
122
+ def is_negative(self, element):
123
+ """Returns ``False`` for any ``ComplexElement``. """
124
+ return False
125
+
126
+ def is_positive(self, element):
127
+ """Returns ``False`` for any ``ComplexElement``. """
128
+ return False
129
+
130
+ def is_nonnegative(self, element):
131
+ """Returns ``False`` for any ``ComplexElement``. """
132
+ return False
133
+
134
+ def is_nonpositive(self, element):
135
+ """Returns ``False`` for any ``ComplexElement``. """
136
+ return False
137
+
138
+ def gcd(self, a, b):
139
+ """Returns GCD of ``a`` and ``b``. """
140
+ return self.one
141
+
142
+ def lcm(self, a, b):
143
+ """Returns LCM of ``a`` and ``b``. """
144
+ return a*b
145
+
146
+ def almosteq(self, a, b, tolerance=None):
147
+ """Check if ``a`` and ``b`` are almost equal. """
148
+ return self._context.almosteq(a, b, tolerance)
149
+
150
+
151
+ CC = ComplexField()
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/domain.py ADDED
@@ -0,0 +1,1304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`Domain` class. """
2
+
3
+ from __future__ import annotations
4
+ from typing import Any
5
+
6
+ from sympy.core.numbers import AlgebraicNumber
7
+ from sympy.core import Basic, sympify
8
+ from sympy.core.sorting import default_sort_key, ordered
9
+ from sympy.external.gmpy import HAS_GMPY
10
+ from sympy.polys.domains.domainelement import DomainElement
11
+ from sympy.polys.orderings import lex
12
+ from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError
13
+ from sympy.polys.polyutils import _unify_gens, _not_a_coeff
14
+ from sympy.utilities import public
15
+ from sympy.utilities.iterables import is_sequence
16
+
17
+
18
+ @public
19
+ class Domain:
20
+ """Superclass for all domains in the polys domains system.
21
+
22
+ See :ref:`polys-domainsintro` for an introductory explanation of the
23
+ domains system.
24
+
25
+ The :py:class:`~.Domain` class is an abstract base class for all of the
26
+ concrete domain types. There are many different :py:class:`~.Domain`
27
+ subclasses each of which has an associated ``dtype`` which is a class
28
+ representing the elements of the domain. The coefficients of a
29
+ :py:class:`~.Poly` are elements of a domain which must be a subclass of
30
+ :py:class:`~.Domain`.
31
+
32
+ Examples
33
+ ========
34
+
35
+ The most common example domains are the integers :ref:`ZZ` and the
36
+ rationals :ref:`QQ`.
37
+
38
+ >>> from sympy import Poly, symbols, Domain
39
+ >>> x, y = symbols('x, y')
40
+ >>> p = Poly(x**2 + y)
41
+ >>> p
42
+ Poly(x**2 + y, x, y, domain='ZZ')
43
+ >>> p.domain
44
+ ZZ
45
+ >>> isinstance(p.domain, Domain)
46
+ True
47
+ >>> Poly(x**2 + y/2)
48
+ Poly(x**2 + 1/2*y, x, y, domain='QQ')
49
+
50
+ The domains can be used directly in which case the domain object e.g.
51
+ (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of
52
+ ``dtype``.
53
+
54
+ >>> from sympy import ZZ, QQ
55
+ >>> ZZ(2)
56
+ 2
57
+ >>> ZZ.dtype # doctest: +SKIP
58
+ <class 'int'>
59
+ >>> type(ZZ(2)) # doctest: +SKIP
60
+ <class 'int'>
61
+ >>> QQ(1, 2)
62
+ 1/2
63
+ >>> type(QQ(1, 2)) # doctest: +SKIP
64
+ <class 'sympy.polys.domains.pythonrational.PythonRational'>
65
+
66
+ The corresponding domain elements can be used with the arithmetic
67
+ operations ``+,-,*,**`` and depending on the domain some combination of
68
+ ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor
69
+ division) and ``%`` (modulo division) can be used but ``/`` (true
70
+ division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements
71
+ can be used with ``/`` but ``//`` and ``%`` should not be used. Some
72
+ domains have a :py:meth:`~.Domain.gcd` method.
73
+
74
+ >>> ZZ(2) + ZZ(3)
75
+ 5
76
+ >>> ZZ(5) // ZZ(2)
77
+ 2
78
+ >>> ZZ(5) % ZZ(2)
79
+ 1
80
+ >>> QQ(1, 2) / QQ(2, 3)
81
+ 3/4
82
+ >>> ZZ.gcd(ZZ(4), ZZ(2))
83
+ 2
84
+ >>> QQ.gcd(QQ(2,7), QQ(5,3))
85
+ 1/21
86
+ >>> ZZ.is_Field
87
+ False
88
+ >>> QQ.is_Field
89
+ True
90
+
91
+ There are also many other domains including:
92
+
93
+ 1. :ref:`GF(p)` for finite fields of prime order.
94
+ 2. :ref:`RR` for real (floating point) numbers.
95
+ 3. :ref:`CC` for complex (floating point) numbers.
96
+ 4. :ref:`QQ(a)` for algebraic number fields.
97
+ 5. :ref:`K[x]` for polynomial rings.
98
+ 6. :ref:`K(x)` for rational function fields.
99
+ 7. :ref:`EX` for arbitrary expressions.
100
+
101
+ Each domain is represented by a domain object and also an implementation
102
+ class (``dtype``) for the elements of the domain. For example the
103
+ :ref:`K[x]` domains are represented by a domain object which is an
104
+ instance of :py:class:`~.PolynomialRing` and the elements are always
105
+ instances of :py:class:`~.PolyElement`. The implementation class
106
+ represents particular types of mathematical expressions in a way that is
107
+ more efficient than a normal SymPy expression which is of type
108
+ :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and
109
+ :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr`
110
+ to a domain element and vice versa.
111
+
112
+ >>> from sympy import Symbol, ZZ, Expr
113
+ >>> x = Symbol('x')
114
+ >>> K = ZZ[x] # polynomial ring domain
115
+ >>> K
116
+ ZZ[x]
117
+ >>> type(K) # class of the domain
118
+ <class 'sympy.polys.domains.polynomialring.PolynomialRing'>
119
+ >>> K.dtype # class of the elements
120
+ <class 'sympy.polys.rings.PolyElement'>
121
+ >>> p_expr = x**2 + 1 # Expr
122
+ >>> p_expr
123
+ x**2 + 1
124
+ >>> type(p_expr)
125
+ <class 'sympy.core.add.Add'>
126
+ >>> isinstance(p_expr, Expr)
127
+ True
128
+ >>> p_domain = K.from_sympy(p_expr)
129
+ >>> p_domain # domain element
130
+ x**2 + 1
131
+ >>> type(p_domain)
132
+ <class 'sympy.polys.rings.PolyElement'>
133
+ >>> K.to_sympy(p_domain) == p_expr
134
+ True
135
+
136
+ The :py:meth:`~.Domain.convert_from` method is used to convert domain
137
+ elements from one domain to another.
138
+
139
+ >>> from sympy import ZZ, QQ
140
+ >>> ez = ZZ(2)
141
+ >>> eq = QQ.convert_from(ez, ZZ)
142
+ >>> type(ez) # doctest: +SKIP
143
+ <class 'int'>
144
+ >>> type(eq) # doctest: +SKIP
145
+ <class 'sympy.polys.domains.pythonrational.PythonRational'>
146
+
147
+ Elements from different domains should not be mixed in arithmetic or other
148
+ operations: they should be converted to a common domain first. The domain
149
+ method :py:meth:`~.Domain.unify` is used to find a domain that can
150
+ represent all the elements of two given domains.
151
+
152
+ >>> from sympy import ZZ, QQ, symbols
153
+ >>> x, y = symbols('x, y')
154
+ >>> ZZ.unify(QQ)
155
+ QQ
156
+ >>> ZZ[x].unify(QQ)
157
+ QQ[x]
158
+ >>> ZZ[x].unify(QQ[y])
159
+ QQ[x,y]
160
+
161
+ If a domain is a :py:class:`~.Ring` then is might have an associated
162
+ :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and
163
+ :py:meth:`~.Domain.get_ring` methods will find or create the associated
164
+ domain.
165
+
166
+ >>> from sympy import ZZ, QQ, Symbol
167
+ >>> x = Symbol('x')
168
+ >>> ZZ.has_assoc_Field
169
+ True
170
+ >>> ZZ.get_field()
171
+ QQ
172
+ >>> QQ.has_assoc_Ring
173
+ True
174
+ >>> QQ.get_ring()
175
+ ZZ
176
+ >>> K = QQ[x]
177
+ >>> K
178
+ QQ[x]
179
+ >>> K.get_field()
180
+ QQ(x)
181
+
182
+ See also
183
+ ========
184
+
185
+ DomainElement: abstract base class for domain elements
186
+ construct_domain: construct a minimal domain for some expressions
187
+
188
+ """
189
+
190
+ dtype: type | None = None
191
+ """The type (class) of the elements of this :py:class:`~.Domain`:
192
+
193
+ >>> from sympy import ZZ, QQ, Symbol
194
+ >>> ZZ.dtype
195
+ <class 'int'>
196
+ >>> z = ZZ(2)
197
+ >>> z
198
+ 2
199
+ >>> type(z)
200
+ <class 'int'>
201
+ >>> type(z) == ZZ.dtype
202
+ True
203
+
204
+ Every domain has an associated **dtype** ("datatype") which is the
205
+ class of the associated domain elements.
206
+
207
+ See also
208
+ ========
209
+
210
+ of_type
211
+ """
212
+
213
+ zero: Any = None
214
+ """The zero element of the :py:class:`~.Domain`:
215
+
216
+ >>> from sympy import QQ
217
+ >>> QQ.zero
218
+ 0
219
+ >>> QQ.of_type(QQ.zero)
220
+ True
221
+
222
+ See also
223
+ ========
224
+
225
+ of_type
226
+ one
227
+ """
228
+
229
+ one: Any = None
230
+ """The one element of the :py:class:`~.Domain`:
231
+
232
+ >>> from sympy import QQ
233
+ >>> QQ.one
234
+ 1
235
+ >>> QQ.of_type(QQ.one)
236
+ True
237
+
238
+ See also
239
+ ========
240
+
241
+ of_type
242
+ zero
243
+ """
244
+
245
+ is_Ring = False
246
+ """Boolean flag indicating if the domain is a :py:class:`~.Ring`.
247
+
248
+ >>> from sympy import ZZ
249
+ >>> ZZ.is_Ring
250
+ True
251
+
252
+ Basically every :py:class:`~.Domain` represents a ring so this flag is
253
+ not that useful.
254
+
255
+ See also
256
+ ========
257
+
258
+ is_PID
259
+ is_Field
260
+ get_ring
261
+ has_assoc_Ring
262
+ """
263
+
264
+ is_Field = False
265
+ """Boolean flag indicating if the domain is a :py:class:`~.Field`.
266
+
267
+ >>> from sympy import ZZ, QQ
268
+ >>> ZZ.is_Field
269
+ False
270
+ >>> QQ.is_Field
271
+ True
272
+
273
+ See also
274
+ ========
275
+
276
+ is_PID
277
+ is_Ring
278
+ get_field
279
+ has_assoc_Field
280
+ """
281
+
282
+ has_assoc_Ring = False
283
+ """Boolean flag indicating if the domain has an associated
284
+ :py:class:`~.Ring`.
285
+
286
+ >>> from sympy import QQ
287
+ >>> QQ.has_assoc_Ring
288
+ True
289
+ >>> QQ.get_ring()
290
+ ZZ
291
+
292
+ See also
293
+ ========
294
+
295
+ is_Field
296
+ get_ring
297
+ """
298
+
299
+ has_assoc_Field = False
300
+ """Boolean flag indicating if the domain has an associated
301
+ :py:class:`~.Field`.
302
+
303
+ >>> from sympy import ZZ
304
+ >>> ZZ.has_assoc_Field
305
+ True
306
+ >>> ZZ.get_field()
307
+ QQ
308
+
309
+ See also
310
+ ========
311
+
312
+ is_Field
313
+ get_field
314
+ """
315
+
316
+ is_FiniteField = is_FF = False
317
+ is_IntegerRing = is_ZZ = False
318
+ is_RationalField = is_QQ = False
319
+ is_GaussianRing = is_ZZ_I = False
320
+ is_GaussianField = is_QQ_I = False
321
+ is_RealField = is_RR = False
322
+ is_ComplexField = is_CC = False
323
+ is_AlgebraicField = is_Algebraic = False
324
+ is_PolynomialRing = is_Poly = False
325
+ is_FractionField = is_Frac = False
326
+ is_SymbolicDomain = is_EX = False
327
+ is_SymbolicRawDomain = is_EXRAW = False
328
+ is_FiniteExtension = False
329
+
330
+ is_Exact = True
331
+ is_Numerical = False
332
+
333
+ is_Simple = False
334
+ is_Composite = False
335
+
336
+ is_PID = False
337
+ """Boolean flag indicating if the domain is a `principal ideal domain`_.
338
+
339
+ >>> from sympy import ZZ
340
+ >>> ZZ.has_assoc_Field
341
+ True
342
+ >>> ZZ.get_field()
343
+ QQ
344
+
345
+ .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain
346
+
347
+ See also
348
+ ========
349
+
350
+ is_Field
351
+ get_field
352
+ """
353
+
354
+ has_CharacteristicZero = False
355
+
356
+ rep: str | None = None
357
+ alias: str | None = None
358
+
359
+ def __init__(self):
360
+ raise NotImplementedError
361
+
362
+ def __str__(self):
363
+ return self.rep
364
+
365
+ def __repr__(self):
366
+ return str(self)
367
+
368
+ def __hash__(self):
369
+ return hash((self.__class__.__name__, self.dtype))
370
+
371
+ def new(self, *args):
372
+ return self.dtype(*args)
373
+
374
+ @property
375
+ def tp(self):
376
+ """Alias for :py:attr:`~.Domain.dtype`"""
377
+ return self.dtype
378
+
379
+ def __call__(self, *args):
380
+ """Construct an element of ``self`` domain from ``args``. """
381
+ return self.new(*args)
382
+
383
+ def normal(self, *args):
384
+ return self.dtype(*args)
385
+
386
+ def convert_from(self, element, base):
387
+ """Convert ``element`` to ``self.dtype`` given the base domain. """
388
+ if base.alias is not None:
389
+ method = "from_" + base.alias
390
+ else:
391
+ method = "from_" + base.__class__.__name__
392
+
393
+ _convert = getattr(self, method)
394
+
395
+ if _convert is not None:
396
+ result = _convert(element, base)
397
+
398
+ if result is not None:
399
+ return result
400
+
401
+ raise CoercionFailed("Cannot convert %s of type %s from %s to %s" % (element, type(element), base, self))
402
+
403
+ def convert(self, element, base=None):
404
+ """Convert ``element`` to ``self.dtype``. """
405
+
406
+ if base is not None:
407
+ if _not_a_coeff(element):
408
+ raise CoercionFailed('%s is not in any domain' % element)
409
+ return self.convert_from(element, base)
410
+
411
+ if self.of_type(element):
412
+ return element
413
+
414
+ if _not_a_coeff(element):
415
+ raise CoercionFailed('%s is not in any domain' % element)
416
+
417
+ from sympy.polys.domains import ZZ, QQ, RealField, ComplexField
418
+
419
+ if ZZ.of_type(element):
420
+ return self.convert_from(element, ZZ)
421
+
422
+ if isinstance(element, int):
423
+ return self.convert_from(ZZ(element), ZZ)
424
+
425
+ if HAS_GMPY:
426
+ integers = ZZ
427
+ if isinstance(element, integers.tp):
428
+ return self.convert_from(element, integers)
429
+
430
+ rationals = QQ
431
+ if isinstance(element, rationals.tp):
432
+ return self.convert_from(element, rationals)
433
+
434
+ if isinstance(element, float):
435
+ parent = RealField(tol=False)
436
+ return self.convert_from(parent(element), parent)
437
+
438
+ if isinstance(element, complex):
439
+ parent = ComplexField(tol=False)
440
+ return self.convert_from(parent(element), parent)
441
+
442
+ if isinstance(element, DomainElement):
443
+ return self.convert_from(element, element.parent())
444
+
445
+ # TODO: implement this in from_ methods
446
+ if self.is_Numerical and getattr(element, 'is_ground', False):
447
+ return self.convert(element.LC())
448
+
449
+ if isinstance(element, Basic):
450
+ try:
451
+ return self.from_sympy(element)
452
+ except (TypeError, ValueError):
453
+ pass
454
+ else: # TODO: remove this branch
455
+ if not is_sequence(element):
456
+ try:
457
+ element = sympify(element, strict=True)
458
+ if isinstance(element, Basic):
459
+ return self.from_sympy(element)
460
+ except (TypeError, ValueError):
461
+ pass
462
+
463
+ raise CoercionFailed("Cannot convert %s of type %s to %s" % (element, type(element), self))
464
+
465
+ def of_type(self, element):
466
+ """Check if ``a`` is of type ``dtype``. """
467
+ return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement
468
+
469
+ def __contains__(self, a):
470
+ """Check if ``a`` belongs to this domain. """
471
+ try:
472
+ if _not_a_coeff(a):
473
+ raise CoercionFailed
474
+ self.convert(a) # this might raise, too
475
+ except CoercionFailed:
476
+ return False
477
+
478
+ return True
479
+
480
+ def to_sympy(self, a):
481
+ """Convert domain element *a* to a SymPy expression (Expr).
482
+
483
+ Explanation
484
+ ===========
485
+
486
+ Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most
487
+ public SymPy functions work with objects of type :py:class:`~.Expr`.
488
+ The elements of a :py:class:`~.Domain` have a different internal
489
+ representation. It is not possible to mix domain elements with
490
+ :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and
491
+ :py:meth:`~.Domain.from_sympy` methods to convert its domain elements
492
+ to and from :py:class:`~.Expr`.
493
+
494
+ Parameters
495
+ ==========
496
+
497
+ a: domain element
498
+ An element of this :py:class:`~.Domain`.
499
+
500
+ Returns
501
+ =======
502
+
503
+ expr: Expr
504
+ A normal SymPy expression of type :py:class:`~.Expr`.
505
+
506
+ Examples
507
+ ========
508
+
509
+ Construct an element of the :ref:`QQ` domain and then convert it to
510
+ :py:class:`~.Expr`.
511
+
512
+ >>> from sympy import QQ, Expr
513
+ >>> q_domain = QQ(2)
514
+ >>> q_domain
515
+ 2
516
+ >>> q_expr = QQ.to_sympy(q_domain)
517
+ >>> q_expr
518
+ 2
519
+
520
+ Although the printed forms look similar these objects are not of the
521
+ same type.
522
+
523
+ >>> isinstance(q_domain, Expr)
524
+ False
525
+ >>> isinstance(q_expr, Expr)
526
+ True
527
+
528
+ Construct an element of :ref:`K[x]` and convert to
529
+ :py:class:`~.Expr`.
530
+
531
+ >>> from sympy import Symbol
532
+ >>> x = Symbol('x')
533
+ >>> K = QQ[x]
534
+ >>> x_domain = K.gens[0] # generator x as a domain element
535
+ >>> p_domain = x_domain**2/3 + 1
536
+ >>> p_domain
537
+ 1/3*x**2 + 1
538
+ >>> p_expr = K.to_sympy(p_domain)
539
+ >>> p_expr
540
+ x**2/3 + 1
541
+
542
+ The :py:meth:`~.Domain.from_sympy` method is used for the opposite
543
+ conversion from a normal SymPy expression to a domain element.
544
+
545
+ >>> p_domain == p_expr
546
+ False
547
+ >>> K.from_sympy(p_expr) == p_domain
548
+ True
549
+ >>> K.to_sympy(p_domain) == p_expr
550
+ True
551
+ >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain
552
+ True
553
+ >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr
554
+ True
555
+
556
+ The :py:meth:`~.Domain.from_sympy` method makes it easier to construct
557
+ domain elements interactively.
558
+
559
+ >>> from sympy import Symbol
560
+ >>> x = Symbol('x')
561
+ >>> K = QQ[x]
562
+ >>> K.from_sympy(x**2/3 + 1)
563
+ 1/3*x**2 + 1
564
+
565
+ See also
566
+ ========
567
+
568
+ from_sympy
569
+ convert_from
570
+ """
571
+ raise NotImplementedError
572
+
573
+ def from_sympy(self, a):
574
+ """Convert a SymPy expression to an element of this domain.
575
+
576
+ Explanation
577
+ ===========
578
+
579
+ See :py:meth:`~.Domain.to_sympy` for explanation and examples.
580
+
581
+ Parameters
582
+ ==========
583
+
584
+ expr: Expr
585
+ A normal SymPy expression of type :py:class:`~.Expr`.
586
+
587
+ Returns
588
+ =======
589
+
590
+ a: domain element
591
+ An element of this :py:class:`~.Domain`.
592
+
593
+ See also
594
+ ========
595
+
596
+ to_sympy
597
+ convert_from
598
+ """
599
+ raise NotImplementedError
600
+
601
+ def sum(self, args):
602
+ return sum(args)
603
+
604
+ def from_FF(K1, a, K0):
605
+ """Convert ``ModularInteger(int)`` to ``dtype``. """
606
+ return None
607
+
608
+ def from_FF_python(K1, a, K0):
609
+ """Convert ``ModularInteger(int)`` to ``dtype``. """
610
+ return None
611
+
612
+ def from_ZZ_python(K1, a, K0):
613
+ """Convert a Python ``int`` object to ``dtype``. """
614
+ return None
615
+
616
+ def from_QQ_python(K1, a, K0):
617
+ """Convert a Python ``Fraction`` object to ``dtype``. """
618
+ return None
619
+
620
+ def from_FF_gmpy(K1, a, K0):
621
+ """Convert ``ModularInteger(mpz)`` to ``dtype``. """
622
+ return None
623
+
624
+ def from_ZZ_gmpy(K1, a, K0):
625
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
626
+ return None
627
+
628
+ def from_QQ_gmpy(K1, a, K0):
629
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
630
+ return None
631
+
632
+ def from_RealField(K1, a, K0):
633
+ """Convert a real element object to ``dtype``. """
634
+ return None
635
+
636
+ def from_ComplexField(K1, a, K0):
637
+ """Convert a complex element to ``dtype``. """
638
+ return None
639
+
640
+ def from_AlgebraicField(K1, a, K0):
641
+ """Convert an algebraic number to ``dtype``. """
642
+ return None
643
+
644
+ def from_PolynomialRing(K1, a, K0):
645
+ """Convert a polynomial to ``dtype``. """
646
+ if a.is_ground:
647
+ return K1.convert(a.LC, K0.dom)
648
+
649
+ def from_FractionField(K1, a, K0):
650
+ """Convert a rational function to ``dtype``. """
651
+ return None
652
+
653
+ def from_MonogenicFiniteExtension(K1, a, K0):
654
+ """Convert an ``ExtensionElement`` to ``dtype``. """
655
+ return K1.convert_from(a.rep, K0.ring)
656
+
657
+ def from_ExpressionDomain(K1, a, K0):
658
+ """Convert a ``EX`` object to ``dtype``. """
659
+ return K1.from_sympy(a.ex)
660
+
661
+ def from_ExpressionRawDomain(K1, a, K0):
662
+ """Convert a ``EX`` object to ``dtype``. """
663
+ return K1.from_sympy(a)
664
+
665
+ def from_GlobalPolynomialRing(K1, a, K0):
666
+ """Convert a polynomial to ``dtype``. """
667
+ if a.degree() <= 0:
668
+ return K1.convert(a.LC(), K0.dom)
669
+
670
+ def from_GeneralizedPolynomialRing(K1, a, K0):
671
+ return K1.from_FractionField(a, K0)
672
+
673
+ def unify_with_symbols(K0, K1, symbols):
674
+ if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))):
675
+ raise UnificationFailed("Cannot unify %s with %s, given %s generators" % (K0, K1, tuple(symbols)))
676
+
677
+ return K0.unify(K1)
678
+
679
+ def unify(K0, K1, symbols=None):
680
+ """
681
+ Construct a minimal domain that contains elements of ``K0`` and ``K1``.
682
+
683
+ Known domains (from smallest to largest):
684
+
685
+ - ``GF(p)``
686
+ - ``ZZ``
687
+ - ``QQ``
688
+ - ``RR(prec, tol)``
689
+ - ``CC(prec, tol)``
690
+ - ``ALG(a, b, c)``
691
+ - ``K[x, y, z]``
692
+ - ``K(x, y, z)``
693
+ - ``EX``
694
+
695
+ """
696
+ if symbols is not None:
697
+ return K0.unify_with_symbols(K1, symbols)
698
+
699
+ if K0 == K1:
700
+ return K0
701
+
702
+ if K0.is_EXRAW:
703
+ return K0
704
+ if K1.is_EXRAW:
705
+ return K1
706
+
707
+ if K0.is_EX:
708
+ return K0
709
+ if K1.is_EX:
710
+ return K1
711
+
712
+ if K0.is_FiniteExtension or K1.is_FiniteExtension:
713
+ if K1.is_FiniteExtension:
714
+ K0, K1 = K1, K0
715
+ if K1.is_FiniteExtension:
716
+ # Unifying two extensions.
717
+ # Try to ensure that K0.unify(K1) == K1.unify(K0)
718
+ if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus:
719
+ K0, K1 = K1, K0
720
+ return K1.set_domain(K0)
721
+ else:
722
+ # Drop the generator from other and unify with the base domain
723
+ K1 = K1.drop(K0.symbol)
724
+ K1 = K0.domain.unify(K1)
725
+ return K0.set_domain(K1)
726
+
727
+ if K0.is_Composite or K1.is_Composite:
728
+ K0_ground = K0.dom if K0.is_Composite else K0
729
+ K1_ground = K1.dom if K1.is_Composite else K1
730
+
731
+ K0_symbols = K0.symbols if K0.is_Composite else ()
732
+ K1_symbols = K1.symbols if K1.is_Composite else ()
733
+
734
+ domain = K0_ground.unify(K1_ground)
735
+ symbols = _unify_gens(K0_symbols, K1_symbols)
736
+ order = K0.order if K0.is_Composite else K1.order
737
+
738
+ if ((K0.is_FractionField and K1.is_PolynomialRing or
739
+ K1.is_FractionField and K0.is_PolynomialRing) and
740
+ (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field
741
+ and domain.has_assoc_Ring):
742
+ domain = domain.get_ring()
743
+
744
+ if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing):
745
+ cls = K0.__class__
746
+ else:
747
+ cls = K1.__class__
748
+
749
+ from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing
750
+ if cls == GlobalPolynomialRing:
751
+ return cls(domain, symbols)
752
+
753
+ return cls(domain, symbols, order)
754
+
755
+ def mkinexact(cls, K0, K1):
756
+ prec = max(K0.precision, K1.precision)
757
+ tol = max(K0.tolerance, K1.tolerance)
758
+ return cls(prec=prec, tol=tol)
759
+
760
+ if K1.is_ComplexField:
761
+ K0, K1 = K1, K0
762
+ if K0.is_ComplexField:
763
+ if K1.is_ComplexField or K1.is_RealField:
764
+ return mkinexact(K0.__class__, K0, K1)
765
+ else:
766
+ return K0
767
+
768
+ if K1.is_RealField:
769
+ K0, K1 = K1, K0
770
+ if K0.is_RealField:
771
+ if K1.is_RealField:
772
+ return mkinexact(K0.__class__, K0, K1)
773
+ elif K1.is_GaussianRing or K1.is_GaussianField:
774
+ from sympy.polys.domains.complexfield import ComplexField
775
+ return ComplexField(prec=K0.precision, tol=K0.tolerance)
776
+ else:
777
+ return K0
778
+
779
+ if K1.is_AlgebraicField:
780
+ K0, K1 = K1, K0
781
+ if K0.is_AlgebraicField:
782
+ if K1.is_GaussianRing:
783
+ K1 = K1.get_field()
784
+ if K1.is_GaussianField:
785
+ K1 = K1.as_AlgebraicField()
786
+ if K1.is_AlgebraicField:
787
+ return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext))
788
+ else:
789
+ return K0
790
+
791
+ if K0.is_GaussianField:
792
+ return K0
793
+ if K1.is_GaussianField:
794
+ return K1
795
+
796
+ if K0.is_GaussianRing:
797
+ if K1.is_RationalField:
798
+ K0 = K0.get_field()
799
+ return K0
800
+ if K1.is_GaussianRing:
801
+ if K0.is_RationalField:
802
+ K1 = K1.get_field()
803
+ return K1
804
+
805
+ if K0.is_RationalField:
806
+ return K0
807
+ if K1.is_RationalField:
808
+ return K1
809
+
810
+ if K0.is_IntegerRing:
811
+ return K0
812
+ if K1.is_IntegerRing:
813
+ return K1
814
+
815
+ if K0.is_FiniteField and K1.is_FiniteField:
816
+ return K0.__class__(max(K0.mod, K1.mod, key=default_sort_key))
817
+
818
+ from sympy.polys.domains import EX
819
+ return EX
820
+
821
+ def __eq__(self, other):
822
+ """Returns ``True`` if two domains are equivalent. """
823
+ return isinstance(other, Domain) and self.dtype == other.dtype
824
+
825
+ def __ne__(self, other):
826
+ """Returns ``False`` if two domains are equivalent. """
827
+ return not self == other
828
+
829
+ def map(self, seq):
830
+ """Rersively apply ``self`` to all elements of ``seq``. """
831
+ result = []
832
+
833
+ for elt in seq:
834
+ if isinstance(elt, list):
835
+ result.append(self.map(elt))
836
+ else:
837
+ result.append(self(elt))
838
+
839
+ return result
840
+
841
+ def get_ring(self):
842
+ """Returns a ring associated with ``self``. """
843
+ raise DomainError('there is no ring associated with %s' % self)
844
+
845
+ def get_field(self):
846
+ """Returns a field associated with ``self``. """
847
+ raise DomainError('there is no field associated with %s' % self)
848
+
849
+ def get_exact(self):
850
+ """Returns an exact domain associated with ``self``. """
851
+ return self
852
+
853
+ def __getitem__(self, symbols):
854
+ """The mathematical way to make a polynomial ring. """
855
+ if hasattr(symbols, '__iter__'):
856
+ return self.poly_ring(*symbols)
857
+ else:
858
+ return self.poly_ring(symbols)
859
+
860
+ def poly_ring(self, *symbols, order=lex):
861
+ """Returns a polynomial ring, i.e. `K[X]`. """
862
+ from sympy.polys.domains.polynomialring import PolynomialRing
863
+ return PolynomialRing(self, symbols, order)
864
+
865
+ def frac_field(self, *symbols, order=lex):
866
+ """Returns a fraction field, i.e. `K(X)`. """
867
+ from sympy.polys.domains.fractionfield import FractionField
868
+ return FractionField(self, symbols, order)
869
+
870
+ def old_poly_ring(self, *symbols, **kwargs):
871
+ """Returns a polynomial ring, i.e. `K[X]`. """
872
+ from sympy.polys.domains.old_polynomialring import PolynomialRing
873
+ return PolynomialRing(self, *symbols, **kwargs)
874
+
875
+ def old_frac_field(self, *symbols, **kwargs):
876
+ """Returns a fraction field, i.e. `K(X)`. """
877
+ from sympy.polys.domains.old_fractionfield import FractionField
878
+ return FractionField(self, *symbols, **kwargs)
879
+
880
+ def algebraic_field(self, *extension, alias=None):
881
+ r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """
882
+ raise DomainError("Cannot create algebraic field over %s" % self)
883
+
884
+ def alg_field_from_poly(self, poly, alias=None, root_index=-1):
885
+ r"""
886
+ Convenience method to construct an algebraic extension on a root of a
887
+ polynomial, chosen by root index.
888
+
889
+ Parameters
890
+ ==========
891
+
892
+ poly : :py:class:`~.Poly`
893
+ The polynomial whose root generates the extension.
894
+ alias : str, optional (default=None)
895
+ Symbol name for the generator of the extension.
896
+ E.g. "alpha" or "theta".
897
+ root_index : int, optional (default=-1)
898
+ Specifies which root of the polynomial is desired. The ordering is
899
+ as defined by the :py:class:`~.ComplexRootOf` class. The default of
900
+ ``-1`` selects the most natural choice in the common cases of
901
+ quadratic and cyclotomic fields (the square root on the positive
902
+ real or imaginary axis, resp. $\mathrm{e}^{2\pi i/n}$).
903
+
904
+ Examples
905
+ ========
906
+
907
+ >>> from sympy import QQ, Poly
908
+ >>> from sympy.abc import x
909
+ >>> f = Poly(x**2 - 2)
910
+ >>> K = QQ.alg_field_from_poly(f)
911
+ >>> K.ext.minpoly == f
912
+ True
913
+ >>> g = Poly(8*x**3 - 6*x - 1)
914
+ >>> L = QQ.alg_field_from_poly(g, "alpha")
915
+ >>> L.ext.minpoly == g
916
+ True
917
+ >>> L.to_sympy(L([1, 1, 1]))
918
+ alpha**2 + alpha + 1
919
+
920
+ """
921
+ from sympy.polys.rootoftools import CRootOf
922
+ root = CRootOf(poly, root_index)
923
+ alpha = AlgebraicNumber(root, alias=alias)
924
+ return self.algebraic_field(alpha, alias=alias)
925
+
926
+ def cyclotomic_field(self, n, ss=False, alias="zeta", gen=None, root_index=-1):
927
+ r"""
928
+ Convenience method to construct a cyclotomic field.
929
+
930
+ Parameters
931
+ ==========
932
+
933
+ n : int
934
+ Construct the nth cyclotomic field.
935
+ ss : boolean, optional (default=False)
936
+ If True, append *n* as a subscript on the alias string.
937
+ alias : str, optional (default="zeta")
938
+ Symbol name for the generator.
939
+ gen : :py:class:`~.Symbol`, optional (default=None)
940
+ Desired variable for the cyclotomic polynomial that defines the
941
+ field. If ``None``, a dummy variable will be used.
942
+ root_index : int, optional (default=-1)
943
+ Specifies which root of the polynomial is desired. The ordering is
944
+ as defined by the :py:class:`~.ComplexRootOf` class. The default of
945
+ ``-1`` selects the root $\mathrm{e}^{2\pi i/n}$.
946
+
947
+ Examples
948
+ ========
949
+
950
+ >>> from sympy import QQ, latex
951
+ >>> K = QQ.cyclotomic_field(5)
952
+ >>> K.to_sympy(K([-1, 1]))
953
+ 1 - zeta
954
+ >>> L = QQ.cyclotomic_field(7, True)
955
+ >>> a = L.to_sympy(L([-1, 1]))
956
+ >>> print(a)
957
+ 1 - zeta7
958
+ >>> print(latex(a))
959
+ 1 - \zeta_{7}
960
+
961
+ """
962
+ from sympy.polys.specialpolys import cyclotomic_poly
963
+ if ss:
964
+ alias += str(n)
965
+ return self.alg_field_from_poly(cyclotomic_poly(n, gen), alias=alias,
966
+ root_index=root_index)
967
+
968
+ def inject(self, *symbols):
969
+ """Inject generators into this domain. """
970
+ raise NotImplementedError
971
+
972
+ def drop(self, *symbols):
973
+ """Drop generators from this domain. """
974
+ if self.is_Simple:
975
+ return self
976
+ raise NotImplementedError # pragma: no cover
977
+
978
+ def is_zero(self, a):
979
+ """Returns True if ``a`` is zero. """
980
+ return not a
981
+
982
+ def is_one(self, a):
983
+ """Returns True if ``a`` is one. """
984
+ return a == self.one
985
+
986
+ def is_positive(self, a):
987
+ """Returns True if ``a`` is positive. """
988
+ return a > 0
989
+
990
+ def is_negative(self, a):
991
+ """Returns True if ``a`` is negative. """
992
+ return a < 0
993
+
994
+ def is_nonpositive(self, a):
995
+ """Returns True if ``a`` is non-positive. """
996
+ return a <= 0
997
+
998
+ def is_nonnegative(self, a):
999
+ """Returns True if ``a`` is non-negative. """
1000
+ return a >= 0
1001
+
1002
+ def canonical_unit(self, a):
1003
+ if self.is_negative(a):
1004
+ return -self.one
1005
+ else:
1006
+ return self.one
1007
+
1008
+ def abs(self, a):
1009
+ """Absolute value of ``a``, implies ``__abs__``. """
1010
+ return abs(a)
1011
+
1012
+ def neg(self, a):
1013
+ """Returns ``a`` negated, implies ``__neg__``. """
1014
+ return -a
1015
+
1016
+ def pos(self, a):
1017
+ """Returns ``a`` positive, implies ``__pos__``. """
1018
+ return +a
1019
+
1020
+ def add(self, a, b):
1021
+ """Sum of ``a`` and ``b``, implies ``__add__``. """
1022
+ return a + b
1023
+
1024
+ def sub(self, a, b):
1025
+ """Difference of ``a`` and ``b``, implies ``__sub__``. """
1026
+ return a - b
1027
+
1028
+ def mul(self, a, b):
1029
+ """Product of ``a`` and ``b``, implies ``__mul__``. """
1030
+ return a * b
1031
+
1032
+ def pow(self, a, b):
1033
+ """Raise ``a`` to power ``b``, implies ``__pow__``. """
1034
+ return a ** b
1035
+
1036
+ def exquo(self, a, b):
1037
+ """Exact quotient of *a* and *b*. Analogue of ``a / b``.
1038
+
1039
+ Explanation
1040
+ ===========
1041
+
1042
+ This is essentially the same as ``a / b`` except that an error will be
1043
+ raised if the division is inexact (if there is any remainder) and the
1044
+ result will always be a domain element. When working in a
1045
+ :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ`
1046
+ or :ref:`K[x]`) ``exquo`` should be used instead of ``/``.
1047
+
1048
+ The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does
1049
+ not raise an exception) then ``a == b*q``.
1050
+
1051
+ Examples
1052
+ ========
1053
+
1054
+ We can use ``K.exquo`` instead of ``/`` for exact division.
1055
+
1056
+ >>> from sympy import ZZ
1057
+ >>> ZZ.exquo(ZZ(4), ZZ(2))
1058
+ 2
1059
+ >>> ZZ.exquo(ZZ(5), ZZ(2))
1060
+ Traceback (most recent call last):
1061
+ ...
1062
+ ExactQuotientFailed: 2 does not divide 5 in ZZ
1063
+
1064
+ Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero
1065
+ divisor) is always exact so in that case ``/`` can be used instead of
1066
+ :py:meth:`~.Domain.exquo`.
1067
+
1068
+ >>> from sympy import QQ
1069
+ >>> QQ.exquo(QQ(5), QQ(2))
1070
+ 5/2
1071
+ >>> QQ(5) / QQ(2)
1072
+ 5/2
1073
+
1074
+ Parameters
1075
+ ==========
1076
+
1077
+ a: domain element
1078
+ The dividend
1079
+ b: domain element
1080
+ The divisor
1081
+
1082
+ Returns
1083
+ =======
1084
+
1085
+ q: domain element
1086
+ The exact quotient
1087
+
1088
+ Raises
1089
+ ======
1090
+
1091
+ ExactQuotientFailed: if exact division is not possible.
1092
+ ZeroDivisionError: when the divisor is zero.
1093
+
1094
+ See also
1095
+ ========
1096
+
1097
+ quo: Analogue of ``a // b``
1098
+ rem: Analogue of ``a % b``
1099
+ div: Analogue of ``divmod(a, b)``
1100
+
1101
+ Notes
1102
+ =====
1103
+
1104
+ Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int``
1105
+ (or ``mpz``) division as ``a / b`` should not be used as it would give
1106
+ a ``float``.
1107
+
1108
+ >>> ZZ(4) / ZZ(2)
1109
+ 2.0
1110
+ >>> ZZ(5) / ZZ(2)
1111
+ 2.5
1112
+
1113
+ Using ``/`` with :ref:`ZZ` will lead to incorrect results so
1114
+ :py:meth:`~.Domain.exquo` should be used instead.
1115
+
1116
+ """
1117
+ raise NotImplementedError
1118
+
1119
+ def quo(self, a, b):
1120
+ """Quotient of *a* and *b*. Analogue of ``a // b``.
1121
+
1122
+ ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See
1123
+ :py:meth:`~.Domain.div` for more explanation.
1124
+
1125
+ See also
1126
+ ========
1127
+
1128
+ rem: Analogue of ``a % b``
1129
+ div: Analogue of ``divmod(a, b)``
1130
+ exquo: Analogue of ``a / b``
1131
+ """
1132
+ raise NotImplementedError
1133
+
1134
+ def rem(self, a, b):
1135
+ """Modulo division of *a* and *b*. Analogue of ``a % b``.
1136
+
1137
+ ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See
1138
+ :py:meth:`~.Domain.div` for more explanation.
1139
+
1140
+ See also
1141
+ ========
1142
+
1143
+ quo: Analogue of ``a // b``
1144
+ div: Analogue of ``divmod(a, b)``
1145
+ exquo: Analogue of ``a / b``
1146
+ """
1147
+ raise NotImplementedError
1148
+
1149
+ def div(self, a, b):
1150
+ """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)``
1151
+
1152
+ Explanation
1153
+ ===========
1154
+
1155
+ This is essentially the same as ``divmod(a, b)`` except that is more
1156
+ consistent when working over some :py:class:`~.Field` domains such as
1157
+ :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the
1158
+ :py:meth:`~.Domain.div` method should be used instead of ``divmod``.
1159
+
1160
+ The key invariant is that if ``q, r = K.div(a, b)`` then
1161
+ ``a == b*q + r``.
1162
+
1163
+ The result of ``K.div(a, b)`` is the same as the tuple
1164
+ ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and
1165
+ remainder are needed then it is more efficient to use
1166
+ :py:meth:`~.Domain.div`.
1167
+
1168
+ Examples
1169
+ ========
1170
+
1171
+ We can use ``K.div`` instead of ``divmod`` for floor division and
1172
+ remainder.
1173
+
1174
+ >>> from sympy import ZZ, QQ
1175
+ >>> ZZ.div(ZZ(5), ZZ(2))
1176
+ (2, 1)
1177
+
1178
+ If ``K`` is a :py:class:`~.Field` then the division is always exact
1179
+ with a remainder of :py:attr:`~.Domain.zero`.
1180
+
1181
+ >>> QQ.div(QQ(5), QQ(2))
1182
+ (5/2, 0)
1183
+
1184
+ Parameters
1185
+ ==========
1186
+
1187
+ a: domain element
1188
+ The dividend
1189
+ b: domain element
1190
+ The divisor
1191
+
1192
+ Returns
1193
+ =======
1194
+
1195
+ (q, r): tuple of domain elements
1196
+ The quotient and remainder
1197
+
1198
+ Raises
1199
+ ======
1200
+
1201
+ ZeroDivisionError: when the divisor is zero.
1202
+
1203
+ See also
1204
+ ========
1205
+
1206
+ quo: Analogue of ``a // b``
1207
+ rem: Analogue of ``a % b``
1208
+ exquo: Analogue of ``a / b``
1209
+
1210
+ Notes
1211
+ =====
1212
+
1213
+ If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as
1214
+ the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type
1215
+ defines ``divmod`` in a way that is undesirable so
1216
+ :py:meth:`~.Domain.div` should be used instead of ``divmod``.
1217
+
1218
+ >>> a = QQ(1)
1219
+ >>> b = QQ(3, 2)
1220
+ >>> a # doctest: +SKIP
1221
+ mpq(1,1)
1222
+ >>> b # doctest: +SKIP
1223
+ mpq(3,2)
1224
+ >>> divmod(a, b) # doctest: +SKIP
1225
+ (mpz(0), mpq(1,1))
1226
+ >>> QQ.div(a, b) # doctest: +SKIP
1227
+ (mpq(2,3), mpq(0,1))
1228
+
1229
+ Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so
1230
+ :py:meth:`~.Domain.div` should be used instead.
1231
+
1232
+ """
1233
+ raise NotImplementedError
1234
+
1235
+ def invert(self, a, b):
1236
+ """Returns inversion of ``a mod b``, implies something. """
1237
+ raise NotImplementedError
1238
+
1239
+ def revert(self, a):
1240
+ """Returns ``a**(-1)`` if possible. """
1241
+ raise NotImplementedError
1242
+
1243
+ def numer(self, a):
1244
+ """Returns numerator of ``a``. """
1245
+ raise NotImplementedError
1246
+
1247
+ def denom(self, a):
1248
+ """Returns denominator of ``a``. """
1249
+ raise NotImplementedError
1250
+
1251
+ def half_gcdex(self, a, b):
1252
+ """Half extended GCD of ``a`` and ``b``. """
1253
+ s, t, h = self.gcdex(a, b)
1254
+ return s, h
1255
+
1256
+ def gcdex(self, a, b):
1257
+ """Extended GCD of ``a`` and ``b``. """
1258
+ raise NotImplementedError
1259
+
1260
+ def cofactors(self, a, b):
1261
+ """Returns GCD and cofactors of ``a`` and ``b``. """
1262
+ gcd = self.gcd(a, b)
1263
+ cfa = self.quo(a, gcd)
1264
+ cfb = self.quo(b, gcd)
1265
+ return gcd, cfa, cfb
1266
+
1267
+ def gcd(self, a, b):
1268
+ """Returns GCD of ``a`` and ``b``. """
1269
+ raise NotImplementedError
1270
+
1271
+ def lcm(self, a, b):
1272
+ """Returns LCM of ``a`` and ``b``. """
1273
+ raise NotImplementedError
1274
+
1275
+ def log(self, a, b):
1276
+ """Returns b-base logarithm of ``a``. """
1277
+ raise NotImplementedError
1278
+
1279
+ def sqrt(self, a):
1280
+ """Returns square root of ``a``. """
1281
+ raise NotImplementedError
1282
+
1283
+ def evalf(self, a, prec=None, **options):
1284
+ """Returns numerical approximation of ``a``. """
1285
+ return self.to_sympy(a).evalf(prec, **options)
1286
+
1287
+ n = evalf
1288
+
1289
+ def real(self, a):
1290
+ return a
1291
+
1292
+ def imag(self, a):
1293
+ return self.zero
1294
+
1295
+ def almosteq(self, a, b, tolerance=None):
1296
+ """Check if ``a`` and ``b`` are almost equal. """
1297
+ return a == b
1298
+
1299
+ def characteristic(self):
1300
+ """Return the characteristic of this domain. """
1301
+ raise NotImplementedError('characteristic()')
1302
+
1303
+
1304
+ __all__ = ['Domain']
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/field.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`Field` class. """
2
+
3
+
4
+ from sympy.polys.domains.ring import Ring
5
+ from sympy.polys.polyerrors import NotReversible, DomainError
6
+ from sympy.utilities import public
7
+
8
+ @public
9
+ class Field(Ring):
10
+ """Represents a field domain. """
11
+
12
+ is_Field = True
13
+ is_PID = True
14
+
15
+ def get_ring(self):
16
+ """Returns a ring associated with ``self``. """
17
+ raise DomainError('there is no ring associated with %s' % self)
18
+
19
+ def get_field(self):
20
+ """Returns a field associated with ``self``. """
21
+ return self
22
+
23
+ def exquo(self, a, b):
24
+ """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """
25
+ return a / b
26
+
27
+ def quo(self, a, b):
28
+ """Quotient of ``a`` and ``b``, implies ``__truediv__``. """
29
+ return a / b
30
+
31
+ def rem(self, a, b):
32
+ """Remainder of ``a`` and ``b``, implies nothing. """
33
+ return self.zero
34
+
35
+ def div(self, a, b):
36
+ """Division of ``a`` and ``b``, implies ``__truediv__``. """
37
+ return a / b, self.zero
38
+
39
+ def gcd(self, a, b):
40
+ """
41
+ Returns GCD of ``a`` and ``b``.
42
+
43
+ This definition of GCD over fields allows to clear denominators
44
+ in `primitive()`.
45
+
46
+ Examples
47
+ ========
48
+
49
+ >>> from sympy.polys.domains import QQ
50
+ >>> from sympy import S, gcd, primitive
51
+ >>> from sympy.abc import x
52
+
53
+ >>> QQ.gcd(QQ(2, 3), QQ(4, 9))
54
+ 2/9
55
+ >>> gcd(S(2)/3, S(4)/9)
56
+ 2/9
57
+ >>> primitive(2*x/3 + S(4)/9)
58
+ (2/9, 3*x + 2)
59
+
60
+ """
61
+ try:
62
+ ring = self.get_ring()
63
+ except DomainError:
64
+ return self.one
65
+
66
+ p = ring.gcd(self.numer(a), self.numer(b))
67
+ q = ring.lcm(self.denom(a), self.denom(b))
68
+
69
+ return self.convert(p, ring)/q
70
+
71
+ def lcm(self, a, b):
72
+ """
73
+ Returns LCM of ``a`` and ``b``.
74
+
75
+ >>> from sympy.polys.domains import QQ
76
+ >>> from sympy import S, lcm
77
+
78
+ >>> QQ.lcm(QQ(2, 3), QQ(4, 9))
79
+ 4/3
80
+ >>> lcm(S(2)/3, S(4)/9)
81
+ 4/3
82
+
83
+ """
84
+
85
+ try:
86
+ ring = self.get_ring()
87
+ except DomainError:
88
+ return a*b
89
+
90
+ p = ring.lcm(self.numer(a), self.numer(b))
91
+ q = ring.gcd(self.denom(a), self.denom(b))
92
+
93
+ return self.convert(p, ring)/q
94
+
95
+ def revert(self, a):
96
+ """Returns ``a**(-1)`` if possible. """
97
+ if a:
98
+ return 1/a
99
+ else:
100
+ raise NotReversible('zero is not reversible')
101
+
102
+ def is_unit(self, a):
103
+ """Return true if ``a`` is a invertible"""
104
+ return bool(a)
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/gmpyintegerring.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`GMPYIntegerRing` class. """
2
+
3
+
4
+ from sympy.polys.domains.groundtypes import (
5
+ GMPYInteger, SymPyInteger,
6
+ factorial as gmpy_factorial,
7
+ gmpy_gcdex, gmpy_gcd, gmpy_lcm, sqrt as gmpy_sqrt,
8
+ )
9
+ from sympy.polys.domains.integerring import IntegerRing
10
+ from sympy.polys.polyerrors import CoercionFailed
11
+ from sympy.utilities import public
12
+
13
+ @public
14
+ class GMPYIntegerRing(IntegerRing):
15
+ """Integer ring based on GMPY's ``mpz`` type.
16
+
17
+ This will be the implementation of :ref:`ZZ` if ``gmpy`` or ``gmpy2`` is
18
+ installed. Elements will be of type ``gmpy.mpz``.
19
+ """
20
+
21
+ dtype = GMPYInteger
22
+ zero = dtype(0)
23
+ one = dtype(1)
24
+ tp = type(one)
25
+ alias = 'ZZ_gmpy'
26
+
27
+ def __init__(self):
28
+ """Allow instantiation of this domain. """
29
+
30
+ def to_sympy(self, a):
31
+ """Convert ``a`` to a SymPy object. """
32
+ return SymPyInteger(int(a))
33
+
34
+ def from_sympy(self, a):
35
+ """Convert SymPy's Integer to ``dtype``. """
36
+ if a.is_Integer:
37
+ return GMPYInteger(a.p)
38
+ elif a.is_Float and int(a) == a:
39
+ return GMPYInteger(int(a))
40
+ else:
41
+ raise CoercionFailed("expected an integer, got %s" % a)
42
+
43
+ def from_FF_python(K1, a, K0):
44
+ """Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """
45
+ return GMPYInteger(a.to_int())
46
+
47
+ def from_ZZ_python(K1, a, K0):
48
+ """Convert Python's ``int`` to GMPY's ``mpz``. """
49
+ return GMPYInteger(a)
50
+
51
+ def from_QQ(K1, a, K0):
52
+ """Convert Python's ``Fraction`` to GMPY's ``mpz``. """
53
+ if a.denominator == 1:
54
+ return GMPYInteger(a.numerator)
55
+
56
+ def from_QQ_python(K1, a, K0):
57
+ """Convert Python's ``Fraction`` to GMPY's ``mpz``. """
58
+ if a.denominator == 1:
59
+ return GMPYInteger(a.numerator)
60
+
61
+ def from_FF_gmpy(K1, a, K0):
62
+ """Convert ``ModularInteger(mpz)`` to GMPY's ``mpz``. """
63
+ return a.to_int()
64
+
65
+ def from_ZZ_gmpy(K1, a, K0):
66
+ """Convert GMPY's ``mpz`` to GMPY's ``mpz``. """
67
+ return a
68
+
69
+ def from_QQ_gmpy(K1, a, K0):
70
+ """Convert GMPY ``mpq`` to GMPY's ``mpz``. """
71
+ if a.denominator == 1:
72
+ return a.numerator
73
+
74
+ def from_RealField(K1, a, K0):
75
+ """Convert mpmath's ``mpf`` to GMPY's ``mpz``. """
76
+ p, q = K0.to_rational(a)
77
+
78
+ if q == 1:
79
+ return GMPYInteger(p)
80
+
81
+ def from_GaussianIntegerRing(K1, a, K0):
82
+ if a.y == 0:
83
+ return a.x
84
+
85
+ def gcdex(self, a, b):
86
+ """Compute extended GCD of ``a`` and ``b``. """
87
+ h, s, t = gmpy_gcdex(a, b)
88
+ return s, t, h
89
+
90
+ def gcd(self, a, b):
91
+ """Compute GCD of ``a`` and ``b``. """
92
+ return gmpy_gcd(a, b)
93
+
94
+ def lcm(self, a, b):
95
+ """Compute LCM of ``a`` and ``b``. """
96
+ return gmpy_lcm(a, b)
97
+
98
+ def sqrt(self, a):
99
+ """Compute square root of ``a``. """
100
+ return gmpy_sqrt(a)
101
+
102
+ def factorial(self, a):
103
+ """Compute factorial of ``a``. """
104
+ return gmpy_factorial(a)
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/modularinteger.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`ModularInteger` class. """
2
+
3
+ from __future__ import annotations
4
+ from typing import Any
5
+
6
+ import operator
7
+
8
+ from sympy.polys.polyutils import PicklableWithSlots
9
+ from sympy.polys.polyerrors import CoercionFailed
10
+ from sympy.polys.domains.domainelement import DomainElement
11
+
12
+ from sympy.utilities import public
13
+
14
+ @public
15
+ class ModularInteger(PicklableWithSlots, DomainElement):
16
+ """A class representing a modular integer. """
17
+
18
+ mod, dom, sym, _parent = None, None, None, None
19
+
20
+ __slots__ = ('val',)
21
+
22
+ def parent(self):
23
+ return self._parent
24
+
25
+ def __init__(self, val):
26
+ if isinstance(val, self.__class__):
27
+ self.val = val.val % self.mod
28
+ else:
29
+ self.val = self.dom.convert(val) % self.mod
30
+
31
+ def __hash__(self):
32
+ return hash((self.val, self.mod))
33
+
34
+ def __repr__(self):
35
+ return "%s(%s)" % (self.__class__.__name__, self.val)
36
+
37
+ def __str__(self):
38
+ return "%s mod %s" % (self.val, self.mod)
39
+
40
+ def __int__(self):
41
+ return int(self.to_int())
42
+
43
+ def to_int(self):
44
+ if self.sym:
45
+ if self.val <= self.mod // 2:
46
+ return self.val
47
+ else:
48
+ return self.val - self.mod
49
+ else:
50
+ return self.val
51
+
52
+ def __pos__(self):
53
+ return self
54
+
55
+ def __neg__(self):
56
+ return self.__class__(-self.val)
57
+
58
+ @classmethod
59
+ def _get_val(cls, other):
60
+ if isinstance(other, cls):
61
+ return other.val
62
+ else:
63
+ try:
64
+ return cls.dom.convert(other)
65
+ except CoercionFailed:
66
+ return None
67
+
68
+ def __add__(self, other):
69
+ val = self._get_val(other)
70
+
71
+ if val is not None:
72
+ return self.__class__(self.val + val)
73
+ else:
74
+ return NotImplemented
75
+
76
+ def __radd__(self, other):
77
+ return self.__add__(other)
78
+
79
+ def __sub__(self, other):
80
+ val = self._get_val(other)
81
+
82
+ if val is not None:
83
+ return self.__class__(self.val - val)
84
+ else:
85
+ return NotImplemented
86
+
87
+ def __rsub__(self, other):
88
+ return (-self).__add__(other)
89
+
90
+ def __mul__(self, other):
91
+ val = self._get_val(other)
92
+
93
+ if val is not None:
94
+ return self.__class__(self.val * val)
95
+ else:
96
+ return NotImplemented
97
+
98
+ def __rmul__(self, other):
99
+ return self.__mul__(other)
100
+
101
+ def __truediv__(self, other):
102
+ val = self._get_val(other)
103
+
104
+ if val is not None:
105
+ return self.__class__(self.val * self._invert(val))
106
+ else:
107
+ return NotImplemented
108
+
109
+ def __rtruediv__(self, other):
110
+ return self.invert().__mul__(other)
111
+
112
+ def __mod__(self, other):
113
+ val = self._get_val(other)
114
+
115
+ if val is not None:
116
+ return self.__class__(self.val % val)
117
+ else:
118
+ return NotImplemented
119
+
120
+ def __rmod__(self, other):
121
+ val = self._get_val(other)
122
+
123
+ if val is not None:
124
+ return self.__class__(val % self.val)
125
+ else:
126
+ return NotImplemented
127
+
128
+ def __pow__(self, exp):
129
+ if not exp:
130
+ return self.__class__(self.dom.one)
131
+
132
+ if exp < 0:
133
+ val, exp = self.invert().val, -exp
134
+ else:
135
+ val = self.val
136
+
137
+ return self.__class__(pow(val, int(exp), self.mod))
138
+
139
+ def _compare(self, other, op):
140
+ val = self._get_val(other)
141
+
142
+ if val is not None:
143
+ return op(self.val, val % self.mod)
144
+ else:
145
+ return NotImplemented
146
+
147
+ def __eq__(self, other):
148
+ return self._compare(other, operator.eq)
149
+
150
+ def __ne__(self, other):
151
+ return self._compare(other, operator.ne)
152
+
153
+ def __lt__(self, other):
154
+ return self._compare(other, operator.lt)
155
+
156
+ def __le__(self, other):
157
+ return self._compare(other, operator.le)
158
+
159
+ def __gt__(self, other):
160
+ return self._compare(other, operator.gt)
161
+
162
+ def __ge__(self, other):
163
+ return self._compare(other, operator.ge)
164
+
165
+ def __bool__(self):
166
+ return bool(self.val)
167
+
168
+ @classmethod
169
+ def _invert(cls, value):
170
+ return cls.dom.invert(value, cls.mod)
171
+
172
+ def invert(self):
173
+ return self.__class__(self._invert(self.val))
174
+
175
+ _modular_integer_cache: dict[tuple[Any, Any, Any], type[ModularInteger]] = {}
176
+
177
+ def ModularIntegerFactory(_mod, _dom, _sym, parent):
178
+ """Create custom class for specific integer modulus."""
179
+ try:
180
+ _mod = _dom.convert(_mod)
181
+ except CoercionFailed:
182
+ ok = False
183
+ else:
184
+ ok = True
185
+
186
+ if not ok or _mod < 1:
187
+ raise ValueError("modulus must be a positive integer, got %s" % _mod)
188
+
189
+ key = _mod, _dom, _sym
190
+
191
+ try:
192
+ cls = _modular_integer_cache[key]
193
+ except KeyError:
194
+ class cls(ModularInteger):
195
+ mod, dom, sym = _mod, _dom, _sym
196
+ _parent = parent
197
+
198
+ if _sym:
199
+ cls.__name__ = "SymmetricModularIntegerMod%s" % _mod
200
+ else:
201
+ cls.__name__ = "ModularIntegerMod%s" % _mod
202
+
203
+ _modular_integer_cache[key] = cls
204
+
205
+ return cls
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/old_fractionfield.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`FractionField` class. """
2
+
3
+
4
+ from sympy.polys.domains.field import Field
5
+ from sympy.polys.domains.compositedomain import CompositeDomain
6
+ from sympy.polys.domains.characteristiczero import CharacteristicZero
7
+ from sympy.polys.polyclasses import DMF
8
+ from sympy.polys.polyerrors import GeneratorsNeeded
9
+ from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder
10
+ from sympy.utilities import public
11
+
12
+ @public
13
+ class FractionField(Field, CharacteristicZero, CompositeDomain):
14
+ """A class for representing rational function fields. """
15
+
16
+ dtype = DMF
17
+ is_FractionField = is_Frac = True
18
+
19
+ has_assoc_Ring = True
20
+ has_assoc_Field = True
21
+
22
+ def __init__(self, dom, *gens):
23
+ if not gens:
24
+ raise GeneratorsNeeded("generators not specified")
25
+
26
+ lev = len(gens) - 1
27
+ self.ngens = len(gens)
28
+
29
+ self.zero = self.dtype.zero(lev, dom, ring=self)
30
+ self.one = self.dtype.one(lev, dom, ring=self)
31
+
32
+ self.domain = self.dom = dom
33
+ self.symbols = self.gens = gens
34
+
35
+ def new(self, element):
36
+ return self.dtype(element, self.dom, len(self.gens) - 1, ring=self)
37
+
38
+ def __str__(self):
39
+ return str(self.dom) + '(' + ','.join(map(str, self.gens)) + ')'
40
+
41
+ def __hash__(self):
42
+ return hash((self.__class__.__name__, self.dtype, self.dom, self.gens))
43
+
44
+ def __eq__(self, other):
45
+ """Returns ``True`` if two domains are equivalent. """
46
+ return isinstance(other, FractionField) and \
47
+ self.dtype == other.dtype and self.dom == other.dom and self.gens == other.gens
48
+
49
+ def to_sympy(self, a):
50
+ """Convert ``a`` to a SymPy object. """
51
+ return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) /
52
+ basic_from_dict(a.denom().to_sympy_dict(), *self.gens))
53
+
54
+ def from_sympy(self, a):
55
+ """Convert SymPy's expression to ``dtype``. """
56
+ p, q = a.as_numer_denom()
57
+
58
+ num, _ = dict_from_basic(p, gens=self.gens)
59
+ den, _ = dict_from_basic(q, gens=self.gens)
60
+
61
+ for k, v in num.items():
62
+ num[k] = self.dom.from_sympy(v)
63
+
64
+ for k, v in den.items():
65
+ den[k] = self.dom.from_sympy(v)
66
+
67
+ return self((num, den)).cancel()
68
+
69
+ def from_ZZ(K1, a, K0):
70
+ """Convert a Python ``int`` object to ``dtype``. """
71
+ return K1(K1.dom.convert(a, K0))
72
+
73
+ def from_ZZ_python(K1, a, K0):
74
+ """Convert a Python ``int`` object to ``dtype``. """
75
+ return K1(K1.dom.convert(a, K0))
76
+
77
+ def from_QQ_python(K1, a, K0):
78
+ """Convert a Python ``Fraction`` object to ``dtype``. """
79
+ return K1(K1.dom.convert(a, K0))
80
+
81
+ def from_ZZ_gmpy(K1, a, K0):
82
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
83
+ return K1(K1.dom.convert(a, K0))
84
+
85
+ def from_QQ_gmpy(K1, a, K0):
86
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
87
+ return K1(K1.dom.convert(a, K0))
88
+
89
+ def from_RealField(K1, a, K0):
90
+ """Convert a mpmath ``mpf`` object to ``dtype``. """
91
+ return K1(K1.dom.convert(a, K0))
92
+
93
+ def from_GlobalPolynomialRing(K1, a, K0):
94
+ """Convert a ``DMF`` object to ``dtype``. """
95
+ if K1.gens == K0.gens:
96
+ if K1.dom == K0.dom:
97
+ return K1(a.rep)
98
+ else:
99
+ return K1(a.convert(K1.dom).rep)
100
+ else:
101
+ monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens)
102
+
103
+ if K1.dom != K0.dom:
104
+ coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ]
105
+
106
+ return K1(dict(zip(monoms, coeffs)))
107
+
108
+ def from_FractionField(K1, a, K0):
109
+ """
110
+ Convert a fraction field element to another fraction field.
111
+
112
+ Examples
113
+ ========
114
+
115
+ >>> from sympy.polys.polyclasses import DMF
116
+ >>> from sympy.polys.domains import ZZ, QQ
117
+ >>> from sympy.abc import x
118
+
119
+ >>> f = DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(1)]), ZZ)
120
+
121
+ >>> QQx = QQ.old_frac_field(x)
122
+ >>> ZZx = ZZ.old_frac_field(x)
123
+
124
+ >>> QQx.from_FractionField(f, ZZx)
125
+ (x + 2)/(x + 1)
126
+
127
+ """
128
+ if K1.gens == K0.gens:
129
+ if K1.dom == K0.dom:
130
+ return a
131
+ else:
132
+ return K1((a.numer().convert(K1.dom).rep,
133
+ a.denom().convert(K1.dom).rep))
134
+ elif set(K0.gens).issubset(K1.gens):
135
+ nmonoms, ncoeffs = _dict_reorder(
136
+ a.numer().to_dict(), K0.gens, K1.gens)
137
+ dmonoms, dcoeffs = _dict_reorder(
138
+ a.denom().to_dict(), K0.gens, K1.gens)
139
+
140
+ if K1.dom != K0.dom:
141
+ ncoeffs = [ K1.dom.convert(c, K0.dom) for c in ncoeffs ]
142
+ dcoeffs = [ K1.dom.convert(c, K0.dom) for c in dcoeffs ]
143
+
144
+ return K1((dict(zip(nmonoms, ncoeffs)), dict(zip(dmonoms, dcoeffs))))
145
+
146
+ def get_ring(self):
147
+ """Returns a ring associated with ``self``. """
148
+ from sympy.polys.domains import PolynomialRing
149
+ return PolynomialRing(self.dom, *self.gens)
150
+
151
+ def poly_ring(self, *gens):
152
+ """Returns a polynomial ring, i.e. `K[X]`. """
153
+ raise NotImplementedError('nested domains not allowed')
154
+
155
+ def frac_field(self, *gens):
156
+ """Returns a fraction field, i.e. `K(X)`. """
157
+ raise NotImplementedError('nested domains not allowed')
158
+
159
+ def is_positive(self, a):
160
+ """Returns True if ``a`` is positive. """
161
+ return self.dom.is_positive(a.numer().LC())
162
+
163
+ def is_negative(self, a):
164
+ """Returns True if ``a`` is negative. """
165
+ return self.dom.is_negative(a.numer().LC())
166
+
167
+ def is_nonpositive(self, a):
168
+ """Returns True if ``a`` is non-positive. """
169
+ return self.dom.is_nonpositive(a.numer().LC())
170
+
171
+ def is_nonnegative(self, a):
172
+ """Returns True if ``a`` is non-negative. """
173
+ return self.dom.is_nonnegative(a.numer().LC())
174
+
175
+ def numer(self, a):
176
+ """Returns numerator of ``a``. """
177
+ return a.numer()
178
+
179
+ def denom(self, a):
180
+ """Returns denominator of ``a``. """
181
+ return a.denom()
182
+
183
+ def factorial(self, a):
184
+ """Returns factorial of ``a``. """
185
+ return self.dtype(self.dom.factorial(a))
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/old_polynomialring.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`PolynomialRing` class. """
2
+
3
+
4
+ from sympy.polys.agca.modules import FreeModulePolyRing
5
+ from sympy.polys.domains.characteristiczero import CharacteristicZero
6
+ from sympy.polys.domains.compositedomain import CompositeDomain
7
+ from sympy.polys.domains.old_fractionfield import FractionField
8
+ from sympy.polys.domains.ring import Ring
9
+ from sympy.polys.orderings import monomial_key, build_product_order
10
+ from sympy.polys.polyclasses import DMP, DMF
11
+ from sympy.polys.polyerrors import (GeneratorsNeeded, PolynomialError,
12
+ CoercionFailed, ExactQuotientFailed, NotReversible)
13
+ from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder
14
+ from sympy.utilities import public
15
+ from sympy.utilities.iterables import iterable
16
+
17
+ # XXX why does this derive from CharacteristicZero???
18
+
19
+ @public
20
+ class PolynomialRingBase(Ring, CharacteristicZero, CompositeDomain):
21
+ """
22
+ Base class for generalized polynomial rings.
23
+
24
+ This base class should be used for uniform access to generalized polynomial
25
+ rings. Subclasses only supply information about the element storage etc.
26
+
27
+ Do not instantiate.
28
+ """
29
+
30
+ has_assoc_Ring = True
31
+ has_assoc_Field = True
32
+
33
+ default_order = "grevlex"
34
+
35
+ def __init__(self, dom, *gens, **opts):
36
+ if not gens:
37
+ raise GeneratorsNeeded("generators not specified")
38
+
39
+ lev = len(gens) - 1
40
+ self.ngens = len(gens)
41
+
42
+ self.zero = self.dtype.zero(lev, dom, ring=self)
43
+ self.one = self.dtype.one(lev, dom, ring=self)
44
+
45
+ self.domain = self.dom = dom
46
+ self.symbols = self.gens = gens
47
+ # NOTE 'order' may not be set if inject was called through CompositeDomain
48
+ self.order = opts.get('order', monomial_key(self.default_order))
49
+
50
+ def new(self, element):
51
+ return self.dtype(element, self.dom, len(self.gens) - 1, ring=self)
52
+
53
+ def __str__(self):
54
+ s_order = str(self.order)
55
+ orderstr = (
56
+ " order=" + s_order) if s_order != self.default_order else ""
57
+ return str(self.dom) + '[' + ','.join(map(str, self.gens)) + orderstr + ']'
58
+
59
+ def __hash__(self):
60
+ return hash((self.__class__.__name__, self.dtype, self.dom,
61
+ self.gens, self.order))
62
+
63
+ def __eq__(self, other):
64
+ """Returns ``True`` if two domains are equivalent. """
65
+ return isinstance(other, PolynomialRingBase) and \
66
+ self.dtype == other.dtype and self.dom == other.dom and \
67
+ self.gens == other.gens and self.order == other.order
68
+
69
+ def from_ZZ(K1, a, K0):
70
+ """Convert a Python ``int`` object to ``dtype``. """
71
+ return K1(K1.dom.convert(a, K0))
72
+
73
+ def from_ZZ_python(K1, a, K0):
74
+ """Convert a Python ``int`` object to ``dtype``. """
75
+ return K1(K1.dom.convert(a, K0))
76
+
77
+ def from_QQ(K1, a, K0):
78
+ """Convert a Python ``Fraction`` object to ``dtype``. """
79
+ return K1(K1.dom.convert(a, K0))
80
+
81
+ def from_QQ_python(K1, a, K0):
82
+ """Convert a Python ``Fraction`` object to ``dtype``. """
83
+ return K1(K1.dom.convert(a, K0))
84
+
85
+ def from_ZZ_gmpy(K1, a, K0):
86
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
87
+ return K1(K1.dom.convert(a, K0))
88
+
89
+ def from_QQ_gmpy(K1, a, K0):
90
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
91
+ return K1(K1.dom.convert(a, K0))
92
+
93
+ def from_RealField(K1, a, K0):
94
+ """Convert a mpmath ``mpf`` object to ``dtype``. """
95
+ return K1(K1.dom.convert(a, K0))
96
+
97
+ def from_AlgebraicField(K1, a, K0):
98
+ """Convert a ``ANP`` object to ``dtype``. """
99
+ if K1.dom == K0:
100
+ return K1(a)
101
+
102
+ def from_PolynomialRing(K1, a, K0):
103
+ """Convert a ``PolyElement`` object to ``dtype``. """
104
+ if K1.gens == K0.symbols:
105
+ if K1.dom == K0.dom:
106
+ return K1(dict(a)) # set the correct ring
107
+ else:
108
+ convert_dom = lambda c: K1.dom.convert_from(c, K0.dom)
109
+ return K1({m: convert_dom(c) for m, c in a.items()})
110
+ else:
111
+ monoms, coeffs = _dict_reorder(a.to_dict(), K0.symbols, K1.gens)
112
+
113
+ if K1.dom != K0.dom:
114
+ coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ]
115
+
116
+ return K1(dict(zip(monoms, coeffs)))
117
+
118
+ def from_GlobalPolynomialRing(K1, a, K0):
119
+ """Convert a ``DMP`` object to ``dtype``. """
120
+ if K1.gens == K0.gens:
121
+ if K1.dom == K0.dom:
122
+ return K1(a.rep) # set the correct ring
123
+ else:
124
+ return K1(a.convert(K1.dom).rep)
125
+ else:
126
+ monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens)
127
+
128
+ if K1.dom != K0.dom:
129
+ coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ]
130
+
131
+ return K1(dict(zip(monoms, coeffs)))
132
+
133
+ def get_field(self):
134
+ """Returns a field associated with ``self``. """
135
+ return FractionField(self.dom, *self.gens)
136
+
137
+ def poly_ring(self, *gens):
138
+ """Returns a polynomial ring, i.e. ``K[X]``. """
139
+ raise NotImplementedError('nested domains not allowed')
140
+
141
+ def frac_field(self, *gens):
142
+ """Returns a fraction field, i.e. ``K(X)``. """
143
+ raise NotImplementedError('nested domains not allowed')
144
+
145
+ def revert(self, a):
146
+ try:
147
+ return 1/a
148
+ except (ExactQuotientFailed, ZeroDivisionError):
149
+ raise NotReversible('%s is not a unit' % a)
150
+
151
+ def gcdex(self, a, b):
152
+ """Extended GCD of ``a`` and ``b``. """
153
+ return a.gcdex(b)
154
+
155
+ def gcd(self, a, b):
156
+ """Returns GCD of ``a`` and ``b``. """
157
+ return a.gcd(b)
158
+
159
+ def lcm(self, a, b):
160
+ """Returns LCM of ``a`` and ``b``. """
161
+ return a.lcm(b)
162
+
163
+ def factorial(self, a):
164
+ """Returns factorial of ``a``. """
165
+ return self.dtype(self.dom.factorial(a))
166
+
167
+ def _vector_to_sdm(self, v, order):
168
+ """
169
+ For internal use by the modules class.
170
+
171
+ Convert an iterable of elements of this ring into a sparse distributed
172
+ module element.
173
+ """
174
+ raise NotImplementedError
175
+
176
+ def _sdm_to_dics(self, s, n):
177
+ """Helper for _sdm_to_vector."""
178
+ from sympy.polys.distributedmodules import sdm_to_dict
179
+ dic = sdm_to_dict(s)
180
+ res = [{} for _ in range(n)]
181
+ for k, v in dic.items():
182
+ res[k[0]][k[1:]] = v
183
+ return res
184
+
185
+ def _sdm_to_vector(self, s, n):
186
+ """
187
+ For internal use by the modules class.
188
+
189
+ Convert a sparse distributed module into a list of length ``n``.
190
+
191
+ Examples
192
+ ========
193
+
194
+ >>> from sympy import QQ, ilex
195
+ >>> from sympy.abc import x, y
196
+ >>> R = QQ.old_poly_ring(x, y, order=ilex)
197
+ >>> L = [((1, 1, 1), QQ(1)), ((0, 1, 0), QQ(1)), ((0, 0, 1), QQ(2))]
198
+ >>> R._sdm_to_vector(L, 2)
199
+ [x + 2*y, x*y]
200
+ """
201
+ dics = self._sdm_to_dics(s, n)
202
+ # NOTE this works for global and local rings!
203
+ return [self(x) for x in dics]
204
+
205
+ def free_module(self, rank):
206
+ """
207
+ Generate a free module of rank ``rank`` over ``self``.
208
+
209
+ Examples
210
+ ========
211
+
212
+ >>> from sympy.abc import x
213
+ >>> from sympy import QQ
214
+ >>> QQ.old_poly_ring(x).free_module(2)
215
+ QQ[x]**2
216
+ """
217
+ return FreeModulePolyRing(self, rank)
218
+
219
+
220
+ def _vector_to_sdm_helper(v, order):
221
+ """Helper method for common code in Global and Local poly rings."""
222
+ from sympy.polys.distributedmodules import sdm_from_dict
223
+ d = {}
224
+ for i, e in enumerate(v):
225
+ for key, value in e.to_dict().items():
226
+ d[(i,) + key] = value
227
+ return sdm_from_dict(d, order)
228
+
229
+
230
+ @public
231
+ class GlobalPolynomialRing(PolynomialRingBase):
232
+ """A true polynomial ring, with objects DMP. """
233
+
234
+ is_PolynomialRing = is_Poly = True
235
+ dtype = DMP
236
+
237
+ def from_FractionField(K1, a, K0):
238
+ """
239
+ Convert a ``DMF`` object to ``DMP``.
240
+
241
+ Examples
242
+ ========
243
+
244
+ >>> from sympy.polys.polyclasses import DMP, DMF
245
+ >>> from sympy.polys.domains import ZZ
246
+ >>> from sympy.abc import x
247
+
248
+ >>> f = DMF(([ZZ(1), ZZ(1)], [ZZ(1)]), ZZ)
249
+ >>> K = ZZ.old_frac_field(x)
250
+
251
+ >>> F = ZZ.old_poly_ring(x).from_FractionField(f, K)
252
+
253
+ >>> F == DMP([ZZ(1), ZZ(1)], ZZ)
254
+ True
255
+ >>> type(F)
256
+ <class 'sympy.polys.polyclasses.DMP'>
257
+
258
+ """
259
+ if a.denom().is_one:
260
+ return K1.from_GlobalPolynomialRing(a.numer(), K0)
261
+
262
+ def to_sympy(self, a):
263
+ """Convert ``a`` to a SymPy object. """
264
+ return basic_from_dict(a.to_sympy_dict(), *self.gens)
265
+
266
+ def from_sympy(self, a):
267
+ """Convert SymPy's expression to ``dtype``. """
268
+ try:
269
+ rep, _ = dict_from_basic(a, gens=self.gens)
270
+ except PolynomialError:
271
+ raise CoercionFailed("Cannot convert %s to type %s" % (a, self))
272
+
273
+ for k, v in rep.items():
274
+ rep[k] = self.dom.from_sympy(v)
275
+
276
+ return self(rep)
277
+
278
+ def is_positive(self, a):
279
+ """Returns True if ``LC(a)`` is positive. """
280
+ return self.dom.is_positive(a.LC())
281
+
282
+ def is_negative(self, a):
283
+ """Returns True if ``LC(a)`` is negative. """
284
+ return self.dom.is_negative(a.LC())
285
+
286
+ def is_nonpositive(self, a):
287
+ """Returns True if ``LC(a)`` is non-positive. """
288
+ return self.dom.is_nonpositive(a.LC())
289
+
290
+ def is_nonnegative(self, a):
291
+ """Returns True if ``LC(a)`` is non-negative. """
292
+ return self.dom.is_nonnegative(a.LC())
293
+
294
+ def _vector_to_sdm(self, v, order):
295
+ """
296
+ Examples
297
+ ========
298
+
299
+ >>> from sympy import lex, QQ
300
+ >>> from sympy.abc import x, y
301
+ >>> R = QQ.old_poly_ring(x, y)
302
+ >>> f = R.convert(x + 2*y)
303
+ >>> g = R.convert(x * y)
304
+ >>> R._vector_to_sdm([f, g], lex)
305
+ [((1, 1, 1), 1), ((0, 1, 0), 1), ((0, 0, 1), 2)]
306
+ """
307
+ return _vector_to_sdm_helper(v, order)
308
+
309
+
310
+ class GeneralizedPolynomialRing(PolynomialRingBase):
311
+ """A generalized polynomial ring, with objects DMF. """
312
+
313
+ dtype = DMF
314
+
315
+ def new(self, a):
316
+ """Construct an element of ``self`` domain from ``a``. """
317
+ res = self.dtype(a, self.dom, len(self.gens) - 1, ring=self)
318
+
319
+ # make sure res is actually in our ring
320
+ if res.denom().terms(order=self.order)[0][0] != (0,)*len(self.gens):
321
+ from sympy.printing.str import sstr
322
+ raise CoercionFailed("denominator %s not allowed in %s"
323
+ % (sstr(res), self))
324
+ return res
325
+
326
+ def __contains__(self, a):
327
+ try:
328
+ a = self.convert(a)
329
+ except CoercionFailed:
330
+ return False
331
+ return a.denom().terms(order=self.order)[0][0] == (0,)*len(self.gens)
332
+
333
+ def from_FractionField(K1, a, K0):
334
+ dmf = K1.get_field().from_FractionField(a, K0)
335
+ return K1((dmf.num, dmf.den))
336
+
337
+ def to_sympy(self, a):
338
+ """Convert ``a`` to a SymPy object. """
339
+ return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) /
340
+ basic_from_dict(a.denom().to_sympy_dict(), *self.gens))
341
+
342
+ def from_sympy(self, a):
343
+ """Convert SymPy's expression to ``dtype``. """
344
+ p, q = a.as_numer_denom()
345
+
346
+ num, _ = dict_from_basic(p, gens=self.gens)
347
+ den, _ = dict_from_basic(q, gens=self.gens)
348
+
349
+ for k, v in num.items():
350
+ num[k] = self.dom.from_sympy(v)
351
+
352
+ for k, v in den.items():
353
+ den[k] = self.dom.from_sympy(v)
354
+
355
+ return self((num, den)).cancel()
356
+
357
+ def _vector_to_sdm(self, v, order):
358
+ """
359
+ Turn an iterable into a sparse distributed module.
360
+
361
+ Note that the vector is multiplied by a unit first to make all entries
362
+ polynomials.
363
+
364
+ Examples
365
+ ========
366
+
367
+ >>> from sympy import ilex, QQ
368
+ >>> from sympy.abc import x, y
369
+ >>> R = QQ.old_poly_ring(x, y, order=ilex)
370
+ >>> f = R.convert((x + 2*y) / (1 + x))
371
+ >>> g = R.convert(x * y)
372
+ >>> R._vector_to_sdm([f, g], ilex)
373
+ [((0, 0, 1), 2), ((0, 1, 0), 1), ((1, 1, 1), 1), ((1,
374
+ 2, 1), 1)]
375
+ """
376
+ # NOTE this is quite inefficient...
377
+ u = self.one.numer()
378
+ for x in v:
379
+ u *= x.denom()
380
+ return _vector_to_sdm_helper([x.numer()*u/x.denom() for x in v], order)
381
+
382
+
383
+ @public
384
+ def PolynomialRing(dom, *gens, **opts):
385
+ r"""
386
+ Create a generalized multivariate polynomial ring.
387
+
388
+ A generalized polynomial ring is defined by a ground field `K`, a set
389
+ of generators (typically `x_1, \ldots, x_n`) and a monomial order `<`.
390
+ The monomial order can be global, local or mixed. In any case it induces
391
+ a total ordering on the monomials, and there exists for every (non-zero)
392
+ polynomial `f \in K[x_1, \ldots, x_n]` a well-defined "leading monomial"
393
+ `LM(f) = LM(f, >)`. One can then define a multiplicative subset
394
+ `S = S_> = \{f \in K[x_1, \ldots, x_n] | LM(f) = 1\}`. The generalized
395
+ polynomial ring corresponding to the monomial order is
396
+ `R = S^{-1}K[x_1, \ldots, x_n]`.
397
+
398
+ If `>` is a so-called global order, that is `1` is the smallest monomial,
399
+ then we just have `S = K` and `R = K[x_1, \ldots, x_n]`.
400
+
401
+ Examples
402
+ ========
403
+
404
+ A few examples may make this clearer.
405
+
406
+ >>> from sympy.abc import x, y
407
+ >>> from sympy import QQ
408
+
409
+ Our first ring uses global lexicographic order.
410
+
411
+ >>> R1 = QQ.old_poly_ring(x, y, order=(("lex", x, y),))
412
+
413
+ The second ring uses local lexicographic order. Note that when using a
414
+ single (non-product) order, you can just specify the name and omit the
415
+ variables:
416
+
417
+ >>> R2 = QQ.old_poly_ring(x, y, order="ilex")
418
+
419
+ The third and fourth rings use a mixed orders:
420
+
421
+ >>> o1 = (("ilex", x), ("lex", y))
422
+ >>> o2 = (("lex", x), ("ilex", y))
423
+ >>> R3 = QQ.old_poly_ring(x, y, order=o1)
424
+ >>> R4 = QQ.old_poly_ring(x, y, order=o2)
425
+
426
+ We will investigate what elements of `K(x, y)` are contained in the various
427
+ rings.
428
+
429
+ >>> L = [x, 1/x, y/(1 + x), 1/(1 + y), 1/(1 + x*y)]
430
+ >>> test = lambda R: [f in R for f in L]
431
+
432
+ The first ring is just `K[x, y]`:
433
+
434
+ >>> test(R1)
435
+ [True, False, False, False, False]
436
+
437
+ The second ring is R1 localised at the maximal ideal (x, y):
438
+
439
+ >>> test(R2)
440
+ [True, False, True, True, True]
441
+
442
+ The third ring is R1 localised at the prime ideal (x):
443
+
444
+ >>> test(R3)
445
+ [True, False, True, False, True]
446
+
447
+ Finally the fourth ring is R1 localised at `S = K[x, y] \setminus yK[y]`:
448
+
449
+ >>> test(R4)
450
+ [True, False, False, True, False]
451
+ """
452
+
453
+ order = opts.get("order", GeneralizedPolynomialRing.default_order)
454
+ if iterable(order):
455
+ order = build_product_order(order, gens)
456
+ order = monomial_key(order)
457
+ opts['order'] = order
458
+
459
+ if order.is_global:
460
+ return GlobalPolynomialRing(dom, *gens, **opts)
461
+ else:
462
+ return GeneralizedPolynomialRing(dom, *gens, **opts)
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/pythonfinitefield.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`PythonFiniteField` class. """
2
+
3
+
4
+ from sympy.polys.domains.finitefield import FiniteField
5
+ from sympy.polys.domains.pythonintegerring import PythonIntegerRing
6
+
7
+ from sympy.utilities import public
8
+
9
+ @public
10
+ class PythonFiniteField(FiniteField):
11
+ """Finite field based on Python's integers. """
12
+
13
+ alias = 'FF_python'
14
+
15
+ def __init__(self, mod, symmetric=True):
16
+ return super().__init__(mod, PythonIntegerRing(), symmetric)
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/rationalfield.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`RationalField` class. """
2
+
3
+
4
+ from sympy.external.gmpy import MPQ
5
+
6
+ from sympy.polys.domains.groundtypes import SymPyRational
7
+
8
+ from sympy.polys.domains.characteristiczero import CharacteristicZero
9
+ from sympy.polys.domains.field import Field
10
+ from sympy.polys.domains.simpledomain import SimpleDomain
11
+ from sympy.polys.polyerrors import CoercionFailed
12
+ from sympy.utilities import public
13
+
14
+ @public
15
+ class RationalField(Field, CharacteristicZero, SimpleDomain):
16
+ r"""Abstract base class for the domain :ref:`QQ`.
17
+
18
+ The :py:class:`RationalField` class represents the field of rational
19
+ numbers $\mathbb{Q}$ as a :py:class:`~.Domain` in the domain system.
20
+ :py:class:`RationalField` is a superclass of
21
+ :py:class:`PythonRationalField` and :py:class:`GMPYRationalField` one of
22
+ which will be the implementation for :ref:`QQ` depending on whether either
23
+ of ``gmpy`` or ``gmpy2`` is installed or not.
24
+
25
+ See also
26
+ ========
27
+
28
+ Domain
29
+ """
30
+
31
+ rep = 'QQ'
32
+ alias = 'QQ'
33
+
34
+ is_RationalField = is_QQ = True
35
+ is_Numerical = True
36
+
37
+ has_assoc_Ring = True
38
+ has_assoc_Field = True
39
+
40
+ dtype = MPQ
41
+ zero = dtype(0)
42
+ one = dtype(1)
43
+ tp = type(one)
44
+
45
+ def __init__(self):
46
+ pass
47
+
48
+ def get_ring(self):
49
+ """Returns ring associated with ``self``. """
50
+ from sympy.polys.domains import ZZ
51
+ return ZZ
52
+
53
+ def to_sympy(self, a):
54
+ """Convert ``a`` to a SymPy object. """
55
+ return SymPyRational(int(a.numerator), int(a.denominator))
56
+
57
+ def from_sympy(self, a):
58
+ """Convert SymPy's Integer to ``dtype``. """
59
+ if a.is_Rational:
60
+ return MPQ(a.p, a.q)
61
+ elif a.is_Float:
62
+ from sympy.polys.domains import RR
63
+ return MPQ(*map(int, RR.to_rational(a)))
64
+ else:
65
+ raise CoercionFailed("expected `Rational` object, got %s" % a)
66
+
67
+ def algebraic_field(self, *extension, alias=None):
68
+ r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`.
69
+
70
+ Parameters
71
+ ==========
72
+
73
+ *extension : One or more :py:class:`~.Expr`
74
+ Generators of the extension. These should be expressions that are
75
+ algebraic over `\mathbb{Q}`.
76
+
77
+ alias : str, :py:class:`~.Symbol`, None, optional (default=None)
78
+ If provided, this will be used as the alias symbol for the
79
+ primitive element of the returned :py:class:`~.AlgebraicField`.
80
+
81
+ Returns
82
+ =======
83
+
84
+ :py:class:`~.AlgebraicField`
85
+ A :py:class:`~.Domain` representing the algebraic field extension.
86
+
87
+ Examples
88
+ ========
89
+
90
+ >>> from sympy import QQ, sqrt
91
+ >>> QQ.algebraic_field(sqrt(2))
92
+ QQ<sqrt(2)>
93
+ """
94
+ from sympy.polys.domains import AlgebraicField
95
+ return AlgebraicField(self, *extension, alias=alias)
96
+
97
+ def from_AlgebraicField(K1, a, K0):
98
+ """Convert a :py:class:`~.ANP` object to :ref:`QQ`.
99
+
100
+ See :py:meth:`~.Domain.convert`
101
+ """
102
+ if a.is_ground:
103
+ return K1.convert(a.LC(), K0.dom)
104
+
105
+ def from_ZZ(K1, a, K0):
106
+ """Convert a Python ``int`` object to ``dtype``. """
107
+ return MPQ(a)
108
+
109
+ def from_ZZ_python(K1, a, K0):
110
+ """Convert a Python ``int`` object to ``dtype``. """
111
+ return MPQ(a)
112
+
113
+ def from_QQ(K1, a, K0):
114
+ """Convert a Python ``Fraction`` object to ``dtype``. """
115
+ return MPQ(a.numerator, a.denominator)
116
+
117
+ def from_QQ_python(K1, a, K0):
118
+ """Convert a Python ``Fraction`` object to ``dtype``. """
119
+ return MPQ(a.numerator, a.denominator)
120
+
121
+ def from_ZZ_gmpy(K1, a, K0):
122
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
123
+ return MPQ(a)
124
+
125
+ def from_QQ_gmpy(K1, a, K0):
126
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
127
+ return a
128
+
129
+ def from_GaussianRationalField(K1, a, K0):
130
+ """Convert a ``GaussianElement`` object to ``dtype``. """
131
+ if a.y == 0:
132
+ return MPQ(a.x)
133
+
134
+ def from_RealField(K1, a, K0):
135
+ """Convert a mpmath ``mpf`` object to ``dtype``. """
136
+ return MPQ(*map(int, K0.to_rational(a)))
137
+
138
+ def exquo(self, a, b):
139
+ """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """
140
+ return MPQ(a) / MPQ(b)
141
+
142
+ def quo(self, a, b):
143
+ """Quotient of ``a`` and ``b``, implies ``__truediv__``. """
144
+ return MPQ(a) / MPQ(b)
145
+
146
+ def rem(self, a, b):
147
+ """Remainder of ``a`` and ``b``, implies nothing. """
148
+ return self.zero
149
+
150
+ def div(self, a, b):
151
+ """Division of ``a`` and ``b``, implies ``__truediv__``. """
152
+ return MPQ(a) / MPQ(b), self.zero
153
+
154
+ def numer(self, a):
155
+ """Returns numerator of ``a``. """
156
+ return a.numerator
157
+
158
+ def denom(self, a):
159
+ """Returns denominator of ``a``. """
160
+ return a.denominator
161
+
162
+
163
+ QQ = RationalField()
llmeval-env/lib/python3.10/site-packages/sympy/polys/domains/ring.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`Ring` class. """
2
+
3
+
4
+ from sympy.polys.domains.domain import Domain
5
+ from sympy.polys.polyerrors import ExactQuotientFailed, NotInvertible, NotReversible
6
+
7
+ from sympy.utilities import public
8
+
9
+ @public
10
+ class Ring(Domain):
11
+ """Represents a ring domain. """
12
+
13
+ is_Ring = True
14
+
15
+ def get_ring(self):
16
+ """Returns a ring associated with ``self``. """
17
+ return self
18
+
19
+ def exquo(self, a, b):
20
+ """Exact quotient of ``a`` and ``b``, implies ``__floordiv__``. """
21
+ if a % b:
22
+ raise ExactQuotientFailed(a, b, self)
23
+ else:
24
+ return a // b
25
+
26
+ def quo(self, a, b):
27
+ """Quotient of ``a`` and ``b``, implies ``__floordiv__``. """
28
+ return a // b
29
+
30
+ def rem(self, a, b):
31
+ """Remainder of ``a`` and ``b``, implies ``__mod__``. """
32
+ return a % b
33
+
34
+ def div(self, a, b):
35
+ """Division of ``a`` and ``b``, implies ``__divmod__``. """
36
+ return divmod(a, b)
37
+
38
+ def invert(self, a, b):
39
+ """Returns inversion of ``a mod b``. """
40
+ s, t, h = self.gcdex(a, b)
41
+
42
+ if self.is_one(h):
43
+ return s % b
44
+ else:
45
+ raise NotInvertible("zero divisor")
46
+
47
+ def revert(self, a):
48
+ """Returns ``a**(-1)`` if possible. """
49
+ if self.is_one(a) or self.is_one(-a):
50
+ return a
51
+ else:
52
+ raise NotReversible('only units are reversible in a ring')
53
+
54
+ def is_unit(self, a):
55
+ try:
56
+ self.revert(a)
57
+ return True
58
+ except NotReversible:
59
+ return False
60
+
61
+ def numer(self, a):
62
+ """Returns numerator of ``a``. """
63
+ return a
64
+
65
+ def denom(self, a):
66
+ """Returns denominator of `a`. """
67
+ return self.one
68
+
69
+ def free_module(self, rank):
70
+ """
71
+ Generate a free module of rank ``rank`` over self.
72
+
73
+ >>> from sympy.abc import x
74
+ >>> from sympy import QQ
75
+ >>> QQ.old_poly_ring(x).free_module(2)
76
+ QQ[x]**2
77
+ """
78
+ raise NotImplementedError
79
+
80
+ def ideal(self, *gens):
81
+ """
82
+ Generate an ideal of ``self``.
83
+
84
+ >>> from sympy.abc import x
85
+ >>> from sympy import QQ
86
+ >>> QQ.old_poly_ring(x).ideal(x**2)
87
+ <x**2>
88
+ """
89
+ from sympy.polys.agca.ideals import ModuleImplementedIdeal
90
+ return ModuleImplementedIdeal(self, self.free_module(1).submodule(
91
+ *[[x] for x in gens]))
92
+
93
+ def quotient_ring(self, e):
94
+ """
95
+ Form a quotient ring of ``self``.
96
+
97
+ Here ``e`` can be an ideal or an iterable.
98
+
99
+ >>> from sympy.abc import x
100
+ >>> from sympy import QQ
101
+ >>> QQ.old_poly_ring(x).quotient_ring(QQ.old_poly_ring(x).ideal(x**2))
102
+ QQ[x]/<x**2>
103
+ >>> QQ.old_poly_ring(x).quotient_ring([x**2])
104
+ QQ[x]/<x**2>
105
+
106
+ The division operator has been overloaded for this:
107
+
108
+ >>> QQ.old_poly_ring(x)/[x**2]
109
+ QQ[x]/<x**2>
110
+ """
111
+ from sympy.polys.agca.ideals import Ideal
112
+ from sympy.polys.domains.quotientring import QuotientRing
113
+ if not isinstance(e, Ideal):
114
+ e = self.ideal(*e)
115
+ return QuotientRing(self, e)
116
+
117
+ def __truediv__(self, e):
118
+ return self.quotient_ring(e)
llmeval-env/lib/python3.10/site-packages/sympy/polys/euclidtools.py ADDED
@@ -0,0 +1,1893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Euclidean algorithms, GCDs, LCMs and polynomial remainder sequences. """
2
+
3
+
4
+ from sympy.polys.densearith import (
5
+ dup_sub_mul,
6
+ dup_neg, dmp_neg,
7
+ dmp_add,
8
+ dmp_sub,
9
+ dup_mul, dmp_mul,
10
+ dmp_pow,
11
+ dup_div, dmp_div,
12
+ dup_rem,
13
+ dup_quo, dmp_quo,
14
+ dup_prem, dmp_prem,
15
+ dup_mul_ground, dmp_mul_ground,
16
+ dmp_mul_term,
17
+ dup_quo_ground, dmp_quo_ground,
18
+ dup_max_norm, dmp_max_norm)
19
+ from sympy.polys.densebasic import (
20
+ dup_strip, dmp_raise,
21
+ dmp_zero, dmp_one, dmp_ground,
22
+ dmp_one_p, dmp_zero_p,
23
+ dmp_zeros,
24
+ dup_degree, dmp_degree, dmp_degree_in,
25
+ dup_LC, dmp_LC, dmp_ground_LC,
26
+ dmp_multi_deflate, dmp_inflate,
27
+ dup_convert, dmp_convert,
28
+ dmp_apply_pairs)
29
+ from sympy.polys.densetools import (
30
+ dup_clear_denoms, dmp_clear_denoms,
31
+ dup_diff, dmp_diff,
32
+ dup_eval, dmp_eval, dmp_eval_in,
33
+ dup_trunc, dmp_ground_trunc,
34
+ dup_monic, dmp_ground_monic,
35
+ dup_primitive, dmp_ground_primitive,
36
+ dup_extract, dmp_ground_extract)
37
+ from sympy.polys.galoistools import (
38
+ gf_int, gf_crt)
39
+ from sympy.polys.polyconfig import query
40
+ from sympy.polys.polyerrors import (
41
+ MultivariatePolynomialError,
42
+ HeuristicGCDFailed,
43
+ HomomorphismFailed,
44
+ NotInvertible,
45
+ DomainError)
46
+
47
+
48
+
49
+
50
+ def dup_half_gcdex(f, g, K):
51
+ """
52
+ Half extended Euclidean algorithm in `F[x]`.
53
+
54
+ Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``.
55
+
56
+ Examples
57
+ ========
58
+
59
+ >>> from sympy.polys import ring, QQ
60
+ >>> R, x = ring("x", QQ)
61
+
62
+ >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
63
+ >>> g = x**3 + x**2 - 4*x - 4
64
+
65
+ >>> R.dup_half_gcdex(f, g)
66
+ (-1/5*x + 3/5, x + 1)
67
+
68
+ """
69
+ if not K.is_Field:
70
+ raise DomainError("Cannot compute half extended GCD over %s" % K)
71
+
72
+ a, b = [K.one], []
73
+
74
+ while g:
75
+ q, r = dup_div(f, g, K)
76
+ f, g = g, r
77
+ a, b = b, dup_sub_mul(a, q, b, K)
78
+
79
+ a = dup_quo_ground(a, dup_LC(f, K), K)
80
+ f = dup_monic(f, K)
81
+
82
+ return a, f
83
+
84
+
85
+ def dmp_half_gcdex(f, g, u, K):
86
+ """
87
+ Half extended Euclidean algorithm in `F[X]`.
88
+
89
+ Examples
90
+ ========
91
+
92
+ >>> from sympy.polys import ring, ZZ
93
+ >>> R, x,y = ring("x,y", ZZ)
94
+
95
+ """
96
+ if not u:
97
+ return dup_half_gcdex(f, g, K)
98
+ else:
99
+ raise MultivariatePolynomialError(f, g)
100
+
101
+
102
+ def dup_gcdex(f, g, K):
103
+ """
104
+ Extended Euclidean algorithm in `F[x]`.
105
+
106
+ Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.
107
+
108
+ Examples
109
+ ========
110
+
111
+ >>> from sympy.polys import ring, QQ
112
+ >>> R, x = ring("x", QQ)
113
+
114
+ >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
115
+ >>> g = x**3 + x**2 - 4*x - 4
116
+
117
+ >>> R.dup_gcdex(f, g)
118
+ (-1/5*x + 3/5, 1/5*x**2 - 6/5*x + 2, x + 1)
119
+
120
+ """
121
+ s, h = dup_half_gcdex(f, g, K)
122
+
123
+ F = dup_sub_mul(h, s, f, K)
124
+ t = dup_quo(F, g, K)
125
+
126
+ return s, t, h
127
+
128
+
129
+ def dmp_gcdex(f, g, u, K):
130
+ """
131
+ Extended Euclidean algorithm in `F[X]`.
132
+
133
+ Examples
134
+ ========
135
+
136
+ >>> from sympy.polys import ring, ZZ
137
+ >>> R, x,y = ring("x,y", ZZ)
138
+
139
+ """
140
+ if not u:
141
+ return dup_gcdex(f, g, K)
142
+ else:
143
+ raise MultivariatePolynomialError(f, g)
144
+
145
+
146
+ def dup_invert(f, g, K):
147
+ """
148
+ Compute multiplicative inverse of `f` modulo `g` in `F[x]`.
149
+
150
+ Examples
151
+ ========
152
+
153
+ >>> from sympy.polys import ring, QQ
154
+ >>> R, x = ring("x", QQ)
155
+
156
+ >>> f = x**2 - 1
157
+ >>> g = 2*x - 1
158
+ >>> h = x - 1
159
+
160
+ >>> R.dup_invert(f, g)
161
+ -4/3
162
+
163
+ >>> R.dup_invert(f, h)
164
+ Traceback (most recent call last):
165
+ ...
166
+ NotInvertible: zero divisor
167
+
168
+ """
169
+ s, h = dup_half_gcdex(f, g, K)
170
+
171
+ if h == [K.one]:
172
+ return dup_rem(s, g, K)
173
+ else:
174
+ raise NotInvertible("zero divisor")
175
+
176
+
177
+ def dmp_invert(f, g, u, K):
178
+ """
179
+ Compute multiplicative inverse of `f` modulo `g` in `F[X]`.
180
+
181
+ Examples
182
+ ========
183
+
184
+ >>> from sympy.polys import ring, QQ
185
+ >>> R, x = ring("x", QQ)
186
+
187
+ """
188
+ if not u:
189
+ return dup_invert(f, g, K)
190
+ else:
191
+ raise MultivariatePolynomialError(f, g)
192
+
193
+
194
+ def dup_euclidean_prs(f, g, K):
195
+ """
196
+ Euclidean polynomial remainder sequence (PRS) in `K[x]`.
197
+
198
+ Examples
199
+ ========
200
+
201
+ >>> from sympy.polys import ring, QQ
202
+ >>> R, x = ring("x", QQ)
203
+
204
+ >>> f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
205
+ >>> g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
206
+
207
+ >>> prs = R.dup_euclidean_prs(f, g)
208
+
209
+ >>> prs[0]
210
+ x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
211
+ >>> prs[1]
212
+ 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
213
+ >>> prs[2]
214
+ -5/9*x**4 + 1/9*x**2 - 1/3
215
+ >>> prs[3]
216
+ -117/25*x**2 - 9*x + 441/25
217
+ >>> prs[4]
218
+ 233150/19773*x - 102500/6591
219
+ >>> prs[5]
220
+ -1288744821/543589225
221
+
222
+ """
223
+ prs = [f, g]
224
+ h = dup_rem(f, g, K)
225
+
226
+ while h:
227
+ prs.append(h)
228
+ f, g = g, h
229
+ h = dup_rem(f, g, K)
230
+
231
+ return prs
232
+
233
+
234
+ def dmp_euclidean_prs(f, g, u, K):
235
+ """
236
+ Euclidean polynomial remainder sequence (PRS) in `K[X]`.
237
+
238
+ Examples
239
+ ========
240
+
241
+ >>> from sympy.polys import ring, ZZ
242
+ >>> R, x,y = ring("x,y", ZZ)
243
+
244
+ """
245
+ if not u:
246
+ return dup_euclidean_prs(f, g, K)
247
+ else:
248
+ raise MultivariatePolynomialError(f, g)
249
+
250
+
251
+ def dup_primitive_prs(f, g, K):
252
+ """
253
+ Primitive polynomial remainder sequence (PRS) in `K[x]`.
254
+
255
+ Examples
256
+ ========
257
+
258
+ >>> from sympy.polys import ring, ZZ
259
+ >>> R, x = ring("x", ZZ)
260
+
261
+ >>> f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
262
+ >>> g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
263
+
264
+ >>> prs = R.dup_primitive_prs(f, g)
265
+
266
+ >>> prs[0]
267
+ x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5
268
+ >>> prs[1]
269
+ 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21
270
+ >>> prs[2]
271
+ -5*x**4 + x**2 - 3
272
+ >>> prs[3]
273
+ 13*x**2 + 25*x - 49
274
+ >>> prs[4]
275
+ 4663*x - 6150
276
+ >>> prs[5]
277
+ 1
278
+
279
+ """
280
+ prs = [f, g]
281
+ _, h = dup_primitive(dup_prem(f, g, K), K)
282
+
283
+ while h:
284
+ prs.append(h)
285
+ f, g = g, h
286
+ _, h = dup_primitive(dup_prem(f, g, K), K)
287
+
288
+ return prs
289
+
290
+
291
+ def dmp_primitive_prs(f, g, u, K):
292
+ """
293
+ Primitive polynomial remainder sequence (PRS) in `K[X]`.
294
+
295
+ Examples
296
+ ========
297
+
298
+ >>> from sympy.polys import ring, ZZ
299
+ >>> R, x,y = ring("x,y", ZZ)
300
+
301
+ """
302
+ if not u:
303
+ return dup_primitive_prs(f, g, K)
304
+ else:
305
+ raise MultivariatePolynomialError(f, g)
306
+
307
+
308
+ def dup_inner_subresultants(f, g, K):
309
+ """
310
+ Subresultant PRS algorithm in `K[x]`.
311
+
312
+ Computes the subresultant polynomial remainder sequence (PRS)
313
+ and the non-zero scalar subresultants of `f` and `g`.
314
+ By [1] Thm. 3, these are the constants '-c' (- to optimize
315
+ computation of sign).
316
+ The first subdeterminant is set to 1 by convention to match
317
+ the polynomial and the scalar subdeterminants.
318
+ If 'deg(f) < deg(g)', the subresultants of '(g,f)' are computed.
319
+
320
+ Examples
321
+ ========
322
+
323
+ >>> from sympy.polys import ring, ZZ
324
+ >>> R, x = ring("x", ZZ)
325
+
326
+ >>> R.dup_inner_subresultants(x**2 + 1, x**2 - 1)
327
+ ([x**2 + 1, x**2 - 1, -2], [1, 1, 4])
328
+
329
+ References
330
+ ==========
331
+
332
+ .. [1] W.S. Brown, The Subresultant PRS Algorithm.
333
+ ACM Transaction of Mathematical Software 4 (1978) 237-249
334
+
335
+ """
336
+ n = dup_degree(f)
337
+ m = dup_degree(g)
338
+
339
+ if n < m:
340
+ f, g = g, f
341
+ n, m = m, n
342
+
343
+ if not f:
344
+ return [], []
345
+
346
+ if not g:
347
+ return [f], [K.one]
348
+
349
+ R = [f, g]
350
+ d = n - m
351
+
352
+ b = (-K.one)**(d + 1)
353
+
354
+ h = dup_prem(f, g, K)
355
+ h = dup_mul_ground(h, b, K)
356
+
357
+ lc = dup_LC(g, K)
358
+ c = lc**d
359
+
360
+ # Conventional first scalar subdeterminant is 1
361
+ S = [K.one, c]
362
+ c = -c
363
+
364
+ while h:
365
+ k = dup_degree(h)
366
+ R.append(h)
367
+
368
+ f, g, m, d = g, h, k, m - k
369
+
370
+ b = -lc * c**d
371
+
372
+ h = dup_prem(f, g, K)
373
+ h = dup_quo_ground(h, b, K)
374
+
375
+ lc = dup_LC(g, K)
376
+
377
+ if d > 1: # abnormal case
378
+ q = c**(d - 1)
379
+ c = K.quo((-lc)**d, q)
380
+ else:
381
+ c = -lc
382
+
383
+ S.append(-c)
384
+
385
+ return R, S
386
+
387
+
388
+ def dup_subresultants(f, g, K):
389
+ """
390
+ Computes subresultant PRS of two polynomials in `K[x]`.
391
+
392
+ Examples
393
+ ========
394
+
395
+ >>> from sympy.polys import ring, ZZ
396
+ >>> R, x = ring("x", ZZ)
397
+
398
+ >>> R.dup_subresultants(x**2 + 1, x**2 - 1)
399
+ [x**2 + 1, x**2 - 1, -2]
400
+
401
+ """
402
+ return dup_inner_subresultants(f, g, K)[0]
403
+
404
+
405
+ def dup_prs_resultant(f, g, K):
406
+ """
407
+ Resultant algorithm in `K[x]` using subresultant PRS.
408
+
409
+ Examples
410
+ ========
411
+
412
+ >>> from sympy.polys import ring, ZZ
413
+ >>> R, x = ring("x", ZZ)
414
+
415
+ >>> R.dup_prs_resultant(x**2 + 1, x**2 - 1)
416
+ (4, [x**2 + 1, x**2 - 1, -2])
417
+
418
+ """
419
+ if not f or not g:
420
+ return (K.zero, [])
421
+
422
+ R, S = dup_inner_subresultants(f, g, K)
423
+
424
+ if dup_degree(R[-1]) > 0:
425
+ return (K.zero, R)
426
+
427
+ return S[-1], R
428
+
429
+
430
+ def dup_resultant(f, g, K, includePRS=False):
431
+ """
432
+ Computes resultant of two polynomials in `K[x]`.
433
+
434
+ Examples
435
+ ========
436
+
437
+ >>> from sympy.polys import ring, ZZ
438
+ >>> R, x = ring("x", ZZ)
439
+
440
+ >>> R.dup_resultant(x**2 + 1, x**2 - 1)
441
+ 4
442
+
443
+ """
444
+ if includePRS:
445
+ return dup_prs_resultant(f, g, K)
446
+ return dup_prs_resultant(f, g, K)[0]
447
+
448
+
449
+ def dmp_inner_subresultants(f, g, u, K):
450
+ """
451
+ Subresultant PRS algorithm in `K[X]`.
452
+
453
+ Examples
454
+ ========
455
+
456
+ >>> from sympy.polys import ring, ZZ
457
+ >>> R, x,y = ring("x,y", ZZ)
458
+
459
+ >>> f = 3*x**2*y - y**3 - 4
460
+ >>> g = x**2 + x*y**3 - 9
461
+
462
+ >>> a = 3*x*y**4 + y**3 - 27*y + 4
463
+ >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16
464
+
465
+ >>> prs = [f, g, a, b]
466
+ >>> sres = [[1], [1], [3, 0, 0, 0, 0], [-3, 0, 0, -12, 1, 0, -54, 8, 729, -216, 16]]
467
+
468
+ >>> R.dmp_inner_subresultants(f, g) == (prs, sres)
469
+ True
470
+
471
+ """
472
+ if not u:
473
+ return dup_inner_subresultants(f, g, K)
474
+
475
+ n = dmp_degree(f, u)
476
+ m = dmp_degree(g, u)
477
+
478
+ if n < m:
479
+ f, g = g, f
480
+ n, m = m, n
481
+
482
+ if dmp_zero_p(f, u):
483
+ return [], []
484
+
485
+ v = u - 1
486
+ if dmp_zero_p(g, u):
487
+ return [f], [dmp_ground(K.one, v)]
488
+
489
+ R = [f, g]
490
+ d = n - m
491
+
492
+ b = dmp_pow(dmp_ground(-K.one, v), d + 1, v, K)
493
+
494
+ h = dmp_prem(f, g, u, K)
495
+ h = dmp_mul_term(h, b, 0, u, K)
496
+
497
+ lc = dmp_LC(g, K)
498
+ c = dmp_pow(lc, d, v, K)
499
+
500
+ S = [dmp_ground(K.one, v), c]
501
+ c = dmp_neg(c, v, K)
502
+
503
+ while not dmp_zero_p(h, u):
504
+ k = dmp_degree(h, u)
505
+ R.append(h)
506
+
507
+ f, g, m, d = g, h, k, m - k
508
+
509
+ b = dmp_mul(dmp_neg(lc, v, K),
510
+ dmp_pow(c, d, v, K), v, K)
511
+
512
+ h = dmp_prem(f, g, u, K)
513
+ h = [ dmp_quo(ch, b, v, K) for ch in h ]
514
+
515
+ lc = dmp_LC(g, K)
516
+
517
+ if d > 1:
518
+ p = dmp_pow(dmp_neg(lc, v, K), d, v, K)
519
+ q = dmp_pow(c, d - 1, v, K)
520
+ c = dmp_quo(p, q, v, K)
521
+ else:
522
+ c = dmp_neg(lc, v, K)
523
+
524
+ S.append(dmp_neg(c, v, K))
525
+
526
+ return R, S
527
+
528
+
529
+ def dmp_subresultants(f, g, u, K):
530
+ """
531
+ Computes subresultant PRS of two polynomials in `K[X]`.
532
+
533
+ Examples
534
+ ========
535
+
536
+ >>> from sympy.polys import ring, ZZ
537
+ >>> R, x,y = ring("x,y", ZZ)
538
+
539
+ >>> f = 3*x**2*y - y**3 - 4
540
+ >>> g = x**2 + x*y**3 - 9
541
+
542
+ >>> a = 3*x*y**4 + y**3 - 27*y + 4
543
+ >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16
544
+
545
+ >>> R.dmp_subresultants(f, g) == [f, g, a, b]
546
+ True
547
+
548
+ """
549
+ return dmp_inner_subresultants(f, g, u, K)[0]
550
+
551
+
552
+ def dmp_prs_resultant(f, g, u, K):
553
+ """
554
+ Resultant algorithm in `K[X]` using subresultant PRS.
555
+
556
+ Examples
557
+ ========
558
+
559
+ >>> from sympy.polys import ring, ZZ
560
+ >>> R, x,y = ring("x,y", ZZ)
561
+
562
+ >>> f = 3*x**2*y - y**3 - 4
563
+ >>> g = x**2 + x*y**3 - 9
564
+
565
+ >>> a = 3*x*y**4 + y**3 - 27*y + 4
566
+ >>> b = -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16
567
+
568
+ >>> res, prs = R.dmp_prs_resultant(f, g)
569
+
570
+ >>> res == b # resultant has n-1 variables
571
+ False
572
+ >>> res == b.drop(x)
573
+ True
574
+ >>> prs == [f, g, a, b]
575
+ True
576
+
577
+ """
578
+ if not u:
579
+ return dup_prs_resultant(f, g, K)
580
+
581
+ if dmp_zero_p(f, u) or dmp_zero_p(g, u):
582
+ return (dmp_zero(u - 1), [])
583
+
584
+ R, S = dmp_inner_subresultants(f, g, u, K)
585
+
586
+ if dmp_degree(R[-1], u) > 0:
587
+ return (dmp_zero(u - 1), R)
588
+
589
+ return S[-1], R
590
+
591
+
592
+ def dmp_zz_modular_resultant(f, g, p, u, K):
593
+ """
594
+ Compute resultant of `f` and `g` modulo a prime `p`.
595
+
596
+ Examples
597
+ ========
598
+
599
+ >>> from sympy.polys import ring, ZZ
600
+ >>> R, x,y = ring("x,y", ZZ)
601
+
602
+ >>> f = x + y + 2
603
+ >>> g = 2*x*y + x + 3
604
+
605
+ >>> R.dmp_zz_modular_resultant(f, g, 5)
606
+ -2*y**2 + 1
607
+
608
+ """
609
+ if not u:
610
+ return gf_int(dup_prs_resultant(f, g, K)[0] % p, p)
611
+
612
+ v = u - 1
613
+
614
+ n = dmp_degree(f, u)
615
+ m = dmp_degree(g, u)
616
+
617
+ N = dmp_degree_in(f, 1, u)
618
+ M = dmp_degree_in(g, 1, u)
619
+
620
+ B = n*M + m*N
621
+
622
+ D, a = [K.one], -K.one
623
+ r = dmp_zero(v)
624
+
625
+ while dup_degree(D) <= B:
626
+ while True:
627
+ a += K.one
628
+
629
+ if a == p:
630
+ raise HomomorphismFailed('no luck')
631
+
632
+ F = dmp_eval_in(f, gf_int(a, p), 1, u, K)
633
+
634
+ if dmp_degree(F, v) == n:
635
+ G = dmp_eval_in(g, gf_int(a, p), 1, u, K)
636
+
637
+ if dmp_degree(G, v) == m:
638
+ break
639
+
640
+ R = dmp_zz_modular_resultant(F, G, p, v, K)
641
+ e = dmp_eval(r, a, v, K)
642
+
643
+ if not v:
644
+ R = dup_strip([R])
645
+ e = dup_strip([e])
646
+ else:
647
+ R = [R]
648
+ e = [e]
649
+
650
+ d = K.invert(dup_eval(D, a, K), p)
651
+ d = dup_mul_ground(D, d, K)
652
+ d = dmp_raise(d, v, 0, K)
653
+
654
+ c = dmp_mul(d, dmp_sub(R, e, v, K), v, K)
655
+ r = dmp_add(r, c, v, K)
656
+
657
+ r = dmp_ground_trunc(r, p, v, K)
658
+
659
+ D = dup_mul(D, [K.one, -a], K)
660
+ D = dup_trunc(D, p, K)
661
+
662
+ return r
663
+
664
+
665
+ def _collins_crt(r, R, P, p, K):
666
+ """Wrapper of CRT for Collins's resultant algorithm. """
667
+ return gf_int(gf_crt([r, R], [P, p], K), P*p)
668
+
669
+
670
+ def dmp_zz_collins_resultant(f, g, u, K):
671
+ """
672
+ Collins's modular resultant algorithm in `Z[X]`.
673
+
674
+ Examples
675
+ ========
676
+
677
+ >>> from sympy.polys import ring, ZZ
678
+ >>> R, x,y = ring("x,y", ZZ)
679
+
680
+ >>> f = x + y + 2
681
+ >>> g = 2*x*y + x + 3
682
+
683
+ >>> R.dmp_zz_collins_resultant(f, g)
684
+ -2*y**2 - 5*y + 1
685
+
686
+ """
687
+
688
+ n = dmp_degree(f, u)
689
+ m = dmp_degree(g, u)
690
+
691
+ if n < 0 or m < 0:
692
+ return dmp_zero(u - 1)
693
+
694
+ A = dmp_max_norm(f, u, K)
695
+ B = dmp_max_norm(g, u, K)
696
+
697
+ a = dmp_ground_LC(f, u, K)
698
+ b = dmp_ground_LC(g, u, K)
699
+
700
+ v = u - 1
701
+
702
+ B = K(2)*K.factorial(K(n + m))*A**m*B**n
703
+ r, p, P = dmp_zero(v), K.one, K.one
704
+
705
+ from sympy.ntheory import nextprime
706
+
707
+ while P <= B:
708
+ p = K(nextprime(p))
709
+
710
+ while not (a % p) or not (b % p):
711
+ p = K(nextprime(p))
712
+
713
+ F = dmp_ground_trunc(f, p, u, K)
714
+ G = dmp_ground_trunc(g, p, u, K)
715
+
716
+ try:
717
+ R = dmp_zz_modular_resultant(F, G, p, u, K)
718
+ except HomomorphismFailed:
719
+ continue
720
+
721
+ if K.is_one(P):
722
+ r = R
723
+ else:
724
+ r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K)
725
+
726
+ P *= p
727
+
728
+ return r
729
+
730
+
731
+ def dmp_qq_collins_resultant(f, g, u, K0):
732
+ """
733
+ Collins's modular resultant algorithm in `Q[X]`.
734
+
735
+ Examples
736
+ ========
737
+
738
+ >>> from sympy.polys import ring, QQ
739
+ >>> R, x,y = ring("x,y", QQ)
740
+
741
+ >>> f = QQ(1,2)*x + y + QQ(2,3)
742
+ >>> g = 2*x*y + x + 3
743
+
744
+ >>> R.dmp_qq_collins_resultant(f, g)
745
+ -2*y**2 - 7/3*y + 5/6
746
+
747
+ """
748
+ n = dmp_degree(f, u)
749
+ m = dmp_degree(g, u)
750
+
751
+ if n < 0 or m < 0:
752
+ return dmp_zero(u - 1)
753
+
754
+ K1 = K0.get_ring()
755
+
756
+ cf, f = dmp_clear_denoms(f, u, K0, K1)
757
+ cg, g = dmp_clear_denoms(g, u, K0, K1)
758
+
759
+ f = dmp_convert(f, u, K0, K1)
760
+ g = dmp_convert(g, u, K0, K1)
761
+
762
+ r = dmp_zz_collins_resultant(f, g, u, K1)
763
+ r = dmp_convert(r, u - 1, K1, K0)
764
+
765
+ c = K0.convert(cf**m * cg**n, K1)
766
+
767
+ return dmp_quo_ground(r, c, u - 1, K0)
768
+
769
+
770
+ def dmp_resultant(f, g, u, K, includePRS=False):
771
+ """
772
+ Computes resultant of two polynomials in `K[X]`.
773
+
774
+ Examples
775
+ ========
776
+
777
+ >>> from sympy.polys import ring, ZZ
778
+ >>> R, x,y = ring("x,y", ZZ)
779
+
780
+ >>> f = 3*x**2*y - y**3 - 4
781
+ >>> g = x**2 + x*y**3 - 9
782
+
783
+ >>> R.dmp_resultant(f, g)
784
+ -3*y**10 - 12*y**7 + y**6 - 54*y**4 + 8*y**3 + 729*y**2 - 216*y + 16
785
+
786
+ """
787
+ if not u:
788
+ return dup_resultant(f, g, K, includePRS=includePRS)
789
+
790
+ if includePRS:
791
+ return dmp_prs_resultant(f, g, u, K)
792
+
793
+ if K.is_Field:
794
+ if K.is_QQ and query('USE_COLLINS_RESULTANT'):
795
+ return dmp_qq_collins_resultant(f, g, u, K)
796
+ else:
797
+ if K.is_ZZ and query('USE_COLLINS_RESULTANT'):
798
+ return dmp_zz_collins_resultant(f, g, u, K)
799
+
800
+ return dmp_prs_resultant(f, g, u, K)[0]
801
+
802
+
803
+ def dup_discriminant(f, K):
804
+ """
805
+ Computes discriminant of a polynomial in `K[x]`.
806
+
807
+ Examples
808
+ ========
809
+
810
+ >>> from sympy.polys import ring, ZZ
811
+ >>> R, x = ring("x", ZZ)
812
+
813
+ >>> R.dup_discriminant(x**2 + 2*x + 3)
814
+ -8
815
+
816
+ """
817
+ d = dup_degree(f)
818
+
819
+ if d <= 0:
820
+ return K.zero
821
+ else:
822
+ s = (-1)**((d*(d - 1)) // 2)
823
+ c = dup_LC(f, K)
824
+
825
+ r = dup_resultant(f, dup_diff(f, 1, K), K)
826
+
827
+ return K.quo(r, c*K(s))
828
+
829
+
830
+ def dmp_discriminant(f, u, K):
831
+ """
832
+ Computes discriminant of a polynomial in `K[X]`.
833
+
834
+ Examples
835
+ ========
836
+
837
+ >>> from sympy.polys import ring, ZZ
838
+ >>> R, x,y,z,t = ring("x,y,z,t", ZZ)
839
+
840
+ >>> R.dmp_discriminant(x**2*y + x*z + t)
841
+ -4*y*t + z**2
842
+
843
+ """
844
+ if not u:
845
+ return dup_discriminant(f, K)
846
+
847
+ d, v = dmp_degree(f, u), u - 1
848
+
849
+ if d <= 0:
850
+ return dmp_zero(v)
851
+ else:
852
+ s = (-1)**((d*(d - 1)) // 2)
853
+ c = dmp_LC(f, K)
854
+
855
+ r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K)
856
+ c = dmp_mul_ground(c, K(s), v, K)
857
+
858
+ return dmp_quo(r, c, v, K)
859
+
860
+
861
+ def _dup_rr_trivial_gcd(f, g, K):
862
+ """Handle trivial cases in GCD algorithm over a ring. """
863
+ if not (f or g):
864
+ return [], [], []
865
+ elif not f:
866
+ if K.is_nonnegative(dup_LC(g, K)):
867
+ return g, [], [K.one]
868
+ else:
869
+ return dup_neg(g, K), [], [-K.one]
870
+ elif not g:
871
+ if K.is_nonnegative(dup_LC(f, K)):
872
+ return f, [K.one], []
873
+ else:
874
+ return dup_neg(f, K), [-K.one], []
875
+
876
+ return None
877
+
878
+
879
+ def _dup_ff_trivial_gcd(f, g, K):
880
+ """Handle trivial cases in GCD algorithm over a field. """
881
+ if not (f or g):
882
+ return [], [], []
883
+ elif not f:
884
+ return dup_monic(g, K), [], [dup_LC(g, K)]
885
+ elif not g:
886
+ return dup_monic(f, K), [dup_LC(f, K)], []
887
+ else:
888
+ return None
889
+
890
+
891
+ def _dmp_rr_trivial_gcd(f, g, u, K):
892
+ """Handle trivial cases in GCD algorithm over a ring. """
893
+ zero_f = dmp_zero_p(f, u)
894
+ zero_g = dmp_zero_p(g, u)
895
+ if_contain_one = dmp_one_p(f, u, K) or dmp_one_p(g, u, K)
896
+
897
+ if zero_f and zero_g:
898
+ return tuple(dmp_zeros(3, u, K))
899
+ elif zero_f:
900
+ if K.is_nonnegative(dmp_ground_LC(g, u, K)):
901
+ return g, dmp_zero(u), dmp_one(u, K)
902
+ else:
903
+ return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u)
904
+ elif zero_g:
905
+ if K.is_nonnegative(dmp_ground_LC(f, u, K)):
906
+ return f, dmp_one(u, K), dmp_zero(u)
907
+ else:
908
+ return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u)
909
+ elif if_contain_one:
910
+ return dmp_one(u, K), f, g
911
+ elif query('USE_SIMPLIFY_GCD'):
912
+ return _dmp_simplify_gcd(f, g, u, K)
913
+ else:
914
+ return None
915
+
916
+
917
+ def _dmp_ff_trivial_gcd(f, g, u, K):
918
+ """Handle trivial cases in GCD algorithm over a field. """
919
+ zero_f = dmp_zero_p(f, u)
920
+ zero_g = dmp_zero_p(g, u)
921
+
922
+ if zero_f and zero_g:
923
+ return tuple(dmp_zeros(3, u, K))
924
+ elif zero_f:
925
+ return (dmp_ground_monic(g, u, K),
926
+ dmp_zero(u),
927
+ dmp_ground(dmp_ground_LC(g, u, K), u))
928
+ elif zero_g:
929
+ return (dmp_ground_monic(f, u, K),
930
+ dmp_ground(dmp_ground_LC(f, u, K), u),
931
+ dmp_zero(u))
932
+ elif query('USE_SIMPLIFY_GCD'):
933
+ return _dmp_simplify_gcd(f, g, u, K)
934
+ else:
935
+ return None
936
+
937
+
938
+ def _dmp_simplify_gcd(f, g, u, K):
939
+ """Try to eliminate `x_0` from GCD computation in `K[X]`. """
940
+ df = dmp_degree(f, u)
941
+ dg = dmp_degree(g, u)
942
+
943
+ if df > 0 and dg > 0:
944
+ return None
945
+
946
+ if not (df or dg):
947
+ F = dmp_LC(f, K)
948
+ G = dmp_LC(g, K)
949
+ else:
950
+ if not df:
951
+ F = dmp_LC(f, K)
952
+ G = dmp_content(g, u, K)
953
+ else:
954
+ F = dmp_content(f, u, K)
955
+ G = dmp_LC(g, K)
956
+
957
+ v = u - 1
958
+ h = dmp_gcd(F, G, v, K)
959
+
960
+ cff = [ dmp_quo(cf, h, v, K) for cf in f ]
961
+ cfg = [ dmp_quo(cg, h, v, K) for cg in g ]
962
+
963
+ return [h], cff, cfg
964
+
965
+
966
+ def dup_rr_prs_gcd(f, g, K):
967
+ """
968
+ Computes polynomial GCD using subresultants over a ring.
969
+
970
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``,
971
+ and ``cfg = quo(g, h)``.
972
+
973
+ Examples
974
+ ========
975
+
976
+ >>> from sympy.polys import ring, ZZ
977
+ >>> R, x = ring("x", ZZ)
978
+
979
+ >>> R.dup_rr_prs_gcd(x**2 - 1, x**2 - 3*x + 2)
980
+ (x - 1, x + 1, x - 2)
981
+
982
+ """
983
+ result = _dup_rr_trivial_gcd(f, g, K)
984
+
985
+ if result is not None:
986
+ return result
987
+
988
+ fc, F = dup_primitive(f, K)
989
+ gc, G = dup_primitive(g, K)
990
+
991
+ c = K.gcd(fc, gc)
992
+
993
+ h = dup_subresultants(F, G, K)[-1]
994
+ _, h = dup_primitive(h, K)
995
+
996
+ c *= K.canonical_unit(dup_LC(h, K))
997
+
998
+ h = dup_mul_ground(h, c, K)
999
+
1000
+ cff = dup_quo(f, h, K)
1001
+ cfg = dup_quo(g, h, K)
1002
+
1003
+ return h, cff, cfg
1004
+
1005
+
1006
+ def dup_ff_prs_gcd(f, g, K):
1007
+ """
1008
+ Computes polynomial GCD using subresultants over a field.
1009
+
1010
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``,
1011
+ and ``cfg = quo(g, h)``.
1012
+
1013
+ Examples
1014
+ ========
1015
+
1016
+ >>> from sympy.polys import ring, QQ
1017
+ >>> R, x = ring("x", QQ)
1018
+
1019
+ >>> R.dup_ff_prs_gcd(x**2 - 1, x**2 - 3*x + 2)
1020
+ (x - 1, x + 1, x - 2)
1021
+
1022
+ """
1023
+ result = _dup_ff_trivial_gcd(f, g, K)
1024
+
1025
+ if result is not None:
1026
+ return result
1027
+
1028
+ h = dup_subresultants(f, g, K)[-1]
1029
+ h = dup_monic(h, K)
1030
+
1031
+ cff = dup_quo(f, h, K)
1032
+ cfg = dup_quo(g, h, K)
1033
+
1034
+ return h, cff, cfg
1035
+
1036
+
1037
+ def dmp_rr_prs_gcd(f, g, u, K):
1038
+ """
1039
+ Computes polynomial GCD using subresultants over a ring.
1040
+
1041
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``,
1042
+ and ``cfg = quo(g, h)``.
1043
+
1044
+ Examples
1045
+ ========
1046
+
1047
+ >>> from sympy.polys import ring, ZZ
1048
+ >>> R, x,y, = ring("x,y", ZZ)
1049
+
1050
+ >>> f = x**2 + 2*x*y + y**2
1051
+ >>> g = x**2 + x*y
1052
+
1053
+ >>> R.dmp_rr_prs_gcd(f, g)
1054
+ (x + y, x + y, x)
1055
+
1056
+ """
1057
+ if not u:
1058
+ return dup_rr_prs_gcd(f, g, K)
1059
+
1060
+ result = _dmp_rr_trivial_gcd(f, g, u, K)
1061
+
1062
+ if result is not None:
1063
+ return result
1064
+
1065
+ fc, F = dmp_primitive(f, u, K)
1066
+ gc, G = dmp_primitive(g, u, K)
1067
+
1068
+ h = dmp_subresultants(F, G, u, K)[-1]
1069
+ c, _, _ = dmp_rr_prs_gcd(fc, gc, u - 1, K)
1070
+
1071
+ if K.is_negative(dmp_ground_LC(h, u, K)):
1072
+ h = dmp_neg(h, u, K)
1073
+
1074
+ _, h = dmp_primitive(h, u, K)
1075
+ h = dmp_mul_term(h, c, 0, u, K)
1076
+
1077
+ cff = dmp_quo(f, h, u, K)
1078
+ cfg = dmp_quo(g, h, u, K)
1079
+
1080
+ return h, cff, cfg
1081
+
1082
+
1083
+ def dmp_ff_prs_gcd(f, g, u, K):
1084
+ """
1085
+ Computes polynomial GCD using subresultants over a field.
1086
+
1087
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``, ``cff = quo(f, h)``,
1088
+ and ``cfg = quo(g, h)``.
1089
+
1090
+ Examples
1091
+ ========
1092
+
1093
+ >>> from sympy.polys import ring, QQ
1094
+ >>> R, x,y, = ring("x,y", QQ)
1095
+
1096
+ >>> f = QQ(1,2)*x**2 + x*y + QQ(1,2)*y**2
1097
+ >>> g = x**2 + x*y
1098
+
1099
+ >>> R.dmp_ff_prs_gcd(f, g)
1100
+ (x + y, 1/2*x + 1/2*y, x)
1101
+
1102
+ """
1103
+ if not u:
1104
+ return dup_ff_prs_gcd(f, g, K)
1105
+
1106
+ result = _dmp_ff_trivial_gcd(f, g, u, K)
1107
+
1108
+ if result is not None:
1109
+ return result
1110
+
1111
+ fc, F = dmp_primitive(f, u, K)
1112
+ gc, G = dmp_primitive(g, u, K)
1113
+
1114
+ h = dmp_subresultants(F, G, u, K)[-1]
1115
+ c, _, _ = dmp_ff_prs_gcd(fc, gc, u - 1, K)
1116
+
1117
+ _, h = dmp_primitive(h, u, K)
1118
+ h = dmp_mul_term(h, c, 0, u, K)
1119
+ h = dmp_ground_monic(h, u, K)
1120
+
1121
+ cff = dmp_quo(f, h, u, K)
1122
+ cfg = dmp_quo(g, h, u, K)
1123
+
1124
+ return h, cff, cfg
1125
+
1126
+ HEU_GCD_MAX = 6
1127
+
1128
+
1129
+ def _dup_zz_gcd_interpolate(h, x, K):
1130
+ """Interpolate polynomial GCD from integer GCD. """
1131
+ f = []
1132
+
1133
+ while h:
1134
+ g = h % x
1135
+
1136
+ if g > x // 2:
1137
+ g -= x
1138
+
1139
+ f.insert(0, g)
1140
+ h = (h - g) // x
1141
+
1142
+ return f
1143
+
1144
+
1145
+ def dup_zz_heu_gcd(f, g, K):
1146
+ """
1147
+ Heuristic polynomial GCD in `Z[x]`.
1148
+
1149
+ Given univariate polynomials `f` and `g` in `Z[x]`, returns
1150
+ their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg``
1151
+ such that::
1152
+
1153
+ h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h)
1154
+
1155
+ The algorithm is purely heuristic which means it may fail to compute
1156
+ the GCD. This will be signaled by raising an exception. In this case
1157
+ you will need to switch to another GCD method.
1158
+
1159
+ The algorithm computes the polynomial GCD by evaluating polynomials
1160
+ f and g at certain points and computing (fast) integer GCD of those
1161
+ evaluations. The polynomial GCD is recovered from the integer image
1162
+ by interpolation. The final step is to verify if the result is the
1163
+ correct GCD. This gives cofactors as a side effect.
1164
+
1165
+ Examples
1166
+ ========
1167
+
1168
+ >>> from sympy.polys import ring, ZZ
1169
+ >>> R, x = ring("x", ZZ)
1170
+
1171
+ >>> R.dup_zz_heu_gcd(x**2 - 1, x**2 - 3*x + 2)
1172
+ (x - 1, x + 1, x - 2)
1173
+
1174
+ References
1175
+ ==========
1176
+
1177
+ .. [1] [Liao95]_
1178
+
1179
+ """
1180
+ result = _dup_rr_trivial_gcd(f, g, K)
1181
+
1182
+ if result is not None:
1183
+ return result
1184
+
1185
+ df = dup_degree(f)
1186
+ dg = dup_degree(g)
1187
+
1188
+ gcd, f, g = dup_extract(f, g, K)
1189
+
1190
+ if df == 0 or dg == 0:
1191
+ return [gcd], f, g
1192
+
1193
+ f_norm = dup_max_norm(f, K)
1194
+ g_norm = dup_max_norm(g, K)
1195
+
1196
+ B = K(2*min(f_norm, g_norm) + 29)
1197
+
1198
+ x = max(min(B, 99*K.sqrt(B)),
1199
+ 2*min(f_norm // abs(dup_LC(f, K)),
1200
+ g_norm // abs(dup_LC(g, K))) + 2)
1201
+
1202
+ for i in range(0, HEU_GCD_MAX):
1203
+ ff = dup_eval(f, x, K)
1204
+ gg = dup_eval(g, x, K)
1205
+
1206
+ if ff and gg:
1207
+ h = K.gcd(ff, gg)
1208
+
1209
+ cff = ff // h
1210
+ cfg = gg // h
1211
+
1212
+ h = _dup_zz_gcd_interpolate(h, x, K)
1213
+ h = dup_primitive(h, K)[1]
1214
+
1215
+ cff_, r = dup_div(f, h, K)
1216
+
1217
+ if not r:
1218
+ cfg_, r = dup_div(g, h, K)
1219
+
1220
+ if not r:
1221
+ h = dup_mul_ground(h, gcd, K)
1222
+ return h, cff_, cfg_
1223
+
1224
+ cff = _dup_zz_gcd_interpolate(cff, x, K)
1225
+
1226
+ h, r = dup_div(f, cff, K)
1227
+
1228
+ if not r:
1229
+ cfg_, r = dup_div(g, h, K)
1230
+
1231
+ if not r:
1232
+ h = dup_mul_ground(h, gcd, K)
1233
+ return h, cff, cfg_
1234
+
1235
+ cfg = _dup_zz_gcd_interpolate(cfg, x, K)
1236
+
1237
+ h, r = dup_div(g, cfg, K)
1238
+
1239
+ if not r:
1240
+ cff_, r = dup_div(f, h, K)
1241
+
1242
+ if not r:
1243
+ h = dup_mul_ground(h, gcd, K)
1244
+ return h, cff_, cfg
1245
+
1246
+ x = 73794*x * K.sqrt(K.sqrt(x)) // 27011
1247
+
1248
+ raise HeuristicGCDFailed('no luck')
1249
+
1250
+
1251
+ def _dmp_zz_gcd_interpolate(h, x, v, K):
1252
+ """Interpolate polynomial GCD from integer GCD. """
1253
+ f = []
1254
+
1255
+ while not dmp_zero_p(h, v):
1256
+ g = dmp_ground_trunc(h, x, v, K)
1257
+ f.insert(0, g)
1258
+
1259
+ h = dmp_sub(h, g, v, K)
1260
+ h = dmp_quo_ground(h, x, v, K)
1261
+
1262
+ if K.is_negative(dmp_ground_LC(f, v + 1, K)):
1263
+ return dmp_neg(f, v + 1, K)
1264
+ else:
1265
+ return f
1266
+
1267
+
1268
+ def dmp_zz_heu_gcd(f, g, u, K):
1269
+ """
1270
+ Heuristic polynomial GCD in `Z[X]`.
1271
+
1272
+ Given univariate polynomials `f` and `g` in `Z[X]`, returns
1273
+ their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg``
1274
+ such that::
1275
+
1276
+ h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h)
1277
+
1278
+ The algorithm is purely heuristic which means it may fail to compute
1279
+ the GCD. This will be signaled by raising an exception. In this case
1280
+ you will need to switch to another GCD method.
1281
+
1282
+ The algorithm computes the polynomial GCD by evaluating polynomials
1283
+ f and g at certain points and computing (fast) integer GCD of those
1284
+ evaluations. The polynomial GCD is recovered from the integer image
1285
+ by interpolation. The evaluation process reduces f and g variable by
1286
+ variable into a large integer. The final step is to verify if the
1287
+ interpolated polynomial is the correct GCD. This gives cofactors of
1288
+ the input polynomials as a side effect.
1289
+
1290
+ Examples
1291
+ ========
1292
+
1293
+ >>> from sympy.polys import ring, ZZ
1294
+ >>> R, x,y, = ring("x,y", ZZ)
1295
+
1296
+ >>> f = x**2 + 2*x*y + y**2
1297
+ >>> g = x**2 + x*y
1298
+
1299
+ >>> R.dmp_zz_heu_gcd(f, g)
1300
+ (x + y, x + y, x)
1301
+
1302
+ References
1303
+ ==========
1304
+
1305
+ .. [1] [Liao95]_
1306
+
1307
+ """
1308
+ if not u:
1309
+ return dup_zz_heu_gcd(f, g, K)
1310
+
1311
+ result = _dmp_rr_trivial_gcd(f, g, u, K)
1312
+
1313
+ if result is not None:
1314
+ return result
1315
+
1316
+ gcd, f, g = dmp_ground_extract(f, g, u, K)
1317
+
1318
+ f_norm = dmp_max_norm(f, u, K)
1319
+ g_norm = dmp_max_norm(g, u, K)
1320
+
1321
+ B = K(2*min(f_norm, g_norm) + 29)
1322
+
1323
+ x = max(min(B, 99*K.sqrt(B)),
1324
+ 2*min(f_norm // abs(dmp_ground_LC(f, u, K)),
1325
+ g_norm // abs(dmp_ground_LC(g, u, K))) + 2)
1326
+
1327
+ for i in range(0, HEU_GCD_MAX):
1328
+ ff = dmp_eval(f, x, u, K)
1329
+ gg = dmp_eval(g, x, u, K)
1330
+
1331
+ v = u - 1
1332
+
1333
+ if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)):
1334
+ h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K)
1335
+
1336
+ h = _dmp_zz_gcd_interpolate(h, x, v, K)
1337
+ h = dmp_ground_primitive(h, u, K)[1]
1338
+
1339
+ cff_, r = dmp_div(f, h, u, K)
1340
+
1341
+ if dmp_zero_p(r, u):
1342
+ cfg_, r = dmp_div(g, h, u, K)
1343
+
1344
+ if dmp_zero_p(r, u):
1345
+ h = dmp_mul_ground(h, gcd, u, K)
1346
+ return h, cff_, cfg_
1347
+
1348
+ cff = _dmp_zz_gcd_interpolate(cff, x, v, K)
1349
+
1350
+ h, r = dmp_div(f, cff, u, K)
1351
+
1352
+ if dmp_zero_p(r, u):
1353
+ cfg_, r = dmp_div(g, h, u, K)
1354
+
1355
+ if dmp_zero_p(r, u):
1356
+ h = dmp_mul_ground(h, gcd, u, K)
1357
+ return h, cff, cfg_
1358
+
1359
+ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K)
1360
+
1361
+ h, r = dmp_div(g, cfg, u, K)
1362
+
1363
+ if dmp_zero_p(r, u):
1364
+ cff_, r = dmp_div(f, h, u, K)
1365
+
1366
+ if dmp_zero_p(r, u):
1367
+ h = dmp_mul_ground(h, gcd, u, K)
1368
+ return h, cff_, cfg
1369
+
1370
+ x = 73794*x * K.sqrt(K.sqrt(x)) // 27011
1371
+
1372
+ raise HeuristicGCDFailed('no luck')
1373
+
1374
+
1375
+ def dup_qq_heu_gcd(f, g, K0):
1376
+ """
1377
+ Heuristic polynomial GCD in `Q[x]`.
1378
+
1379
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``,
1380
+ ``cff = quo(f, h)``, and ``cfg = quo(g, h)``.
1381
+
1382
+ Examples
1383
+ ========
1384
+
1385
+ >>> from sympy.polys import ring, QQ
1386
+ >>> R, x = ring("x", QQ)
1387
+
1388
+ >>> f = QQ(1,2)*x**2 + QQ(7,4)*x + QQ(3,2)
1389
+ >>> g = QQ(1,2)*x**2 + x
1390
+
1391
+ >>> R.dup_qq_heu_gcd(f, g)
1392
+ (x + 2, 1/2*x + 3/4, 1/2*x)
1393
+
1394
+ """
1395
+ result = _dup_ff_trivial_gcd(f, g, K0)
1396
+
1397
+ if result is not None:
1398
+ return result
1399
+
1400
+ K1 = K0.get_ring()
1401
+
1402
+ cf, f = dup_clear_denoms(f, K0, K1)
1403
+ cg, g = dup_clear_denoms(g, K0, K1)
1404
+
1405
+ f = dup_convert(f, K0, K1)
1406
+ g = dup_convert(g, K0, K1)
1407
+
1408
+ h, cff, cfg = dup_zz_heu_gcd(f, g, K1)
1409
+
1410
+ h = dup_convert(h, K1, K0)
1411
+
1412
+ c = dup_LC(h, K0)
1413
+ h = dup_monic(h, K0)
1414
+
1415
+ cff = dup_convert(cff, K1, K0)
1416
+ cfg = dup_convert(cfg, K1, K0)
1417
+
1418
+ cff = dup_mul_ground(cff, K0.quo(c, cf), K0)
1419
+ cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0)
1420
+
1421
+ return h, cff, cfg
1422
+
1423
+
1424
+ def dmp_qq_heu_gcd(f, g, u, K0):
1425
+ """
1426
+ Heuristic polynomial GCD in `Q[X]`.
1427
+
1428
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``,
1429
+ ``cff = quo(f, h)``, and ``cfg = quo(g, h)``.
1430
+
1431
+ Examples
1432
+ ========
1433
+
1434
+ >>> from sympy.polys import ring, QQ
1435
+ >>> R, x,y, = ring("x,y", QQ)
1436
+
1437
+ >>> f = QQ(1,4)*x**2 + x*y + y**2
1438
+ >>> g = QQ(1,2)*x**2 + x*y
1439
+
1440
+ >>> R.dmp_qq_heu_gcd(f, g)
1441
+ (x + 2*y, 1/4*x + 1/2*y, 1/2*x)
1442
+
1443
+ """
1444
+ result = _dmp_ff_trivial_gcd(f, g, u, K0)
1445
+
1446
+ if result is not None:
1447
+ return result
1448
+
1449
+ K1 = K0.get_ring()
1450
+
1451
+ cf, f = dmp_clear_denoms(f, u, K0, K1)
1452
+ cg, g = dmp_clear_denoms(g, u, K0, K1)
1453
+
1454
+ f = dmp_convert(f, u, K0, K1)
1455
+ g = dmp_convert(g, u, K0, K1)
1456
+
1457
+ h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1)
1458
+
1459
+ h = dmp_convert(h, u, K1, K0)
1460
+
1461
+ c = dmp_ground_LC(h, u, K0)
1462
+ h = dmp_ground_monic(h, u, K0)
1463
+
1464
+ cff = dmp_convert(cff, u, K1, K0)
1465
+ cfg = dmp_convert(cfg, u, K1, K0)
1466
+
1467
+ cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0)
1468
+ cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0)
1469
+
1470
+ return h, cff, cfg
1471
+
1472
+
1473
+ def dup_inner_gcd(f, g, K):
1474
+ """
1475
+ Computes polynomial GCD and cofactors of `f` and `g` in `K[x]`.
1476
+
1477
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``,
1478
+ ``cff = quo(f, h)``, and ``cfg = quo(g, h)``.
1479
+
1480
+ Examples
1481
+ ========
1482
+
1483
+ >>> from sympy.polys import ring, ZZ
1484
+ >>> R, x = ring("x", ZZ)
1485
+
1486
+ >>> R.dup_inner_gcd(x**2 - 1, x**2 - 3*x + 2)
1487
+ (x - 1, x + 1, x - 2)
1488
+
1489
+ """
1490
+ if not K.is_Exact:
1491
+ try:
1492
+ exact = K.get_exact()
1493
+ except DomainError:
1494
+ return [K.one], f, g
1495
+
1496
+ f = dup_convert(f, K, exact)
1497
+ g = dup_convert(g, K, exact)
1498
+
1499
+ h, cff, cfg = dup_inner_gcd(f, g, exact)
1500
+
1501
+ h = dup_convert(h, exact, K)
1502
+ cff = dup_convert(cff, exact, K)
1503
+ cfg = dup_convert(cfg, exact, K)
1504
+
1505
+ return h, cff, cfg
1506
+ elif K.is_Field:
1507
+ if K.is_QQ and query('USE_HEU_GCD'):
1508
+ try:
1509
+ return dup_qq_heu_gcd(f, g, K)
1510
+ except HeuristicGCDFailed:
1511
+ pass
1512
+
1513
+ return dup_ff_prs_gcd(f, g, K)
1514
+ else:
1515
+ if K.is_ZZ and query('USE_HEU_GCD'):
1516
+ try:
1517
+ return dup_zz_heu_gcd(f, g, K)
1518
+ except HeuristicGCDFailed:
1519
+ pass
1520
+
1521
+ return dup_rr_prs_gcd(f, g, K)
1522
+
1523
+
1524
+ def _dmp_inner_gcd(f, g, u, K):
1525
+ """Helper function for `dmp_inner_gcd()`. """
1526
+ if not K.is_Exact:
1527
+ try:
1528
+ exact = K.get_exact()
1529
+ except DomainError:
1530
+ return dmp_one(u, K), f, g
1531
+
1532
+ f = dmp_convert(f, u, K, exact)
1533
+ g = dmp_convert(g, u, K, exact)
1534
+
1535
+ h, cff, cfg = _dmp_inner_gcd(f, g, u, exact)
1536
+
1537
+ h = dmp_convert(h, u, exact, K)
1538
+ cff = dmp_convert(cff, u, exact, K)
1539
+ cfg = dmp_convert(cfg, u, exact, K)
1540
+
1541
+ return h, cff, cfg
1542
+ elif K.is_Field:
1543
+ if K.is_QQ and query('USE_HEU_GCD'):
1544
+ try:
1545
+ return dmp_qq_heu_gcd(f, g, u, K)
1546
+ except HeuristicGCDFailed:
1547
+ pass
1548
+
1549
+ return dmp_ff_prs_gcd(f, g, u, K)
1550
+ else:
1551
+ if K.is_ZZ and query('USE_HEU_GCD'):
1552
+ try:
1553
+ return dmp_zz_heu_gcd(f, g, u, K)
1554
+ except HeuristicGCDFailed:
1555
+ pass
1556
+
1557
+ return dmp_rr_prs_gcd(f, g, u, K)
1558
+
1559
+
1560
+ def dmp_inner_gcd(f, g, u, K):
1561
+ """
1562
+ Computes polynomial GCD and cofactors of `f` and `g` in `K[X]`.
1563
+
1564
+ Returns ``(h, cff, cfg)`` such that ``a = gcd(f, g)``,
1565
+ ``cff = quo(f, h)``, and ``cfg = quo(g, h)``.
1566
+
1567
+ Examples
1568
+ ========
1569
+
1570
+ >>> from sympy.polys import ring, ZZ
1571
+ >>> R, x,y, = ring("x,y", ZZ)
1572
+
1573
+ >>> f = x**2 + 2*x*y + y**2
1574
+ >>> g = x**2 + x*y
1575
+
1576
+ >>> R.dmp_inner_gcd(f, g)
1577
+ (x + y, x + y, x)
1578
+
1579
+ """
1580
+ if not u:
1581
+ return dup_inner_gcd(f, g, K)
1582
+
1583
+ J, (f, g) = dmp_multi_deflate((f, g), u, K)
1584
+ h, cff, cfg = _dmp_inner_gcd(f, g, u, K)
1585
+
1586
+ return (dmp_inflate(h, J, u, K),
1587
+ dmp_inflate(cff, J, u, K),
1588
+ dmp_inflate(cfg, J, u, K))
1589
+
1590
+
1591
+ def dup_gcd(f, g, K):
1592
+ """
1593
+ Computes polynomial GCD of `f` and `g` in `K[x]`.
1594
+
1595
+ Examples
1596
+ ========
1597
+
1598
+ >>> from sympy.polys import ring, ZZ
1599
+ >>> R, x = ring("x", ZZ)
1600
+
1601
+ >>> R.dup_gcd(x**2 - 1, x**2 - 3*x + 2)
1602
+ x - 1
1603
+
1604
+ """
1605
+ return dup_inner_gcd(f, g, K)[0]
1606
+
1607
+
1608
+ def dmp_gcd(f, g, u, K):
1609
+ """
1610
+ Computes polynomial GCD of `f` and `g` in `K[X]`.
1611
+
1612
+ Examples
1613
+ ========
1614
+
1615
+ >>> from sympy.polys import ring, ZZ
1616
+ >>> R, x,y, = ring("x,y", ZZ)
1617
+
1618
+ >>> f = x**2 + 2*x*y + y**2
1619
+ >>> g = x**2 + x*y
1620
+
1621
+ >>> R.dmp_gcd(f, g)
1622
+ x + y
1623
+
1624
+ """
1625
+ return dmp_inner_gcd(f, g, u, K)[0]
1626
+
1627
+
1628
+ def dup_rr_lcm(f, g, K):
1629
+ """
1630
+ Computes polynomial LCM over a ring in `K[x]`.
1631
+
1632
+ Examples
1633
+ ========
1634
+
1635
+ >>> from sympy.polys import ring, ZZ
1636
+ >>> R, x = ring("x", ZZ)
1637
+
1638
+ >>> R.dup_rr_lcm(x**2 - 1, x**2 - 3*x + 2)
1639
+ x**3 - 2*x**2 - x + 2
1640
+
1641
+ """
1642
+ fc, f = dup_primitive(f, K)
1643
+ gc, g = dup_primitive(g, K)
1644
+
1645
+ c = K.lcm(fc, gc)
1646
+
1647
+ h = dup_quo(dup_mul(f, g, K),
1648
+ dup_gcd(f, g, K), K)
1649
+
1650
+ return dup_mul_ground(h, c, K)
1651
+
1652
+
1653
+ def dup_ff_lcm(f, g, K):
1654
+ """
1655
+ Computes polynomial LCM over a field in `K[x]`.
1656
+
1657
+ Examples
1658
+ ========
1659
+
1660
+ >>> from sympy.polys import ring, QQ
1661
+ >>> R, x = ring("x", QQ)
1662
+
1663
+ >>> f = QQ(1,2)*x**2 + QQ(7,4)*x + QQ(3,2)
1664
+ >>> g = QQ(1,2)*x**2 + x
1665
+
1666
+ >>> R.dup_ff_lcm(f, g)
1667
+ x**3 + 7/2*x**2 + 3*x
1668
+
1669
+ """
1670
+ h = dup_quo(dup_mul(f, g, K),
1671
+ dup_gcd(f, g, K), K)
1672
+
1673
+ return dup_monic(h, K)
1674
+
1675
+
1676
+ def dup_lcm(f, g, K):
1677
+ """
1678
+ Computes polynomial LCM of `f` and `g` in `K[x]`.
1679
+
1680
+ Examples
1681
+ ========
1682
+
1683
+ >>> from sympy.polys import ring, ZZ
1684
+ >>> R, x = ring("x", ZZ)
1685
+
1686
+ >>> R.dup_lcm(x**2 - 1, x**2 - 3*x + 2)
1687
+ x**3 - 2*x**2 - x + 2
1688
+
1689
+ """
1690
+ if K.is_Field:
1691
+ return dup_ff_lcm(f, g, K)
1692
+ else:
1693
+ return dup_rr_lcm(f, g, K)
1694
+
1695
+
1696
+ def dmp_rr_lcm(f, g, u, K):
1697
+ """
1698
+ Computes polynomial LCM over a ring in `K[X]`.
1699
+
1700
+ Examples
1701
+ ========
1702
+
1703
+ >>> from sympy.polys import ring, ZZ
1704
+ >>> R, x,y, = ring("x,y", ZZ)
1705
+
1706
+ >>> f = x**2 + 2*x*y + y**2
1707
+ >>> g = x**2 + x*y
1708
+
1709
+ >>> R.dmp_rr_lcm(f, g)
1710
+ x**3 + 2*x**2*y + x*y**2
1711
+
1712
+ """
1713
+ fc, f = dmp_ground_primitive(f, u, K)
1714
+ gc, g = dmp_ground_primitive(g, u, K)
1715
+
1716
+ c = K.lcm(fc, gc)
1717
+
1718
+ h = dmp_quo(dmp_mul(f, g, u, K),
1719
+ dmp_gcd(f, g, u, K), u, K)
1720
+
1721
+ return dmp_mul_ground(h, c, u, K)
1722
+
1723
+
1724
+ def dmp_ff_lcm(f, g, u, K):
1725
+ """
1726
+ Computes polynomial LCM over a field in `K[X]`.
1727
+
1728
+ Examples
1729
+ ========
1730
+
1731
+ >>> from sympy.polys import ring, QQ
1732
+ >>> R, x,y, = ring("x,y", QQ)
1733
+
1734
+ >>> f = QQ(1,4)*x**2 + x*y + y**2
1735
+ >>> g = QQ(1,2)*x**2 + x*y
1736
+
1737
+ >>> R.dmp_ff_lcm(f, g)
1738
+ x**3 + 4*x**2*y + 4*x*y**2
1739
+
1740
+ """
1741
+ h = dmp_quo(dmp_mul(f, g, u, K),
1742
+ dmp_gcd(f, g, u, K), u, K)
1743
+
1744
+ return dmp_ground_monic(h, u, K)
1745
+
1746
+
1747
+ def dmp_lcm(f, g, u, K):
1748
+ """
1749
+ Computes polynomial LCM of `f` and `g` in `K[X]`.
1750
+
1751
+ Examples
1752
+ ========
1753
+
1754
+ >>> from sympy.polys import ring, ZZ
1755
+ >>> R, x,y, = ring("x,y", ZZ)
1756
+
1757
+ >>> f = x**2 + 2*x*y + y**2
1758
+ >>> g = x**2 + x*y
1759
+
1760
+ >>> R.dmp_lcm(f, g)
1761
+ x**3 + 2*x**2*y + x*y**2
1762
+
1763
+ """
1764
+ if not u:
1765
+ return dup_lcm(f, g, K)
1766
+
1767
+ if K.is_Field:
1768
+ return dmp_ff_lcm(f, g, u, K)
1769
+ else:
1770
+ return dmp_rr_lcm(f, g, u, K)
1771
+
1772
+
1773
+ def dmp_content(f, u, K):
1774
+ """
1775
+ Returns GCD of multivariate coefficients.
1776
+
1777
+ Examples
1778
+ ========
1779
+
1780
+ >>> from sympy.polys import ring, ZZ
1781
+ >>> R, x,y, = ring("x,y", ZZ)
1782
+
1783
+ >>> R.dmp_content(2*x*y + 6*x + 4*y + 12)
1784
+ 2*y + 6
1785
+
1786
+ """
1787
+ cont, v = dmp_LC(f, K), u - 1
1788
+
1789
+ if dmp_zero_p(f, u):
1790
+ return cont
1791
+
1792
+ for c in f[1:]:
1793
+ cont = dmp_gcd(cont, c, v, K)
1794
+
1795
+ if dmp_one_p(cont, v, K):
1796
+ break
1797
+
1798
+ if K.is_negative(dmp_ground_LC(cont, v, K)):
1799
+ return dmp_neg(cont, v, K)
1800
+ else:
1801
+ return cont
1802
+
1803
+
1804
+ def dmp_primitive(f, u, K):
1805
+ """
1806
+ Returns multivariate content and a primitive polynomial.
1807
+
1808
+ Examples
1809
+ ========
1810
+
1811
+ >>> from sympy.polys import ring, ZZ
1812
+ >>> R, x,y, = ring("x,y", ZZ)
1813
+
1814
+ >>> R.dmp_primitive(2*x*y + 6*x + 4*y + 12)
1815
+ (2*y + 6, x + 2)
1816
+
1817
+ """
1818
+ cont, v = dmp_content(f, u, K), u - 1
1819
+
1820
+ if dmp_zero_p(f, u) or dmp_one_p(cont, v, K):
1821
+ return cont, f
1822
+ else:
1823
+ return cont, [ dmp_quo(c, cont, v, K) for c in f ]
1824
+
1825
+
1826
+ def dup_cancel(f, g, K, include=True):
1827
+ """
1828
+ Cancel common factors in a rational function `f/g`.
1829
+
1830
+ Examples
1831
+ ========
1832
+
1833
+ >>> from sympy.polys import ring, ZZ
1834
+ >>> R, x = ring("x", ZZ)
1835
+
1836
+ >>> R.dup_cancel(2*x**2 - 2, x**2 - 2*x + 1)
1837
+ (2*x + 2, x - 1)
1838
+
1839
+ """
1840
+ return dmp_cancel(f, g, 0, K, include=include)
1841
+
1842
+
1843
+ def dmp_cancel(f, g, u, K, include=True):
1844
+ """
1845
+ Cancel common factors in a rational function `f/g`.
1846
+
1847
+ Examples
1848
+ ========
1849
+
1850
+ >>> from sympy.polys import ring, ZZ
1851
+ >>> R, x,y = ring("x,y", ZZ)
1852
+
1853
+ >>> R.dmp_cancel(2*x**2 - 2, x**2 - 2*x + 1)
1854
+ (2*x + 2, x - 1)
1855
+
1856
+ """
1857
+ K0 = None
1858
+
1859
+ if K.is_Field and K.has_assoc_Ring:
1860
+ K0, K = K, K.get_ring()
1861
+
1862
+ cq, f = dmp_clear_denoms(f, u, K0, K, convert=True)
1863
+ cp, g = dmp_clear_denoms(g, u, K0, K, convert=True)
1864
+ else:
1865
+ cp, cq = K.one, K.one
1866
+
1867
+ _, p, q = dmp_inner_gcd(f, g, u, K)
1868
+
1869
+ if K0 is not None:
1870
+ _, cp, cq = K.cofactors(cp, cq)
1871
+
1872
+ p = dmp_convert(p, u, K, K0)
1873
+ q = dmp_convert(q, u, K, K0)
1874
+
1875
+ K = K0
1876
+
1877
+ p_neg = K.is_negative(dmp_ground_LC(p, u, K))
1878
+ q_neg = K.is_negative(dmp_ground_LC(q, u, K))
1879
+
1880
+ if p_neg and q_neg:
1881
+ p, q = dmp_neg(p, u, K), dmp_neg(q, u, K)
1882
+ elif p_neg:
1883
+ cp, p = -cp, dmp_neg(p, u, K)
1884
+ elif q_neg:
1885
+ cp, q = -cp, dmp_neg(q, u, K)
1886
+
1887
+ if not include:
1888
+ return cp, cq, p, q
1889
+
1890
+ p = dmp_mul_ground(p, cp, u, K)
1891
+ q = dmp_mul_ground(q, cq, u, K)
1892
+
1893
+ return p, q
llmeval-env/lib/python3.10/site-packages/sympy/polys/factortools.py ADDED
@@ -0,0 +1,1502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Polynomial factorization routines in characteristic zero. """
2
+
3
+ from sympy.core.random import _randint
4
+
5
+ from sympy.polys.galoistools import (
6
+ gf_from_int_poly, gf_to_int_poly,
7
+ gf_lshift, gf_add_mul, gf_mul,
8
+ gf_div, gf_rem,
9
+ gf_gcdex,
10
+ gf_sqf_p,
11
+ gf_factor_sqf, gf_factor)
12
+
13
+ from sympy.polys.densebasic import (
14
+ dup_LC, dmp_LC, dmp_ground_LC,
15
+ dup_TC,
16
+ dup_convert, dmp_convert,
17
+ dup_degree, dmp_degree,
18
+ dmp_degree_in, dmp_degree_list,
19
+ dmp_from_dict,
20
+ dmp_zero_p,
21
+ dmp_one,
22
+ dmp_nest, dmp_raise,
23
+ dup_strip,
24
+ dmp_ground,
25
+ dup_inflate,
26
+ dmp_exclude, dmp_include,
27
+ dmp_inject, dmp_eject,
28
+ dup_terms_gcd, dmp_terms_gcd)
29
+
30
+ from sympy.polys.densearith import (
31
+ dup_neg, dmp_neg,
32
+ dup_add, dmp_add,
33
+ dup_sub, dmp_sub,
34
+ dup_mul, dmp_mul,
35
+ dup_sqr,
36
+ dmp_pow,
37
+ dup_div, dmp_div,
38
+ dup_quo, dmp_quo,
39
+ dmp_expand,
40
+ dmp_add_mul,
41
+ dup_sub_mul, dmp_sub_mul,
42
+ dup_lshift,
43
+ dup_max_norm, dmp_max_norm,
44
+ dup_l1_norm,
45
+ dup_mul_ground, dmp_mul_ground,
46
+ dup_quo_ground, dmp_quo_ground)
47
+
48
+ from sympy.polys.densetools import (
49
+ dup_clear_denoms, dmp_clear_denoms,
50
+ dup_trunc, dmp_ground_trunc,
51
+ dup_content,
52
+ dup_monic, dmp_ground_monic,
53
+ dup_primitive, dmp_ground_primitive,
54
+ dmp_eval_tail,
55
+ dmp_eval_in, dmp_diff_eval_in,
56
+ dmp_compose,
57
+ dup_shift, dup_mirror)
58
+
59
+ from sympy.polys.euclidtools import (
60
+ dmp_primitive,
61
+ dup_inner_gcd, dmp_inner_gcd)
62
+
63
+ from sympy.polys.sqfreetools import (
64
+ dup_sqf_p,
65
+ dup_sqf_norm, dmp_sqf_norm,
66
+ dup_sqf_part, dmp_sqf_part)
67
+
68
+ from sympy.polys.polyutils import _sort_factors
69
+ from sympy.polys.polyconfig import query
70
+
71
+ from sympy.polys.polyerrors import (
72
+ ExtraneousFactors, DomainError, CoercionFailed, EvaluationFailed)
73
+
74
+ from sympy.utilities import subsets
75
+
76
+ from math import ceil as _ceil, log as _log
77
+
78
+
79
+ def dup_trial_division(f, factors, K):
80
+ """
81
+ Determine multiplicities of factors for a univariate polynomial
82
+ using trial division.
83
+ """
84
+ result = []
85
+
86
+ for factor in factors:
87
+ k = 0
88
+
89
+ while True:
90
+ q, r = dup_div(f, factor, K)
91
+
92
+ if not r:
93
+ f, k = q, k + 1
94
+ else:
95
+ break
96
+
97
+ result.append((factor, k))
98
+
99
+ return _sort_factors(result)
100
+
101
+
102
+ def dmp_trial_division(f, factors, u, K):
103
+ """
104
+ Determine multiplicities of factors for a multivariate polynomial
105
+ using trial division.
106
+ """
107
+ result = []
108
+
109
+ for factor in factors:
110
+ k = 0
111
+
112
+ while True:
113
+ q, r = dmp_div(f, factor, u, K)
114
+
115
+ if dmp_zero_p(r, u):
116
+ f, k = q, k + 1
117
+ else:
118
+ break
119
+
120
+ result.append((factor, k))
121
+
122
+ return _sort_factors(result)
123
+
124
+
125
+ def dup_zz_mignotte_bound(f, K):
126
+ """
127
+ The Knuth-Cohen variant of Mignotte bound for
128
+ univariate polynomials in `K[x]`.
129
+
130
+ Examples
131
+ ========
132
+
133
+ >>> from sympy.polys import ring, ZZ
134
+ >>> R, x = ring("x", ZZ)
135
+
136
+ >>> f = x**3 + 14*x**2 + 56*x + 64
137
+ >>> R.dup_zz_mignotte_bound(f)
138
+ 152
139
+
140
+ By checking `factor(f)` we can see that max coeff is 8
141
+
142
+ Also consider a case that `f` is irreducible for example `f = 2*x**2 + 3*x + 4`
143
+ To avoid a bug for these cases, we return the bound plus the max coefficient of `f`
144
+
145
+ >>> f = 2*x**2 + 3*x + 4
146
+ >>> R.dup_zz_mignotte_bound(f)
147
+ 6
148
+
149
+ Lastly,To see the difference between the new and the old Mignotte bound
150
+ consider the irreducible polynomial::
151
+
152
+ >>> f = 87*x**7 + 4*x**6 + 80*x**5 + 17*x**4 + 9*x**3 + 12*x**2 + 49*x + 26
153
+ >>> R.dup_zz_mignotte_bound(f)
154
+ 744
155
+
156
+ The new Mignotte bound is 744 whereas the old one (SymPy 1.5.1) is 1937664.
157
+
158
+
159
+ References
160
+ ==========
161
+
162
+ ..[1] [Abbott2013]_
163
+
164
+ """
165
+ from sympy.functions.combinatorial.factorials import binomial
166
+ d = dup_degree(f)
167
+ delta = _ceil(d / 2)
168
+ delta2 = _ceil(delta / 2)
169
+
170
+ # euclidean-norm
171
+ eucl_norm = K.sqrt( sum( [cf**2 for cf in f] ) )
172
+
173
+ # biggest values of binomial coefficients (p. 538 of reference)
174
+ t1 = binomial(delta - 1, delta2)
175
+ t2 = binomial(delta - 1, delta2 - 1)
176
+
177
+ lc = K.abs(dup_LC(f, K)) # leading coefficient
178
+ bound = t1 * eucl_norm + t2 * lc # (p. 538 of reference)
179
+ bound += dup_max_norm(f, K) # add max coeff for irreducible polys
180
+ bound = _ceil(bound / 2) * 2 # round up to even integer
181
+
182
+ return bound
183
+
184
+ def dmp_zz_mignotte_bound(f, u, K):
185
+ """Mignotte bound for multivariate polynomials in `K[X]`. """
186
+ a = dmp_max_norm(f, u, K)
187
+ b = abs(dmp_ground_LC(f, u, K))
188
+ n = sum(dmp_degree_list(f, u))
189
+
190
+ return K.sqrt(K(n + 1))*2**n*a*b
191
+
192
+
193
+ def dup_zz_hensel_step(m, f, g, h, s, t, K):
194
+ """
195
+ One step in Hensel lifting in `Z[x]`.
196
+
197
+ Given positive integer `m` and `Z[x]` polynomials `f`, `g`, `h`, `s`
198
+ and `t` such that::
199
+
200
+ f = g*h (mod m)
201
+ s*g + t*h = 1 (mod m)
202
+
203
+ lc(f) is not a zero divisor (mod m)
204
+ lc(h) = 1
205
+
206
+ deg(f) = deg(g) + deg(h)
207
+ deg(s) < deg(h)
208
+ deg(t) < deg(g)
209
+
210
+ returns polynomials `G`, `H`, `S` and `T`, such that::
211
+
212
+ f = G*H (mod m**2)
213
+ S*G + T*H = 1 (mod m**2)
214
+
215
+ References
216
+ ==========
217
+
218
+ .. [1] [Gathen99]_
219
+
220
+ """
221
+ M = m**2
222
+
223
+ e = dup_sub_mul(f, g, h, K)
224
+ e = dup_trunc(e, M, K)
225
+
226
+ q, r = dup_div(dup_mul(s, e, K), h, K)
227
+
228
+ q = dup_trunc(q, M, K)
229
+ r = dup_trunc(r, M, K)
230
+
231
+ u = dup_add(dup_mul(t, e, K), dup_mul(q, g, K), K)
232
+ G = dup_trunc(dup_add(g, u, K), M, K)
233
+ H = dup_trunc(dup_add(h, r, K), M, K)
234
+
235
+ u = dup_add(dup_mul(s, G, K), dup_mul(t, H, K), K)
236
+ b = dup_trunc(dup_sub(u, [K.one], K), M, K)
237
+
238
+ c, d = dup_div(dup_mul(s, b, K), H, K)
239
+
240
+ c = dup_trunc(c, M, K)
241
+ d = dup_trunc(d, M, K)
242
+
243
+ u = dup_add(dup_mul(t, b, K), dup_mul(c, G, K), K)
244
+ S = dup_trunc(dup_sub(s, d, K), M, K)
245
+ T = dup_trunc(dup_sub(t, u, K), M, K)
246
+
247
+ return G, H, S, T
248
+
249
+
250
+ def dup_zz_hensel_lift(p, f, f_list, l, K):
251
+ r"""
252
+ Multifactor Hensel lifting in `Z[x]`.
253
+
254
+ Given a prime `p`, polynomial `f` over `Z[x]` such that `lc(f)`
255
+ is a unit modulo `p`, monic pair-wise coprime polynomials `f_i`
256
+ over `Z[x]` satisfying::
257
+
258
+ f = lc(f) f_1 ... f_r (mod p)
259
+
260
+ and a positive integer `l`, returns a list of monic polynomials
261
+ `F_1,\ F_2,\ \dots,\ F_r` satisfying::
262
+
263
+ f = lc(f) F_1 ... F_r (mod p**l)
264
+
265
+ F_i = f_i (mod p), i = 1..r
266
+
267
+ References
268
+ ==========
269
+
270
+ .. [1] [Gathen99]_
271
+
272
+ """
273
+ r = len(f_list)
274
+ lc = dup_LC(f, K)
275
+
276
+ if r == 1:
277
+ F = dup_mul_ground(f, K.gcdex(lc, p**l)[0], K)
278
+ return [ dup_trunc(F, p**l, K) ]
279
+
280
+ m = p
281
+ k = r // 2
282
+ d = int(_ceil(_log(l, 2)))
283
+
284
+ g = gf_from_int_poly([lc], p)
285
+
286
+ for f_i in f_list[:k]:
287
+ g = gf_mul(g, gf_from_int_poly(f_i, p), p, K)
288
+
289
+ h = gf_from_int_poly(f_list[k], p)
290
+
291
+ for f_i in f_list[k + 1:]:
292
+ h = gf_mul(h, gf_from_int_poly(f_i, p), p, K)
293
+
294
+ s, t, _ = gf_gcdex(g, h, p, K)
295
+
296
+ g = gf_to_int_poly(g, p)
297
+ h = gf_to_int_poly(h, p)
298
+ s = gf_to_int_poly(s, p)
299
+ t = gf_to_int_poly(t, p)
300
+
301
+ for _ in range(1, d + 1):
302
+ (g, h, s, t), m = dup_zz_hensel_step(m, f, g, h, s, t, K), m**2
303
+
304
+ return dup_zz_hensel_lift(p, g, f_list[:k], l, K) \
305
+ + dup_zz_hensel_lift(p, h, f_list[k:], l, K)
306
+
307
+ def _test_pl(fc, q, pl):
308
+ if q > pl // 2:
309
+ q = q - pl
310
+ if not q:
311
+ return True
312
+ return fc % q == 0
313
+
314
+ def dup_zz_zassenhaus(f, K):
315
+ """Factor primitive square-free polynomials in `Z[x]`. """
316
+ n = dup_degree(f)
317
+
318
+ if n == 1:
319
+ return [f]
320
+
321
+ from sympy.ntheory import isprime
322
+
323
+ fc = f[-1]
324
+ A = dup_max_norm(f, K)
325
+ b = dup_LC(f, K)
326
+ B = int(abs(K.sqrt(K(n + 1))*2**n*A*b))
327
+ C = int((n + 1)**(2*n)*A**(2*n - 1))
328
+ gamma = int(_ceil(2*_log(C, 2)))
329
+ bound = int(2*gamma*_log(gamma))
330
+ a = []
331
+ # choose a prime number `p` such that `f` be square free in Z_p
332
+ # if there are many factors in Z_p, choose among a few different `p`
333
+ # the one with fewer factors
334
+ for px in range(3, bound + 1):
335
+ if not isprime(px) or b % px == 0:
336
+ continue
337
+
338
+ px = K.convert(px)
339
+
340
+ F = gf_from_int_poly(f, px)
341
+
342
+ if not gf_sqf_p(F, px, K):
343
+ continue
344
+ fsqfx = gf_factor_sqf(F, px, K)[1]
345
+ a.append((px, fsqfx))
346
+ if len(fsqfx) < 15 or len(a) > 4:
347
+ break
348
+ p, fsqf = min(a, key=lambda x: len(x[1]))
349
+
350
+ l = int(_ceil(_log(2*B + 1, p)))
351
+
352
+ modular = [gf_to_int_poly(ff, p) for ff in fsqf]
353
+
354
+ g = dup_zz_hensel_lift(p, f, modular, l, K)
355
+
356
+ sorted_T = range(len(g))
357
+ T = set(sorted_T)
358
+ factors, s = [], 1
359
+ pl = p**l
360
+
361
+ while 2*s <= len(T):
362
+ for S in subsets(sorted_T, s):
363
+ # lift the constant coefficient of the product `G` of the factors
364
+ # in the subset `S`; if it is does not divide `fc`, `G` does
365
+ # not divide the input polynomial
366
+
367
+ if b == 1:
368
+ q = 1
369
+ for i in S:
370
+ q = q*g[i][-1]
371
+ q = q % pl
372
+ if not _test_pl(fc, q, pl):
373
+ continue
374
+ else:
375
+ G = [b]
376
+ for i in S:
377
+ G = dup_mul(G, g[i], K)
378
+ G = dup_trunc(G, pl, K)
379
+ G = dup_primitive(G, K)[1]
380
+ q = G[-1]
381
+ if q and fc % q != 0:
382
+ continue
383
+
384
+ H = [b]
385
+ S = set(S)
386
+ T_S = T - S
387
+
388
+ if b == 1:
389
+ G = [b]
390
+ for i in S:
391
+ G = dup_mul(G, g[i], K)
392
+ G = dup_trunc(G, pl, K)
393
+
394
+ for i in T_S:
395
+ H = dup_mul(H, g[i], K)
396
+
397
+ H = dup_trunc(H, pl, K)
398
+
399
+ G_norm = dup_l1_norm(G, K)
400
+ H_norm = dup_l1_norm(H, K)
401
+
402
+ if G_norm*H_norm <= B:
403
+ T = T_S
404
+ sorted_T = [i for i in sorted_T if i not in S]
405
+
406
+ G = dup_primitive(G, K)[1]
407
+ f = dup_primitive(H, K)[1]
408
+
409
+ factors.append(G)
410
+ b = dup_LC(f, K)
411
+
412
+ break
413
+ else:
414
+ s += 1
415
+
416
+ return factors + [f]
417
+
418
+
419
+ def dup_zz_irreducible_p(f, K):
420
+ """Test irreducibility using Eisenstein's criterion. """
421
+ lc = dup_LC(f, K)
422
+ tc = dup_TC(f, K)
423
+
424
+ e_fc = dup_content(f[1:], K)
425
+
426
+ if e_fc:
427
+ from sympy.ntheory import factorint
428
+ e_ff = factorint(int(e_fc))
429
+
430
+ for p in e_ff.keys():
431
+ if (lc % p) and (tc % p**2):
432
+ return True
433
+
434
+
435
+ def dup_cyclotomic_p(f, K, irreducible=False):
436
+ """
437
+ Efficiently test if ``f`` is a cyclotomic polynomial.
438
+
439
+ Examples
440
+ ========
441
+
442
+ >>> from sympy.polys import ring, ZZ
443
+ >>> R, x = ring("x", ZZ)
444
+
445
+ >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1
446
+ >>> R.dup_cyclotomic_p(f)
447
+ False
448
+
449
+ >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1
450
+ >>> R.dup_cyclotomic_p(g)
451
+ True
452
+
453
+ References
454
+ ==========
455
+
456
+ Bradford, Russell J., and James H. Davenport. "Effective tests for
457
+ cyclotomic polynomials." In International Symposium on Symbolic and
458
+ Algebraic Computation, pp. 244-251. Springer, Berlin, Heidelberg, 1988.
459
+
460
+ """
461
+ if K.is_QQ:
462
+ try:
463
+ K0, K = K, K.get_ring()
464
+ f = dup_convert(f, K0, K)
465
+ except CoercionFailed:
466
+ return False
467
+ elif not K.is_ZZ:
468
+ return False
469
+
470
+ lc = dup_LC(f, K)
471
+ tc = dup_TC(f, K)
472
+
473
+ if lc != 1 or (tc != -1 and tc != 1):
474
+ return False
475
+
476
+ if not irreducible:
477
+ coeff, factors = dup_factor_list(f, K)
478
+
479
+ if coeff != K.one or factors != [(f, 1)]:
480
+ return False
481
+
482
+ n = dup_degree(f)
483
+ g, h = [], []
484
+
485
+ for i in range(n, -1, -2):
486
+ g.insert(0, f[i])
487
+
488
+ for i in range(n - 1, -1, -2):
489
+ h.insert(0, f[i])
490
+
491
+ g = dup_sqr(dup_strip(g), K)
492
+ h = dup_sqr(dup_strip(h), K)
493
+
494
+ F = dup_sub(g, dup_lshift(h, 1, K), K)
495
+
496
+ if K.is_negative(dup_LC(F, K)):
497
+ F = dup_neg(F, K)
498
+
499
+ if F == f:
500
+ return True
501
+
502
+ g = dup_mirror(f, K)
503
+
504
+ if K.is_negative(dup_LC(g, K)):
505
+ g = dup_neg(g, K)
506
+
507
+ if F == g and dup_cyclotomic_p(g, K):
508
+ return True
509
+
510
+ G = dup_sqf_part(F, K)
511
+
512
+ if dup_sqr(G, K) == F and dup_cyclotomic_p(G, K):
513
+ return True
514
+
515
+ return False
516
+
517
+
518
+ def dup_zz_cyclotomic_poly(n, K):
519
+ """Efficiently generate n-th cyclotomic polynomial. """
520
+ from sympy.ntheory import factorint
521
+ h = [K.one, -K.one]
522
+
523
+ for p, k in factorint(n).items():
524
+ h = dup_quo(dup_inflate(h, p, K), h, K)
525
+ h = dup_inflate(h, p**(k - 1), K)
526
+
527
+ return h
528
+
529
+
530
+ def _dup_cyclotomic_decompose(n, K):
531
+ from sympy.ntheory import factorint
532
+
533
+ H = [[K.one, -K.one]]
534
+
535
+ for p, k in factorint(n).items():
536
+ Q = [ dup_quo(dup_inflate(h, p, K), h, K) for h in H ]
537
+ H.extend(Q)
538
+
539
+ for i in range(1, k):
540
+ Q = [ dup_inflate(q, p, K) for q in Q ]
541
+ H.extend(Q)
542
+
543
+ return H
544
+
545
+
546
+ def dup_zz_cyclotomic_factor(f, K):
547
+ """
548
+ Efficiently factor polynomials `x**n - 1` and `x**n + 1` in `Z[x]`.
549
+
550
+ Given a univariate polynomial `f` in `Z[x]` returns a list of factors
551
+ of `f`, provided that `f` is in the form `x**n - 1` or `x**n + 1` for
552
+ `n >= 1`. Otherwise returns None.
553
+
554
+ Factorization is performed using cyclotomic decomposition of `f`,
555
+ which makes this method much faster that any other direct factorization
556
+ approach (e.g. Zassenhaus's).
557
+
558
+ References
559
+ ==========
560
+
561
+ .. [1] [Weisstein09]_
562
+
563
+ """
564
+ lc_f, tc_f = dup_LC(f, K), dup_TC(f, K)
565
+
566
+ if dup_degree(f) <= 0:
567
+ return None
568
+
569
+ if lc_f != 1 or tc_f not in [-1, 1]:
570
+ return None
571
+
572
+ if any(bool(cf) for cf in f[1:-1]):
573
+ return None
574
+
575
+ n = dup_degree(f)
576
+ F = _dup_cyclotomic_decompose(n, K)
577
+
578
+ if not K.is_one(tc_f):
579
+ return F
580
+ else:
581
+ H = []
582
+
583
+ for h in _dup_cyclotomic_decompose(2*n, K):
584
+ if h not in F:
585
+ H.append(h)
586
+
587
+ return H
588
+
589
+
590
+ def dup_zz_factor_sqf(f, K):
591
+ """Factor square-free (non-primitive) polynomials in `Z[x]`. """
592
+ cont, g = dup_primitive(f, K)
593
+
594
+ n = dup_degree(g)
595
+
596
+ if dup_LC(g, K) < 0:
597
+ cont, g = -cont, dup_neg(g, K)
598
+
599
+ if n <= 0:
600
+ return cont, []
601
+ elif n == 1:
602
+ return cont, [g]
603
+
604
+ if query('USE_IRREDUCIBLE_IN_FACTOR'):
605
+ if dup_zz_irreducible_p(g, K):
606
+ return cont, [g]
607
+
608
+ factors = None
609
+
610
+ if query('USE_CYCLOTOMIC_FACTOR'):
611
+ factors = dup_zz_cyclotomic_factor(g, K)
612
+
613
+ if factors is None:
614
+ factors = dup_zz_zassenhaus(g, K)
615
+
616
+ return cont, _sort_factors(factors, multiple=False)
617
+
618
+
619
+ def dup_zz_factor(f, K):
620
+ """
621
+ Factor (non square-free) polynomials in `Z[x]`.
622
+
623
+ Given a univariate polynomial `f` in `Z[x]` computes its complete
624
+ factorization `f_1, ..., f_n` into irreducibles over integers::
625
+
626
+ f = content(f) f_1**k_1 ... f_n**k_n
627
+
628
+ The factorization is computed by reducing the input polynomial
629
+ into a primitive square-free polynomial and factoring it using
630
+ Zassenhaus algorithm. Trial division is used to recover the
631
+ multiplicities of factors.
632
+
633
+ The result is returned as a tuple consisting of::
634
+
635
+ (content(f), [(f_1, k_1), ..., (f_n, k_n))
636
+
637
+ Examples
638
+ ========
639
+
640
+ Consider the polynomial `f = 2*x**4 - 2`::
641
+
642
+ >>> from sympy.polys import ring, ZZ
643
+ >>> R, x = ring("x", ZZ)
644
+
645
+ >>> R.dup_zz_factor(2*x**4 - 2)
646
+ (2, [(x - 1, 1), (x + 1, 1), (x**2 + 1, 1)])
647
+
648
+ In result we got the following factorization::
649
+
650
+ f = 2 (x - 1) (x + 1) (x**2 + 1)
651
+
652
+ Note that this is a complete factorization over integers,
653
+ however over Gaussian integers we can factor the last term.
654
+
655
+ By default, polynomials `x**n - 1` and `x**n + 1` are factored
656
+ using cyclotomic decomposition to speedup computations. To
657
+ disable this behaviour set cyclotomic=False.
658
+
659
+ References
660
+ ==========
661
+
662
+ .. [1] [Gathen99]_
663
+
664
+ """
665
+ cont, g = dup_primitive(f, K)
666
+
667
+ n = dup_degree(g)
668
+
669
+ if dup_LC(g, K) < 0:
670
+ cont, g = -cont, dup_neg(g, K)
671
+
672
+ if n <= 0:
673
+ return cont, []
674
+ elif n == 1:
675
+ return cont, [(g, 1)]
676
+
677
+ if query('USE_IRREDUCIBLE_IN_FACTOR'):
678
+ if dup_zz_irreducible_p(g, K):
679
+ return cont, [(g, 1)]
680
+
681
+ g = dup_sqf_part(g, K)
682
+ H = None
683
+
684
+ if query('USE_CYCLOTOMIC_FACTOR'):
685
+ H = dup_zz_cyclotomic_factor(g, K)
686
+
687
+ if H is None:
688
+ H = dup_zz_zassenhaus(g, K)
689
+
690
+ factors = dup_trial_division(f, H, K)
691
+ return cont, factors
692
+
693
+
694
+ def dmp_zz_wang_non_divisors(E, cs, ct, K):
695
+ """Wang/EEZ: Compute a set of valid divisors. """
696
+ result = [ cs*ct ]
697
+
698
+ for q in E:
699
+ q = abs(q)
700
+
701
+ for r in reversed(result):
702
+ while r != 1:
703
+ r = K.gcd(r, q)
704
+ q = q // r
705
+
706
+ if K.is_one(q):
707
+ return None
708
+
709
+ result.append(q)
710
+
711
+ return result[1:]
712
+
713
+
714
+ def dmp_zz_wang_test_points(f, T, ct, A, u, K):
715
+ """Wang/EEZ: Test evaluation points for suitability. """
716
+ if not dmp_eval_tail(dmp_LC(f, K), A, u - 1, K):
717
+ raise EvaluationFailed('no luck')
718
+
719
+ g = dmp_eval_tail(f, A, u, K)
720
+
721
+ if not dup_sqf_p(g, K):
722
+ raise EvaluationFailed('no luck')
723
+
724
+ c, h = dup_primitive(g, K)
725
+
726
+ if K.is_negative(dup_LC(h, K)):
727
+ c, h = -c, dup_neg(h, K)
728
+
729
+ v = u - 1
730
+
731
+ E = [ dmp_eval_tail(t, A, v, K) for t, _ in T ]
732
+ D = dmp_zz_wang_non_divisors(E, c, ct, K)
733
+
734
+ if D is not None:
735
+ return c, h, E
736
+ else:
737
+ raise EvaluationFailed('no luck')
738
+
739
+
740
+ def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K):
741
+ """Wang/EEZ: Compute correct leading coefficients. """
742
+ C, J, v = [], [0]*len(E), u - 1
743
+
744
+ for h in H:
745
+ c = dmp_one(v, K)
746
+ d = dup_LC(h, K)*cs
747
+
748
+ for i in reversed(range(len(E))):
749
+ k, e, (t, _) = 0, E[i], T[i]
750
+
751
+ while not (d % e):
752
+ d, k = d//e, k + 1
753
+
754
+ if k != 0:
755
+ c, J[i] = dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1
756
+
757
+ C.append(c)
758
+
759
+ if not all(J):
760
+ raise ExtraneousFactors # pragma: no cover
761
+
762
+ CC, HH = [], []
763
+
764
+ for c, h in zip(C, H):
765
+ d = dmp_eval_tail(c, A, v, K)
766
+ lc = dup_LC(h, K)
767
+
768
+ if K.is_one(cs):
769
+ cc = lc//d
770
+ else:
771
+ g = K.gcd(lc, d)
772
+ d, cc = d//g, lc//g
773
+ h, cs = dup_mul_ground(h, d, K), cs//d
774
+
775
+ c = dmp_mul_ground(c, cc, v, K)
776
+
777
+ CC.append(c)
778
+ HH.append(h)
779
+
780
+ if K.is_one(cs):
781
+ return f, HH, CC
782
+
783
+ CCC, HHH = [], []
784
+
785
+ for c, h in zip(CC, HH):
786
+ CCC.append(dmp_mul_ground(c, cs, v, K))
787
+ HHH.append(dmp_mul_ground(h, cs, 0, K))
788
+
789
+ f = dmp_mul_ground(f, cs**(len(H) - 1), u, K)
790
+
791
+ return f, HHH, CCC
792
+
793
+
794
+ def dup_zz_diophantine(F, m, p, K):
795
+ """Wang/EEZ: Solve univariate Diophantine equations. """
796
+ if len(F) == 2:
797
+ a, b = F
798
+
799
+ f = gf_from_int_poly(a, p)
800
+ g = gf_from_int_poly(b, p)
801
+
802
+ s, t, G = gf_gcdex(g, f, p, K)
803
+
804
+ s = gf_lshift(s, m, K)
805
+ t = gf_lshift(t, m, K)
806
+
807
+ q, s = gf_div(s, f, p, K)
808
+
809
+ t = gf_add_mul(t, q, g, p, K)
810
+
811
+ s = gf_to_int_poly(s, p)
812
+ t = gf_to_int_poly(t, p)
813
+
814
+ result = [s, t]
815
+ else:
816
+ G = [F[-1]]
817
+
818
+ for f in reversed(F[1:-1]):
819
+ G.insert(0, dup_mul(f, G[0], K))
820
+
821
+ S, T = [], [[1]]
822
+
823
+ for f, g in zip(F, G):
824
+ t, s = dmp_zz_diophantine([g, f], T[-1], [], 0, p, 1, K)
825
+ T.append(t)
826
+ S.append(s)
827
+
828
+ result, S = [], S + [T[-1]]
829
+
830
+ for s, f in zip(S, F):
831
+ s = gf_from_int_poly(s, p)
832
+ f = gf_from_int_poly(f, p)
833
+
834
+ r = gf_rem(gf_lshift(s, m, K), f, p, K)
835
+ s = gf_to_int_poly(r, p)
836
+
837
+ result.append(s)
838
+
839
+ return result
840
+
841
+
842
+ def dmp_zz_diophantine(F, c, A, d, p, u, K):
843
+ """Wang/EEZ: Solve multivariate Diophantine equations. """
844
+ if not A:
845
+ S = [ [] for _ in F ]
846
+ n = dup_degree(c)
847
+
848
+ for i, coeff in enumerate(c):
849
+ if not coeff:
850
+ continue
851
+
852
+ T = dup_zz_diophantine(F, n - i, p, K)
853
+
854
+ for j, (s, t) in enumerate(zip(S, T)):
855
+ t = dup_mul_ground(t, coeff, K)
856
+ S[j] = dup_trunc(dup_add(s, t, K), p, K)
857
+ else:
858
+ n = len(A)
859
+ e = dmp_expand(F, u, K)
860
+
861
+ a, A = A[-1], A[:-1]
862
+ B, G = [], []
863
+
864
+ for f in F:
865
+ B.append(dmp_quo(e, f, u, K))
866
+ G.append(dmp_eval_in(f, a, n, u, K))
867
+
868
+ C = dmp_eval_in(c, a, n, u, K)
869
+
870
+ v = u - 1
871
+
872
+ S = dmp_zz_diophantine(G, C, A, d, p, v, K)
873
+ S = [ dmp_raise(s, 1, v, K) for s in S ]
874
+
875
+ for s, b in zip(S, B):
876
+ c = dmp_sub_mul(c, s, b, u, K)
877
+
878
+ c = dmp_ground_trunc(c, p, u, K)
879
+
880
+ m = dmp_nest([K.one, -a], n, K)
881
+ M = dmp_one(n, K)
882
+
883
+ for k in K.map(range(0, d)):
884
+ if dmp_zero_p(c, u):
885
+ break
886
+
887
+ M = dmp_mul(M, m, u, K)
888
+ C = dmp_diff_eval_in(c, k + 1, a, n, u, K)
889
+
890
+ if not dmp_zero_p(C, v):
891
+ C = dmp_quo_ground(C, K.factorial(k + 1), v, K)
892
+ T = dmp_zz_diophantine(G, C, A, d, p, v, K)
893
+
894
+ for i, t in enumerate(T):
895
+ T[i] = dmp_mul(dmp_raise(t, 1, v, K), M, u, K)
896
+
897
+ for i, (s, t) in enumerate(zip(S, T)):
898
+ S[i] = dmp_add(s, t, u, K)
899
+
900
+ for t, b in zip(T, B):
901
+ c = dmp_sub_mul(c, t, b, u, K)
902
+
903
+ c = dmp_ground_trunc(c, p, u, K)
904
+
905
+ S = [ dmp_ground_trunc(s, p, u, K) for s in S ]
906
+
907
+ return S
908
+
909
+
910
+ def dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K):
911
+ """Wang/EEZ: Parallel Hensel lifting algorithm. """
912
+ S, n, v = [f], len(A), u - 1
913
+
914
+ H = list(H)
915
+
916
+ for i, a in enumerate(reversed(A[1:])):
917
+ s = dmp_eval_in(S[0], a, n - i, u - i, K)
918
+ S.insert(0, dmp_ground_trunc(s, p, v - i, K))
919
+
920
+ d = max(dmp_degree_list(f, u)[1:])
921
+
922
+ for j, s, a in zip(range(2, n + 2), S, A):
923
+ G, w = list(H), j - 1
924
+
925
+ I, J = A[:j - 2], A[j - 1:]
926
+
927
+ for i, (h, lc) in enumerate(zip(H, LC)):
928
+ lc = dmp_ground_trunc(dmp_eval_tail(lc, J, v, K), p, w - 1, K)
929
+ H[i] = [lc] + dmp_raise(h[1:], 1, w - 1, K)
930
+
931
+ m = dmp_nest([K.one, -a], w, K)
932
+ M = dmp_one(w, K)
933
+
934
+ c = dmp_sub(s, dmp_expand(H, w, K), w, K)
935
+
936
+ dj = dmp_degree_in(s, w, w)
937
+
938
+ for k in K.map(range(0, dj)):
939
+ if dmp_zero_p(c, w):
940
+ break
941
+
942
+ M = dmp_mul(M, m, w, K)
943
+ C = dmp_diff_eval_in(c, k + 1, a, w, w, K)
944
+
945
+ if not dmp_zero_p(C, w - 1):
946
+ C = dmp_quo_ground(C, K.factorial(k + 1), w - 1, K)
947
+ T = dmp_zz_diophantine(G, C, I, d, p, w - 1, K)
948
+
949
+ for i, (h, t) in enumerate(zip(H, T)):
950
+ h = dmp_add_mul(h, dmp_raise(t, 1, w - 1, K), M, w, K)
951
+ H[i] = dmp_ground_trunc(h, p, w, K)
952
+
953
+ h = dmp_sub(s, dmp_expand(H, w, K), w, K)
954
+ c = dmp_ground_trunc(h, p, w, K)
955
+
956
+ if dmp_expand(H, u, K) != f:
957
+ raise ExtraneousFactors # pragma: no cover
958
+ else:
959
+ return H
960
+
961
+
962
+ def dmp_zz_wang(f, u, K, mod=None, seed=None):
963
+ r"""
964
+ Factor primitive square-free polynomials in `Z[X]`.
965
+
966
+ Given a multivariate polynomial `f` in `Z[x_1,...,x_n]`, which is
967
+ primitive and square-free in `x_1`, computes factorization of `f` into
968
+ irreducibles over integers.
969
+
970
+ The procedure is based on Wang's Enhanced Extended Zassenhaus
971
+ algorithm. The algorithm works by viewing `f` as a univariate polynomial
972
+ in `Z[x_2,...,x_n][x_1]`, for which an evaluation mapping is computed::
973
+
974
+ x_2 -> a_2, ..., x_n -> a_n
975
+
976
+ where `a_i`, for `i = 2, \dots, n`, are carefully chosen integers. The
977
+ mapping is used to transform `f` into a univariate polynomial in `Z[x_1]`,
978
+ which can be factored efficiently using Zassenhaus algorithm. The last
979
+ step is to lift univariate factors to obtain true multivariate
980
+ factors. For this purpose a parallel Hensel lifting procedure is used.
981
+
982
+ The parameter ``seed`` is passed to _randint and can be used to seed randint
983
+ (when an integer) or (for testing purposes) can be a sequence of numbers.
984
+
985
+ References
986
+ ==========
987
+
988
+ .. [1] [Wang78]_
989
+ .. [2] [Geddes92]_
990
+
991
+ """
992
+ from sympy.ntheory import nextprime
993
+
994
+ randint = _randint(seed)
995
+
996
+ ct, T = dmp_zz_factor(dmp_LC(f, K), u - 1, K)
997
+
998
+ b = dmp_zz_mignotte_bound(f, u, K)
999
+ p = K(nextprime(b))
1000
+
1001
+ if mod is None:
1002
+ if u == 1:
1003
+ mod = 2
1004
+ else:
1005
+ mod = 1
1006
+
1007
+ history, configs, A, r = set(), [], [K.zero]*u, None
1008
+
1009
+ try:
1010
+ cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K)
1011
+
1012
+ _, H = dup_zz_factor_sqf(s, K)
1013
+
1014
+ r = len(H)
1015
+
1016
+ if r == 1:
1017
+ return [f]
1018
+
1019
+ configs = [(s, cs, E, H, A)]
1020
+ except EvaluationFailed:
1021
+ pass
1022
+
1023
+ eez_num_configs = query('EEZ_NUMBER_OF_CONFIGS')
1024
+ eez_num_tries = query('EEZ_NUMBER_OF_TRIES')
1025
+ eez_mod_step = query('EEZ_MODULUS_STEP')
1026
+
1027
+ while len(configs) < eez_num_configs:
1028
+ for _ in range(eez_num_tries):
1029
+ A = [ K(randint(-mod, mod)) for _ in range(u) ]
1030
+
1031
+ if tuple(A) not in history:
1032
+ history.add(tuple(A))
1033
+ else:
1034
+ continue
1035
+
1036
+ try:
1037
+ cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K)
1038
+ except EvaluationFailed:
1039
+ continue
1040
+
1041
+ _, H = dup_zz_factor_sqf(s, K)
1042
+
1043
+ rr = len(H)
1044
+
1045
+ if r is not None:
1046
+ if rr != r: # pragma: no cover
1047
+ if rr < r:
1048
+ configs, r = [], rr
1049
+ else:
1050
+ continue
1051
+ else:
1052
+ r = rr
1053
+
1054
+ if r == 1:
1055
+ return [f]
1056
+
1057
+ configs.append((s, cs, E, H, A))
1058
+
1059
+ if len(configs) == eez_num_configs:
1060
+ break
1061
+ else:
1062
+ mod += eez_mod_step
1063
+
1064
+ s_norm, s_arg, i = None, 0, 0
1065
+
1066
+ for s, _, _, _, _ in configs:
1067
+ _s_norm = dup_max_norm(s, K)
1068
+
1069
+ if s_norm is not None:
1070
+ if _s_norm < s_norm:
1071
+ s_norm = _s_norm
1072
+ s_arg = i
1073
+ else:
1074
+ s_norm = _s_norm
1075
+
1076
+ i += 1
1077
+
1078
+ _, cs, E, H, A = configs[s_arg]
1079
+ orig_f = f
1080
+
1081
+ try:
1082
+ f, H, LC = dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K)
1083
+ factors = dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K)
1084
+ except ExtraneousFactors: # pragma: no cover
1085
+ if query('EEZ_RESTART_IF_NEEDED'):
1086
+ return dmp_zz_wang(orig_f, u, K, mod + 1)
1087
+ else:
1088
+ raise ExtraneousFactors(
1089
+ "we need to restart algorithm with better parameters")
1090
+
1091
+ result = []
1092
+
1093
+ for f in factors:
1094
+ _, f = dmp_ground_primitive(f, u, K)
1095
+
1096
+ if K.is_negative(dmp_ground_LC(f, u, K)):
1097
+ f = dmp_neg(f, u, K)
1098
+
1099
+ result.append(f)
1100
+
1101
+ return result
1102
+
1103
+
1104
+ def dmp_zz_factor(f, u, K):
1105
+ r"""
1106
+ Factor (non square-free) polynomials in `Z[X]`.
1107
+
1108
+ Given a multivariate polynomial `f` in `Z[x]` computes its complete
1109
+ factorization `f_1, \dots, f_n` into irreducibles over integers::
1110
+
1111
+ f = content(f) f_1**k_1 ... f_n**k_n
1112
+
1113
+ The factorization is computed by reducing the input polynomial
1114
+ into a primitive square-free polynomial and factoring it using
1115
+ Enhanced Extended Zassenhaus (EEZ) algorithm. Trial division
1116
+ is used to recover the multiplicities of factors.
1117
+
1118
+ The result is returned as a tuple consisting of::
1119
+
1120
+ (content(f), [(f_1, k_1), ..., (f_n, k_n))
1121
+
1122
+ Consider polynomial `f = 2*(x**2 - y**2)`::
1123
+
1124
+ >>> from sympy.polys import ring, ZZ
1125
+ >>> R, x,y = ring("x,y", ZZ)
1126
+
1127
+ >>> R.dmp_zz_factor(2*x**2 - 2*y**2)
1128
+ (2, [(x - y, 1), (x + y, 1)])
1129
+
1130
+ In result we got the following factorization::
1131
+
1132
+ f = 2 (x - y) (x + y)
1133
+
1134
+ References
1135
+ ==========
1136
+
1137
+ .. [1] [Gathen99]_
1138
+
1139
+ """
1140
+ if not u:
1141
+ return dup_zz_factor(f, K)
1142
+
1143
+ if dmp_zero_p(f, u):
1144
+ return K.zero, []
1145
+
1146
+ cont, g = dmp_ground_primitive(f, u, K)
1147
+
1148
+ if dmp_ground_LC(g, u, K) < 0:
1149
+ cont, g = -cont, dmp_neg(g, u, K)
1150
+
1151
+ if all(d <= 0 for d in dmp_degree_list(g, u)):
1152
+ return cont, []
1153
+
1154
+ G, g = dmp_primitive(g, u, K)
1155
+
1156
+ factors = []
1157
+
1158
+ if dmp_degree(g, u) > 0:
1159
+ g = dmp_sqf_part(g, u, K)
1160
+ H = dmp_zz_wang(g, u, K)
1161
+ factors = dmp_trial_division(f, H, u, K)
1162
+
1163
+ for g, k in dmp_zz_factor(G, u - 1, K)[1]:
1164
+ factors.insert(0, ([g], k))
1165
+
1166
+ return cont, _sort_factors(factors)
1167
+
1168
+
1169
+ def dup_qq_i_factor(f, K0):
1170
+ """Factor univariate polynomials into irreducibles in `QQ_I[x]`. """
1171
+ # Factor in QQ<I>
1172
+ K1 = K0.as_AlgebraicField()
1173
+ f = dup_convert(f, K0, K1)
1174
+ coeff, factors = dup_factor_list(f, K1)
1175
+ factors = [(dup_convert(fac, K1, K0), i) for fac, i in factors]
1176
+ coeff = K0.convert(coeff, K1)
1177
+ return coeff, factors
1178
+
1179
+
1180
+ def dup_zz_i_factor(f, K0):
1181
+ """Factor univariate polynomials into irreducibles in `ZZ_I[x]`. """
1182
+ # First factor in QQ_I
1183
+ K1 = K0.get_field()
1184
+ f = dup_convert(f, K0, K1)
1185
+ coeff, factors = dup_qq_i_factor(f, K1)
1186
+
1187
+ new_factors = []
1188
+ for fac, i in factors:
1189
+ # Extract content
1190
+ fac_denom, fac_num = dup_clear_denoms(fac, K1)
1191
+ fac_num_ZZ_I = dup_convert(fac_num, K1, K0)
1192
+ content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, 0, K1)
1193
+
1194
+ coeff = (coeff * content ** i) // fac_denom ** i
1195
+ new_factors.append((fac_prim, i))
1196
+
1197
+ factors = new_factors
1198
+ coeff = K0.convert(coeff, K1)
1199
+ return coeff, factors
1200
+
1201
+
1202
+ def dmp_qq_i_factor(f, u, K0):
1203
+ """Factor multivariate polynomials into irreducibles in `QQ_I[X]`. """
1204
+ # Factor in QQ<I>
1205
+ K1 = K0.as_AlgebraicField()
1206
+ f = dmp_convert(f, u, K0, K1)
1207
+ coeff, factors = dmp_factor_list(f, u, K1)
1208
+ factors = [(dmp_convert(fac, u, K1, K0), i) for fac, i in factors]
1209
+ coeff = K0.convert(coeff, K1)
1210
+ return coeff, factors
1211
+
1212
+
1213
+ def dmp_zz_i_factor(f, u, K0):
1214
+ """Factor multivariate polynomials into irreducibles in `ZZ_I[X]`. """
1215
+ # First factor in QQ_I
1216
+ K1 = K0.get_field()
1217
+ f = dmp_convert(f, u, K0, K1)
1218
+ coeff, factors = dmp_qq_i_factor(f, u, K1)
1219
+
1220
+ new_factors = []
1221
+ for fac, i in factors:
1222
+ # Extract content
1223
+ fac_denom, fac_num = dmp_clear_denoms(fac, u, K1)
1224
+ fac_num_ZZ_I = dmp_convert(fac_num, u, K1, K0)
1225
+ content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, u, K1)
1226
+
1227
+ coeff = (coeff * content ** i) // fac_denom ** i
1228
+ new_factors.append((fac_prim, i))
1229
+
1230
+ factors = new_factors
1231
+ coeff = K0.convert(coeff, K1)
1232
+ return coeff, factors
1233
+
1234
+
1235
+ def dup_ext_factor(f, K):
1236
+ """Factor univariate polynomials over algebraic number fields. """
1237
+ n, lc = dup_degree(f), dup_LC(f, K)
1238
+
1239
+ f = dup_monic(f, K)
1240
+
1241
+ if n <= 0:
1242
+ return lc, []
1243
+ if n == 1:
1244
+ return lc, [(f, 1)]
1245
+
1246
+ f, F = dup_sqf_part(f, K), f
1247
+ s, g, r = dup_sqf_norm(f, K)
1248
+
1249
+ factors = dup_factor_list_include(r, K.dom)
1250
+
1251
+ if len(factors) == 1:
1252
+ return lc, [(f, n//dup_degree(f))]
1253
+
1254
+ H = s*K.unit
1255
+
1256
+ for i, (factor, _) in enumerate(factors):
1257
+ h = dup_convert(factor, K.dom, K)
1258
+ h, _, g = dup_inner_gcd(h, g, K)
1259
+ h = dup_shift(h, H, K)
1260
+ factors[i] = h
1261
+
1262
+ factors = dup_trial_division(F, factors, K)
1263
+ return lc, factors
1264
+
1265
+
1266
+ def dmp_ext_factor(f, u, K):
1267
+ """Factor multivariate polynomials over algebraic number fields. """
1268
+ if not u:
1269
+ return dup_ext_factor(f, K)
1270
+
1271
+ lc = dmp_ground_LC(f, u, K)
1272
+ f = dmp_ground_monic(f, u, K)
1273
+
1274
+ if all(d <= 0 for d in dmp_degree_list(f, u)):
1275
+ return lc, []
1276
+
1277
+ f, F = dmp_sqf_part(f, u, K), f
1278
+ s, g, r = dmp_sqf_norm(f, u, K)
1279
+
1280
+ factors = dmp_factor_list_include(r, u, K.dom)
1281
+
1282
+ if len(factors) == 1:
1283
+ factors = [f]
1284
+ else:
1285
+ H = dmp_raise([K.one, s*K.unit], u, 0, K)
1286
+
1287
+ for i, (factor, _) in enumerate(factors):
1288
+ h = dmp_convert(factor, u, K.dom, K)
1289
+ h, _, g = dmp_inner_gcd(h, g, u, K)
1290
+ h = dmp_compose(h, H, u, K)
1291
+ factors[i] = h
1292
+
1293
+ return lc, dmp_trial_division(F, factors, u, K)
1294
+
1295
+
1296
+ def dup_gf_factor(f, K):
1297
+ """Factor univariate polynomials over finite fields. """
1298
+ f = dup_convert(f, K, K.dom)
1299
+
1300
+ coeff, factors = gf_factor(f, K.mod, K.dom)
1301
+
1302
+ for i, (f, k) in enumerate(factors):
1303
+ factors[i] = (dup_convert(f, K.dom, K), k)
1304
+
1305
+ return K.convert(coeff, K.dom), factors
1306
+
1307
+
1308
+ def dmp_gf_factor(f, u, K):
1309
+ """Factor multivariate polynomials over finite fields. """
1310
+ raise NotImplementedError('multivariate polynomials over finite fields')
1311
+
1312
+
1313
+ def dup_factor_list(f, K0):
1314
+ """Factor univariate polynomials into irreducibles in `K[x]`. """
1315
+ j, f = dup_terms_gcd(f, K0)
1316
+ cont, f = dup_primitive(f, K0)
1317
+
1318
+ if K0.is_FiniteField:
1319
+ coeff, factors = dup_gf_factor(f, K0)
1320
+ elif K0.is_Algebraic:
1321
+ coeff, factors = dup_ext_factor(f, K0)
1322
+ elif K0.is_GaussianRing:
1323
+ coeff, factors = dup_zz_i_factor(f, K0)
1324
+ elif K0.is_GaussianField:
1325
+ coeff, factors = dup_qq_i_factor(f, K0)
1326
+ else:
1327
+ if not K0.is_Exact:
1328
+ K0_inexact, K0 = K0, K0.get_exact()
1329
+ f = dup_convert(f, K0_inexact, K0)
1330
+ else:
1331
+ K0_inexact = None
1332
+
1333
+ if K0.is_Field:
1334
+ K = K0.get_ring()
1335
+
1336
+ denom, f = dup_clear_denoms(f, K0, K)
1337
+ f = dup_convert(f, K0, K)
1338
+ else:
1339
+ K = K0
1340
+
1341
+ if K.is_ZZ:
1342
+ coeff, factors = dup_zz_factor(f, K)
1343
+ elif K.is_Poly:
1344
+ f, u = dmp_inject(f, 0, K)
1345
+
1346
+ coeff, factors = dmp_factor_list(f, u, K.dom)
1347
+
1348
+ for i, (f, k) in enumerate(factors):
1349
+ factors[i] = (dmp_eject(f, u, K), k)
1350
+
1351
+ coeff = K.convert(coeff, K.dom)
1352
+ else: # pragma: no cover
1353
+ raise DomainError('factorization not supported over %s' % K0)
1354
+
1355
+ if K0.is_Field:
1356
+ for i, (f, k) in enumerate(factors):
1357
+ factors[i] = (dup_convert(f, K, K0), k)
1358
+
1359
+ coeff = K0.convert(coeff, K)
1360
+ coeff = K0.quo(coeff, denom)
1361
+
1362
+ if K0_inexact:
1363
+ for i, (f, k) in enumerate(factors):
1364
+ max_norm = dup_max_norm(f, K0)
1365
+ f = dup_quo_ground(f, max_norm, K0)
1366
+ f = dup_convert(f, K0, K0_inexact)
1367
+ factors[i] = (f, k)
1368
+ coeff = K0.mul(coeff, K0.pow(max_norm, k))
1369
+
1370
+ coeff = K0_inexact.convert(coeff, K0)
1371
+ K0 = K0_inexact
1372
+
1373
+ if j:
1374
+ factors.insert(0, ([K0.one, K0.zero], j))
1375
+
1376
+ return coeff*cont, _sort_factors(factors)
1377
+
1378
+
1379
+ def dup_factor_list_include(f, K):
1380
+ """Factor univariate polynomials into irreducibles in `K[x]`. """
1381
+ coeff, factors = dup_factor_list(f, K)
1382
+
1383
+ if not factors:
1384
+ return [(dup_strip([coeff]), 1)]
1385
+ else:
1386
+ g = dup_mul_ground(factors[0][0], coeff, K)
1387
+ return [(g, factors[0][1])] + factors[1:]
1388
+
1389
+
1390
+ def dmp_factor_list(f, u, K0):
1391
+ """Factor multivariate polynomials into irreducibles in `K[X]`. """
1392
+ if not u:
1393
+ return dup_factor_list(f, K0)
1394
+
1395
+ J, f = dmp_terms_gcd(f, u, K0)
1396
+ cont, f = dmp_ground_primitive(f, u, K0)
1397
+
1398
+ if K0.is_FiniteField: # pragma: no cover
1399
+ coeff, factors = dmp_gf_factor(f, u, K0)
1400
+ elif K0.is_Algebraic:
1401
+ coeff, factors = dmp_ext_factor(f, u, K0)
1402
+ elif K0.is_GaussianRing:
1403
+ coeff, factors = dmp_zz_i_factor(f, u, K0)
1404
+ elif K0.is_GaussianField:
1405
+ coeff, factors = dmp_qq_i_factor(f, u, K0)
1406
+ else:
1407
+ if not K0.is_Exact:
1408
+ K0_inexact, K0 = K0, K0.get_exact()
1409
+ f = dmp_convert(f, u, K0_inexact, K0)
1410
+ else:
1411
+ K0_inexact = None
1412
+
1413
+ if K0.is_Field:
1414
+ K = K0.get_ring()
1415
+
1416
+ denom, f = dmp_clear_denoms(f, u, K0, K)
1417
+ f = dmp_convert(f, u, K0, K)
1418
+ else:
1419
+ K = K0
1420
+
1421
+ if K.is_ZZ:
1422
+ levels, f, v = dmp_exclude(f, u, K)
1423
+ coeff, factors = dmp_zz_factor(f, v, K)
1424
+
1425
+ for i, (f, k) in enumerate(factors):
1426
+ factors[i] = (dmp_include(f, levels, v, K), k)
1427
+ elif K.is_Poly:
1428
+ f, v = dmp_inject(f, u, K)
1429
+
1430
+ coeff, factors = dmp_factor_list(f, v, K.dom)
1431
+
1432
+ for i, (f, k) in enumerate(factors):
1433
+ factors[i] = (dmp_eject(f, v, K), k)
1434
+
1435
+ coeff = K.convert(coeff, K.dom)
1436
+ else: # pragma: no cover
1437
+ raise DomainError('factorization not supported over %s' % K0)
1438
+
1439
+ if K0.is_Field:
1440
+ for i, (f, k) in enumerate(factors):
1441
+ factors[i] = (dmp_convert(f, u, K, K0), k)
1442
+
1443
+ coeff = K0.convert(coeff, K)
1444
+ coeff = K0.quo(coeff, denom)
1445
+
1446
+ if K0_inexact:
1447
+ for i, (f, k) in enumerate(factors):
1448
+ max_norm = dmp_max_norm(f, u, K0)
1449
+ f = dmp_quo_ground(f, max_norm, u, K0)
1450
+ f = dmp_convert(f, u, K0, K0_inexact)
1451
+ factors[i] = (f, k)
1452
+ coeff = K0.mul(coeff, K0.pow(max_norm, k))
1453
+
1454
+ coeff = K0_inexact.convert(coeff, K0)
1455
+ K0 = K0_inexact
1456
+
1457
+ for i, j in enumerate(reversed(J)):
1458
+ if not j:
1459
+ continue
1460
+
1461
+ term = {(0,)*(u - i) + (1,) + (0,)*i: K0.one}
1462
+ factors.insert(0, (dmp_from_dict(term, u, K0), j))
1463
+
1464
+ return coeff*cont, _sort_factors(factors)
1465
+
1466
+
1467
+ def dmp_factor_list_include(f, u, K):
1468
+ """Factor multivariate polynomials into irreducibles in `K[X]`. """
1469
+ if not u:
1470
+ return dup_factor_list_include(f, K)
1471
+
1472
+ coeff, factors = dmp_factor_list(f, u, K)
1473
+
1474
+ if not factors:
1475
+ return [(dmp_ground(coeff, u), 1)]
1476
+ else:
1477
+ g = dmp_mul_ground(factors[0][0], coeff, u, K)
1478
+ return [(g, factors[0][1])] + factors[1:]
1479
+
1480
+
1481
+ def dup_irreducible_p(f, K):
1482
+ """
1483
+ Returns ``True`` if a univariate polynomial ``f`` has no factors
1484
+ over its domain.
1485
+ """
1486
+ return dmp_irreducible_p(f, 0, K)
1487
+
1488
+
1489
+ def dmp_irreducible_p(f, u, K):
1490
+ """
1491
+ Returns ``True`` if a multivariate polynomial ``f`` has no factors
1492
+ over its domain.
1493
+ """
1494
+ _, factors = dmp_factor_list(f, u, K)
1495
+
1496
+ if not factors:
1497
+ return True
1498
+ elif len(factors) > 1:
1499
+ return False
1500
+ else:
1501
+ _, k = factors[0]
1502
+ return k == 1
llmeval-env/lib/python3.10/site-packages/sympy/polys/fglmtools.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of matrix FGLM Groebner basis conversion algorithm. """
2
+
3
+
4
+ from sympy.polys.monomials import monomial_mul, monomial_div
5
+
6
+ def matrix_fglm(F, ring, O_to):
7
+ """
8
+ Converts the reduced Groebner basis ``F`` of a zero-dimensional
9
+ ideal w.r.t. ``O_from`` to a reduced Groebner basis
10
+ w.r.t. ``O_to``.
11
+
12
+ References
13
+ ==========
14
+
15
+ .. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient
16
+ Computation of Zero-dimensional Groebner Bases by Change of
17
+ Ordering
18
+ """
19
+ domain = ring.domain
20
+ ngens = ring.ngens
21
+
22
+ ring_to = ring.clone(order=O_to)
23
+
24
+ old_basis = _basis(F, ring)
25
+ M = _representing_matrices(old_basis, F, ring)
26
+
27
+ # V contains the normalforms (wrt O_from) of S
28
+ S = [ring.zero_monom]
29
+ V = [[domain.one] + [domain.zero] * (len(old_basis) - 1)]
30
+ G = []
31
+
32
+ L = [(i, 0) for i in range(ngens)] # (i, j) corresponds to x_i * S[j]
33
+ L.sort(key=lambda k_l: O_to(_incr_k(S[k_l[1]], k_l[0])), reverse=True)
34
+ t = L.pop()
35
+
36
+ P = _identity_matrix(len(old_basis), domain)
37
+
38
+ while True:
39
+ s = len(S)
40
+ v = _matrix_mul(M[t[0]], V[t[1]])
41
+ _lambda = _matrix_mul(P, v)
42
+
43
+ if all(_lambda[i] == domain.zero for i in range(s, len(old_basis))):
44
+ # there is a linear combination of v by V
45
+ lt = ring.term_new(_incr_k(S[t[1]], t[0]), domain.one)
46
+ rest = ring.from_dict({S[i]: _lambda[i] for i in range(s)})
47
+
48
+ g = (lt - rest).set_ring(ring_to)
49
+ if g:
50
+ G.append(g)
51
+ else:
52
+ # v is linearly independent from V
53
+ P = _update(s, _lambda, P)
54
+ S.append(_incr_k(S[t[1]], t[0]))
55
+ V.append(v)
56
+
57
+ L.extend([(i, s) for i in range(ngens)])
58
+ L = list(set(L))
59
+ L.sort(key=lambda k_l: O_to(_incr_k(S[k_l[1]], k_l[0])), reverse=True)
60
+
61
+ L = [(k, l) for (k, l) in L if all(monomial_div(_incr_k(S[l], k), g.LM) is None for g in G)]
62
+
63
+ if not L:
64
+ G = [ g.monic() for g in G ]
65
+ return sorted(G, key=lambda g: O_to(g.LM), reverse=True)
66
+
67
+ t = L.pop()
68
+
69
+
70
+ def _incr_k(m, k):
71
+ return tuple(list(m[:k]) + [m[k] + 1] + list(m[k + 1:]))
72
+
73
+
74
+ def _identity_matrix(n, domain):
75
+ M = [[domain.zero]*n for _ in range(n)]
76
+
77
+ for i in range(n):
78
+ M[i][i] = domain.one
79
+
80
+ return M
81
+
82
+
83
+ def _matrix_mul(M, v):
84
+ return [sum([row[i] * v[i] for i in range(len(v))]) for row in M]
85
+
86
+
87
+ def _update(s, _lambda, P):
88
+ """
89
+ Update ``P`` such that for the updated `P'` `P' v = e_{s}`.
90
+ """
91
+ k = min([j for j in range(s, len(_lambda)) if _lambda[j] != 0])
92
+
93
+ for r in range(len(_lambda)):
94
+ if r != k:
95
+ P[r] = [P[r][j] - (P[k][j] * _lambda[r]) / _lambda[k] for j in range(len(P[r]))]
96
+
97
+ P[k] = [P[k][j] / _lambda[k] for j in range(len(P[k]))]
98
+ P[k], P[s] = P[s], P[k]
99
+
100
+ return P
101
+
102
+
103
+ def _representing_matrices(basis, G, ring):
104
+ r"""
105
+ Compute the matrices corresponding to the linear maps `m \mapsto
106
+ x_i m` for all variables `x_i`.
107
+ """
108
+ domain = ring.domain
109
+ u = ring.ngens-1
110
+
111
+ def var(i):
112
+ return tuple([0] * i + [1] + [0] * (u - i))
113
+
114
+ def representing_matrix(m):
115
+ M = [[domain.zero] * len(basis) for _ in range(len(basis))]
116
+
117
+ for i, v in enumerate(basis):
118
+ r = ring.term_new(monomial_mul(m, v), domain.one).rem(G)
119
+
120
+ for monom, coeff in r.terms():
121
+ j = basis.index(monom)
122
+ M[j][i] = coeff
123
+
124
+ return M
125
+
126
+ return [representing_matrix(var(i)) for i in range(u + 1)]
127
+
128
+
129
+ def _basis(G, ring):
130
+ r"""
131
+ Computes a list of monomials which are not divisible by the leading
132
+ monomials wrt to ``O`` of ``G``. These monomials are a basis of
133
+ `K[X_1, \ldots, X_n]/(G)`.
134
+ """
135
+ order = ring.order
136
+
137
+ leading_monomials = [g.LM for g in G]
138
+ candidates = [ring.zero_monom]
139
+ basis = []
140
+
141
+ while candidates:
142
+ t = candidates.pop()
143
+ basis.append(t)
144
+
145
+ new_candidates = [_incr_k(t, k) for k in range(ring.ngens)
146
+ if all(monomial_div(_incr_k(t, k), lmg) is None
147
+ for lmg in leading_monomials)]
148
+ candidates.extend(new_candidates)
149
+ candidates.sort(key=order, reverse=True)
150
+
151
+ basis = list(set(basis))
152
+
153
+ return sorted(basis, key=order)
llmeval-env/lib/python3.10/site-packages/sympy/polys/fields.py ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sparse rational function fields. """
2
+
3
+ from __future__ import annotations
4
+ from typing import Any
5
+ from functools import reduce
6
+
7
+ from operator import add, mul, lt, le, gt, ge
8
+
9
+ from sympy.core.expr import Expr
10
+ from sympy.core.mod import Mod
11
+ from sympy.core.numbers import Exp1
12
+ from sympy.core.singleton import S
13
+ from sympy.core.symbol import Symbol
14
+ from sympy.core.sympify import CantSympify, sympify
15
+ from sympy.functions.elementary.exponential import ExpBase
16
+ from sympy.polys.domains.domainelement import DomainElement
17
+ from sympy.polys.domains.fractionfield import FractionField
18
+ from sympy.polys.domains.polynomialring import PolynomialRing
19
+ from sympy.polys.constructor import construct_domain
20
+ from sympy.polys.orderings import lex
21
+ from sympy.polys.polyerrors import CoercionFailed
22
+ from sympy.polys.polyoptions import build_options
23
+ from sympy.polys.polyutils import _parallel_dict_from_expr
24
+ from sympy.polys.rings import PolyElement
25
+ from sympy.printing.defaults import DefaultPrinting
26
+ from sympy.utilities import public
27
+ from sympy.utilities.iterables import is_sequence
28
+ from sympy.utilities.magic import pollute
29
+
30
+ @public
31
+ def field(symbols, domain, order=lex):
32
+ """Construct new rational function field returning (field, x1, ..., xn). """
33
+ _field = FracField(symbols, domain, order)
34
+ return (_field,) + _field.gens
35
+
36
+ @public
37
+ def xfield(symbols, domain, order=lex):
38
+ """Construct new rational function field returning (field, (x1, ..., xn)). """
39
+ _field = FracField(symbols, domain, order)
40
+ return (_field, _field.gens)
41
+
42
+ @public
43
+ def vfield(symbols, domain, order=lex):
44
+ """Construct new rational function field and inject generators into global namespace. """
45
+ _field = FracField(symbols, domain, order)
46
+ pollute([ sym.name for sym in _field.symbols ], _field.gens)
47
+ return _field
48
+
49
+ @public
50
+ def sfield(exprs, *symbols, **options):
51
+ """Construct a field deriving generators and domain
52
+ from options and input expressions.
53
+
54
+ Parameters
55
+ ==========
56
+
57
+ exprs : py:class:`~.Expr` or sequence of :py:class:`~.Expr` (sympifiable)
58
+
59
+ symbols : sequence of :py:class:`~.Symbol`/:py:class:`~.Expr`
60
+
61
+ options : keyword arguments understood by :py:class:`~.Options`
62
+
63
+ Examples
64
+ ========
65
+
66
+ >>> from sympy import exp, log, symbols, sfield
67
+
68
+ >>> x = symbols("x")
69
+ >>> K, f = sfield((x*log(x) + 4*x**2)*exp(1/x + log(x)/3)/x**2)
70
+ >>> K
71
+ Rational function field in x, exp(1/x), log(x), x**(1/3) over ZZ with lex order
72
+ >>> f
73
+ (4*x**2*(exp(1/x)) + x*(exp(1/x))*(log(x)))/((x**(1/3))**5)
74
+ """
75
+ single = False
76
+ if not is_sequence(exprs):
77
+ exprs, single = [exprs], True
78
+
79
+ exprs = list(map(sympify, exprs))
80
+ opt = build_options(symbols, options)
81
+ numdens = []
82
+ for expr in exprs:
83
+ numdens.extend(expr.as_numer_denom())
84
+ reps, opt = _parallel_dict_from_expr(numdens, opt)
85
+
86
+ if opt.domain is None:
87
+ # NOTE: this is inefficient because construct_domain() automatically
88
+ # performs conversion to the target domain. It shouldn't do this.
89
+ coeffs = sum([list(rep.values()) for rep in reps], [])
90
+ opt.domain, _ = construct_domain(coeffs, opt=opt)
91
+
92
+ _field = FracField(opt.gens, opt.domain, opt.order)
93
+ fracs = []
94
+ for i in range(0, len(reps), 2):
95
+ fracs.append(_field(tuple(reps[i:i+2])))
96
+
97
+ if single:
98
+ return (_field, fracs[0])
99
+ else:
100
+ return (_field, fracs)
101
+
102
+ _field_cache: dict[Any, Any] = {}
103
+
104
+ class FracField(DefaultPrinting):
105
+ """Multivariate distributed rational function field. """
106
+
107
+ def __new__(cls, symbols, domain, order=lex):
108
+ from sympy.polys.rings import PolyRing
109
+ ring = PolyRing(symbols, domain, order)
110
+ symbols = ring.symbols
111
+ ngens = ring.ngens
112
+ domain = ring.domain
113
+ order = ring.order
114
+
115
+ _hash_tuple = (cls.__name__, symbols, ngens, domain, order)
116
+ obj = _field_cache.get(_hash_tuple)
117
+
118
+ if obj is None:
119
+ obj = object.__new__(cls)
120
+ obj._hash_tuple = _hash_tuple
121
+ obj._hash = hash(_hash_tuple)
122
+ obj.ring = ring
123
+ obj.dtype = type("FracElement", (FracElement,), {"field": obj})
124
+ obj.symbols = symbols
125
+ obj.ngens = ngens
126
+ obj.domain = domain
127
+ obj.order = order
128
+
129
+ obj.zero = obj.dtype(ring.zero)
130
+ obj.one = obj.dtype(ring.one)
131
+
132
+ obj.gens = obj._gens()
133
+
134
+ for symbol, generator in zip(obj.symbols, obj.gens):
135
+ if isinstance(symbol, Symbol):
136
+ name = symbol.name
137
+
138
+ if not hasattr(obj, name):
139
+ setattr(obj, name, generator)
140
+
141
+ _field_cache[_hash_tuple] = obj
142
+
143
+ return obj
144
+
145
+ def _gens(self):
146
+ """Return a list of polynomial generators. """
147
+ return tuple([ self.dtype(gen) for gen in self.ring.gens ])
148
+
149
+ def __getnewargs__(self):
150
+ return (self.symbols, self.domain, self.order)
151
+
152
+ def __hash__(self):
153
+ return self._hash
154
+
155
+ def index(self, gen):
156
+ if isinstance(gen, self.dtype):
157
+ return self.ring.index(gen.to_poly())
158
+ else:
159
+ raise ValueError("expected a %s, got %s instead" % (self.dtype,gen))
160
+
161
+ def __eq__(self, other):
162
+ return isinstance(other, FracField) and \
163
+ (self.symbols, self.ngens, self.domain, self.order) == \
164
+ (other.symbols, other.ngens, other.domain, other.order)
165
+
166
+ def __ne__(self, other):
167
+ return not self == other
168
+
169
+ def raw_new(self, numer, denom=None):
170
+ return self.dtype(numer, denom)
171
+ def new(self, numer, denom=None):
172
+ if denom is None: denom = self.ring.one
173
+ numer, denom = numer.cancel(denom)
174
+ return self.raw_new(numer, denom)
175
+
176
+ def domain_new(self, element):
177
+ return self.domain.convert(element)
178
+
179
+ def ground_new(self, element):
180
+ try:
181
+ return self.new(self.ring.ground_new(element))
182
+ except CoercionFailed:
183
+ domain = self.domain
184
+
185
+ if not domain.is_Field and domain.has_assoc_Field:
186
+ ring = self.ring
187
+ ground_field = domain.get_field()
188
+ element = ground_field.convert(element)
189
+ numer = ring.ground_new(ground_field.numer(element))
190
+ denom = ring.ground_new(ground_field.denom(element))
191
+ return self.raw_new(numer, denom)
192
+ else:
193
+ raise
194
+
195
+ def field_new(self, element):
196
+ if isinstance(element, FracElement):
197
+ if self == element.field:
198
+ return element
199
+
200
+ if isinstance(self.domain, FractionField) and \
201
+ self.domain.field == element.field:
202
+ return self.ground_new(element)
203
+ elif isinstance(self.domain, PolynomialRing) and \
204
+ self.domain.ring.to_field() == element.field:
205
+ return self.ground_new(element)
206
+ else:
207
+ raise NotImplementedError("conversion")
208
+ elif isinstance(element, PolyElement):
209
+ denom, numer = element.clear_denoms()
210
+
211
+ if isinstance(self.domain, PolynomialRing) and \
212
+ numer.ring == self.domain.ring:
213
+ numer = self.ring.ground_new(numer)
214
+ elif isinstance(self.domain, FractionField) and \
215
+ numer.ring == self.domain.field.to_ring():
216
+ numer = self.ring.ground_new(numer)
217
+ else:
218
+ numer = numer.set_ring(self.ring)
219
+
220
+ denom = self.ring.ground_new(denom)
221
+ return self.raw_new(numer, denom)
222
+ elif isinstance(element, tuple) and len(element) == 2:
223
+ numer, denom = list(map(self.ring.ring_new, element))
224
+ return self.new(numer, denom)
225
+ elif isinstance(element, str):
226
+ raise NotImplementedError("parsing")
227
+ elif isinstance(element, Expr):
228
+ return self.from_expr(element)
229
+ else:
230
+ return self.ground_new(element)
231
+
232
+ __call__ = field_new
233
+
234
+ def _rebuild_expr(self, expr, mapping):
235
+ domain = self.domain
236
+ powers = tuple((gen, gen.as_base_exp()) for gen in mapping.keys()
237
+ if gen.is_Pow or isinstance(gen, ExpBase))
238
+
239
+ def _rebuild(expr):
240
+ generator = mapping.get(expr)
241
+
242
+ if generator is not None:
243
+ return generator
244
+ elif expr.is_Add:
245
+ return reduce(add, list(map(_rebuild, expr.args)))
246
+ elif expr.is_Mul:
247
+ return reduce(mul, list(map(_rebuild, expr.args)))
248
+ elif expr.is_Pow or isinstance(expr, (ExpBase, Exp1)):
249
+ b, e = expr.as_base_exp()
250
+ # look for bg**eg whose integer power may be b**e
251
+ for gen, (bg, eg) in powers:
252
+ if bg == b and Mod(e, eg) == 0:
253
+ return mapping.get(gen)**int(e/eg)
254
+ if e.is_Integer and e is not S.One:
255
+ return _rebuild(b)**int(e)
256
+ elif mapping.get(1/expr) is not None:
257
+ return 1/mapping.get(1/expr)
258
+
259
+ try:
260
+ return domain.convert(expr)
261
+ except CoercionFailed:
262
+ if not domain.is_Field and domain.has_assoc_Field:
263
+ return domain.get_field().convert(expr)
264
+ else:
265
+ raise
266
+
267
+ return _rebuild(expr)
268
+
269
+ def from_expr(self, expr):
270
+ mapping = dict(list(zip(self.symbols, self.gens)))
271
+
272
+ try:
273
+ frac = self._rebuild_expr(sympify(expr), mapping)
274
+ except CoercionFailed:
275
+ raise ValueError("expected an expression convertible to a rational function in %s, got %s" % (self, expr))
276
+ else:
277
+ return self.field_new(frac)
278
+
279
+ def to_domain(self):
280
+ return FractionField(self)
281
+
282
+ def to_ring(self):
283
+ from sympy.polys.rings import PolyRing
284
+ return PolyRing(self.symbols, self.domain, self.order)
285
+
286
+ class FracElement(DomainElement, DefaultPrinting, CantSympify):
287
+ """Element of multivariate distributed rational function field. """
288
+
289
+ def __init__(self, numer, denom=None):
290
+ if denom is None:
291
+ denom = self.field.ring.one
292
+ elif not denom:
293
+ raise ZeroDivisionError("zero denominator")
294
+
295
+ self.numer = numer
296
+ self.denom = denom
297
+
298
+ def raw_new(f, numer, denom):
299
+ return f.__class__(numer, denom)
300
+ def new(f, numer, denom):
301
+ return f.raw_new(*numer.cancel(denom))
302
+
303
+ def to_poly(f):
304
+ if f.denom != 1:
305
+ raise ValueError("f.denom should be 1")
306
+ return f.numer
307
+
308
+ def parent(self):
309
+ return self.field.to_domain()
310
+
311
+ def __getnewargs__(self):
312
+ return (self.field, self.numer, self.denom)
313
+
314
+ _hash = None
315
+
316
+ def __hash__(self):
317
+ _hash = self._hash
318
+ if _hash is None:
319
+ self._hash = _hash = hash((self.field, self.numer, self.denom))
320
+ return _hash
321
+
322
+ def copy(self):
323
+ return self.raw_new(self.numer.copy(), self.denom.copy())
324
+
325
+ def set_field(self, new_field):
326
+ if self.field == new_field:
327
+ return self
328
+ else:
329
+ new_ring = new_field.ring
330
+ numer = self.numer.set_ring(new_ring)
331
+ denom = self.denom.set_ring(new_ring)
332
+ return new_field.new(numer, denom)
333
+
334
+ def as_expr(self, *symbols):
335
+ return self.numer.as_expr(*symbols)/self.denom.as_expr(*symbols)
336
+
337
+ def __eq__(f, g):
338
+ if isinstance(g, FracElement) and f.field == g.field:
339
+ return f.numer == g.numer and f.denom == g.denom
340
+ else:
341
+ return f.numer == g and f.denom == f.field.ring.one
342
+
343
+ def __ne__(f, g):
344
+ return not f == g
345
+
346
+ def __bool__(f):
347
+ return bool(f.numer)
348
+
349
+ def sort_key(self):
350
+ return (self.denom.sort_key(), self.numer.sort_key())
351
+
352
+ def _cmp(f1, f2, op):
353
+ if isinstance(f2, f1.field.dtype):
354
+ return op(f1.sort_key(), f2.sort_key())
355
+ else:
356
+ return NotImplemented
357
+
358
+ def __lt__(f1, f2):
359
+ return f1._cmp(f2, lt)
360
+ def __le__(f1, f2):
361
+ return f1._cmp(f2, le)
362
+ def __gt__(f1, f2):
363
+ return f1._cmp(f2, gt)
364
+ def __ge__(f1, f2):
365
+ return f1._cmp(f2, ge)
366
+
367
+ def __pos__(f):
368
+ """Negate all coefficients in ``f``. """
369
+ return f.raw_new(f.numer, f.denom)
370
+
371
+ def __neg__(f):
372
+ """Negate all coefficients in ``f``. """
373
+ return f.raw_new(-f.numer, f.denom)
374
+
375
+ def _extract_ground(self, element):
376
+ domain = self.field.domain
377
+
378
+ try:
379
+ element = domain.convert(element)
380
+ except CoercionFailed:
381
+ if not domain.is_Field and domain.has_assoc_Field:
382
+ ground_field = domain.get_field()
383
+
384
+ try:
385
+ element = ground_field.convert(element)
386
+ except CoercionFailed:
387
+ pass
388
+ else:
389
+ return -1, ground_field.numer(element), ground_field.denom(element)
390
+
391
+ return 0, None, None
392
+ else:
393
+ return 1, element, None
394
+
395
+ def __add__(f, g):
396
+ """Add rational functions ``f`` and ``g``. """
397
+ field = f.field
398
+
399
+ if not g:
400
+ return f
401
+ elif not f:
402
+ return g
403
+ elif isinstance(g, field.dtype):
404
+ if f.denom == g.denom:
405
+ return f.new(f.numer + g.numer, f.denom)
406
+ else:
407
+ return f.new(f.numer*g.denom + f.denom*g.numer, f.denom*g.denom)
408
+ elif isinstance(g, field.ring.dtype):
409
+ return f.new(f.numer + f.denom*g, f.denom)
410
+ else:
411
+ if isinstance(g, FracElement):
412
+ if isinstance(field.domain, FractionField) and field.domain.field == g.field:
413
+ pass
414
+ elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field:
415
+ return g.__radd__(f)
416
+ else:
417
+ return NotImplemented
418
+ elif isinstance(g, PolyElement):
419
+ if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring:
420
+ pass
421
+ else:
422
+ return g.__radd__(f)
423
+
424
+ return f.__radd__(g)
425
+
426
+ def __radd__(f, c):
427
+ if isinstance(c, f.field.ring.dtype):
428
+ return f.new(f.numer + f.denom*c, f.denom)
429
+
430
+ op, g_numer, g_denom = f._extract_ground(c)
431
+
432
+ if op == 1:
433
+ return f.new(f.numer + f.denom*g_numer, f.denom)
434
+ elif not op:
435
+ return NotImplemented
436
+ else:
437
+ return f.new(f.numer*g_denom + f.denom*g_numer, f.denom*g_denom)
438
+
439
+ def __sub__(f, g):
440
+ """Subtract rational functions ``f`` and ``g``. """
441
+ field = f.field
442
+
443
+ if not g:
444
+ return f
445
+ elif not f:
446
+ return -g
447
+ elif isinstance(g, field.dtype):
448
+ if f.denom == g.denom:
449
+ return f.new(f.numer - g.numer, f.denom)
450
+ else:
451
+ return f.new(f.numer*g.denom - f.denom*g.numer, f.denom*g.denom)
452
+ elif isinstance(g, field.ring.dtype):
453
+ return f.new(f.numer - f.denom*g, f.denom)
454
+ else:
455
+ if isinstance(g, FracElement):
456
+ if isinstance(field.domain, FractionField) and field.domain.field == g.field:
457
+ pass
458
+ elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field:
459
+ return g.__rsub__(f)
460
+ else:
461
+ return NotImplemented
462
+ elif isinstance(g, PolyElement):
463
+ if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring:
464
+ pass
465
+ else:
466
+ return g.__rsub__(f)
467
+
468
+ op, g_numer, g_denom = f._extract_ground(g)
469
+
470
+ if op == 1:
471
+ return f.new(f.numer - f.denom*g_numer, f.denom)
472
+ elif not op:
473
+ return NotImplemented
474
+ else:
475
+ return f.new(f.numer*g_denom - f.denom*g_numer, f.denom*g_denom)
476
+
477
+ def __rsub__(f, c):
478
+ if isinstance(c, f.field.ring.dtype):
479
+ return f.new(-f.numer + f.denom*c, f.denom)
480
+
481
+ op, g_numer, g_denom = f._extract_ground(c)
482
+
483
+ if op == 1:
484
+ return f.new(-f.numer + f.denom*g_numer, f.denom)
485
+ elif not op:
486
+ return NotImplemented
487
+ else:
488
+ return f.new(-f.numer*g_denom + f.denom*g_numer, f.denom*g_denom)
489
+
490
+ def __mul__(f, g):
491
+ """Multiply rational functions ``f`` and ``g``. """
492
+ field = f.field
493
+
494
+ if not f or not g:
495
+ return field.zero
496
+ elif isinstance(g, field.dtype):
497
+ return f.new(f.numer*g.numer, f.denom*g.denom)
498
+ elif isinstance(g, field.ring.dtype):
499
+ return f.new(f.numer*g, f.denom)
500
+ else:
501
+ if isinstance(g, FracElement):
502
+ if isinstance(field.domain, FractionField) and field.domain.field == g.field:
503
+ pass
504
+ elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field:
505
+ return g.__rmul__(f)
506
+ else:
507
+ return NotImplemented
508
+ elif isinstance(g, PolyElement):
509
+ if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring:
510
+ pass
511
+ else:
512
+ return g.__rmul__(f)
513
+
514
+ return f.__rmul__(g)
515
+
516
+ def __rmul__(f, c):
517
+ if isinstance(c, f.field.ring.dtype):
518
+ return f.new(f.numer*c, f.denom)
519
+
520
+ op, g_numer, g_denom = f._extract_ground(c)
521
+
522
+ if op == 1:
523
+ return f.new(f.numer*g_numer, f.denom)
524
+ elif not op:
525
+ return NotImplemented
526
+ else:
527
+ return f.new(f.numer*g_numer, f.denom*g_denom)
528
+
529
+ def __truediv__(f, g):
530
+ """Computes quotient of fractions ``f`` and ``g``. """
531
+ field = f.field
532
+
533
+ if not g:
534
+ raise ZeroDivisionError
535
+ elif isinstance(g, field.dtype):
536
+ return f.new(f.numer*g.denom, f.denom*g.numer)
537
+ elif isinstance(g, field.ring.dtype):
538
+ return f.new(f.numer, f.denom*g)
539
+ else:
540
+ if isinstance(g, FracElement):
541
+ if isinstance(field.domain, FractionField) and field.domain.field == g.field:
542
+ pass
543
+ elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field:
544
+ return g.__rtruediv__(f)
545
+ else:
546
+ return NotImplemented
547
+ elif isinstance(g, PolyElement):
548
+ if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring:
549
+ pass
550
+ else:
551
+ return g.__rtruediv__(f)
552
+
553
+ op, g_numer, g_denom = f._extract_ground(g)
554
+
555
+ if op == 1:
556
+ return f.new(f.numer, f.denom*g_numer)
557
+ elif not op:
558
+ return NotImplemented
559
+ else:
560
+ return f.new(f.numer*g_denom, f.denom*g_numer)
561
+
562
+ def __rtruediv__(f, c):
563
+ if not f:
564
+ raise ZeroDivisionError
565
+ elif isinstance(c, f.field.ring.dtype):
566
+ return f.new(f.denom*c, f.numer)
567
+
568
+ op, g_numer, g_denom = f._extract_ground(c)
569
+
570
+ if op == 1:
571
+ return f.new(f.denom*g_numer, f.numer)
572
+ elif not op:
573
+ return NotImplemented
574
+ else:
575
+ return f.new(f.denom*g_numer, f.numer*g_denom)
576
+
577
+ def __pow__(f, n):
578
+ """Raise ``f`` to a non-negative power ``n``. """
579
+ if n >= 0:
580
+ return f.raw_new(f.numer**n, f.denom**n)
581
+ elif not f:
582
+ raise ZeroDivisionError
583
+ else:
584
+ return f.raw_new(f.denom**-n, f.numer**-n)
585
+
586
+ def diff(f, x):
587
+ """Computes partial derivative in ``x``.
588
+
589
+ Examples
590
+ ========
591
+
592
+ >>> from sympy.polys.fields import field
593
+ >>> from sympy.polys.domains import ZZ
594
+
595
+ >>> _, x, y, z = field("x,y,z", ZZ)
596
+ >>> ((x**2 + y)/(z + 1)).diff(x)
597
+ 2*x/(z + 1)
598
+
599
+ """
600
+ x = x.to_poly()
601
+ return f.new(f.numer.diff(x)*f.denom - f.numer*f.denom.diff(x), f.denom**2)
602
+
603
+ def __call__(f, *values):
604
+ if 0 < len(values) <= f.field.ngens:
605
+ return f.evaluate(list(zip(f.field.gens, values)))
606
+ else:
607
+ raise ValueError("expected at least 1 and at most %s values, got %s" % (f.field.ngens, len(values)))
608
+
609
+ def evaluate(f, x, a=None):
610
+ if isinstance(x, list) and a is None:
611
+ x = [ (X.to_poly(), a) for X, a in x ]
612
+ numer, denom = f.numer.evaluate(x), f.denom.evaluate(x)
613
+ else:
614
+ x = x.to_poly()
615
+ numer, denom = f.numer.evaluate(x, a), f.denom.evaluate(x, a)
616
+
617
+ field = numer.ring.to_field()
618
+ return field.new(numer, denom)
619
+
620
+ def subs(f, x, a=None):
621
+ if isinstance(x, list) and a is None:
622
+ x = [ (X.to_poly(), a) for X, a in x ]
623
+ numer, denom = f.numer.subs(x), f.denom.subs(x)
624
+ else:
625
+ x = x.to_poly()
626
+ numer, denom = f.numer.subs(x, a), f.denom.subs(x, a)
627
+
628
+ return f.new(numer, denom)
629
+
630
+ def compose(f, x, a=None):
631
+ raise NotImplementedError
llmeval-env/lib/python3.10/site-packages/sympy/polys/galoistools.py ADDED
@@ -0,0 +1,2363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dense univariate polynomials with coefficients in Galois fields. """
2
+
3
+ from math import ceil as _ceil, sqrt as _sqrt, prod
4
+
5
+ from sympy.core.random import uniform
6
+ from sympy.external.gmpy import SYMPY_INTS
7
+ from sympy.polys.polyconfig import query
8
+ from sympy.polys.polyerrors import ExactQuotientFailed
9
+ from sympy.polys.polyutils import _sort_factors
10
+
11
+
12
+ def gf_crt(U, M, K=None):
13
+ """
14
+ Chinese Remainder Theorem.
15
+
16
+ Given a set of integer residues ``u_0,...,u_n`` and a set of
17
+ co-prime integer moduli ``m_0,...,m_n``, returns an integer
18
+ ``u``, such that ``u = u_i mod m_i`` for ``i = ``0,...,n``.
19
+
20
+ Examples
21
+ ========
22
+
23
+ Consider a set of residues ``U = [49, 76, 65]``
24
+ and a set of moduli ``M = [99, 97, 95]``. Then we have::
25
+
26
+ >>> from sympy.polys.domains import ZZ
27
+ >>> from sympy.polys.galoistools import gf_crt
28
+
29
+ >>> gf_crt([49, 76, 65], [99, 97, 95], ZZ)
30
+ 639985
31
+
32
+ This is the correct result because::
33
+
34
+ >>> [639985 % m for m in [99, 97, 95]]
35
+ [49, 76, 65]
36
+
37
+ Note: this is a low-level routine with no error checking.
38
+
39
+ See Also
40
+ ========
41
+
42
+ sympy.ntheory.modular.crt : a higher level crt routine
43
+ sympy.ntheory.modular.solve_congruence
44
+
45
+ """
46
+ p = prod(M, start=K.one)
47
+ v = K.zero
48
+
49
+ for u, m in zip(U, M):
50
+ e = p // m
51
+ s, _, _ = K.gcdex(e, m)
52
+ v += e*(u*s % m)
53
+
54
+ return v % p
55
+
56
+
57
+ def gf_crt1(M, K):
58
+ """
59
+ First part of the Chinese Remainder Theorem.
60
+
61
+ Examples
62
+ ========
63
+
64
+ >>> from sympy.polys.domains import ZZ
65
+ >>> from sympy.polys.galoistools import gf_crt1
66
+
67
+ >>> gf_crt1([99, 97, 95], ZZ)
68
+ (912285, [9215, 9405, 9603], [62, 24, 12])
69
+
70
+ """
71
+ E, S = [], []
72
+ p = prod(M, start=K.one)
73
+
74
+ for m in M:
75
+ E.append(p // m)
76
+ S.append(K.gcdex(E[-1], m)[0] % m)
77
+
78
+ return p, E, S
79
+
80
+
81
+ def gf_crt2(U, M, p, E, S, K):
82
+ """
83
+ Second part of the Chinese Remainder Theorem.
84
+
85
+ Examples
86
+ ========
87
+
88
+ >>> from sympy.polys.domains import ZZ
89
+ >>> from sympy.polys.galoistools import gf_crt2
90
+
91
+ >>> U = [49, 76, 65]
92
+ >>> M = [99, 97, 95]
93
+ >>> p = 912285
94
+ >>> E = [9215, 9405, 9603]
95
+ >>> S = [62, 24, 12]
96
+
97
+ >>> gf_crt2(U, M, p, E, S, ZZ)
98
+ 639985
99
+
100
+ """
101
+ v = K.zero
102
+
103
+ for u, m, e, s in zip(U, M, E, S):
104
+ v += e*(u*s % m)
105
+
106
+ return v % p
107
+
108
+
109
+ def gf_int(a, p):
110
+ """
111
+ Coerce ``a mod p`` to an integer in the range ``[-p/2, p/2]``.
112
+
113
+ Examples
114
+ ========
115
+
116
+ >>> from sympy.polys.galoistools import gf_int
117
+
118
+ >>> gf_int(2, 7)
119
+ 2
120
+ >>> gf_int(5, 7)
121
+ -2
122
+
123
+ """
124
+ if a <= p // 2:
125
+ return a
126
+ else:
127
+ return a - p
128
+
129
+
130
+ def gf_degree(f):
131
+ """
132
+ Return the leading degree of ``f``.
133
+
134
+ Examples
135
+ ========
136
+
137
+ >>> from sympy.polys.galoistools import gf_degree
138
+
139
+ >>> gf_degree([1, 1, 2, 0])
140
+ 3
141
+ >>> gf_degree([])
142
+ -1
143
+
144
+ """
145
+ return len(f) - 1
146
+
147
+
148
+ def gf_LC(f, K):
149
+ """
150
+ Return the leading coefficient of ``f``.
151
+
152
+ Examples
153
+ ========
154
+
155
+ >>> from sympy.polys.domains import ZZ
156
+ >>> from sympy.polys.galoistools import gf_LC
157
+
158
+ >>> gf_LC([3, 0, 1], ZZ)
159
+ 3
160
+
161
+ """
162
+ if not f:
163
+ return K.zero
164
+ else:
165
+ return f[0]
166
+
167
+
168
+ def gf_TC(f, K):
169
+ """
170
+ Return the trailing coefficient of ``f``.
171
+
172
+ Examples
173
+ ========
174
+
175
+ >>> from sympy.polys.domains import ZZ
176
+ >>> from sympy.polys.galoistools import gf_TC
177
+
178
+ >>> gf_TC([3, 0, 1], ZZ)
179
+ 1
180
+
181
+ """
182
+ if not f:
183
+ return K.zero
184
+ else:
185
+ return f[-1]
186
+
187
+
188
+ def gf_strip(f):
189
+ """
190
+ Remove leading zeros from ``f``.
191
+
192
+
193
+ Examples
194
+ ========
195
+
196
+ >>> from sympy.polys.galoistools import gf_strip
197
+
198
+ >>> gf_strip([0, 0, 0, 3, 0, 1])
199
+ [3, 0, 1]
200
+
201
+ """
202
+ if not f or f[0]:
203
+ return f
204
+
205
+ k = 0
206
+
207
+ for coeff in f:
208
+ if coeff:
209
+ break
210
+ else:
211
+ k += 1
212
+
213
+ return f[k:]
214
+
215
+
216
+ def gf_trunc(f, p):
217
+ """
218
+ Reduce all coefficients modulo ``p``.
219
+
220
+ Examples
221
+ ========
222
+
223
+ >>> from sympy.polys.galoistools import gf_trunc
224
+
225
+ >>> gf_trunc([7, -2, 3], 5)
226
+ [2, 3, 3]
227
+
228
+ """
229
+ return gf_strip([ a % p for a in f ])
230
+
231
+
232
+ def gf_normal(f, p, K):
233
+ """
234
+ Normalize all coefficients in ``K``.
235
+
236
+ Examples
237
+ ========
238
+
239
+ >>> from sympy.polys.domains import ZZ
240
+ >>> from sympy.polys.galoistools import gf_normal
241
+
242
+ >>> gf_normal([5, 10, 21, -3], 5, ZZ)
243
+ [1, 2]
244
+
245
+ """
246
+ return gf_trunc(list(map(K, f)), p)
247
+
248
+
249
+ def gf_from_dict(f, p, K):
250
+ """
251
+ Create a ``GF(p)[x]`` polynomial from a dict.
252
+
253
+ Examples
254
+ ========
255
+
256
+ >>> from sympy.polys.domains import ZZ
257
+ >>> from sympy.polys.galoistools import gf_from_dict
258
+
259
+ >>> gf_from_dict({10: ZZ(4), 4: ZZ(33), 0: ZZ(-1)}, 5, ZZ)
260
+ [4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4]
261
+
262
+ """
263
+ n, h = max(f.keys()), []
264
+
265
+ if isinstance(n, SYMPY_INTS):
266
+ for k in range(n, -1, -1):
267
+ h.append(f.get(k, K.zero) % p)
268
+ else:
269
+ (n,) = n
270
+
271
+ for k in range(n, -1, -1):
272
+ h.append(f.get((k,), K.zero) % p)
273
+
274
+ return gf_trunc(h, p)
275
+
276
+
277
+ def gf_to_dict(f, p, symmetric=True):
278
+ """
279
+ Convert a ``GF(p)[x]`` polynomial to a dict.
280
+
281
+ Examples
282
+ ========
283
+
284
+ >>> from sympy.polys.galoistools import gf_to_dict
285
+
286
+ >>> gf_to_dict([4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4], 5)
287
+ {0: -1, 4: -2, 10: -1}
288
+ >>> gf_to_dict([4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4], 5, symmetric=False)
289
+ {0: 4, 4: 3, 10: 4}
290
+
291
+ """
292
+ n, result = gf_degree(f), {}
293
+
294
+ for k in range(0, n + 1):
295
+ if symmetric:
296
+ a = gf_int(f[n - k], p)
297
+ else:
298
+ a = f[n - k]
299
+
300
+ if a:
301
+ result[k] = a
302
+
303
+ return result
304
+
305
+
306
+ def gf_from_int_poly(f, p):
307
+ """
308
+ Create a ``GF(p)[x]`` polynomial from ``Z[x]``.
309
+
310
+ Examples
311
+ ========
312
+
313
+ >>> from sympy.polys.galoistools import gf_from_int_poly
314
+
315
+ >>> gf_from_int_poly([7, -2, 3], 5)
316
+ [2, 3, 3]
317
+
318
+ """
319
+ return gf_trunc(f, p)
320
+
321
+
322
+ def gf_to_int_poly(f, p, symmetric=True):
323
+ """
324
+ Convert a ``GF(p)[x]`` polynomial to ``Z[x]``.
325
+
326
+
327
+ Examples
328
+ ========
329
+
330
+ >>> from sympy.polys.galoistools import gf_to_int_poly
331
+
332
+ >>> gf_to_int_poly([2, 3, 3], 5)
333
+ [2, -2, -2]
334
+ >>> gf_to_int_poly([2, 3, 3], 5, symmetric=False)
335
+ [2, 3, 3]
336
+
337
+ """
338
+ if symmetric:
339
+ return [ gf_int(c, p) for c in f ]
340
+ else:
341
+ return f
342
+
343
+
344
+ def gf_neg(f, p, K):
345
+ """
346
+ Negate a polynomial in ``GF(p)[x]``.
347
+
348
+ Examples
349
+ ========
350
+
351
+ >>> from sympy.polys.domains import ZZ
352
+ >>> from sympy.polys.galoistools import gf_neg
353
+
354
+ >>> gf_neg([3, 2, 1, 0], 5, ZZ)
355
+ [2, 3, 4, 0]
356
+
357
+ """
358
+ return [ -coeff % p for coeff in f ]
359
+
360
+
361
+ def gf_add_ground(f, a, p, K):
362
+ """
363
+ Compute ``f + a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.
364
+
365
+ Examples
366
+ ========
367
+
368
+ >>> from sympy.polys.domains import ZZ
369
+ >>> from sympy.polys.galoistools import gf_add_ground
370
+
371
+ >>> gf_add_ground([3, 2, 4], 2, 5, ZZ)
372
+ [3, 2, 1]
373
+
374
+ """
375
+ if not f:
376
+ a = a % p
377
+ else:
378
+ a = (f[-1] + a) % p
379
+
380
+ if len(f) > 1:
381
+ return f[:-1] + [a]
382
+
383
+ if not a:
384
+ return []
385
+ else:
386
+ return [a]
387
+
388
+
389
+ def gf_sub_ground(f, a, p, K):
390
+ """
391
+ Compute ``f - a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.
392
+
393
+ Examples
394
+ ========
395
+
396
+ >>> from sympy.polys.domains import ZZ
397
+ >>> from sympy.polys.galoistools import gf_sub_ground
398
+
399
+ >>> gf_sub_ground([3, 2, 4], 2, 5, ZZ)
400
+ [3, 2, 2]
401
+
402
+ """
403
+ if not f:
404
+ a = -a % p
405
+ else:
406
+ a = (f[-1] - a) % p
407
+
408
+ if len(f) > 1:
409
+ return f[:-1] + [a]
410
+
411
+ if not a:
412
+ return []
413
+ else:
414
+ return [a]
415
+
416
+
417
+ def gf_mul_ground(f, a, p, K):
418
+ """
419
+ Compute ``f * a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.
420
+
421
+ Examples
422
+ ========
423
+
424
+ >>> from sympy.polys.domains import ZZ
425
+ >>> from sympy.polys.galoistools import gf_mul_ground
426
+
427
+ >>> gf_mul_ground([3, 2, 4], 2, 5, ZZ)
428
+ [1, 4, 3]
429
+
430
+ """
431
+ if not a:
432
+ return []
433
+ else:
434
+ return [ (a*b) % p for b in f ]
435
+
436
+
437
+ def gf_quo_ground(f, a, p, K):
438
+ """
439
+ Compute ``f/a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.
440
+
441
+ Examples
442
+ ========
443
+
444
+ >>> from sympy.polys.domains import ZZ
445
+ >>> from sympy.polys.galoistools import gf_quo_ground
446
+
447
+ >>> gf_quo_ground(ZZ.map([3, 2, 4]), ZZ(2), 5, ZZ)
448
+ [4, 1, 2]
449
+
450
+ """
451
+ return gf_mul_ground(f, K.invert(a, p), p, K)
452
+
453
+
454
+ def gf_add(f, g, p, K):
455
+ """
456
+ Add polynomials in ``GF(p)[x]``.
457
+
458
+ Examples
459
+ ========
460
+
461
+ >>> from sympy.polys.domains import ZZ
462
+ >>> from sympy.polys.galoistools import gf_add
463
+
464
+ >>> gf_add([3, 2, 4], [2, 2, 2], 5, ZZ)
465
+ [4, 1]
466
+
467
+ """
468
+ if not f:
469
+ return g
470
+ if not g:
471
+ return f
472
+
473
+ df = gf_degree(f)
474
+ dg = gf_degree(g)
475
+
476
+ if df == dg:
477
+ return gf_strip([ (a + b) % p for a, b in zip(f, g) ])
478
+ else:
479
+ k = abs(df - dg)
480
+
481
+ if df > dg:
482
+ h, f = f[:k], f[k:]
483
+ else:
484
+ h, g = g[:k], g[k:]
485
+
486
+ return h + [ (a + b) % p for a, b in zip(f, g) ]
487
+
488
+
489
+ def gf_sub(f, g, p, K):
490
+ """
491
+ Subtract polynomials in ``GF(p)[x]``.
492
+
493
+ Examples
494
+ ========
495
+
496
+ >>> from sympy.polys.domains import ZZ
497
+ >>> from sympy.polys.galoistools import gf_sub
498
+
499
+ >>> gf_sub([3, 2, 4], [2, 2, 2], 5, ZZ)
500
+ [1, 0, 2]
501
+
502
+ """
503
+ if not g:
504
+ return f
505
+ if not f:
506
+ return gf_neg(g, p, K)
507
+
508
+ df = gf_degree(f)
509
+ dg = gf_degree(g)
510
+
511
+ if df == dg:
512
+ return gf_strip([ (a - b) % p for a, b in zip(f, g) ])
513
+ else:
514
+ k = abs(df - dg)
515
+
516
+ if df > dg:
517
+ h, f = f[:k], f[k:]
518
+ else:
519
+ h, g = gf_neg(g[:k], p, K), g[k:]
520
+
521
+ return h + [ (a - b) % p for a, b in zip(f, g) ]
522
+
523
+
524
+ def gf_mul(f, g, p, K):
525
+ """
526
+ Multiply polynomials in ``GF(p)[x]``.
527
+
528
+ Examples
529
+ ========
530
+
531
+ >>> from sympy.polys.domains import ZZ
532
+ >>> from sympy.polys.galoistools import gf_mul
533
+
534
+ >>> gf_mul([3, 2, 4], [2, 2, 2], 5, ZZ)
535
+ [1, 0, 3, 2, 3]
536
+
537
+ """
538
+ df = gf_degree(f)
539
+ dg = gf_degree(g)
540
+
541
+ dh = df + dg
542
+ h = [0]*(dh + 1)
543
+
544
+ for i in range(0, dh + 1):
545
+ coeff = K.zero
546
+
547
+ for j in range(max(0, i - dg), min(i, df) + 1):
548
+ coeff += f[j]*g[i - j]
549
+
550
+ h[i] = coeff % p
551
+
552
+ return gf_strip(h)
553
+
554
+
555
+ def gf_sqr(f, p, K):
556
+ """
557
+ Square polynomials in ``GF(p)[x]``.
558
+
559
+ Examples
560
+ ========
561
+
562
+ >>> from sympy.polys.domains import ZZ
563
+ >>> from sympy.polys.galoistools import gf_sqr
564
+
565
+ >>> gf_sqr([3, 2, 4], 5, ZZ)
566
+ [4, 2, 3, 1, 1]
567
+
568
+ """
569
+ df = gf_degree(f)
570
+
571
+ dh = 2*df
572
+ h = [0]*(dh + 1)
573
+
574
+ for i in range(0, dh + 1):
575
+ coeff = K.zero
576
+
577
+ jmin = max(0, i - df)
578
+ jmax = min(i, df)
579
+
580
+ n = jmax - jmin + 1
581
+
582
+ jmax = jmin + n // 2 - 1
583
+
584
+ for j in range(jmin, jmax + 1):
585
+ coeff += f[j]*f[i - j]
586
+
587
+ coeff += coeff
588
+
589
+ if n & 1:
590
+ elem = f[jmax + 1]
591
+ coeff += elem**2
592
+
593
+ h[i] = coeff % p
594
+
595
+ return gf_strip(h)
596
+
597
+
598
+ def gf_add_mul(f, g, h, p, K):
599
+ """
600
+ Returns ``f + g*h`` where ``f``, ``g``, ``h`` in ``GF(p)[x]``.
601
+
602
+ Examples
603
+ ========
604
+
605
+ >>> from sympy.polys.domains import ZZ
606
+ >>> from sympy.polys.galoistools import gf_add_mul
607
+ >>> gf_add_mul([3, 2, 4], [2, 2, 2], [1, 4], 5, ZZ)
608
+ [2, 3, 2, 2]
609
+ """
610
+ return gf_add(f, gf_mul(g, h, p, K), p, K)
611
+
612
+
613
+ def gf_sub_mul(f, g, h, p, K):
614
+ """
615
+ Compute ``f - g*h`` where ``f``, ``g``, ``h`` in ``GF(p)[x]``.
616
+
617
+ Examples
618
+ ========
619
+
620
+ >>> from sympy.polys.domains import ZZ
621
+ >>> from sympy.polys.galoistools import gf_sub_mul
622
+
623
+ >>> gf_sub_mul([3, 2, 4], [2, 2, 2], [1, 4], 5, ZZ)
624
+ [3, 3, 2, 1]
625
+
626
+ """
627
+ return gf_sub(f, gf_mul(g, h, p, K), p, K)
628
+
629
+
630
+ def gf_expand(F, p, K):
631
+ """
632
+ Expand results of :func:`~.factor` in ``GF(p)[x]``.
633
+
634
+ Examples
635
+ ========
636
+
637
+ >>> from sympy.polys.domains import ZZ
638
+ >>> from sympy.polys.galoistools import gf_expand
639
+
640
+ >>> gf_expand([([3, 2, 4], 1), ([2, 2], 2), ([3, 1], 3)], 5, ZZ)
641
+ [4, 3, 0, 3, 0, 1, 4, 1]
642
+
643
+ """
644
+ if isinstance(F, tuple):
645
+ lc, F = F
646
+ else:
647
+ lc = K.one
648
+
649
+ g = [lc]
650
+
651
+ for f, k in F:
652
+ f = gf_pow(f, k, p, K)
653
+ g = gf_mul(g, f, p, K)
654
+
655
+ return g
656
+
657
+
658
+ def gf_div(f, g, p, K):
659
+ """
660
+ Division with remainder in ``GF(p)[x]``.
661
+
662
+ Given univariate polynomials ``f`` and ``g`` with coefficients in a
663
+ finite field with ``p`` elements, returns polynomials ``q`` and ``r``
664
+ (quotient and remainder) such that ``f = q*g + r``.
665
+
666
+ Consider polynomials ``x**3 + x + 1`` and ``x**2 + x`` in GF(2)::
667
+
668
+ >>> from sympy.polys.domains import ZZ
669
+ >>> from sympy.polys.galoistools import gf_div, gf_add_mul
670
+
671
+ >>> gf_div(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ)
672
+ ([1, 1], [1])
673
+
674
+ As result we obtained quotient ``x + 1`` and remainder ``1``, thus::
675
+
676
+ >>> gf_add_mul(ZZ.map([1]), ZZ.map([1, 1]), ZZ.map([1, 1, 0]), 2, ZZ)
677
+ [1, 0, 1, 1]
678
+
679
+ References
680
+ ==========
681
+
682
+ .. [1] [Monagan93]_
683
+ .. [2] [Gathen99]_
684
+
685
+ """
686
+ df = gf_degree(f)
687
+ dg = gf_degree(g)
688
+
689
+ if not g:
690
+ raise ZeroDivisionError("polynomial division")
691
+ elif df < dg:
692
+ return [], f
693
+
694
+ inv = K.invert(g[0], p)
695
+
696
+ h, dq, dr = list(f), df - dg, dg - 1
697
+
698
+ for i in range(0, df + 1):
699
+ coeff = h[i]
700
+
701
+ for j in range(max(0, dg - i), min(df - i, dr) + 1):
702
+ coeff -= h[i + j - dg] * g[dg - j]
703
+
704
+ if i <= dq:
705
+ coeff *= inv
706
+
707
+ h[i] = coeff % p
708
+
709
+ return h[:dq + 1], gf_strip(h[dq + 1:])
710
+
711
+
712
+ def gf_rem(f, g, p, K):
713
+ """
714
+ Compute polynomial remainder in ``GF(p)[x]``.
715
+
716
+ Examples
717
+ ========
718
+
719
+ >>> from sympy.polys.domains import ZZ
720
+ >>> from sympy.polys.galoistools import gf_rem
721
+
722
+ >>> gf_rem(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ)
723
+ [1]
724
+
725
+ """
726
+ return gf_div(f, g, p, K)[1]
727
+
728
+
729
+ def gf_quo(f, g, p, K):
730
+ """
731
+ Compute exact quotient in ``GF(p)[x]``.
732
+
733
+ Examples
734
+ ========
735
+
736
+ >>> from sympy.polys.domains import ZZ
737
+ >>> from sympy.polys.galoistools import gf_quo
738
+
739
+ >>> gf_quo(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ)
740
+ [1, 1]
741
+ >>> gf_quo(ZZ.map([1, 0, 3, 2, 3]), ZZ.map([2, 2, 2]), 5, ZZ)
742
+ [3, 2, 4]
743
+
744
+ """
745
+ df = gf_degree(f)
746
+ dg = gf_degree(g)
747
+
748
+ if not g:
749
+ raise ZeroDivisionError("polynomial division")
750
+ elif df < dg:
751
+ return []
752
+
753
+ inv = K.invert(g[0], p)
754
+
755
+ h, dq, dr = f[:], df - dg, dg - 1
756
+
757
+ for i in range(0, dq + 1):
758
+ coeff = h[i]
759
+
760
+ for j in range(max(0, dg - i), min(df - i, dr) + 1):
761
+ coeff -= h[i + j - dg] * g[dg - j]
762
+
763
+ h[i] = (coeff * inv) % p
764
+
765
+ return h[:dq + 1]
766
+
767
+
768
+ def gf_exquo(f, g, p, K):
769
+ """
770
+ Compute polynomial quotient in ``GF(p)[x]``.
771
+
772
+ Examples
773
+ ========
774
+
775
+ >>> from sympy.polys.domains import ZZ
776
+ >>> from sympy.polys.galoistools import gf_exquo
777
+
778
+ >>> gf_exquo(ZZ.map([1, 0, 3, 2, 3]), ZZ.map([2, 2, 2]), 5, ZZ)
779
+ [3, 2, 4]
780
+
781
+ >>> gf_exquo(ZZ.map([1, 0, 1, 1]), ZZ.map([1, 1, 0]), 2, ZZ)
782
+ Traceback (most recent call last):
783
+ ...
784
+ ExactQuotientFailed: [1, 1, 0] does not divide [1, 0, 1, 1]
785
+
786
+ """
787
+ q, r = gf_div(f, g, p, K)
788
+
789
+ if not r:
790
+ return q
791
+ else:
792
+ raise ExactQuotientFailed(f, g)
793
+
794
+
795
+ def gf_lshift(f, n, K):
796
+ """
797
+ Efficiently multiply ``f`` by ``x**n``.
798
+
799
+ Examples
800
+ ========
801
+
802
+ >>> from sympy.polys.domains import ZZ
803
+ >>> from sympy.polys.galoistools import gf_lshift
804
+
805
+ >>> gf_lshift([3, 2, 4], 4, ZZ)
806
+ [3, 2, 4, 0, 0, 0, 0]
807
+
808
+ """
809
+ if not f:
810
+ return f
811
+ else:
812
+ return f + [K.zero]*n
813
+
814
+
815
+ def gf_rshift(f, n, K):
816
+ """
817
+ Efficiently divide ``f`` by ``x**n``.
818
+
819
+ Examples
820
+ ========
821
+
822
+ >>> from sympy.polys.domains import ZZ
823
+ >>> from sympy.polys.galoistools import gf_rshift
824
+
825
+ >>> gf_rshift([1, 2, 3, 4, 0], 3, ZZ)
826
+ ([1, 2], [3, 4, 0])
827
+
828
+ """
829
+ if not n:
830
+ return f, []
831
+ else:
832
+ return f[:-n], f[-n:]
833
+
834
+
835
+ def gf_pow(f, n, p, K):
836
+ """
837
+ Compute ``f**n`` in ``GF(p)[x]`` using repeated squaring.
838
+
839
+ Examples
840
+ ========
841
+
842
+ >>> from sympy.polys.domains import ZZ
843
+ >>> from sympy.polys.galoistools import gf_pow
844
+
845
+ >>> gf_pow([3, 2, 4], 3, 5, ZZ)
846
+ [2, 4, 4, 2, 2, 1, 4]
847
+
848
+ """
849
+ if not n:
850
+ return [K.one]
851
+ elif n == 1:
852
+ return f
853
+ elif n == 2:
854
+ return gf_sqr(f, p, K)
855
+
856
+ h = [K.one]
857
+
858
+ while True:
859
+ if n & 1:
860
+ h = gf_mul(h, f, p, K)
861
+ n -= 1
862
+
863
+ n >>= 1
864
+
865
+ if not n:
866
+ break
867
+
868
+ f = gf_sqr(f, p, K)
869
+
870
+ return h
871
+
872
+ def gf_frobenius_monomial_base(g, p, K):
873
+ """
874
+ return the list of ``x**(i*p) mod g in Z_p`` for ``i = 0, .., n - 1``
875
+ where ``n = gf_degree(g)``
876
+
877
+ Examples
878
+ ========
879
+
880
+ >>> from sympy.polys.domains import ZZ
881
+ >>> from sympy.polys.galoistools import gf_frobenius_monomial_base
882
+ >>> g = ZZ.map([1, 0, 2, 1])
883
+ >>> gf_frobenius_monomial_base(g, 5, ZZ)
884
+ [[1], [4, 4, 2], [1, 2]]
885
+
886
+ """
887
+ n = gf_degree(g)
888
+ if n == 0:
889
+ return []
890
+ b = [0]*n
891
+ b[0] = [1]
892
+ if p < n:
893
+ for i in range(1, n):
894
+ mon = gf_lshift(b[i - 1], p, K)
895
+ b[i] = gf_rem(mon, g, p, K)
896
+ elif n > 1:
897
+ b[1] = gf_pow_mod([K.one, K.zero], p, g, p, K)
898
+ for i in range(2, n):
899
+ b[i] = gf_mul(b[i - 1], b[1], p, K)
900
+ b[i] = gf_rem(b[i], g, p, K)
901
+
902
+ return b
903
+
904
+ def gf_frobenius_map(f, g, b, p, K):
905
+ """
906
+ compute gf_pow_mod(f, p, g, p, K) using the Frobenius map
907
+
908
+ Parameters
909
+ ==========
910
+
911
+ f, g : polynomials in ``GF(p)[x]``
912
+ b : frobenius monomial base
913
+ p : prime number
914
+ K : domain
915
+
916
+ Examples
917
+ ========
918
+
919
+ >>> from sympy.polys.domains import ZZ
920
+ >>> from sympy.polys.galoistools import gf_frobenius_monomial_base, gf_frobenius_map
921
+ >>> f = ZZ.map([2, 1, 0, 1])
922
+ >>> g = ZZ.map([1, 0, 2, 1])
923
+ >>> p = 5
924
+ >>> b = gf_frobenius_monomial_base(g, p, ZZ)
925
+ >>> r = gf_frobenius_map(f, g, b, p, ZZ)
926
+ >>> gf_frobenius_map(f, g, b, p, ZZ)
927
+ [4, 0, 3]
928
+ """
929
+ m = gf_degree(g)
930
+ if gf_degree(f) >= m:
931
+ f = gf_rem(f, g, p, K)
932
+ if not f:
933
+ return []
934
+ n = gf_degree(f)
935
+ sf = [f[-1]]
936
+ for i in range(1, n + 1):
937
+ v = gf_mul_ground(b[i], f[n - i], p, K)
938
+ sf = gf_add(sf, v, p, K)
939
+ return sf
940
+
941
+ def _gf_pow_pnm1d2(f, n, g, b, p, K):
942
+ """
943
+ utility function for ``gf_edf_zassenhaus``
944
+ Compute ``f**((p**n - 1) // 2)`` in ``GF(p)[x]/(g)``
945
+ ``f**((p**n - 1) // 2) = (f*f**p*...*f**(p**n - 1))**((p - 1) // 2)``
946
+ """
947
+ f = gf_rem(f, g, p, K)
948
+ h = f
949
+ r = f
950
+ for i in range(1, n):
951
+ h = gf_frobenius_map(h, g, b, p, K)
952
+ r = gf_mul(r, h, p, K)
953
+ r = gf_rem(r, g, p, K)
954
+
955
+ res = gf_pow_mod(r, (p - 1)//2, g, p, K)
956
+ return res
957
+
958
+ def gf_pow_mod(f, n, g, p, K):
959
+ """
960
+ Compute ``f**n`` in ``GF(p)[x]/(g)`` using repeated squaring.
961
+
962
+ Given polynomials ``f`` and ``g`` in ``GF(p)[x]`` and a non-negative
963
+ integer ``n``, efficiently computes ``f**n (mod g)`` i.e. the remainder
964
+ of ``f**n`` from division by ``g``, using the repeated squaring algorithm.
965
+
966
+ Examples
967
+ ========
968
+
969
+ >>> from sympy.polys.domains import ZZ
970
+ >>> from sympy.polys.galoistools import gf_pow_mod
971
+
972
+ >>> gf_pow_mod(ZZ.map([3, 2, 4]), 3, ZZ.map([1, 1]), 5, ZZ)
973
+ []
974
+
975
+ References
976
+ ==========
977
+
978
+ .. [1] [Gathen99]_
979
+
980
+ """
981
+ if not n:
982
+ return [K.one]
983
+ elif n == 1:
984
+ return gf_rem(f, g, p, K)
985
+ elif n == 2:
986
+ return gf_rem(gf_sqr(f, p, K), g, p, K)
987
+
988
+ h = [K.one]
989
+
990
+ while True:
991
+ if n & 1:
992
+ h = gf_mul(h, f, p, K)
993
+ h = gf_rem(h, g, p, K)
994
+ n -= 1
995
+
996
+ n >>= 1
997
+
998
+ if not n:
999
+ break
1000
+
1001
+ f = gf_sqr(f, p, K)
1002
+ f = gf_rem(f, g, p, K)
1003
+
1004
+ return h
1005
+
1006
+
1007
+ def gf_gcd(f, g, p, K):
1008
+ """
1009
+ Euclidean Algorithm in ``GF(p)[x]``.
1010
+
1011
+ Examples
1012
+ ========
1013
+
1014
+ >>> from sympy.polys.domains import ZZ
1015
+ >>> from sympy.polys.galoistools import gf_gcd
1016
+
1017
+ >>> gf_gcd(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ)
1018
+ [1, 3]
1019
+
1020
+ """
1021
+ while g:
1022
+ f, g = g, gf_rem(f, g, p, K)
1023
+
1024
+ return gf_monic(f, p, K)[1]
1025
+
1026
+
1027
+ def gf_lcm(f, g, p, K):
1028
+ """
1029
+ Compute polynomial LCM in ``GF(p)[x]``.
1030
+
1031
+ Examples
1032
+ ========
1033
+
1034
+ >>> from sympy.polys.domains import ZZ
1035
+ >>> from sympy.polys.galoistools import gf_lcm
1036
+
1037
+ >>> gf_lcm(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ)
1038
+ [1, 2, 0, 4]
1039
+
1040
+ """
1041
+ if not f or not g:
1042
+ return []
1043
+
1044
+ h = gf_quo(gf_mul(f, g, p, K),
1045
+ gf_gcd(f, g, p, K), p, K)
1046
+
1047
+ return gf_monic(h, p, K)[1]
1048
+
1049
+
1050
+ def gf_cofactors(f, g, p, K):
1051
+ """
1052
+ Compute polynomial GCD and cofactors in ``GF(p)[x]``.
1053
+
1054
+ Examples
1055
+ ========
1056
+
1057
+ >>> from sympy.polys.domains import ZZ
1058
+ >>> from sympy.polys.galoistools import gf_cofactors
1059
+
1060
+ >>> gf_cofactors(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 3]), 5, ZZ)
1061
+ ([1, 3], [3, 3], [2, 1])
1062
+
1063
+ """
1064
+ if not f and not g:
1065
+ return ([], [], [])
1066
+
1067
+ h = gf_gcd(f, g, p, K)
1068
+
1069
+ return (h, gf_quo(f, h, p, K),
1070
+ gf_quo(g, h, p, K))
1071
+
1072
+
1073
+ def gf_gcdex(f, g, p, K):
1074
+ """
1075
+ Extended Euclidean Algorithm in ``GF(p)[x]``.
1076
+
1077
+ Given polynomials ``f`` and ``g`` in ``GF(p)[x]``, computes polynomials
1078
+ ``s``, ``t`` and ``h``, such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.
1079
+ The typical application of EEA is solving polynomial diophantine equations.
1080
+
1081
+ Consider polynomials ``f = (x + 7) (x + 1)``, ``g = (x + 7) (x**2 + 1)``
1082
+ in ``GF(11)[x]``. Application of Extended Euclidean Algorithm gives::
1083
+
1084
+ >>> from sympy.polys.domains import ZZ
1085
+ >>> from sympy.polys.galoistools import gf_gcdex, gf_mul, gf_add
1086
+
1087
+ >>> s, t, g = gf_gcdex(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ)
1088
+ >>> s, t, g
1089
+ ([5, 6], [6], [1, 7])
1090
+
1091
+ As result we obtained polynomials ``s = 5*x + 6`` and ``t = 6``, and
1092
+ additionally ``gcd(f, g) = x + 7``. This is correct because::
1093
+
1094
+ >>> S = gf_mul(s, ZZ.map([1, 8, 7]), 11, ZZ)
1095
+ >>> T = gf_mul(t, ZZ.map([1, 7, 1, 7]), 11, ZZ)
1096
+
1097
+ >>> gf_add(S, T, 11, ZZ) == [1, 7]
1098
+ True
1099
+
1100
+ References
1101
+ ==========
1102
+
1103
+ .. [1] [Gathen99]_
1104
+
1105
+ """
1106
+ if not (f or g):
1107
+ return [K.one], [], []
1108
+
1109
+ p0, r0 = gf_monic(f, p, K)
1110
+ p1, r1 = gf_monic(g, p, K)
1111
+
1112
+ if not f:
1113
+ return [], [K.invert(p1, p)], r1
1114
+ if not g:
1115
+ return [K.invert(p0, p)], [], r0
1116
+
1117
+ s0, s1 = [K.invert(p0, p)], []
1118
+ t0, t1 = [], [K.invert(p1, p)]
1119
+
1120
+ while True:
1121
+ Q, R = gf_div(r0, r1, p, K)
1122
+
1123
+ if not R:
1124
+ break
1125
+
1126
+ (lc, r1), r0 = gf_monic(R, p, K), r1
1127
+
1128
+ inv = K.invert(lc, p)
1129
+
1130
+ s = gf_sub_mul(s0, s1, Q, p, K)
1131
+ t = gf_sub_mul(t0, t1, Q, p, K)
1132
+
1133
+ s1, s0 = gf_mul_ground(s, inv, p, K), s1
1134
+ t1, t0 = gf_mul_ground(t, inv, p, K), t1
1135
+
1136
+ return s1, t1, r1
1137
+
1138
+
1139
+ def gf_monic(f, p, K):
1140
+ """
1141
+ Compute LC and a monic polynomial in ``GF(p)[x]``.
1142
+
1143
+ Examples
1144
+ ========
1145
+
1146
+ >>> from sympy.polys.domains import ZZ
1147
+ >>> from sympy.polys.galoistools import gf_monic
1148
+
1149
+ >>> gf_monic(ZZ.map([3, 2, 4]), 5, ZZ)
1150
+ (3, [1, 4, 3])
1151
+
1152
+ """
1153
+ if not f:
1154
+ return K.zero, []
1155
+ else:
1156
+ lc = f[0]
1157
+
1158
+ if K.is_one(lc):
1159
+ return lc, list(f)
1160
+ else:
1161
+ return lc, gf_quo_ground(f, lc, p, K)
1162
+
1163
+
1164
+ def gf_diff(f, p, K):
1165
+ """
1166
+ Differentiate polynomial in ``GF(p)[x]``.
1167
+
1168
+ Examples
1169
+ ========
1170
+
1171
+ >>> from sympy.polys.domains import ZZ
1172
+ >>> from sympy.polys.galoistools import gf_diff
1173
+
1174
+ >>> gf_diff([3, 2, 4], 5, ZZ)
1175
+ [1, 2]
1176
+
1177
+ """
1178
+ df = gf_degree(f)
1179
+
1180
+ h, n = [K.zero]*df, df
1181
+
1182
+ for coeff in f[:-1]:
1183
+ coeff *= K(n)
1184
+ coeff %= p
1185
+
1186
+ if coeff:
1187
+ h[df - n] = coeff
1188
+
1189
+ n -= 1
1190
+
1191
+ return gf_strip(h)
1192
+
1193
+
1194
+ def gf_eval(f, a, p, K):
1195
+ """
1196
+ Evaluate ``f(a)`` in ``GF(p)`` using Horner scheme.
1197
+
1198
+ Examples
1199
+ ========
1200
+
1201
+ >>> from sympy.polys.domains import ZZ
1202
+ >>> from sympy.polys.galoistools import gf_eval
1203
+
1204
+ >>> gf_eval([3, 2, 4], 2, 5, ZZ)
1205
+ 0
1206
+
1207
+ """
1208
+ result = K.zero
1209
+
1210
+ for c in f:
1211
+ result *= a
1212
+ result += c
1213
+ result %= p
1214
+
1215
+ return result
1216
+
1217
+
1218
+ def gf_multi_eval(f, A, p, K):
1219
+ """
1220
+ Evaluate ``f(a)`` for ``a`` in ``[a_1, ..., a_n]``.
1221
+
1222
+ Examples
1223
+ ========
1224
+
1225
+ >>> from sympy.polys.domains import ZZ
1226
+ >>> from sympy.polys.galoistools import gf_multi_eval
1227
+
1228
+ >>> gf_multi_eval([3, 2, 4], [0, 1, 2, 3, 4], 5, ZZ)
1229
+ [4, 4, 0, 2, 0]
1230
+
1231
+ """
1232
+ return [ gf_eval(f, a, p, K) for a in A ]
1233
+
1234
+
1235
+ def gf_compose(f, g, p, K):
1236
+ """
1237
+ Compute polynomial composition ``f(g)`` in ``GF(p)[x]``.
1238
+
1239
+ Examples
1240
+ ========
1241
+
1242
+ >>> from sympy.polys.domains import ZZ
1243
+ >>> from sympy.polys.galoistools import gf_compose
1244
+
1245
+ >>> gf_compose([3, 2, 4], [2, 2, 2], 5, ZZ)
1246
+ [2, 4, 0, 3, 0]
1247
+
1248
+ """
1249
+ if len(g) <= 1:
1250
+ return gf_strip([gf_eval(f, gf_LC(g, K), p, K)])
1251
+
1252
+ if not f:
1253
+ return []
1254
+
1255
+ h = [f[0]]
1256
+
1257
+ for c in f[1:]:
1258
+ h = gf_mul(h, g, p, K)
1259
+ h = gf_add_ground(h, c, p, K)
1260
+
1261
+ return h
1262
+
1263
+
1264
+ def gf_compose_mod(g, h, f, p, K):
1265
+ """
1266
+ Compute polynomial composition ``g(h)`` in ``GF(p)[x]/(f)``.
1267
+
1268
+ Examples
1269
+ ========
1270
+
1271
+ >>> from sympy.polys.domains import ZZ
1272
+ >>> from sympy.polys.galoistools import gf_compose_mod
1273
+
1274
+ >>> gf_compose_mod(ZZ.map([3, 2, 4]), ZZ.map([2, 2, 2]), ZZ.map([4, 3]), 5, ZZ)
1275
+ [4]
1276
+
1277
+ """
1278
+ if not g:
1279
+ return []
1280
+
1281
+ comp = [g[0]]
1282
+
1283
+ for a in g[1:]:
1284
+ comp = gf_mul(comp, h, p, K)
1285
+ comp = gf_add_ground(comp, a, p, K)
1286
+ comp = gf_rem(comp, f, p, K)
1287
+
1288
+ return comp
1289
+
1290
+
1291
+ def gf_trace_map(a, b, c, n, f, p, K):
1292
+ """
1293
+ Compute polynomial trace map in ``GF(p)[x]/(f)``.
1294
+
1295
+ Given a polynomial ``f`` in ``GF(p)[x]``, polynomials ``a``, ``b``,
1296
+ ``c`` in the quotient ring ``GF(p)[x]/(f)`` such that ``b = c**t
1297
+ (mod f)`` for some positive power ``t`` of ``p``, and a positive
1298
+ integer ``n``, returns a mapping::
1299
+
1300
+ a -> a**t**n, a + a**t + a**t**2 + ... + a**t**n (mod f)
1301
+
1302
+ In factorization context, ``b = x**p mod f`` and ``c = x mod f``.
1303
+ This way we can efficiently compute trace polynomials in equal
1304
+ degree factorization routine, much faster than with other methods,
1305
+ like iterated Frobenius algorithm, for large degrees.
1306
+
1307
+ Examples
1308
+ ========
1309
+
1310
+ >>> from sympy.polys.domains import ZZ
1311
+ >>> from sympy.polys.galoistools import gf_trace_map
1312
+
1313
+ >>> gf_trace_map([1, 2], [4, 4], [1, 1], 4, [3, 2, 4], 5, ZZ)
1314
+ ([1, 3], [1, 3])
1315
+
1316
+ References
1317
+ ==========
1318
+
1319
+ .. [1] [Gathen92]_
1320
+
1321
+ """
1322
+ u = gf_compose_mod(a, b, f, p, K)
1323
+ v = b
1324
+
1325
+ if n & 1:
1326
+ U = gf_add(a, u, p, K)
1327
+ V = b
1328
+ else:
1329
+ U = a
1330
+ V = c
1331
+
1332
+ n >>= 1
1333
+
1334
+ while n:
1335
+ u = gf_add(u, gf_compose_mod(u, v, f, p, K), p, K)
1336
+ v = gf_compose_mod(v, v, f, p, K)
1337
+
1338
+ if n & 1:
1339
+ U = gf_add(U, gf_compose_mod(u, V, f, p, K), p, K)
1340
+ V = gf_compose_mod(v, V, f, p, K)
1341
+
1342
+ n >>= 1
1343
+
1344
+ return gf_compose_mod(a, V, f, p, K), U
1345
+
1346
+ def _gf_trace_map(f, n, g, b, p, K):
1347
+ """
1348
+ utility for ``gf_edf_shoup``
1349
+ """
1350
+ f = gf_rem(f, g, p, K)
1351
+ h = f
1352
+ r = f
1353
+ for i in range(1, n):
1354
+ h = gf_frobenius_map(h, g, b, p, K)
1355
+ r = gf_add(r, h, p, K)
1356
+ r = gf_rem(r, g, p, K)
1357
+ return r
1358
+
1359
+
1360
+ def gf_random(n, p, K):
1361
+ """
1362
+ Generate a random polynomial in ``GF(p)[x]`` of degree ``n``.
1363
+
1364
+ Examples
1365
+ ========
1366
+
1367
+ >>> from sympy.polys.domains import ZZ
1368
+ >>> from sympy.polys.galoistools import gf_random
1369
+ >>> gf_random(10, 5, ZZ) #doctest: +SKIP
1370
+ [1, 2, 3, 2, 1, 1, 1, 2, 0, 4, 2]
1371
+
1372
+ """
1373
+ return [K.one] + [ K(int(uniform(0, p))) for i in range(0, n) ]
1374
+
1375
+
1376
+ def gf_irreducible(n, p, K):
1377
+ """
1378
+ Generate random irreducible polynomial of degree ``n`` in ``GF(p)[x]``.
1379
+
1380
+ Examples
1381
+ ========
1382
+
1383
+ >>> from sympy.polys.domains import ZZ
1384
+ >>> from sympy.polys.galoistools import gf_irreducible
1385
+ >>> gf_irreducible(10, 5, ZZ) #doctest: +SKIP
1386
+ [1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]
1387
+
1388
+ """
1389
+ while True:
1390
+ f = gf_random(n, p, K)
1391
+ if gf_irreducible_p(f, p, K):
1392
+ return f
1393
+
1394
+
1395
+ def gf_irred_p_ben_or(f, p, K):
1396
+ """
1397
+ Ben-Or's polynomial irreducibility test over finite fields.
1398
+
1399
+ Examples
1400
+ ========
1401
+
1402
+ >>> from sympy.polys.domains import ZZ
1403
+ >>> from sympy.polys.galoistools import gf_irred_p_ben_or
1404
+
1405
+ >>> gf_irred_p_ben_or(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ)
1406
+ True
1407
+ >>> gf_irred_p_ben_or(ZZ.map([3, 2, 4]), 5, ZZ)
1408
+ False
1409
+
1410
+ """
1411
+ n = gf_degree(f)
1412
+
1413
+ if n <= 1:
1414
+ return True
1415
+
1416
+ _, f = gf_monic(f, p, K)
1417
+ if n < 5:
1418
+ H = h = gf_pow_mod([K.one, K.zero], p, f, p, K)
1419
+
1420
+ for i in range(0, n//2):
1421
+ g = gf_sub(h, [K.one, K.zero], p, K)
1422
+
1423
+ if gf_gcd(f, g, p, K) == [K.one]:
1424
+ h = gf_compose_mod(h, H, f, p, K)
1425
+ else:
1426
+ return False
1427
+ else:
1428
+ b = gf_frobenius_monomial_base(f, p, K)
1429
+ H = h = gf_frobenius_map([K.one, K.zero], f, b, p, K)
1430
+ for i in range(0, n//2):
1431
+ g = gf_sub(h, [K.one, K.zero], p, K)
1432
+ if gf_gcd(f, g, p, K) == [K.one]:
1433
+ h = gf_frobenius_map(h, f, b, p, K)
1434
+ else:
1435
+ return False
1436
+
1437
+ return True
1438
+
1439
+
1440
+ def gf_irred_p_rabin(f, p, K):
1441
+ """
1442
+ Rabin's polynomial irreducibility test over finite fields.
1443
+
1444
+ Examples
1445
+ ========
1446
+
1447
+ >>> from sympy.polys.domains import ZZ
1448
+ >>> from sympy.polys.galoistools import gf_irred_p_rabin
1449
+
1450
+ >>> gf_irred_p_rabin(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ)
1451
+ True
1452
+ >>> gf_irred_p_rabin(ZZ.map([3, 2, 4]), 5, ZZ)
1453
+ False
1454
+
1455
+ """
1456
+ n = gf_degree(f)
1457
+
1458
+ if n <= 1:
1459
+ return True
1460
+
1461
+ _, f = gf_monic(f, p, K)
1462
+
1463
+ x = [K.one, K.zero]
1464
+
1465
+ from sympy.ntheory import factorint
1466
+
1467
+ indices = { n//d for d in factorint(n) }
1468
+
1469
+ b = gf_frobenius_monomial_base(f, p, K)
1470
+ h = b[1]
1471
+
1472
+ for i in range(1, n):
1473
+ if i in indices:
1474
+ g = gf_sub(h, x, p, K)
1475
+
1476
+ if gf_gcd(f, g, p, K) != [K.one]:
1477
+ return False
1478
+
1479
+ h = gf_frobenius_map(h, f, b, p, K)
1480
+
1481
+ return h == x
1482
+
1483
+ _irred_methods = {
1484
+ 'ben-or': gf_irred_p_ben_or,
1485
+ 'rabin': gf_irred_p_rabin,
1486
+ }
1487
+
1488
+
1489
+ def gf_irreducible_p(f, p, K):
1490
+ """
1491
+ Test irreducibility of a polynomial ``f`` in ``GF(p)[x]``.
1492
+
1493
+ Examples
1494
+ ========
1495
+
1496
+ >>> from sympy.polys.domains import ZZ
1497
+ >>> from sympy.polys.galoistools import gf_irreducible_p
1498
+
1499
+ >>> gf_irreducible_p(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ)
1500
+ True
1501
+ >>> gf_irreducible_p(ZZ.map([3, 2, 4]), 5, ZZ)
1502
+ False
1503
+
1504
+ """
1505
+ method = query('GF_IRRED_METHOD')
1506
+
1507
+ if method is not None:
1508
+ irred = _irred_methods[method](f, p, K)
1509
+ else:
1510
+ irred = gf_irred_p_rabin(f, p, K)
1511
+
1512
+ return irred
1513
+
1514
+
1515
+ def gf_sqf_p(f, p, K):
1516
+ """
1517
+ Return ``True`` if ``f`` is square-free in ``GF(p)[x]``.
1518
+
1519
+ Examples
1520
+ ========
1521
+
1522
+ >>> from sympy.polys.domains import ZZ
1523
+ >>> from sympy.polys.galoistools import gf_sqf_p
1524
+
1525
+ >>> gf_sqf_p(ZZ.map([3, 2, 4]), 5, ZZ)
1526
+ True
1527
+ >>> gf_sqf_p(ZZ.map([2, 4, 4, 2, 2, 1, 4]), 5, ZZ)
1528
+ False
1529
+
1530
+ """
1531
+ _, f = gf_monic(f, p, K)
1532
+
1533
+ if not f:
1534
+ return True
1535
+ else:
1536
+ return gf_gcd(f, gf_diff(f, p, K), p, K) == [K.one]
1537
+
1538
+
1539
+ def gf_sqf_part(f, p, K):
1540
+ """
1541
+ Return square-free part of a ``GF(p)[x]`` polynomial.
1542
+
1543
+ Examples
1544
+ ========
1545
+
1546
+ >>> from sympy.polys.domains import ZZ
1547
+ >>> from sympy.polys.galoistools import gf_sqf_part
1548
+
1549
+ >>> gf_sqf_part(ZZ.map([1, 1, 3, 0, 1, 0, 2, 2, 1]), 5, ZZ)
1550
+ [1, 4, 3]
1551
+
1552
+ """
1553
+ _, sqf = gf_sqf_list(f, p, K)
1554
+
1555
+ g = [K.one]
1556
+
1557
+ for f, _ in sqf:
1558
+ g = gf_mul(g, f, p, K)
1559
+
1560
+ return g
1561
+
1562
+
1563
+ def gf_sqf_list(f, p, K, all=False):
1564
+ """
1565
+ Return the square-free decomposition of a ``GF(p)[x]`` polynomial.
1566
+
1567
+ Given a polynomial ``f`` in ``GF(p)[x]``, returns the leading coefficient
1568
+ of ``f`` and a square-free decomposition ``f_1**e_1 f_2**e_2 ... f_k**e_k``
1569
+ such that all ``f_i`` are monic polynomials and ``(f_i, f_j)`` for ``i != j``
1570
+ are co-prime and ``e_1 ... e_k`` are given in increasing order. All trivial
1571
+ terms (i.e. ``f_i = 1``) are not included in the output.
1572
+
1573
+ Consider polynomial ``f = x**11 + 1`` over ``GF(11)[x]``::
1574
+
1575
+ >>> from sympy.polys.domains import ZZ
1576
+
1577
+ >>> from sympy.polys.galoistools import (
1578
+ ... gf_from_dict, gf_diff, gf_sqf_list, gf_pow,
1579
+ ... )
1580
+ ... # doctest: +NORMALIZE_WHITESPACE
1581
+
1582
+ >>> f = gf_from_dict({11: ZZ(1), 0: ZZ(1)}, 11, ZZ)
1583
+
1584
+ Note that ``f'(x) = 0``::
1585
+
1586
+ >>> gf_diff(f, 11, ZZ)
1587
+ []
1588
+
1589
+ This phenomenon does not happen in characteristic zero. However we can
1590
+ still compute square-free decomposition of ``f`` using ``gf_sqf()``::
1591
+
1592
+ >>> gf_sqf_list(f, 11, ZZ)
1593
+ (1, [([1, 1], 11)])
1594
+
1595
+ We obtained factorization ``f = (x + 1)**11``. This is correct because::
1596
+
1597
+ >>> gf_pow([1, 1], 11, 11, ZZ) == f
1598
+ True
1599
+
1600
+ References
1601
+ ==========
1602
+
1603
+ .. [1] [Geddes92]_
1604
+
1605
+ """
1606
+ n, sqf, factors, r = 1, False, [], int(p)
1607
+
1608
+ lc, f = gf_monic(f, p, K)
1609
+
1610
+ if gf_degree(f) < 1:
1611
+ return lc, []
1612
+
1613
+ while True:
1614
+ F = gf_diff(f, p, K)
1615
+
1616
+ if F != []:
1617
+ g = gf_gcd(f, F, p, K)
1618
+ h = gf_quo(f, g, p, K)
1619
+
1620
+ i = 1
1621
+
1622
+ while h != [K.one]:
1623
+ G = gf_gcd(g, h, p, K)
1624
+ H = gf_quo(h, G, p, K)
1625
+
1626
+ if gf_degree(H) > 0:
1627
+ factors.append((H, i*n))
1628
+
1629
+ g, h, i = gf_quo(g, G, p, K), G, i + 1
1630
+
1631
+ if g == [K.one]:
1632
+ sqf = True
1633
+ else:
1634
+ f = g
1635
+
1636
+ if not sqf:
1637
+ d = gf_degree(f) // r
1638
+
1639
+ for i in range(0, d + 1):
1640
+ f[i] = f[i*r]
1641
+
1642
+ f, n = f[:d + 1], n*r
1643
+ else:
1644
+ break
1645
+
1646
+ if all:
1647
+ raise ValueError("'all=True' is not supported yet")
1648
+
1649
+ return lc, factors
1650
+
1651
+
1652
+ def gf_Qmatrix(f, p, K):
1653
+ """
1654
+ Calculate Berlekamp's ``Q`` matrix.
1655
+
1656
+ Examples
1657
+ ========
1658
+
1659
+ >>> from sympy.polys.domains import ZZ
1660
+ >>> from sympy.polys.galoistools import gf_Qmatrix
1661
+
1662
+ >>> gf_Qmatrix([3, 2, 4], 5, ZZ)
1663
+ [[1, 0],
1664
+ [3, 4]]
1665
+
1666
+ >>> gf_Qmatrix([1, 0, 0, 0, 1], 5, ZZ)
1667
+ [[1, 0, 0, 0],
1668
+ [0, 4, 0, 0],
1669
+ [0, 0, 1, 0],
1670
+ [0, 0, 0, 4]]
1671
+
1672
+ """
1673
+ n, r = gf_degree(f), int(p)
1674
+
1675
+ q = [K.one] + [K.zero]*(n - 1)
1676
+ Q = [list(q)] + [[]]*(n - 1)
1677
+
1678
+ for i in range(1, (n - 1)*r + 1):
1679
+ qq, c = [(-q[-1]*f[-1]) % p], q[-1]
1680
+
1681
+ for j in range(1, n):
1682
+ qq.append((q[j - 1] - c*f[-j - 1]) % p)
1683
+
1684
+ if not (i % r):
1685
+ Q[i//r] = list(qq)
1686
+
1687
+ q = qq
1688
+
1689
+ return Q
1690
+
1691
+
1692
+ def gf_Qbasis(Q, p, K):
1693
+ """
1694
+ Compute a basis of the kernel of ``Q``.
1695
+
1696
+ Examples
1697
+ ========
1698
+
1699
+ >>> from sympy.polys.domains import ZZ
1700
+ >>> from sympy.polys.galoistools import gf_Qmatrix, gf_Qbasis
1701
+
1702
+ >>> gf_Qbasis(gf_Qmatrix([1, 0, 0, 0, 1], 5, ZZ), 5, ZZ)
1703
+ [[1, 0, 0, 0], [0, 0, 1, 0]]
1704
+
1705
+ >>> gf_Qbasis(gf_Qmatrix([3, 2, 4], 5, ZZ), 5, ZZ)
1706
+ [[1, 0]]
1707
+
1708
+ """
1709
+ Q, n = [ list(q) for q in Q ], len(Q)
1710
+
1711
+ for k in range(0, n):
1712
+ Q[k][k] = (Q[k][k] - K.one) % p
1713
+
1714
+ for k in range(0, n):
1715
+ for i in range(k, n):
1716
+ if Q[k][i]:
1717
+ break
1718
+ else:
1719
+ continue
1720
+
1721
+ inv = K.invert(Q[k][i], p)
1722
+
1723
+ for j in range(0, n):
1724
+ Q[j][i] = (Q[j][i]*inv) % p
1725
+
1726
+ for j in range(0, n):
1727
+ t = Q[j][k]
1728
+ Q[j][k] = Q[j][i]
1729
+ Q[j][i] = t
1730
+
1731
+ for i in range(0, n):
1732
+ if i != k:
1733
+ q = Q[k][i]
1734
+
1735
+ for j in range(0, n):
1736
+ Q[j][i] = (Q[j][i] - Q[j][k]*q) % p
1737
+
1738
+ for i in range(0, n):
1739
+ for j in range(0, n):
1740
+ if i == j:
1741
+ Q[i][j] = (K.one - Q[i][j]) % p
1742
+ else:
1743
+ Q[i][j] = (-Q[i][j]) % p
1744
+
1745
+ basis = []
1746
+
1747
+ for q in Q:
1748
+ if any(q):
1749
+ basis.append(q)
1750
+
1751
+ return basis
1752
+
1753
+
1754
+ def gf_berlekamp(f, p, K):
1755
+ """
1756
+ Factor a square-free ``f`` in ``GF(p)[x]`` for small ``p``.
1757
+
1758
+ Examples
1759
+ ========
1760
+
1761
+ >>> from sympy.polys.domains import ZZ
1762
+ >>> from sympy.polys.galoistools import gf_berlekamp
1763
+
1764
+ >>> gf_berlekamp([1, 0, 0, 0, 1], 5, ZZ)
1765
+ [[1, 0, 2], [1, 0, 3]]
1766
+
1767
+ """
1768
+ Q = gf_Qmatrix(f, p, K)
1769
+ V = gf_Qbasis(Q, p, K)
1770
+
1771
+ for i, v in enumerate(V):
1772
+ V[i] = gf_strip(list(reversed(v)))
1773
+
1774
+ factors = [f]
1775
+
1776
+ for k in range(1, len(V)):
1777
+ for f in list(factors):
1778
+ s = K.zero
1779
+
1780
+ while s < p:
1781
+ g = gf_sub_ground(V[k], s, p, K)
1782
+ h = gf_gcd(f, g, p, K)
1783
+
1784
+ if h != [K.one] and h != f:
1785
+ factors.remove(f)
1786
+
1787
+ f = gf_quo(f, h, p, K)
1788
+ factors.extend([f, h])
1789
+
1790
+ if len(factors) == len(V):
1791
+ return _sort_factors(factors, multiple=False)
1792
+
1793
+ s += K.one
1794
+
1795
+ return _sort_factors(factors, multiple=False)
1796
+
1797
+
1798
+ def gf_ddf_zassenhaus(f, p, K):
1799
+ """
1800
+ Cantor-Zassenhaus: Deterministic Distinct Degree Factorization
1801
+
1802
+ Given a monic square-free polynomial ``f`` in ``GF(p)[x]``, computes
1803
+ partial distinct degree factorization ``f_1 ... f_d`` of ``f`` where
1804
+ ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a
1805
+ list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0``
1806
+ is an argument to the equal degree factorization routine.
1807
+
1808
+ Consider the polynomial ``x**15 - 1`` in ``GF(11)[x]``::
1809
+
1810
+ >>> from sympy.polys.domains import ZZ
1811
+ >>> from sympy.polys.galoistools import gf_from_dict
1812
+
1813
+ >>> f = gf_from_dict({15: ZZ(1), 0: ZZ(-1)}, 11, ZZ)
1814
+
1815
+ Distinct degree factorization gives::
1816
+
1817
+ >>> from sympy.polys.galoistools import gf_ddf_zassenhaus
1818
+
1819
+ >>> gf_ddf_zassenhaus(f, 11, ZZ)
1820
+ [([1, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 2)]
1821
+
1822
+ which means ``x**15 - 1 = (x**5 - 1) (x**10 + x**5 + 1)``. To obtain
1823
+ factorization into irreducibles, use equal degree factorization
1824
+ procedure (EDF) with each of the factors.
1825
+
1826
+ References
1827
+ ==========
1828
+
1829
+ .. [1] [Gathen99]_
1830
+ .. [2] [Geddes92]_
1831
+
1832
+ """
1833
+ i, g, factors = 1, [K.one, K.zero], []
1834
+
1835
+ b = gf_frobenius_monomial_base(f, p, K)
1836
+ while 2*i <= gf_degree(f):
1837
+ g = gf_frobenius_map(g, f, b, p, K)
1838
+ h = gf_gcd(f, gf_sub(g, [K.one, K.zero], p, K), p, K)
1839
+
1840
+ if h != [K.one]:
1841
+ factors.append((h, i))
1842
+
1843
+ f = gf_quo(f, h, p, K)
1844
+ g = gf_rem(g, f, p, K)
1845
+ b = gf_frobenius_monomial_base(f, p, K)
1846
+
1847
+ i += 1
1848
+
1849
+ if f != [K.one]:
1850
+ return factors + [(f, gf_degree(f))]
1851
+ else:
1852
+ return factors
1853
+
1854
+
1855
+ def gf_edf_zassenhaus(f, n, p, K):
1856
+ """
1857
+ Cantor-Zassenhaus: Probabilistic Equal Degree Factorization
1858
+
1859
+ Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and
1860
+ an integer ``n``, such that ``n`` divides ``deg(f)``, returns all
1861
+ irreducible factors ``f_1,...,f_d`` of ``f``, each of degree ``n``.
1862
+ EDF procedure gives complete factorization over Galois fields.
1863
+
1864
+ Consider the square-free polynomial ``f = x**3 + x**2 + x + 1`` in
1865
+ ``GF(5)[x]``. Let's compute its irreducible factors of degree one::
1866
+
1867
+ >>> from sympy.polys.domains import ZZ
1868
+ >>> from sympy.polys.galoistools import gf_edf_zassenhaus
1869
+
1870
+ >>> gf_edf_zassenhaus([1,1,1,1], 1, 5, ZZ)
1871
+ [[1, 1], [1, 2], [1, 3]]
1872
+
1873
+ Notes
1874
+ =====
1875
+
1876
+ The case p == 2 is handled by Cohen's Algorithm 3.4.8. The case p odd is
1877
+ as in Geddes Algorithm 8.9 (or Cohen's Algorithm 3.4.6).
1878
+
1879
+ References
1880
+ ==========
1881
+
1882
+ .. [1] [Gathen99]_
1883
+ .. [2] [Geddes92]_ Algorithm 8.9
1884
+ .. [3] [Cohen93]_ Algorithm 3.4.8
1885
+
1886
+ """
1887
+ factors = [f]
1888
+
1889
+ if gf_degree(f) <= n:
1890
+ return factors
1891
+
1892
+ N = gf_degree(f) // n
1893
+ if p != 2:
1894
+ b = gf_frobenius_monomial_base(f, p, K)
1895
+
1896
+ t = [K.one, K.zero]
1897
+ while len(factors) < N:
1898
+ if p == 2:
1899
+ h = r = t
1900
+
1901
+ for i in range(n - 1):
1902
+ r = gf_pow_mod(r, 2, f, p, K)
1903
+ h = gf_add(h, r, p, K)
1904
+
1905
+ g = gf_gcd(f, h, p, K)
1906
+ t += [K.zero, K.zero]
1907
+ else:
1908
+ r = gf_random(2 * n - 1, p, K)
1909
+ h = _gf_pow_pnm1d2(r, n, f, b, p, K)
1910
+ g = gf_gcd(f, gf_sub_ground(h, K.one, p, K), p, K)
1911
+
1912
+ if g != [K.one] and g != f:
1913
+ factors = gf_edf_zassenhaus(g, n, p, K) \
1914
+ + gf_edf_zassenhaus(gf_quo(f, g, p, K), n, p, K)
1915
+
1916
+ return _sort_factors(factors, multiple=False)
1917
+
1918
+
1919
+ def gf_ddf_shoup(f, p, K):
1920
+ """
1921
+ Kaltofen-Shoup: Deterministic Distinct Degree Factorization
1922
+
1923
+ Given a monic square-free polynomial ``f`` in ``GF(p)[x]``, computes
1924
+ partial distinct degree factorization ``f_1,...,f_d`` of ``f`` where
1925
+ ``deg(f_i) != deg(f_j)`` for ``i != j``. The result is returned as a
1926
+ list of pairs ``(f_i, e_i)`` where ``deg(f_i) > 0`` and ``e_i > 0``
1927
+ is an argument to the equal degree factorization routine.
1928
+
1929
+ This algorithm is an improved version of Zassenhaus algorithm for
1930
+ large ``deg(f)`` and modulus ``p`` (especially for ``deg(f) ~ lg(p)``).
1931
+
1932
+ Examples
1933
+ ========
1934
+
1935
+ >>> from sympy.polys.domains import ZZ
1936
+ >>> from sympy.polys.galoistools import gf_ddf_shoup, gf_from_dict
1937
+
1938
+ >>> f = gf_from_dict({6: ZZ(1), 5: ZZ(-1), 4: ZZ(1), 3: ZZ(1), 1: ZZ(-1)}, 3, ZZ)
1939
+
1940
+ >>> gf_ddf_shoup(f, 3, ZZ)
1941
+ [([1, 1, 0], 1), ([1, 1, 0, 1, 2], 2)]
1942
+
1943
+ References
1944
+ ==========
1945
+
1946
+ .. [1] [Kaltofen98]_
1947
+ .. [2] [Shoup95]_
1948
+ .. [3] [Gathen92]_
1949
+
1950
+ """
1951
+ n = gf_degree(f)
1952
+ k = int(_ceil(_sqrt(n//2)))
1953
+ b = gf_frobenius_monomial_base(f, p, K)
1954
+ h = gf_frobenius_map([K.one, K.zero], f, b, p, K)
1955
+ # U[i] = x**(p**i)
1956
+ U = [[K.one, K.zero], h] + [K.zero]*(k - 1)
1957
+
1958
+ for i in range(2, k + 1):
1959
+ U[i] = gf_frobenius_map(U[i-1], f, b, p, K)
1960
+
1961
+ h, U = U[k], U[:k]
1962
+ # V[i] = x**(p**(k*(i+1)))
1963
+ V = [h] + [K.zero]*(k - 1)
1964
+
1965
+ for i in range(1, k):
1966
+ V[i] = gf_compose_mod(V[i - 1], h, f, p, K)
1967
+
1968
+ factors = []
1969
+
1970
+ for i, v in enumerate(V):
1971
+ h, j = [K.one], k - 1
1972
+
1973
+ for u in U:
1974
+ g = gf_sub(v, u, p, K)
1975
+ h = gf_mul(h, g, p, K)
1976
+ h = gf_rem(h, f, p, K)
1977
+
1978
+ g = gf_gcd(f, h, p, K)
1979
+ f = gf_quo(f, g, p, K)
1980
+
1981
+ for u in reversed(U):
1982
+ h = gf_sub(v, u, p, K)
1983
+ F = gf_gcd(g, h, p, K)
1984
+
1985
+ if F != [K.one]:
1986
+ factors.append((F, k*(i + 1) - j))
1987
+
1988
+ g, j = gf_quo(g, F, p, K), j - 1
1989
+
1990
+ if f != [K.one]:
1991
+ factors.append((f, gf_degree(f)))
1992
+
1993
+ return factors
1994
+
1995
+ def gf_edf_shoup(f, n, p, K):
1996
+ """
1997
+ Gathen-Shoup: Probabilistic Equal Degree Factorization
1998
+
1999
+ Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and integer
2000
+ ``n`` such that ``n`` divides ``deg(f)``, returns all irreducible factors
2001
+ ``f_1,...,f_d`` of ``f``, each of degree ``n``. This is a complete
2002
+ factorization over Galois fields.
2003
+
2004
+ This algorithm is an improved version of Zassenhaus algorithm for
2005
+ large ``deg(f)`` and modulus ``p`` (especially for ``deg(f) ~ lg(p)``).
2006
+
2007
+ Examples
2008
+ ========
2009
+
2010
+ >>> from sympy.polys.domains import ZZ
2011
+ >>> from sympy.polys.galoistools import gf_edf_shoup
2012
+
2013
+ >>> gf_edf_shoup(ZZ.map([1, 2837, 2277]), 1, 2917, ZZ)
2014
+ [[1, 852], [1, 1985]]
2015
+
2016
+ References
2017
+ ==========
2018
+
2019
+ .. [1] [Shoup91]_
2020
+ .. [2] [Gathen92]_
2021
+
2022
+ """
2023
+ N, q = gf_degree(f), int(p)
2024
+
2025
+ if not N:
2026
+ return []
2027
+ if N <= n:
2028
+ return [f]
2029
+
2030
+ factors, x = [f], [K.one, K.zero]
2031
+
2032
+ r = gf_random(N - 1, p, K)
2033
+
2034
+ if p == 2:
2035
+ h = gf_pow_mod(x, q, f, p, K)
2036
+ H = gf_trace_map(r, h, x, n - 1, f, p, K)[1]
2037
+ h1 = gf_gcd(f, H, p, K)
2038
+ h2 = gf_quo(f, h1, p, K)
2039
+
2040
+ factors = gf_edf_shoup(h1, n, p, K) \
2041
+ + gf_edf_shoup(h2, n, p, K)
2042
+ else:
2043
+ b = gf_frobenius_monomial_base(f, p, K)
2044
+ H = _gf_trace_map(r, n, f, b, p, K)
2045
+ h = gf_pow_mod(H, (q - 1)//2, f, p, K)
2046
+
2047
+ h1 = gf_gcd(f, h, p, K)
2048
+ h2 = gf_gcd(f, gf_sub_ground(h, K.one, p, K), p, K)
2049
+ h3 = gf_quo(f, gf_mul(h1, h2, p, K), p, K)
2050
+
2051
+ factors = gf_edf_shoup(h1, n, p, K) \
2052
+ + gf_edf_shoup(h2, n, p, K) \
2053
+ + gf_edf_shoup(h3, n, p, K)
2054
+
2055
+ return _sort_factors(factors, multiple=False)
2056
+
2057
+
2058
+ def gf_zassenhaus(f, p, K):
2059
+ """
2060
+ Factor a square-free ``f`` in ``GF(p)[x]`` for medium ``p``.
2061
+
2062
+ Examples
2063
+ ========
2064
+
2065
+ >>> from sympy.polys.domains import ZZ
2066
+ >>> from sympy.polys.galoistools import gf_zassenhaus
2067
+
2068
+ >>> gf_zassenhaus(ZZ.map([1, 4, 3]), 5, ZZ)
2069
+ [[1, 1], [1, 3]]
2070
+
2071
+ """
2072
+ factors = []
2073
+
2074
+ for factor, n in gf_ddf_zassenhaus(f, p, K):
2075
+ factors += gf_edf_zassenhaus(factor, n, p, K)
2076
+
2077
+ return _sort_factors(factors, multiple=False)
2078
+
2079
+
2080
+ def gf_shoup(f, p, K):
2081
+ """
2082
+ Factor a square-free ``f`` in ``GF(p)[x]`` for large ``p``.
2083
+
2084
+ Examples
2085
+ ========
2086
+
2087
+ >>> from sympy.polys.domains import ZZ
2088
+ >>> from sympy.polys.galoistools import gf_shoup
2089
+
2090
+ >>> gf_shoup(ZZ.map([1, 4, 3]), 5, ZZ)
2091
+ [[1, 1], [1, 3]]
2092
+
2093
+ """
2094
+ factors = []
2095
+
2096
+ for factor, n in gf_ddf_shoup(f, p, K):
2097
+ factors += gf_edf_shoup(factor, n, p, K)
2098
+
2099
+ return _sort_factors(factors, multiple=False)
2100
+
2101
+ _factor_methods = {
2102
+ 'berlekamp': gf_berlekamp, # ``p`` : small
2103
+ 'zassenhaus': gf_zassenhaus, # ``p`` : medium
2104
+ 'shoup': gf_shoup, # ``p`` : large
2105
+ }
2106
+
2107
+
2108
+ def gf_factor_sqf(f, p, K, method=None):
2109
+ """
2110
+ Factor a square-free polynomial ``f`` in ``GF(p)[x]``.
2111
+
2112
+ Examples
2113
+ ========
2114
+
2115
+ >>> from sympy.polys.domains import ZZ
2116
+ >>> from sympy.polys.galoistools import gf_factor_sqf
2117
+
2118
+ >>> gf_factor_sqf(ZZ.map([3, 2, 4]), 5, ZZ)
2119
+ (3, [[1, 1], [1, 3]])
2120
+
2121
+ """
2122
+ lc, f = gf_monic(f, p, K)
2123
+
2124
+ if gf_degree(f) < 1:
2125
+ return lc, []
2126
+
2127
+ method = method or query('GF_FACTOR_METHOD')
2128
+
2129
+ if method is not None:
2130
+ factors = _factor_methods[method](f, p, K)
2131
+ else:
2132
+ factors = gf_zassenhaus(f, p, K)
2133
+
2134
+ return lc, factors
2135
+
2136
+
2137
+ def gf_factor(f, p, K):
2138
+ """
2139
+ Factor (non square-free) polynomials in ``GF(p)[x]``.
2140
+
2141
+ Given a possibly non square-free polynomial ``f`` in ``GF(p)[x]``,
2142
+ returns its complete factorization into irreducibles::
2143
+
2144
+ f_1(x)**e_1 f_2(x)**e_2 ... f_d(x)**e_d
2145
+
2146
+ where each ``f_i`` is a monic polynomial and ``gcd(f_i, f_j) == 1``,
2147
+ for ``i != j``. The result is given as a tuple consisting of the
2148
+ leading coefficient of ``f`` and a list of factors of ``f`` with
2149
+ their multiplicities.
2150
+
2151
+ The algorithm proceeds by first computing square-free decomposition
2152
+ of ``f`` and then iteratively factoring each of square-free factors.
2153
+
2154
+ Consider a non square-free polynomial ``f = (7*x + 1) (x + 2)**2`` in
2155
+ ``GF(11)[x]``. We obtain its factorization into irreducibles as follows::
2156
+
2157
+ >>> from sympy.polys.domains import ZZ
2158
+ >>> from sympy.polys.galoistools import gf_factor
2159
+
2160
+ >>> gf_factor(ZZ.map([5, 2, 7, 2]), 11, ZZ)
2161
+ (5, [([1, 2], 1), ([1, 8], 2)])
2162
+
2163
+ We arrived with factorization ``f = 5 (x + 2) (x + 8)**2``. We did not
2164
+ recover the exact form of the input polynomial because we requested to
2165
+ get monic factors of ``f`` and its leading coefficient separately.
2166
+
2167
+ Square-free factors of ``f`` can be factored into irreducibles over
2168
+ ``GF(p)`` using three very different methods:
2169
+
2170
+ Berlekamp
2171
+ efficient for very small values of ``p`` (usually ``p < 25``)
2172
+ Cantor-Zassenhaus
2173
+ efficient on average input and with "typical" ``p``
2174
+ Shoup-Kaltofen-Gathen
2175
+ efficient with very large inputs and modulus
2176
+
2177
+ If you want to use a specific factorization method, instead of the default
2178
+ one, set ``GF_FACTOR_METHOD`` with one of ``berlekamp``, ``zassenhaus`` or
2179
+ ``shoup`` values.
2180
+
2181
+ References
2182
+ ==========
2183
+
2184
+ .. [1] [Gathen99]_
2185
+
2186
+ """
2187
+ lc, f = gf_monic(f, p, K)
2188
+
2189
+ if gf_degree(f) < 1:
2190
+ return lc, []
2191
+
2192
+ factors = []
2193
+
2194
+ for g, n in gf_sqf_list(f, p, K)[1]:
2195
+ for h in gf_factor_sqf(g, p, K)[1]:
2196
+ factors.append((h, n))
2197
+
2198
+ return lc, _sort_factors(factors)
2199
+
2200
+
2201
+ def gf_value(f, a):
2202
+ """
2203
+ Value of polynomial 'f' at 'a' in field R.
2204
+
2205
+ Examples
2206
+ ========
2207
+
2208
+ >>> from sympy.polys.galoistools import gf_value
2209
+
2210
+ >>> gf_value([1, 7, 2, 4], 11)
2211
+ 2204
2212
+
2213
+ """
2214
+ result = 0
2215
+ for c in f:
2216
+ result *= a
2217
+ result += c
2218
+ return result
2219
+
2220
+
2221
+ def linear_congruence(a, b, m):
2222
+ """
2223
+ Returns the values of x satisfying a*x congruent b mod(m)
2224
+
2225
+ Here m is positive integer and a, b are natural numbers.
2226
+ This function returns only those values of x which are distinct mod(m).
2227
+
2228
+ Examples
2229
+ ========
2230
+
2231
+ >>> from sympy.polys.galoistools import linear_congruence
2232
+
2233
+ >>> linear_congruence(3, 12, 15)
2234
+ [4, 9, 14]
2235
+
2236
+ There are 3 solutions distinct mod(15) since gcd(a, m) = gcd(3, 15) = 3.
2237
+
2238
+ References
2239
+ ==========
2240
+
2241
+ .. [1] https://en.wikipedia.org/wiki/Linear_congruence_theorem
2242
+
2243
+ """
2244
+ from sympy.polys.polytools import gcdex
2245
+ if a % m == 0:
2246
+ if b % m == 0:
2247
+ return list(range(m))
2248
+ else:
2249
+ return []
2250
+ r, _, g = gcdex(a, m)
2251
+ if b % g != 0:
2252
+ return []
2253
+ return [(r * b // g + t * m // g) % m for t in range(g)]
2254
+
2255
+
2256
+ def _raise_mod_power(x, s, p, f):
2257
+ """
2258
+ Used in gf_csolve to generate solutions of f(x) cong 0 mod(p**(s + 1))
2259
+ from the solutions of f(x) cong 0 mod(p**s).
2260
+
2261
+ Examples
2262
+ ========
2263
+
2264
+ >>> from sympy.polys.galoistools import _raise_mod_power
2265
+ >>> from sympy.polys.galoistools import csolve_prime
2266
+
2267
+ These is the solutions of f(x) = x**2 + x + 7 cong 0 mod(3)
2268
+
2269
+ >>> f = [1, 1, 7]
2270
+ >>> csolve_prime(f, 3)
2271
+ [1]
2272
+ >>> [ i for i in range(3) if not (i**2 + i + 7) % 3]
2273
+ [1]
2274
+
2275
+ The solutions of f(x) cong 0 mod(9) are constructed from the
2276
+ values returned from _raise_mod_power:
2277
+
2278
+ >>> x, s, p = 1, 1, 3
2279
+ >>> V = _raise_mod_power(x, s, p, f)
2280
+ >>> [x + v * p**s for v in V]
2281
+ [1, 4, 7]
2282
+
2283
+ And these are confirmed with the following:
2284
+
2285
+ >>> [ i for i in range(3**2) if not (i**2 + i + 7) % 3**2]
2286
+ [1, 4, 7]
2287
+
2288
+ """
2289
+ from sympy.polys.domains import ZZ
2290
+ f_f = gf_diff(f, p, ZZ)
2291
+ alpha = gf_value(f_f, x)
2292
+ beta = - gf_value(f, x) // p**s
2293
+ return linear_congruence(alpha, beta, p)
2294
+
2295
+
2296
+ def csolve_prime(f, p, e=1):
2297
+ """
2298
+ Solutions of f(x) congruent 0 mod(p**e).
2299
+
2300
+ Examples
2301
+ ========
2302
+
2303
+ >>> from sympy.polys.galoistools import csolve_prime
2304
+
2305
+ >>> csolve_prime([1, 1, 7], 3, 1)
2306
+ [1]
2307
+ >>> csolve_prime([1, 1, 7], 3, 2)
2308
+ [1, 4, 7]
2309
+
2310
+ Solutions [7, 4, 1] (mod 3**2) are generated by ``_raise_mod_power()``
2311
+ from solution [1] (mod 3).
2312
+ """
2313
+ from sympy.polys.domains import ZZ
2314
+ X1 = [i for i in range(p) if gf_eval(f, i, p, ZZ) == 0]
2315
+ if e == 1:
2316
+ return X1
2317
+ X = []
2318
+ S = list(zip(X1, [1]*len(X1)))
2319
+ while S:
2320
+ x, s = S.pop()
2321
+ if s == e:
2322
+ X.append(x)
2323
+ else:
2324
+ s1 = s + 1
2325
+ ps = p**s
2326
+ S.extend([(x + v*ps, s1) for v in _raise_mod_power(x, s, p, f)])
2327
+ return sorted(X)
2328
+
2329
+
2330
+ def gf_csolve(f, n):
2331
+ """
2332
+ To solve f(x) congruent 0 mod(n).
2333
+
2334
+ n is divided into canonical factors and f(x) cong 0 mod(p**e) will be
2335
+ solved for each factor. Applying the Chinese Remainder Theorem to the
2336
+ results returns the final answers.
2337
+
2338
+ Examples
2339
+ ========
2340
+
2341
+ Solve [1, 1, 7] congruent 0 mod(189):
2342
+
2343
+ >>> from sympy.polys.galoistools import gf_csolve
2344
+ >>> gf_csolve([1, 1, 7], 189)
2345
+ [13, 49, 76, 112, 139, 175]
2346
+
2347
+ References
2348
+ ==========
2349
+
2350
+ .. [1] 'An introduction to the Theory of Numbers' 5th Edition by Ivan Niven,
2351
+ Zuckerman and Montgomery.
2352
+
2353
+ """
2354
+ from sympy.polys.domains import ZZ
2355
+ from sympy.ntheory import factorint
2356
+ P = factorint(n)
2357
+ X = [csolve_prime(f, p, e) for p, e in P.items()]
2358
+ pools = list(map(tuple, X))
2359
+ perms = [[]]
2360
+ for pool in pools:
2361
+ perms = [x + [y] for x in perms for y in pool]
2362
+ dist_factors = [pow(p, e) for p, e in P.items()]
2363
+ return sorted([gf_crt(per, dist_factors, ZZ) for per in perms])
llmeval-env/lib/python3.10/site-packages/sympy/polys/groebnertools.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Groebner bases algorithms. """
2
+
3
+
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.polys.monomials import monomial_mul, monomial_lcm, monomial_divides, term_div
6
+ from sympy.polys.orderings import lex
7
+ from sympy.polys.polyerrors import DomainError
8
+ from sympy.polys.polyconfig import query
9
+
10
+ def groebner(seq, ring, method=None):
11
+ """
12
+ Computes Groebner basis for a set of polynomials in `K[X]`.
13
+
14
+ Wrapper around the (default) improved Buchberger and the other algorithms
15
+ for computing Groebner bases. The choice of algorithm can be changed via
16
+ ``method`` argument or :func:`sympy.polys.polyconfig.setup`, where
17
+ ``method`` can be either ``buchberger`` or ``f5b``.
18
+
19
+ """
20
+ if method is None:
21
+ method = query('groebner')
22
+
23
+ _groebner_methods = {
24
+ 'buchberger': _buchberger,
25
+ 'f5b': _f5b,
26
+ }
27
+
28
+ try:
29
+ _groebner = _groebner_methods[method]
30
+ except KeyError:
31
+ raise ValueError("'%s' is not a valid Groebner bases algorithm (valid are 'buchberger' and 'f5b')" % method)
32
+
33
+ domain, orig = ring.domain, None
34
+
35
+ if not domain.is_Field or not domain.has_assoc_Field:
36
+ try:
37
+ orig, ring = ring, ring.clone(domain=domain.get_field())
38
+ except DomainError:
39
+ raise DomainError("Cannot compute a Groebner basis over %s" % domain)
40
+ else:
41
+ seq = [ s.set_ring(ring) for s in seq ]
42
+
43
+ G = _groebner(seq, ring)
44
+
45
+ if orig is not None:
46
+ G = [ g.clear_denoms()[1].set_ring(orig) for g in G ]
47
+
48
+ return G
49
+
50
+ def _buchberger(f, ring):
51
+ """
52
+ Computes Groebner basis for a set of polynomials in `K[X]`.
53
+
54
+ Given a set of multivariate polynomials `F`, finds another
55
+ set `G`, such that Ideal `F = Ideal G` and `G` is a reduced
56
+ Groebner basis.
57
+
58
+ The resulting basis is unique and has monic generators if the
59
+ ground domains is a field. Otherwise the result is non-unique
60
+ but Groebner bases over e.g. integers can be computed (if the
61
+ input polynomials are monic).
62
+
63
+ Groebner bases can be used to choose specific generators for a
64
+ polynomial ideal. Because these bases are unique you can check
65
+ for ideal equality by comparing the Groebner bases. To see if
66
+ one polynomial lies in an ideal, divide by the elements in the
67
+ base and see if the remainder vanishes.
68
+
69
+ They can also be used to solve systems of polynomial equations
70
+ as, by choosing lexicographic ordering, you can eliminate one
71
+ variable at a time, provided that the ideal is zero-dimensional
72
+ (finite number of solutions).
73
+
74
+ Notes
75
+ =====
76
+
77
+ Algorithm used: an improved version of Buchberger's algorithm
78
+ as presented in T. Becker, V. Weispfenning, Groebner Bases: A
79
+ Computational Approach to Commutative Algebra, Springer, 1993,
80
+ page 232.
81
+
82
+ References
83
+ ==========
84
+
85
+ .. [1] [Bose03]_
86
+ .. [2] [Giovini91]_
87
+ .. [3] [Ajwa95]_
88
+ .. [4] [Cox97]_
89
+
90
+ """
91
+ order = ring.order
92
+
93
+ monomial_mul = ring.monomial_mul
94
+ monomial_div = ring.monomial_div
95
+ monomial_lcm = ring.monomial_lcm
96
+
97
+ def select(P):
98
+ # normal selection strategy
99
+ # select the pair with minimum LCM(LM(f), LM(g))
100
+ pr = min(P, key=lambda pair: order(monomial_lcm(f[pair[0]].LM, f[pair[1]].LM)))
101
+ return pr
102
+
103
+ def normal(g, J):
104
+ h = g.rem([ f[j] for j in J ])
105
+
106
+ if not h:
107
+ return None
108
+ else:
109
+ h = h.monic()
110
+
111
+ if h not in I:
112
+ I[h] = len(f)
113
+ f.append(h)
114
+
115
+ return h.LM, I[h]
116
+
117
+ def update(G, B, ih):
118
+ # update G using the set of critical pairs B and h
119
+ # [BW] page 230
120
+ h = f[ih]
121
+ mh = h.LM
122
+
123
+ # filter new pairs (h, g), g in G
124
+ C = G.copy()
125
+ D = set()
126
+
127
+ while C:
128
+ # select a pair (h, g) by popping an element from C
129
+ ig = C.pop()
130
+ g = f[ig]
131
+ mg = g.LM
132
+ LCMhg = monomial_lcm(mh, mg)
133
+
134
+ def lcm_divides(ip):
135
+ # LCM(LM(h), LM(p)) divides LCM(LM(h), LM(g))
136
+ m = monomial_lcm(mh, f[ip].LM)
137
+ return monomial_div(LCMhg, m)
138
+
139
+ # HT(h) and HT(g) disjoint: mh*mg == LCMhg
140
+ if monomial_mul(mh, mg) == LCMhg or (
141
+ not any(lcm_divides(ipx) for ipx in C) and
142
+ not any(lcm_divides(pr[1]) for pr in D)):
143
+ D.add((ih, ig))
144
+
145
+ E = set()
146
+
147
+ while D:
148
+ # select h, g from D (h the same as above)
149
+ ih, ig = D.pop()
150
+ mg = f[ig].LM
151
+ LCMhg = monomial_lcm(mh, mg)
152
+
153
+ if not monomial_mul(mh, mg) == LCMhg:
154
+ E.add((ih, ig))
155
+
156
+ # filter old pairs
157
+ B_new = set()
158
+
159
+ while B:
160
+ # select g1, g2 from B (-> CP)
161
+ ig1, ig2 = B.pop()
162
+ mg1 = f[ig1].LM
163
+ mg2 = f[ig2].LM
164
+ LCM12 = monomial_lcm(mg1, mg2)
165
+
166
+ # if HT(h) does not divide lcm(HT(g1), HT(g2))
167
+ if not monomial_div(LCM12, mh) or \
168
+ monomial_lcm(mg1, mh) == LCM12 or \
169
+ monomial_lcm(mg2, mh) == LCM12:
170
+ B_new.add((ig1, ig2))
171
+
172
+ B_new |= E
173
+
174
+ # filter polynomials
175
+ G_new = set()
176
+
177
+ while G:
178
+ ig = G.pop()
179
+ mg = f[ig].LM
180
+
181
+ if not monomial_div(mg, mh):
182
+ G_new.add(ig)
183
+
184
+ G_new.add(ih)
185
+
186
+ return G_new, B_new
187
+ # end of update ################################
188
+
189
+ if not f:
190
+ return []
191
+
192
+ # replace f with a reduced list of initial polynomials; see [BW] page 203
193
+ f1 = f[:]
194
+
195
+ while True:
196
+ f = f1[:]
197
+ f1 = []
198
+
199
+ for i in range(len(f)):
200
+ p = f[i]
201
+ r = p.rem(f[:i])
202
+
203
+ if r:
204
+ f1.append(r.monic())
205
+
206
+ if f == f1:
207
+ break
208
+
209
+ I = {} # ip = I[p]; p = f[ip]
210
+ F = set() # set of indices of polynomials
211
+ G = set() # set of indices of intermediate would-be Groebner basis
212
+ CP = set() # set of pairs of indices of critical pairs
213
+
214
+ for i, h in enumerate(f):
215
+ I[h] = i
216
+ F.add(i)
217
+
218
+ #####################################
219
+ # algorithm GROEBNERNEWS2 in [BW] page 232
220
+
221
+ while F:
222
+ # select p with minimum monomial according to the monomial ordering
223
+ h = min([f[x] for x in F], key=lambda f: order(f.LM))
224
+ ih = I[h]
225
+ F.remove(ih)
226
+ G, CP = update(G, CP, ih)
227
+
228
+ # count the number of critical pairs which reduce to zero
229
+ reductions_to_zero = 0
230
+
231
+ while CP:
232
+ ig1, ig2 = select(CP)
233
+ CP.remove((ig1, ig2))
234
+
235
+ h = spoly(f[ig1], f[ig2], ring)
236
+ # ordering divisors is on average more efficient [Cox] page 111
237
+ G1 = sorted(G, key=lambda g: order(f[g].LM))
238
+ ht = normal(h, G1)
239
+
240
+ if ht:
241
+ G, CP = update(G, CP, ht[1])
242
+ else:
243
+ reductions_to_zero += 1
244
+
245
+ ######################################
246
+ # now G is a Groebner basis; reduce it
247
+ Gr = set()
248
+
249
+ for ig in G:
250
+ ht = normal(f[ig], G - {ig})
251
+
252
+ if ht:
253
+ Gr.add(ht[1])
254
+
255
+ Gr = [f[ig] for ig in Gr]
256
+
257
+ # order according to the monomial ordering
258
+ Gr = sorted(Gr, key=lambda f: order(f.LM), reverse=True)
259
+
260
+ return Gr
261
+
262
+ def spoly(p1, p2, ring):
263
+ """
264
+ Compute LCM(LM(p1), LM(p2))/LM(p1)*p1 - LCM(LM(p1), LM(p2))/LM(p2)*p2
265
+ This is the S-poly provided p1 and p2 are monic
266
+ """
267
+ LM1 = p1.LM
268
+ LM2 = p2.LM
269
+ LCM12 = ring.monomial_lcm(LM1, LM2)
270
+ m1 = ring.monomial_div(LCM12, LM1)
271
+ m2 = ring.monomial_div(LCM12, LM2)
272
+ s1 = p1.mul_monom(m1)
273
+ s2 = p2.mul_monom(m2)
274
+ s = s1 - s2
275
+ return s
276
+
277
+ # F5B
278
+
279
+ # convenience functions
280
+
281
+
282
+ def Sign(f):
283
+ return f[0]
284
+
285
+
286
+ def Polyn(f):
287
+ return f[1]
288
+
289
+
290
+ def Num(f):
291
+ return f[2]
292
+
293
+
294
+ def sig(monomial, index):
295
+ return (monomial, index)
296
+
297
+
298
+ def lbp(signature, polynomial, number):
299
+ return (signature, polynomial, number)
300
+
301
+ # signature functions
302
+
303
+
304
+ def sig_cmp(u, v, order):
305
+ """
306
+ Compare two signatures by extending the term order to K[X]^n.
307
+
308
+ u < v iff
309
+ - the index of v is greater than the index of u
310
+ or
311
+ - the index of v is equal to the index of u and u[0] < v[0] w.r.t. order
312
+
313
+ u > v otherwise
314
+ """
315
+ if u[1] > v[1]:
316
+ return -1
317
+ if u[1] == v[1]:
318
+ #if u[0] == v[0]:
319
+ # return 0
320
+ if order(u[0]) < order(v[0]):
321
+ return -1
322
+ return 1
323
+
324
+
325
+ def sig_key(s, order):
326
+ """
327
+ Key for comparing two signatures.
328
+
329
+ s = (m, k), t = (n, l)
330
+
331
+ s < t iff [k > l] or [k == l and m < n]
332
+ s > t otherwise
333
+ """
334
+ return (-s[1], order(s[0]))
335
+
336
+
337
+ def sig_mult(s, m):
338
+ """
339
+ Multiply a signature by a monomial.
340
+
341
+ The product of a signature (m, i) and a monomial n is defined as
342
+ (m * t, i).
343
+ """
344
+ return sig(monomial_mul(s[0], m), s[1])
345
+
346
+ # labeled polynomial functions
347
+
348
+
349
+ def lbp_sub(f, g):
350
+ """
351
+ Subtract labeled polynomial g from f.
352
+
353
+ The signature and number of the difference of f and g are signature
354
+ and number of the maximum of f and g, w.r.t. lbp_cmp.
355
+ """
356
+ if sig_cmp(Sign(f), Sign(g), Polyn(f).ring.order) < 0:
357
+ max_poly = g
358
+ else:
359
+ max_poly = f
360
+
361
+ ret = Polyn(f) - Polyn(g)
362
+
363
+ return lbp(Sign(max_poly), ret, Num(max_poly))
364
+
365
+
366
+ def lbp_mul_term(f, cx):
367
+ """
368
+ Multiply a labeled polynomial with a term.
369
+
370
+ The product of a labeled polynomial (s, p, k) by a monomial is
371
+ defined as (m * s, m * p, k).
372
+ """
373
+ return lbp(sig_mult(Sign(f), cx[0]), Polyn(f).mul_term(cx), Num(f))
374
+
375
+
376
+ def lbp_cmp(f, g):
377
+ """
378
+ Compare two labeled polynomials.
379
+
380
+ f < g iff
381
+ - Sign(f) < Sign(g)
382
+ or
383
+ - Sign(f) == Sign(g) and Num(f) > Num(g)
384
+
385
+ f > g otherwise
386
+ """
387
+ if sig_cmp(Sign(f), Sign(g), Polyn(f).ring.order) == -1:
388
+ return -1
389
+ if Sign(f) == Sign(g):
390
+ if Num(f) > Num(g):
391
+ return -1
392
+ #if Num(f) == Num(g):
393
+ # return 0
394
+ return 1
395
+
396
+
397
+ def lbp_key(f):
398
+ """
399
+ Key for comparing two labeled polynomials.
400
+ """
401
+ return (sig_key(Sign(f), Polyn(f).ring.order), -Num(f))
402
+
403
+ # algorithm and helper functions
404
+
405
+
406
+ def critical_pair(f, g, ring):
407
+ """
408
+ Compute the critical pair corresponding to two labeled polynomials.
409
+
410
+ A critical pair is a tuple (um, f, vm, g), where um and vm are
411
+ terms such that um * f - vm * g is the S-polynomial of f and g (so,
412
+ wlog assume um * f > vm * g).
413
+ For performance sake, a critical pair is represented as a tuple
414
+ (Sign(um * f), um, f, Sign(vm * g), vm, g), since um * f creates
415
+ a new, relatively expensive object in memory, whereas Sign(um *
416
+ f) and um are lightweight and f (in the tuple) is a reference to
417
+ an already existing object in memory.
418
+ """
419
+ domain = ring.domain
420
+
421
+ ltf = Polyn(f).LT
422
+ ltg = Polyn(g).LT
423
+ lt = (monomial_lcm(ltf[0], ltg[0]), domain.one)
424
+
425
+ um = term_div(lt, ltf, domain)
426
+ vm = term_div(lt, ltg, domain)
427
+
428
+ # The full information is not needed (now), so only the product
429
+ # with the leading term is considered:
430
+ fr = lbp_mul_term(lbp(Sign(f), Polyn(f).leading_term(), Num(f)), um)
431
+ gr = lbp_mul_term(lbp(Sign(g), Polyn(g).leading_term(), Num(g)), vm)
432
+
433
+ # return in proper order, such that the S-polynomial is just
434
+ # u_first * f_first - u_second * f_second:
435
+ if lbp_cmp(fr, gr) == -1:
436
+ return (Sign(gr), vm, g, Sign(fr), um, f)
437
+ else:
438
+ return (Sign(fr), um, f, Sign(gr), vm, g)
439
+
440
+
441
+ def cp_cmp(c, d):
442
+ """
443
+ Compare two critical pairs c and d.
444
+
445
+ c < d iff
446
+ - lbp(c[0], _, Num(c[2]) < lbp(d[0], _, Num(d[2])) (this
447
+ corresponds to um_c * f_c and um_d * f_d)
448
+ or
449
+ - lbp(c[0], _, Num(c[2]) >< lbp(d[0], _, Num(d[2])) and
450
+ lbp(c[3], _, Num(c[5])) < lbp(d[3], _, Num(d[5])) (this
451
+ corresponds to vm_c * g_c and vm_d * g_d)
452
+
453
+ c > d otherwise
454
+ """
455
+ zero = Polyn(c[2]).ring.zero
456
+
457
+ c0 = lbp(c[0], zero, Num(c[2]))
458
+ d0 = lbp(d[0], zero, Num(d[2]))
459
+
460
+ r = lbp_cmp(c0, d0)
461
+
462
+ if r == -1:
463
+ return -1
464
+ if r == 0:
465
+ c1 = lbp(c[3], zero, Num(c[5]))
466
+ d1 = lbp(d[3], zero, Num(d[5]))
467
+
468
+ r = lbp_cmp(c1, d1)
469
+
470
+ if r == -1:
471
+ return -1
472
+ #if r == 0:
473
+ # return 0
474
+ return 1
475
+
476
+
477
+ def cp_key(c, ring):
478
+ """
479
+ Key for comparing critical pairs.
480
+ """
481
+ return (lbp_key(lbp(c[0], ring.zero, Num(c[2]))), lbp_key(lbp(c[3], ring.zero, Num(c[5]))))
482
+
483
+
484
+ def s_poly(cp):
485
+ """
486
+ Compute the S-polynomial of a critical pair.
487
+
488
+ The S-polynomial of a critical pair cp is cp[1] * cp[2] - cp[4] * cp[5].
489
+ """
490
+ return lbp_sub(lbp_mul_term(cp[2], cp[1]), lbp_mul_term(cp[5], cp[4]))
491
+
492
+
493
+ def is_rewritable_or_comparable(sign, num, B):
494
+ """
495
+ Check if a labeled polynomial is redundant by checking if its
496
+ signature and number imply rewritability or comparability.
497
+
498
+ (sign, num) is comparable if there exists a labeled polynomial
499
+ h in B, such that sign[1] (the index) is less than Sign(h)[1]
500
+ and sign[0] is divisible by the leading monomial of h.
501
+
502
+ (sign, num) is rewritable if there exists a labeled polynomial
503
+ h in B, such thatsign[1] is equal to Sign(h)[1], num < Num(h)
504
+ and sign[0] is divisible by Sign(h)[0].
505
+ """
506
+ for h in B:
507
+ # comparable
508
+ if sign[1] < Sign(h)[1]:
509
+ if monomial_divides(Polyn(h).LM, sign[0]):
510
+ return True
511
+
512
+ # rewritable
513
+ if sign[1] == Sign(h)[1]:
514
+ if num < Num(h):
515
+ if monomial_divides(Sign(h)[0], sign[0]):
516
+ return True
517
+ return False
518
+
519
+
520
+ def f5_reduce(f, B):
521
+ """
522
+ F5-reduce a labeled polynomial f by B.
523
+
524
+ Continuously searches for non-zero labeled polynomial h in B, such
525
+ that the leading term lt_h of h divides the leading term lt_f of
526
+ f and Sign(lt_h * h) < Sign(f). If such a labeled polynomial h is
527
+ found, f gets replaced by f - lt_f / lt_h * h. If no such h can be
528
+ found or f is 0, f is no further F5-reducible and f gets returned.
529
+
530
+ A polynomial that is reducible in the usual sense need not be
531
+ F5-reducible, e.g.:
532
+
533
+ >>> from sympy.polys.groebnertools import lbp, sig, f5_reduce, Polyn
534
+ >>> from sympy.polys import ring, QQ, lex
535
+
536
+ >>> R, x,y,z = ring("x,y,z", QQ, lex)
537
+
538
+ >>> f = lbp(sig((1, 1, 1), 4), x, 3)
539
+ >>> g = lbp(sig((0, 0, 0), 2), x, 2)
540
+
541
+ >>> Polyn(f).rem([Polyn(g)])
542
+ 0
543
+ >>> f5_reduce(f, [g])
544
+ (((1, 1, 1), 4), x, 3)
545
+
546
+ """
547
+ order = Polyn(f).ring.order
548
+ domain = Polyn(f).ring.domain
549
+
550
+ if not Polyn(f):
551
+ return f
552
+
553
+ while True:
554
+ g = f
555
+
556
+ for h in B:
557
+ if Polyn(h):
558
+ if monomial_divides(Polyn(h).LM, Polyn(f).LM):
559
+ t = term_div(Polyn(f).LT, Polyn(h).LT, domain)
560
+ if sig_cmp(sig_mult(Sign(h), t[0]), Sign(f), order) < 0:
561
+ # The following check need not be done and is in general slower than without.
562
+ #if not is_rewritable_or_comparable(Sign(gp), Num(gp), B):
563
+ hp = lbp_mul_term(h, t)
564
+ f = lbp_sub(f, hp)
565
+ break
566
+
567
+ if g == f or not Polyn(f):
568
+ return f
569
+
570
+
571
+ def _f5b(F, ring):
572
+ """
573
+ Computes a reduced Groebner basis for the ideal generated by F.
574
+
575
+ f5b is an implementation of the F5B algorithm by Yao Sun and
576
+ Dingkang Wang. Similarly to Buchberger's algorithm, the algorithm
577
+ proceeds by computing critical pairs, computing the S-polynomial,
578
+ reducing it and adjoining the reduced S-polynomial if it is not 0.
579
+
580
+ Unlike Buchberger's algorithm, each polynomial contains additional
581
+ information, namely a signature and a number. The signature
582
+ specifies the path of computation (i.e. from which polynomial in
583
+ the original basis was it derived and how), the number says when
584
+ the polynomial was added to the basis. With this information it
585
+ is (often) possible to decide if an S-polynomial will reduce to
586
+ 0 and can be discarded.
587
+
588
+ Optimizations include: Reducing the generators before computing
589
+ a Groebner basis, removing redundant critical pairs when a new
590
+ polynomial enters the basis and sorting the critical pairs and
591
+ the current basis.
592
+
593
+ Once a Groebner basis has been found, it gets reduced.
594
+
595
+ References
596
+ ==========
597
+
598
+ .. [1] Yao Sun, Dingkang Wang: "A New Proof for the Correctness of F5
599
+ (F5-Like) Algorithm", https://arxiv.org/abs/1004.0084 (specifically
600
+ v4)
601
+
602
+ .. [2] Thomas Becker, Volker Weispfenning, Groebner bases: A computational
603
+ approach to commutative algebra, 1993, p. 203, 216
604
+ """
605
+ order = ring.order
606
+
607
+ # reduce polynomials (like in Mario Pernici's implementation) (Becker, Weispfenning, p. 203)
608
+ B = F
609
+ while True:
610
+ F = B
611
+ B = []
612
+
613
+ for i in range(len(F)):
614
+ p = F[i]
615
+ r = p.rem(F[:i])
616
+
617
+ if r:
618
+ B.append(r)
619
+
620
+ if F == B:
621
+ break
622
+
623
+ # basis
624
+ B = [lbp(sig(ring.zero_monom, i + 1), F[i], i + 1) for i in range(len(F))]
625
+ B.sort(key=lambda f: order(Polyn(f).LM), reverse=True)
626
+
627
+ # critical pairs
628
+ CP = [critical_pair(B[i], B[j], ring) for i in range(len(B)) for j in range(i + 1, len(B))]
629
+ CP.sort(key=lambda cp: cp_key(cp, ring), reverse=True)
630
+
631
+ k = len(B)
632
+
633
+ reductions_to_zero = 0
634
+
635
+ while len(CP):
636
+ cp = CP.pop()
637
+
638
+ # discard redundant critical pairs:
639
+ if is_rewritable_or_comparable(cp[0], Num(cp[2]), B):
640
+ continue
641
+ if is_rewritable_or_comparable(cp[3], Num(cp[5]), B):
642
+ continue
643
+
644
+ s = s_poly(cp)
645
+
646
+ p = f5_reduce(s, B)
647
+
648
+ p = lbp(Sign(p), Polyn(p).monic(), k + 1)
649
+
650
+ if Polyn(p):
651
+ # remove old critical pairs, that become redundant when adding p:
652
+ indices = []
653
+ for i, cp in enumerate(CP):
654
+ if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p]):
655
+ indices.append(i)
656
+ elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p]):
657
+ indices.append(i)
658
+
659
+ for i in reversed(indices):
660
+ del CP[i]
661
+
662
+ # only add new critical pairs that are not made redundant by p:
663
+ for g in B:
664
+ if Polyn(g):
665
+ cp = critical_pair(p, g, ring)
666
+ if is_rewritable_or_comparable(cp[0], Num(cp[2]), [p]):
667
+ continue
668
+ elif is_rewritable_or_comparable(cp[3], Num(cp[5]), [p]):
669
+ continue
670
+
671
+ CP.append(cp)
672
+
673
+ # sort (other sorting methods/selection strategies were not as successful)
674
+ CP.sort(key=lambda cp: cp_key(cp, ring), reverse=True)
675
+
676
+ # insert p into B:
677
+ m = Polyn(p).LM
678
+ if order(m) <= order(Polyn(B[-1]).LM):
679
+ B.append(p)
680
+ else:
681
+ for i, q in enumerate(B):
682
+ if order(m) > order(Polyn(q).LM):
683
+ B.insert(i, p)
684
+ break
685
+
686
+ k += 1
687
+
688
+ #print(len(B), len(CP), "%d critical pairs removed" % len(indices))
689
+ else:
690
+ reductions_to_zero += 1
691
+
692
+ # reduce Groebner basis:
693
+ H = [Polyn(g).monic() for g in B]
694
+ H = red_groebner(H, ring)
695
+
696
+ return sorted(H, key=lambda f: order(f.LM), reverse=True)
697
+
698
+
699
+ def red_groebner(G, ring):
700
+ """
701
+ Compute reduced Groebner basis, from BeckerWeispfenning93, p. 216
702
+
703
+ Selects a subset of generators, that already generate the ideal
704
+ and computes a reduced Groebner basis for them.
705
+ """
706
+ def reduction(P):
707
+ """
708
+ The actual reduction algorithm.
709
+ """
710
+ Q = []
711
+ for i, p in enumerate(P):
712
+ h = p.rem(P[:i] + P[i + 1:])
713
+ if h:
714
+ Q.append(h)
715
+
716
+ return [p.monic() for p in Q]
717
+
718
+ F = G
719
+ H = []
720
+
721
+ while F:
722
+ f0 = F.pop()
723
+
724
+ if not any(monomial_divides(f.LM, f0.LM) for f in F + H):
725
+ H.append(f0)
726
+
727
+ # Becker, Weispfenning, p. 217: H is Groebner basis of the ideal generated by G.
728
+ return reduction(H)
729
+
730
+
731
+ def is_groebner(G, ring):
732
+ """
733
+ Check if G is a Groebner basis.
734
+ """
735
+ for i in range(len(G)):
736
+ for j in range(i + 1, len(G)):
737
+ s = spoly(G[i], G[j], ring)
738
+ s = s.rem(G)
739
+ if s:
740
+ return False
741
+
742
+ return True
743
+
744
+
745
+ def is_minimal(G, ring):
746
+ """
747
+ Checks if G is a minimal Groebner basis.
748
+ """
749
+ order = ring.order
750
+ domain = ring.domain
751
+
752
+ G.sort(key=lambda g: order(g.LM))
753
+
754
+ for i, g in enumerate(G):
755
+ if g.LC != domain.one:
756
+ return False
757
+
758
+ for h in G[:i] + G[i + 1:]:
759
+ if monomial_divides(h.LM, g.LM):
760
+ return False
761
+
762
+ return True
763
+
764
+
765
+ def is_reduced(G, ring):
766
+ """
767
+ Checks if G is a reduced Groebner basis.
768
+ """
769
+ order = ring.order
770
+ domain = ring.domain
771
+
772
+ G.sort(key=lambda g: order(g.LM))
773
+
774
+ for i, g in enumerate(G):
775
+ if g.LC != domain.one:
776
+ return False
777
+
778
+ for term in g.terms():
779
+ for h in G[:i] + G[i + 1:]:
780
+ if monomial_divides(h.LM, term[0]):
781
+ return False
782
+
783
+ return True
784
+
785
+ def groebner_lcm(f, g):
786
+ """
787
+ Computes LCM of two polynomials using Groebner bases.
788
+
789
+ The LCM is computed as the unique generator of the intersection
790
+ of the two ideals generated by `f` and `g`. The approach is to
791
+ compute a Groebner basis with respect to lexicographic ordering
792
+ of `t*f` and `(1 - t)*g`, where `t` is an unrelated variable and
793
+ then filtering out the solution that does not contain `t`.
794
+
795
+ References
796
+ ==========
797
+
798
+ .. [1] [Cox97]_
799
+
800
+ """
801
+ if f.ring != g.ring:
802
+ raise ValueError("Values should be equal")
803
+
804
+ ring = f.ring
805
+ domain = ring.domain
806
+
807
+ if not f or not g:
808
+ return ring.zero
809
+
810
+ if len(f) <= 1 and len(g) <= 1:
811
+ monom = monomial_lcm(f.LM, g.LM)
812
+ coeff = domain.lcm(f.LC, g.LC)
813
+ return ring.term_new(monom, coeff)
814
+
815
+ fc, f = f.primitive()
816
+ gc, g = g.primitive()
817
+
818
+ lcm = domain.lcm(fc, gc)
819
+
820
+ f_terms = [ ((1,) + monom, coeff) for monom, coeff in f.terms() ]
821
+ g_terms = [ ((0,) + monom, coeff) for monom, coeff in g.terms() ] \
822
+ + [ ((1,) + monom,-coeff) for monom, coeff in g.terms() ]
823
+
824
+ t = Dummy("t")
825
+ t_ring = ring.clone(symbols=(t,) + ring.symbols, order=lex)
826
+
827
+ F = t_ring.from_terms(f_terms)
828
+ G = t_ring.from_terms(g_terms)
829
+
830
+ basis = groebner([F, G], t_ring)
831
+
832
+ def is_independent(h, j):
833
+ return not any(monom[j] for monom in h.monoms())
834
+
835
+ H = [ h for h in basis if is_independent(h, 0) ]
836
+
837
+ h_terms = [ (monom[1:], coeff*lcm) for monom, coeff in H[0].terms() ]
838
+ h = ring.from_terms(h_terms)
839
+
840
+ return h
841
+
842
+ def groebner_gcd(f, g):
843
+ """Computes GCD of two polynomials using Groebner bases. """
844
+ if f.ring != g.ring:
845
+ raise ValueError("Values should be equal")
846
+ domain = f.ring.domain
847
+
848
+ if not domain.is_Field:
849
+ fc, f = f.primitive()
850
+ gc, g = g.primitive()
851
+ gcd = domain.gcd(fc, gc)
852
+
853
+ H = (f*g).quo([groebner_lcm(f, g)])
854
+
855
+ if len(H) != 1:
856
+ raise ValueError("Length should be 1")
857
+ h = H[0]
858
+
859
+ if not domain.is_Field:
860
+ return gcd*h
861
+ else:
862
+ return h.monic()
llmeval-env/lib/python3.10/site-packages/sympy/polys/heuristicgcd.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Heuristic polynomial GCD algorithm (HEUGCD). """
2
+
3
+ from .polyerrors import HeuristicGCDFailed
4
+
5
+ HEU_GCD_MAX = 6
6
+
7
+ def heugcd(f, g):
8
+ """
9
+ Heuristic polynomial GCD in ``Z[X]``.
10
+
11
+ Given univariate polynomials ``f`` and ``g`` in ``Z[X]``, returns
12
+ their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg``
13
+ such that::
14
+
15
+ h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h)
16
+
17
+ The algorithm is purely heuristic which means it may fail to compute
18
+ the GCD. This will be signaled by raising an exception. In this case
19
+ you will need to switch to another GCD method.
20
+
21
+ The algorithm computes the polynomial GCD by evaluating polynomials
22
+ ``f`` and ``g`` at certain points and computing (fast) integer GCD
23
+ of those evaluations. The polynomial GCD is recovered from the integer
24
+ image by interpolation. The evaluation process reduces f and g variable
25
+ by variable into a large integer. The final step is to verify if the
26
+ interpolated polynomial is the correct GCD. This gives cofactors of
27
+ the input polynomials as a side effect.
28
+
29
+ Examples
30
+ ========
31
+
32
+ >>> from sympy.polys.heuristicgcd import heugcd
33
+ >>> from sympy.polys import ring, ZZ
34
+
35
+ >>> R, x,y, = ring("x,y", ZZ)
36
+
37
+ >>> f = x**2 + 2*x*y + y**2
38
+ >>> g = x**2 + x*y
39
+
40
+ >>> h, cff, cfg = heugcd(f, g)
41
+ >>> h, cff, cfg
42
+ (x + y, x + y, x)
43
+
44
+ >>> cff*h == f
45
+ True
46
+ >>> cfg*h == g
47
+ True
48
+
49
+ References
50
+ ==========
51
+
52
+ .. [1] [Liao95]_
53
+
54
+ """
55
+ assert f.ring == g.ring and f.ring.domain.is_ZZ
56
+
57
+ ring = f.ring
58
+ x0 = ring.gens[0]
59
+ domain = ring.domain
60
+
61
+ gcd, f, g = f.extract_ground(g)
62
+
63
+ f_norm = f.max_norm()
64
+ g_norm = g.max_norm()
65
+
66
+ B = domain(2*min(f_norm, g_norm) + 29)
67
+
68
+ x = max(min(B, 99*domain.sqrt(B)),
69
+ 2*min(f_norm // abs(f.LC),
70
+ g_norm // abs(g.LC)) + 4)
71
+
72
+ for i in range(0, HEU_GCD_MAX):
73
+ ff = f.evaluate(x0, x)
74
+ gg = g.evaluate(x0, x)
75
+
76
+ if ff and gg:
77
+ if ring.ngens == 1:
78
+ h, cff, cfg = domain.cofactors(ff, gg)
79
+ else:
80
+ h, cff, cfg = heugcd(ff, gg)
81
+
82
+ h = _gcd_interpolate(h, x, ring)
83
+ h = h.primitive()[1]
84
+
85
+ cff_, r = f.div(h)
86
+
87
+ if not r:
88
+ cfg_, r = g.div(h)
89
+
90
+ if not r:
91
+ h = h.mul_ground(gcd)
92
+ return h, cff_, cfg_
93
+
94
+ cff = _gcd_interpolate(cff, x, ring)
95
+
96
+ h, r = f.div(cff)
97
+
98
+ if not r:
99
+ cfg_, r = g.div(h)
100
+
101
+ if not r:
102
+ h = h.mul_ground(gcd)
103
+ return h, cff, cfg_
104
+
105
+ cfg = _gcd_interpolate(cfg, x, ring)
106
+
107
+ h, r = g.div(cfg)
108
+
109
+ if not r:
110
+ cff_, r = f.div(h)
111
+
112
+ if not r:
113
+ h = h.mul_ground(gcd)
114
+ return h, cff_, cfg
115
+
116
+ x = 73794*x * domain.sqrt(domain.sqrt(x)) // 27011
117
+
118
+ raise HeuristicGCDFailed('no luck')
119
+
120
+ def _gcd_interpolate(h, x, ring):
121
+ """Interpolate polynomial GCD from integer GCD. """
122
+ f, i = ring.zero, 0
123
+
124
+ # TODO: don't expose poly repr implementation details
125
+ if ring.ngens == 1:
126
+ while h:
127
+ g = h % x
128
+ if g > x // 2: g -= x
129
+ h = (h - g) // x
130
+
131
+ # f += X**i*g
132
+ if g:
133
+ f[(i,)] = g
134
+ i += 1
135
+ else:
136
+ while h:
137
+ g = h.trunc_ground(x)
138
+ h = (h - g).quo_ground(x)
139
+
140
+ # f += X**i*g
141
+ if g:
142
+ for monom, coeff in g.iterterms():
143
+ f[(i,) + monom] = coeff
144
+ i += 1
145
+
146
+ if f.LC < 0:
147
+ return -f
148
+ else:
149
+ return f