galois_resolvents.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. r"""
  2. Galois resolvents
  3. Each of the functions in ``sympy.polys.numberfields.galoisgroups`` that
  4. computes Galois groups for a particular degree $n$ uses resolvents. Given the
  5. polynomial $T$ whose Galois group is to be computed, a resolvent is a
  6. polynomial $R$ whose roots are defined as functions of the roots of $T$.
  7. One way to compute the coefficients of $R$ is by approximating the roots of $T$
  8. to sufficient precision. This module defines a :py:class:`~.Resolvent` class
  9. that handles this job, determining the necessary precision, and computing $R$.
  10. In some cases, the coefficients of $R$ are symmetric in the roots of $T$,
  11. meaning they are equal to fixed functions of the coefficients of $T$. Therefore
  12. another approach is to compute these functions once and for all, and record
  13. them in a lookup table. This module defines code that can compute such tables.
  14. The tables for polynomials $T$ of degrees 4 through 6, produced by this code,
  15. are recorded in the resolvent_lookup.py module.
  16. """
  17. from sympy.core.evalf import (
  18. evalf, fastlog, _evalf_with_bounded_error, quad_to_mpmath,
  19. )
  20. from sympy.core.symbol import symbols, Dummy
  21. from sympy.polys.densetools import dup_eval
  22. from sympy.polys.domains import ZZ
  23. from sympy.polys.orderings import lex
  24. from sympy.polys.polyroots import preprocess_roots
  25. from sympy.polys.polytools import Poly
  26. from sympy.polys.rings import xring
  27. from sympy.polys.specialpolys import symmetric_poly
  28. from sympy.utilities.lambdify import lambdify
  29. from mpmath import MPContext
  30. from mpmath.libmp.libmpf import prec_to_dps
  31. class GaloisGroupException(Exception):
  32. ...
  33. class ResolventException(GaloisGroupException):
  34. ...
  35. class Resolvent:
  36. r"""
  37. If $G$ is a subgroup of the symmetric group $S_n$,
  38. $F$ a multivariate polynomial in $\mathbb{Z}[X_1, \ldots, X_n]$,
  39. $H$ the stabilizer of $F$ in $G$ (i.e. the permutations $\sigma$ such that
  40. $F(X_{\sigma(1)}, \ldots, X_{\sigma(n)}) = F(X_1, \ldots, X_n)$), and $s$
  41. a set of left coset representatives of $H$ in $G$, then the resolvent
  42. polynomial $R(Y)$ is the product over $\sigma \in s$ of
  43. $Y - F(X_{\sigma(1)}, \ldots, X_{\sigma(n)})$.
  44. For example, consider the resolvent for the form
  45. $$F = X_0 X_2 + X_1 X_3$$
  46. and the group $G = S_4$. In this case, the stabilizer $H$ is the dihedral
  47. group $D4 = < (0123), (02) >$, and a set of representatives of $G/H$ is
  48. $\{I, (01), (03)\}$. The resolvent can be constructed as follows:
  49. >>> from sympy.combinatorics.permutations import Permutation
  50. >>> from sympy.core.symbol import symbols
  51. >>> from sympy.polys.numberfields.galoisgroups import Resolvent
  52. >>> X = symbols('X0 X1 X2 X3')
  53. >>> F = X[0]*X[2] + X[1]*X[3]
  54. >>> s = [Permutation([0, 1, 2, 3]), Permutation([1, 0, 2, 3]),
  55. ... Permutation([3, 1, 2, 0])]
  56. >>> R = Resolvent(F, X, s)
  57. This resolvent has three roots, which are the conjugates of ``F`` under the
  58. three permutations in ``s``:
  59. >>> R.root_lambdas[0](*X)
  60. X0*X2 + X1*X3
  61. >>> R.root_lambdas[1](*X)
  62. X0*X3 + X1*X2
  63. >>> R.root_lambdas[2](*X)
  64. X0*X1 + X2*X3
  65. Resolvents are useful for computing Galois groups. Given a polynomial $T$
  66. of degree $n$, we will use a resolvent $R$ where $Gal(T) \leq G \leq S_n$.
  67. We will then want to substitute the roots of $T$ for the variables $X_i$
  68. in $R$, and study things like the discriminant of $R$, and the way $R$
  69. factors over $\mathbb{Q}$.
  70. From the symmetry in $R$'s construction, and since $Gal(T) \leq G$, we know
  71. from Galois theory that the coefficients of $R$ must lie in $\mathbb{Z}$.
  72. This allows us to compute the coefficients of $R$ by approximating the
  73. roots of $T$ to sufficient precision, plugging these values in for the
  74. variables $X_i$ in the coefficient expressions of $R$, and then simply
  75. rounding to the nearest integer.
  76. In order to determine a sufficient precision for the roots of $T$, this
  77. ``Resolvent`` class imposes certain requirements on the form ``F``. It
  78. could be possible to design a different ``Resolvent`` class, that made
  79. different precision estimates, and different assumptions about ``F``.
  80. ``F`` must be homogeneous, and all terms must have unit coefficient.
  81. Furthermore, if $r$ is the number of terms in ``F``, and $t$ the total
  82. degree, and if $m$ is the number of conjugates of ``F``, i.e. the number
  83. of permutations in ``s``, then we require that $m < r 2^t$. Again, it is
  84. not impossible to work with forms ``F`` that violate these assumptions, but
  85. this ``Resolvent`` class requires them.
  86. Since determining the integer coefficients of the resolvent for a given
  87. polynomial $T$ is one of the main problems this class solves, we take some
  88. time to explain the precision bounds it uses.
  89. The general problem is:
  90. Given a multivariate polynomial $P \in \mathbb{Z}[X_1, \ldots, X_n]$, and a
  91. bound $M \in \mathbb{R}_+$, compute an $\varepsilon > 0$ such that for any
  92. complex numbers $a_1, \ldots, a_n$ with $|a_i| < M$, if the $a_i$ are
  93. approximated to within an accuracy of $\varepsilon$ by $b_i$, that is,
  94. $|a_i - b_i| < \varepsilon$ for $i = 1, \ldots, n$, then
  95. $|P(a_1, \ldots, a_n) - P(b_1, \ldots, b_n)| < 1/2$. In other words, if it
  96. is known that $P(a_1, \ldots, a_n) = c$ for some $c \in \mathbb{Z}$, then
  97. $P(b_1, \ldots, b_n)$ can be rounded to the nearest integer in order to
  98. determine $c$.
  99. To derive our error bound, consider the monomial $xyz$. Defining
  100. $d_i = b_i - a_i$, our error is
  101. $|(a_1 + d_1)(a_2 + d_2)(a_3 + d_3) - a_1 a_2 a_3|$, which is bounded
  102. above by $|(M + \varepsilon)^3 - M^3|$. Passing to a general monomial of
  103. total degree $t$, this expression is bounded by
  104. $M^{t-1}\varepsilon(t + 2^t\varepsilon/M)$ provided $\varepsilon < M$,
  105. and by $(t+1)M^{t-1}\varepsilon$ provided $\varepsilon < M/2^t$.
  106. But since our goal is to make the error less than $1/2$, we will choose
  107. $\varepsilon < 1/(2(t+1)M^{t-1})$, which implies the condition that
  108. $\varepsilon < M/2^t$, as long as $M \geq 2$.
  109. Passing from the general monomial to the general polynomial is easy, by
  110. scaling and summing error bounds.
  111. In our specific case, we are given a homogeneous polynomial $F$ of
  112. $r$ terms and total degree $t$, all of whose coefficients are $\pm 1$. We
  113. are given the $m$ permutations that make the conjugates of $F$, and
  114. we want to bound the error in the coefficients of the monic polynomial
  115. $R(Y)$ having $F$ and its conjugates as roots (i.e. the resolvent).
  116. For $j$ from $1$ to $m$, the coefficient of $Y^{m-j}$ in $R(Y)$ is the
  117. $j$th elementary symmetric polynomial in the conjugates of $F$. This sums
  118. the products of these conjugates, taken $j$ at a time, in all possible
  119. combinations. There are $\binom{m}{j}$ such combinations, and each product
  120. of $j$ conjugates of $F$ expands to a sum of $r^j$ terms, each of unit
  121. coefficient, and total degree $jt$. An error bound for the $j$th coeff of
  122. $R$ is therefore
  123. $$\binom{m}{j} r^j (jt + 1) M^{jt - 1} \varepsilon$$
  124. When our goal is to evaluate all the coefficients of $R$, we will want to
  125. use the maximum of these error bounds. It is clear that this bound is
  126. strictly increasing for $j$ up to the ceiling of $m/2$. After that point,
  127. the first factor $\binom{m}{j}$ begins to decrease, while the others
  128. continue to increase. However, the binomial coefficient never falls by more
  129. than a factor of $1/m$ at a time, so our assumptions that $M \geq 2$ and
  130. $m < r 2^t$ are enough to tell us that the constant coefficient of $R$,
  131. i.e. that where $j = m$, has the largest error bound. Therefore we can use
  132. $$r^m (mt + 1) M^{mt - 1} \varepsilon$$
  133. as our error bound for all the coefficients.
  134. Note that this bound is also (more than) adequate to determine whether any
  135. of the roots of $R$ is an integer. Each of these roots is a single
  136. conjugate of $F$, which contains less error than the trace, i.e. the
  137. coefficient of $Y^{m - 1}$. By rounding the roots of $R$ to the nearest
  138. integers, we therefore get all the candidates for integer roots of $R$. By
  139. plugging these candidates into $R$, we can check whether any of them
  140. actually is a root.
  141. Note: We take the definition of resolvent from Cohen, but the error bound
  142. is ours.
  143. References
  144. ==========
  145. .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
  146. (Def 6.3.2)
  147. """
  148. def __init__(self, F, X, s):
  149. r"""
  150. Parameters
  151. ==========
  152. F : :py:class:`~.Expr`
  153. polynomial in the symbols in *X*
  154. X : list of :py:class:`~.Symbol`
  155. s : list of :py:class:`~.Permutation`
  156. representing the cosets of the stabilizer of *F* in
  157. some subgroup $G$ of $S_n$, where $n$ is the length of *X*.
  158. """
  159. self.F = F
  160. self.X = X
  161. self.s = s
  162. # Number of conjugates:
  163. self.m = len(s)
  164. # Total degree of F (computed below):
  165. self.t = None
  166. # Number of terms in F (computed below):
  167. self.r = 0
  168. for monom, coeff in Poly(F).terms():
  169. if abs(coeff) != 1:
  170. raise ResolventException('Resolvent class expects forms with unit coeffs')
  171. t = sum(monom)
  172. if t != self.t and self.t is not None:
  173. raise ResolventException('Resolvent class expects homogeneous forms')
  174. self.t = t
  175. self.r += 1
  176. m, t, r = self.m, self.t, self.r
  177. if not m < r * 2**t:
  178. raise ResolventException('Resolvent class expects m < r*2^t')
  179. M = symbols('M')
  180. # Precision sufficient for computing the coeffs of the resolvent:
  181. self.coeff_prec_func = Poly(r**m*(m*t + 1)*M**(m*t - 1))
  182. # Precision sufficient for checking whether any of the roots of the
  183. # resolvent are integers:
  184. self.root_prec_func = Poly(r*(t + 1)*M**(t - 1))
  185. # The conjugates of F are the roots of the resolvent.
  186. # For evaluating these to required numerical precisions, we need
  187. # lambdified versions.
  188. # Note: for a given permutation sigma, the conjugate (sigma F) is
  189. # equivalent to lambda [sigma^(-1) X]: F.
  190. self.root_lambdas = [
  191. lambdify((~s[j])(X), F)
  192. for j in range(self.m)
  193. ]
  194. # For evaluating the coeffs, we'll also need lambdified versions of
  195. # the elementary symmetric functions for degree m.
  196. Y = symbols('Y')
  197. R = symbols(' '.join(f'R{i}' for i in range(m)))
  198. f = 1
  199. for r in R:
  200. f *= (Y - r)
  201. C = Poly(f, Y).coeffs()
  202. self.esf_lambdas = [lambdify(R, c) for c in C]
  203. def get_prec(self, M, target='coeffs'):
  204. r"""
  205. For a given upper bound *M* on the magnitude of the complex numbers to
  206. be plugged in for this resolvent's symbols, compute a sufficient
  207. precision for evaluating those complex numbers, such that the
  208. coefficients, or the integer roots, of the resolvent can be determined.
  209. Parameters
  210. ==========
  211. M : real number
  212. Upper bound on magnitude of the complex numbers to be plugged in.
  213. target : str, 'coeffs' or 'roots', default='coeffs'
  214. Name the task for which a sufficient precision is desired.
  215. This is either determining the coefficients of the resolvent
  216. ('coeffs') or determining its possible integer roots ('roots').
  217. The latter may require significantly lower precision.
  218. Returns
  219. =======
  220. int $m$
  221. such that $2^{-m}$ is a sufficient upper bound on the
  222. error in approximating the complex numbers to be plugged in.
  223. """
  224. # As explained in the docstring for this class, our precision estimates
  225. # require that M be at least 2.
  226. M = max(M, 2)
  227. f = self.coeff_prec_func if target == 'coeffs' else self.root_prec_func
  228. r, _, _, _ = evalf(2*f(M), 1, {})
  229. return fastlog(r) + 1
  230. def approximate_roots_of_poly(self, T, target='coeffs'):
  231. """
  232. Approximate the roots of a given polynomial *T* to sufficient precision
  233. in order to evaluate this resolvent's coefficients, or determine
  234. whether the resolvent has an integer root.
  235. Parameters
  236. ==========
  237. T : :py:class:`~.Poly`
  238. target : str, 'coeffs' or 'roots', default='coeffs'
  239. Set the approximation precision to be sufficient for the desired
  240. task, which is either determining the coefficients of the resolvent
  241. ('coeffs') or determining its possible integer roots ('roots').
  242. The latter may require significantly lower precision.
  243. Returns
  244. =======
  245. list of elements of :ref:`CC`
  246. """
  247. ctx = MPContext()
  248. # Because sympy.polys.polyroots._integer_basis() is called when a CRootOf
  249. # is formed, we proactively extract the integer basis now. This means that
  250. # when we call T.all_roots(), every root will be a CRootOf, not a Mul
  251. # of Integer*CRootOf.
  252. coeff, T = preprocess_roots(T)
  253. coeff = ctx.mpf(str(coeff))
  254. scaled_roots = T.all_roots(radicals=False)
  255. # Since we're going to be approximating the roots of T anyway, we can
  256. # get a good upper bound on the magnitude of the roots by starting with
  257. # a very low precision approx.
  258. approx0 = [coeff * quad_to_mpmath(_evalf_with_bounded_error(r, m=0)) for r in scaled_roots]
  259. # Here we add 1 to account for the possible error in our initial approximation.
  260. M = max(abs(b) for b in approx0) + 1
  261. m = self.get_prec(M, target=target)
  262. n = fastlog(M._mpf_) + 1
  263. p = m + n + 1
  264. ctx.prec = p
  265. d = prec_to_dps(p)
  266. approx1 = [r.eval_approx(d, return_mpmath=True) for r in scaled_roots]
  267. approx1 = [coeff*ctx.mpc(r) for r in approx1]
  268. return approx1
  269. @staticmethod
  270. def round_mpf(a):
  271. if isinstance(a, int):
  272. return a
  273. # If we use python's built-in `round()`, we lose precision.
  274. # If we use `ZZ` directly, we may add or subtract 1.
  275. #
  276. # XXX: We have to convert to int before converting to ZZ because
  277. # flint.fmpz cannot convert a mpmath mpf.
  278. return ZZ(int(a.context.nint(a)))
  279. def round_roots_to_integers_for_poly(self, T):
  280. """
  281. For a given polynomial *T*, round the roots of this resolvent to the
  282. nearest integers.
  283. Explanation
  284. ===========
  285. None of the integers returned by this method is guaranteed to be a
  286. root of the resolvent; however, if the resolvent has any integer roots
  287. (for the given polynomial *T*), then they must be among these.
  288. If the coefficients of the resolvent are also desired, then this method
  289. should not be used. Instead, use the ``eval_for_poly`` method. This
  290. method may be significantly faster than ``eval_for_poly``.
  291. Parameters
  292. ==========
  293. T : :py:class:`~.Poly`
  294. Returns
  295. =======
  296. dict
  297. Keys are the indices of those permutations in ``self.s`` such that
  298. the corresponding root did round to a rational integer.
  299. Values are :ref:`ZZ`.
  300. """
  301. approx_roots_of_T = self.approximate_roots_of_poly(T, target='roots')
  302. approx_roots_of_self = [r(*approx_roots_of_T) for r in self.root_lambdas]
  303. return {
  304. i: self.round_mpf(r.real)
  305. for i, r in enumerate(approx_roots_of_self)
  306. if self.round_mpf(r.imag) == 0
  307. }
  308. def eval_for_poly(self, T, find_integer_root=False):
  309. r"""
  310. Compute the integer values of the coefficients of this resolvent, when
  311. plugging in the roots of a given polynomial.
  312. Parameters
  313. ==========
  314. T : :py:class:`~.Poly`
  315. find_integer_root : ``bool``, default ``False``
  316. If ``True``, then also determine whether the resolvent has an
  317. integer root, and return the first one found, along with its
  318. index, i.e. the index of the permutation ``self.s[i]`` it
  319. corresponds to.
  320. Returns
  321. =======
  322. Tuple ``(R, a, i)``
  323. ``R`` is this resolvent as a dense univariate polynomial over
  324. :ref:`ZZ`, i.e. a list of :ref:`ZZ`.
  325. If *find_integer_root* was ``True``, then ``a`` and ``i`` are the
  326. first integer root found, and its index, if one exists.
  327. Otherwise ``a`` and ``i`` are both ``None``.
  328. """
  329. approx_roots_of_T = self.approximate_roots_of_poly(T, target='coeffs')
  330. approx_roots_of_self = [r(*approx_roots_of_T) for r in self.root_lambdas]
  331. approx_coeffs_of_self = [c(*approx_roots_of_self) for c in self.esf_lambdas]
  332. R = []
  333. for c in approx_coeffs_of_self:
  334. if self.round_mpf(c.imag) != 0:
  335. # If precision was enough, this should never happen.
  336. raise ResolventException(f"Got non-integer coeff for resolvent: {c}")
  337. R.append(self.round_mpf(c.real))
  338. a0, i0 = None, None
  339. if find_integer_root:
  340. for i, r in enumerate(approx_roots_of_self):
  341. if self.round_mpf(r.imag) != 0:
  342. continue
  343. if not dup_eval(R, (a := self.round_mpf(r.real)), ZZ):
  344. a0, i0 = a, i
  345. break
  346. return R, a0, i0
  347. def wrap(text, width=80):
  348. """Line wrap a polynomial expression. """
  349. out = ''
  350. col = 0
  351. for c in text:
  352. if c == ' ' and col > width:
  353. c, col = '\n', 0
  354. else:
  355. col += 1
  356. out += c
  357. return out
  358. def s_vars(n):
  359. """Form the symbols s1, s2, ..., sn to stand for elem. symm. polys. """
  360. return symbols([f's{i + 1}' for i in range(n)])
  361. def sparse_symmetrize_resolvent_coeffs(F, X, s, verbose=False):
  362. """
  363. Compute the coefficients of a resolvent as functions of the coefficients of
  364. the associated polynomial.
  365. F must be a sparse polynomial.
  366. """
  367. import time, sys
  368. # Roots of resolvent as multivariate forms over vars X:
  369. root_forms = [
  370. F.compose(list(zip(X, sigma(X))))
  371. for sigma in s
  372. ]
  373. # Coeffs of resolvent (besides lead coeff of 1) as symmetric forms over vars X:
  374. Y = [Dummy(f'Y{i}') for i in range(len(s))]
  375. coeff_forms = []
  376. for i in range(1, len(s) + 1):
  377. if verbose:
  378. print('----')
  379. print(f'Computing symmetric poly of degree {i}...')
  380. sys.stdout.flush()
  381. t0 = time.time()
  382. G = symmetric_poly(i, *Y)
  383. t1 = time.time()
  384. if verbose:
  385. print(f'took {t1 - t0} seconds')
  386. print('lambdifying...')
  387. sys.stdout.flush()
  388. t0 = time.time()
  389. C = lambdify(Y, (-1)**i*G)
  390. t1 = time.time()
  391. if verbose:
  392. print(f'took {t1 - t0} seconds')
  393. sys.stdout.flush()
  394. coeff_forms.append(C)
  395. coeffs = []
  396. for i, f in enumerate(coeff_forms):
  397. if verbose:
  398. print('----')
  399. print(f'Plugging root forms into elem symm poly {i+1}...')
  400. sys.stdout.flush()
  401. t0 = time.time()
  402. g = f(*root_forms)
  403. t1 = time.time()
  404. coeffs.append(g)
  405. if verbose:
  406. print(f'took {t1 - t0} seconds')
  407. sys.stdout.flush()
  408. # Now symmetrize these coeffs. This means recasting them as polynomials in
  409. # the elementary symmetric polys over X.
  410. symmetrized = []
  411. symmetrization_times = []
  412. ss = s_vars(len(X))
  413. for i, A in list(enumerate(coeffs)):
  414. if verbose:
  415. print('-----')
  416. print(f'Coeff {i+1}...')
  417. sys.stdout.flush()
  418. t0 = time.time()
  419. B, rem, _ = A.symmetrize()
  420. t1 = time.time()
  421. if rem != 0:
  422. msg = f"Got nonzero remainder {rem} for resolvent (F, X, s) = ({F}, {X}, {s})"
  423. raise ResolventException(msg)
  424. B_str = str(B.as_expr(*ss))
  425. symmetrized.append(B_str)
  426. symmetrization_times.append(t1 - t0)
  427. if verbose:
  428. print(wrap(B_str))
  429. print(f'took {t1 - t0} seconds')
  430. sys.stdout.flush()
  431. return symmetrized, symmetrization_times
  432. def define_resolvents():
  433. """Define all the resolvents for polys T of degree 4 through 6. """
  434. from sympy.combinatorics.galois import PGL2F5
  435. from sympy.combinatorics.permutations import Permutation
  436. R4, X4 = xring("X0,X1,X2,X3", ZZ, lex)
  437. X = X4
  438. # The one resolvent used in `_galois_group_degree_4_lookup()`:
  439. F40 = X[0]*X[1]**2 + X[1]*X[2]**2 + X[2]*X[3]**2 + X[3]*X[0]**2
  440. s40 = [
  441. Permutation(3),
  442. Permutation(3)(0, 1),
  443. Permutation(3)(0, 2),
  444. Permutation(3)(0, 3),
  445. Permutation(3)(1, 2),
  446. Permutation(3)(2, 3),
  447. ]
  448. # First resolvent used in `_galois_group_degree_4_root_approx()`:
  449. F41 = X[0]*X[2] + X[1]*X[3]
  450. s41 = [
  451. Permutation(3),
  452. Permutation(3)(0, 1),
  453. Permutation(3)(0, 3)
  454. ]
  455. R5, X5 = xring("X0,X1,X2,X3,X4", ZZ, lex)
  456. X = X5
  457. # First resolvent used in `_galois_group_degree_5_hybrid()`,
  458. # and only one used in `_galois_group_degree_5_lookup_ext_factor()`:
  459. F51 = ( X[0]**2*(X[1]*X[4] + X[2]*X[3])
  460. + X[1]**2*(X[2]*X[0] + X[3]*X[4])
  461. + X[2]**2*(X[3]*X[1] + X[4]*X[0])
  462. + X[3]**2*(X[4]*X[2] + X[0]*X[1])
  463. + X[4]**2*(X[0]*X[3] + X[1]*X[2]))
  464. s51 = [
  465. Permutation(4),
  466. Permutation(4)(0, 1),
  467. Permutation(4)(0, 2),
  468. Permutation(4)(0, 3),
  469. Permutation(4)(0, 4),
  470. Permutation(4)(1, 4)
  471. ]
  472. R6, X6 = xring("X0,X1,X2,X3,X4,X5", ZZ, lex)
  473. X = X6
  474. # First resolvent used in `_galois_group_degree_6_lookup()`:
  475. H = PGL2F5()
  476. term0 = X[0]**2*X[5]**2*(X[1]*X[4] + X[2]*X[3])
  477. terms = {term0.compose(list(zip(X, s(X)))) for s in H.elements}
  478. F61 = sum(terms)
  479. s61 = [Permutation(5)] + [Permutation(5)(0, n) for n in range(1, 6)]
  480. # Second resolvent used in `_galois_group_degree_6_lookup()`:
  481. F62 = X[0]*X[1]*X[2] + X[3]*X[4]*X[5]
  482. s62 = [Permutation(5)] + [
  483. Permutation(5)(i, j + 3) for i in range(3) for j in range(3)
  484. ]
  485. return {
  486. (4, 0): (F40, X4, s40),
  487. (4, 1): (F41, X4, s41),
  488. (5, 1): (F51, X5, s51),
  489. (6, 1): (F61, X6, s61),
  490. (6, 2): (F62, X6, s62),
  491. }
  492. def generate_lambda_lookup(verbose=False, trial_run=False):
  493. """
  494. Generate the whole lookup table of coeff lambdas, for all resolvents.
  495. """
  496. jobs = define_resolvents()
  497. lambda_lists = {}
  498. total_time = 0
  499. time_for_61 = 0
  500. time_for_61_last = 0
  501. for k, (F, X, s) in jobs.items():
  502. symmetrized, times = sparse_symmetrize_resolvent_coeffs(F, X, s, verbose=verbose)
  503. total_time += sum(times)
  504. if k == (6, 1):
  505. time_for_61 = sum(times)
  506. time_for_61_last = times[-1]
  507. sv = s_vars(len(X))
  508. head = f'lambda {", ".join(str(v) for v in sv)}:'
  509. lambda_lists[k] = ',\n '.join([
  510. f'{head} ({wrap(f)})'
  511. for f in symmetrized
  512. ])
  513. if trial_run:
  514. break
  515. table = (
  516. "# This table was generated by a call to\n"
  517. "# `sympy.polys.numberfields.galois_resolvents.generate_lambda_lookup()`.\n"
  518. f"# The entire job took {total_time:.2f}s.\n"
  519. f"# Of this, Case (6, 1) took {time_for_61:.2f}s.\n"
  520. f"# The final polynomial of Case (6, 1) alone took {time_for_61_last:.2f}s.\n"
  521. "resolvent_coeff_lambdas = {\n")
  522. for k, L in lambda_lists.items():
  523. table += f" {k}: [\n"
  524. table += " " + L + '\n'
  525. table += " ],\n"
  526. table += "}\n"
  527. return table
  528. def get_resolvent_by_lookup(T, number):
  529. """
  530. Use the lookup table, to return a resolvent (as dup) for a given
  531. polynomial *T*.
  532. Parameters
  533. ==========
  534. T : Poly
  535. The polynomial whose resolvent is needed
  536. number : int
  537. For some degrees, there are multiple resolvents.
  538. Use this to indicate which one you want.
  539. Returns
  540. =======
  541. dup
  542. """
  543. from sympy.polys.numberfields.resolvent_lookup import resolvent_coeff_lambdas
  544. degree = T.degree()
  545. L = resolvent_coeff_lambdas[(degree, number)]
  546. T_coeffs = T.rep.to_list()[1:]
  547. return [ZZ(1)] + [c(*T_coeffs) for c in L]
  548. # Use
  549. # (.venv) $ python -m sympy.polys.numberfields.galois_resolvents
  550. # to reproduce the table found in resolvent_lookup.py
  551. if __name__ == "__main__":
  552. import sys
  553. verbose = '-v' in sys.argv[1:]
  554. trial_run = '-t' in sys.argv[1:]
  555. table = generate_lambda_lookup(verbose=verbose, trial_run=trial_run)
  556. print(table)