distributedmodules.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. r"""
  2. Sparse distributed elements of free modules over multivariate (generalized)
  3. polynomial rings.
  4. This code and its data structures are very much like the distributed
  5. polynomials, except that the first "exponent" of the monomial is
  6. a module generator index. That is, the multi-exponent ``(i, e_1, ..., e_n)``
  7. represents the "monomial" `x_1^{e_1} \cdots x_n^{e_n} f_i` of the free module
  8. `F` generated by `f_1, \ldots, f_r` over (a localization of) the ring
  9. `K[x_1, \ldots, x_n]`. A module element is simply stored as a list of terms
  10. ordered by the monomial order. Here a term is a pair of a multi-exponent and a
  11. coefficient. In general, this coefficient should never be zero (since it can
  12. then be omitted). The zero module element is stored as an empty list.
  13. The main routines are ``sdm_nf_mora`` and ``sdm_groebner`` which can be used
  14. to compute, respectively, weak normal forms and standard bases. They work with
  15. arbitrary (not necessarily global) monomial orders.
  16. In general, product orders have to be used to construct valid monomial orders
  17. for modules. However, ``lex`` can be used as-is.
  18. Note that the "level" (number of variables, i.e. parameter u+1 in
  19. distributedpolys.py) is never needed in this code.
  20. The main reference for this file is [SCA],
  21. "A Singular Introduction to Commutative Algebra".
  22. """
  23. from itertools import permutations
  24. from sympy.polys.monomials import (
  25. monomial_mul, monomial_lcm, monomial_div, monomial_deg
  26. )
  27. from sympy.polys.polytools import Poly
  28. from sympy.polys.polyutils import parallel_dict_from_expr
  29. from sympy.core.singleton import S
  30. from sympy.core.sympify import sympify
  31. # Additional monomial tools.
  32. def sdm_monomial_mul(M, X):
  33. """
  34. Multiply tuple ``X`` representing a monomial of `K[X]` into the tuple
  35. ``M`` representing a monomial of `F`.
  36. Examples
  37. ========
  38. Multiplying `xy^3` into `x f_1` yields `x^2 y^3 f_1`:
  39. >>> from sympy.polys.distributedmodules import sdm_monomial_mul
  40. >>> sdm_monomial_mul((1, 1, 0), (1, 3))
  41. (1, 2, 3)
  42. """
  43. return (M[0],) + monomial_mul(X, M[1:])
  44. def sdm_monomial_deg(M):
  45. """
  46. Return the total degree of ``M``.
  47. Examples
  48. ========
  49. For example, the total degree of `x^2 y f_5` is 3:
  50. >>> from sympy.polys.distributedmodules import sdm_monomial_deg
  51. >>> sdm_monomial_deg((5, 2, 1))
  52. 3
  53. """
  54. return monomial_deg(M[1:])
  55. def sdm_monomial_lcm(A, B):
  56. r"""
  57. Return the "least common multiple" of ``A`` and ``B``.
  58. IF `A = M e_j` and `B = N e_j`, where `M` and `N` are polynomial monomials,
  59. this returns `\lcm(M, N) e_j`. Note that ``A`` and ``B`` involve distinct
  60. monomials.
  61. Otherwise the result is undefined.
  62. Examples
  63. ========
  64. >>> from sympy.polys.distributedmodules import sdm_monomial_lcm
  65. >>> sdm_monomial_lcm((1, 2, 3), (1, 0, 5))
  66. (1, 2, 5)
  67. """
  68. return (A[0],) + monomial_lcm(A[1:], B[1:])
  69. def sdm_monomial_divides(A, B):
  70. """
  71. Does there exist a (polynomial) monomial X such that XA = B?
  72. Examples
  73. ========
  74. Positive examples:
  75. In the following examples, the monomial is given in terms of x, y and the
  76. generator(s), f_1, f_2 etc. The tuple form of that monomial is used in
  77. the call to sdm_monomial_divides.
  78. Note: the generator appears last in the expression but first in the tuple
  79. and other factors appear in the same order that they appear in the monomial
  80. expression.
  81. `A = f_1` divides `B = f_1`
  82. >>> from sympy.polys.distributedmodules import sdm_monomial_divides
  83. >>> sdm_monomial_divides((1, 0, 0), (1, 0, 0))
  84. True
  85. `A = f_1` divides `B = x^2 y f_1`
  86. >>> sdm_monomial_divides((1, 0, 0), (1, 2, 1))
  87. True
  88. `A = xy f_5` divides `B = x^2 y f_5`
  89. >>> sdm_monomial_divides((5, 1, 1), (5, 2, 1))
  90. True
  91. Negative examples:
  92. `A = f_1` does not divide `B = f_2`
  93. >>> sdm_monomial_divides((1, 0, 0), (2, 0, 0))
  94. False
  95. `A = x f_1` does not divide `B = f_1`
  96. >>> sdm_monomial_divides((1, 1, 0), (1, 0, 0))
  97. False
  98. `A = xy^2 f_5` does not divide `B = y f_5`
  99. >>> sdm_monomial_divides((5, 1, 2), (5, 0, 1))
  100. False
  101. """
  102. return A[0] == B[0] and all(a <= b for a, b in zip(A[1:], B[1:]))
  103. # The actual distributed modules code.
  104. def sdm_LC(f, K):
  105. """Returns the leading coeffcient of ``f``. """
  106. if not f:
  107. return K.zero
  108. else:
  109. return f[0][1]
  110. def sdm_to_dict(f):
  111. """Make a dictionary from a distributed polynomial. """
  112. return dict(f)
  113. def sdm_from_dict(d, O):
  114. """
  115. Create an sdm from a dictionary.
  116. Here ``O`` is the monomial order to use.
  117. Examples
  118. ========
  119. >>> from sympy.polys.distributedmodules import sdm_from_dict
  120. >>> from sympy.polys import QQ, lex
  121. >>> dic = {(1, 1, 0): QQ(1), (1, 0, 0): QQ(2), (0, 1, 0): QQ(0)}
  122. >>> sdm_from_dict(dic, lex)
  123. [((1, 1, 0), 1), ((1, 0, 0), 2)]
  124. """
  125. return sdm_strip(sdm_sort(list(d.items()), O))
  126. def sdm_sort(f, O):
  127. """Sort terms in ``f`` using the given monomial order ``O``. """
  128. return sorted(f, key=lambda term: O(term[0]), reverse=True)
  129. def sdm_strip(f):
  130. """Remove terms with zero coefficients from ``f`` in ``K[X]``. """
  131. return [ (monom, coeff) for monom, coeff in f if coeff ]
  132. def sdm_add(f, g, O, K):
  133. """
  134. Add two module elements ``f``, ``g``.
  135. Addition is done over the ground field ``K``, monomials are ordered
  136. according to ``O``.
  137. Examples
  138. ========
  139. All examples use lexicographic order.
  140. `(xy f_1) + (f_2) = f_2 + xy f_1`
  141. >>> from sympy.polys.distributedmodules import sdm_add
  142. >>> from sympy.polys import lex, QQ
  143. >>> sdm_add([((1, 1, 1), QQ(1))], [((2, 0, 0), QQ(1))], lex, QQ)
  144. [((2, 0, 0), 1), ((1, 1, 1), 1)]
  145. `(xy f_1) + (-xy f_1)` = 0`
  146. >>> sdm_add([((1, 1, 1), QQ(1))], [((1, 1, 1), QQ(-1))], lex, QQ)
  147. []
  148. `(f_1) + (2f_1) = 3f_1`
  149. >>> sdm_add([((1, 0, 0), QQ(1))], [((1, 0, 0), QQ(2))], lex, QQ)
  150. [((1, 0, 0), 3)]
  151. `(yf_1) + (xf_1) = xf_1 + yf_1`
  152. >>> sdm_add([((1, 0, 1), QQ(1))], [((1, 1, 0), QQ(1))], lex, QQ)
  153. [((1, 1, 0), 1), ((1, 0, 1), 1)]
  154. """
  155. h = dict(f)
  156. for monom, c in g:
  157. if monom in h:
  158. coeff = h[monom] + c
  159. if not coeff:
  160. del h[monom]
  161. else:
  162. h[monom] = coeff
  163. else:
  164. h[monom] = c
  165. return sdm_from_dict(h, O)
  166. def sdm_LM(f):
  167. r"""
  168. Returns the leading monomial of ``f``.
  169. Only valid if `f \ne 0`.
  170. Examples
  171. ========
  172. >>> from sympy.polys.distributedmodules import sdm_LM, sdm_from_dict
  173. >>> from sympy.polys import QQ, lex
  174. >>> dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(1), (4, 0, 1): QQ(1)}
  175. >>> sdm_LM(sdm_from_dict(dic, lex))
  176. (4, 0, 1)
  177. """
  178. return f[0][0]
  179. def sdm_LT(f):
  180. r"""
  181. Returns the leading term of ``f``.
  182. Only valid if `f \ne 0`.
  183. Examples
  184. ========
  185. >>> from sympy.polys.distributedmodules import sdm_LT, sdm_from_dict
  186. >>> from sympy.polys import QQ, lex
  187. >>> dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(2), (4, 0, 1): QQ(3)}
  188. >>> sdm_LT(sdm_from_dict(dic, lex))
  189. ((4, 0, 1), 3)
  190. """
  191. return f[0]
  192. def sdm_mul_term(f, term, O, K):
  193. """
  194. Multiply a distributed module element ``f`` by a (polynomial) term ``term``.
  195. Multiplication of coefficients is done over the ground field ``K``, and
  196. monomials are ordered according to ``O``.
  197. Examples
  198. ========
  199. `0 f_1 = 0`
  200. >>> from sympy.polys.distributedmodules import sdm_mul_term
  201. >>> from sympy.polys import lex, QQ
  202. >>> sdm_mul_term([((1, 0, 0), QQ(1))], ((0, 0), QQ(0)), lex, QQ)
  203. []
  204. `x 0 = 0`
  205. >>> sdm_mul_term([], ((1, 0), QQ(1)), lex, QQ)
  206. []
  207. `(x) (f_1) = xf_1`
  208. >>> sdm_mul_term([((1, 0, 0), QQ(1))], ((1, 0), QQ(1)), lex, QQ)
  209. [((1, 1, 0), 1)]
  210. `(2xy) (3x f_1 + 4y f_2) = 8xy^2 f_2 + 6x^2y f_1`
  211. >>> f = [((2, 0, 1), QQ(4)), ((1, 1, 0), QQ(3))]
  212. >>> sdm_mul_term(f, ((1, 1), QQ(2)), lex, QQ)
  213. [((2, 1, 2), 8), ((1, 2, 1), 6)]
  214. """
  215. X, c = term
  216. if not f or not c:
  217. return []
  218. else:
  219. if K.is_one(c):
  220. return [ (sdm_monomial_mul(f_M, X), f_c) for f_M, f_c in f ]
  221. else:
  222. return [ (sdm_monomial_mul(f_M, X), f_c * c) for f_M, f_c in f ]
  223. def sdm_zero():
  224. """Return the zero module element."""
  225. return []
  226. def sdm_deg(f):
  227. """
  228. Degree of ``f``.
  229. This is the maximum of the degrees of all its monomials.
  230. Invalid if ``f`` is zero.
  231. Examples
  232. ========
  233. >>> from sympy.polys.distributedmodules import sdm_deg
  234. >>> sdm_deg([((1, 2, 3), 1), ((10, 0, 1), 1), ((2, 3, 4), 4)])
  235. 7
  236. """
  237. return max(sdm_monomial_deg(M[0]) for M in f)
  238. # Conversion
  239. def sdm_from_vector(vec, O, K, **opts):
  240. """
  241. Create an sdm from an iterable of expressions.
  242. Coefficients are created in the ground field ``K``, and terms are ordered
  243. according to monomial order ``O``. Named arguments are passed on to the
  244. polys conversion code and can be used to specify for example generators.
  245. Examples
  246. ========
  247. >>> from sympy.polys.distributedmodules import sdm_from_vector
  248. >>> from sympy.abc import x, y, z
  249. >>> from sympy.polys import QQ, lex
  250. >>> sdm_from_vector([x**2+y**2, 2*z], lex, QQ)
  251. [((1, 0, 0, 1), 2), ((0, 2, 0, 0), 1), ((0, 0, 2, 0), 1)]
  252. """
  253. dics, gens = parallel_dict_from_expr(sympify(vec), **opts)
  254. dic = {}
  255. for i, d in enumerate(dics):
  256. for k, v in d.items():
  257. dic[(i,) + k] = K.convert(v)
  258. return sdm_from_dict(dic, O)
  259. def sdm_to_vector(f, gens, K, n=None):
  260. """
  261. Convert sdm ``f`` into a list of polynomial expressions.
  262. The generators for the polynomial ring are specified via ``gens``. The rank
  263. of the module is guessed, or passed via ``n``. The ground field is assumed
  264. to be ``K``.
  265. Examples
  266. ========
  267. >>> from sympy.polys.distributedmodules import sdm_to_vector
  268. >>> from sympy.abc import x, y, z
  269. >>> from sympy.polys import QQ
  270. >>> f = [((1, 0, 0, 1), QQ(2)), ((0, 2, 0, 0), QQ(1)), ((0, 0, 2, 0), QQ(1))]
  271. >>> sdm_to_vector(f, [x, y, z], QQ)
  272. [x**2 + y**2, 2*z]
  273. """
  274. dic = sdm_to_dict(f)
  275. dics = {}
  276. for k, v in dic.items():
  277. dics.setdefault(k[0], []).append((k[1:], v))
  278. n = n or len(dics)
  279. res = []
  280. for k in range(n):
  281. if k in dics:
  282. res.append(Poly(dict(dics[k]), gens=gens, domain=K).as_expr())
  283. else:
  284. res.append(S.Zero)
  285. return res
  286. # Algorithms.
  287. def sdm_spoly(f, g, O, K, phantom=None):
  288. """
  289. Compute the generalized s-polynomial of ``f`` and ``g``.
  290. The ground field is assumed to be ``K``, and monomials ordered according to
  291. ``O``.
  292. This is invalid if either of ``f`` or ``g`` is zero.
  293. If the leading terms of `f` and `g` involve different basis elements of
  294. `F`, their s-poly is defined to be zero. Otherwise it is a certain linear
  295. combination of `f` and `g` in which the leading terms cancel.
  296. See [SCA, defn 2.3.6] for details.
  297. If ``phantom`` is not ``None``, it should be a pair of module elements on
  298. which to perform the same operation(s) as on ``f`` and ``g``. The in this
  299. case both results are returned.
  300. Examples
  301. ========
  302. >>> from sympy.polys.distributedmodules import sdm_spoly
  303. >>> from sympy.polys import QQ, lex
  304. >>> f = [((2, 1, 1), QQ(1)), ((1, 0, 1), QQ(1))]
  305. >>> g = [((2, 3, 0), QQ(1))]
  306. >>> h = [((1, 2, 3), QQ(1))]
  307. >>> sdm_spoly(f, h, lex, QQ)
  308. []
  309. >>> sdm_spoly(f, g, lex, QQ)
  310. [((1, 2, 1), 1)]
  311. """
  312. if not f or not g:
  313. return sdm_zero()
  314. LM1 = sdm_LM(f)
  315. LM2 = sdm_LM(g)
  316. if LM1[0] != LM2[0]:
  317. return sdm_zero()
  318. LM1 = LM1[1:]
  319. LM2 = LM2[1:]
  320. lcm = monomial_lcm(LM1, LM2)
  321. m1 = monomial_div(lcm, LM1)
  322. m2 = monomial_div(lcm, LM2)
  323. c = K.quo(-sdm_LC(f, K), sdm_LC(g, K))
  324. r1 = sdm_add(sdm_mul_term(f, (m1, K.one), O, K),
  325. sdm_mul_term(g, (m2, c), O, K), O, K)
  326. if phantom is None:
  327. return r1
  328. r2 = sdm_add(sdm_mul_term(phantom[0], (m1, K.one), O, K),
  329. sdm_mul_term(phantom[1], (m2, c), O, K), O, K)
  330. return r1, r2
  331. def sdm_ecart(f):
  332. """
  333. Compute the ecart of ``f``.
  334. This is defined to be the difference of the total degree of `f` and the
  335. total degree of the leading monomial of `f` [SCA, defn 2.3.7].
  336. Invalid if f is zero.
  337. Examples
  338. ========
  339. >>> from sympy.polys.distributedmodules import sdm_ecart
  340. >>> sdm_ecart([((1, 2, 3), 1), ((1, 0, 1), 1)])
  341. 0
  342. >>> sdm_ecart([((2, 2, 1), 1), ((1, 5, 1), 1)])
  343. 3
  344. """
  345. return sdm_deg(f) - sdm_monomial_deg(sdm_LM(f))
  346. def sdm_nf_mora(f, G, O, K, phantom=None):
  347. r"""
  348. Compute a weak normal form of ``f`` with respect to ``G`` and order ``O``.
  349. The ground field is assumed to be ``K``, and monomials ordered according to
  350. ``O``.
  351. Weak normal forms are defined in [SCA, defn 2.3.3]. They are not unique.
  352. This function deterministically computes a weak normal form, depending on
  353. the order of `G`.
  354. The most important property of a weak normal form is the following: if
  355. `R` is the ring associated with the monomial ordering (if the ordering is
  356. global, we just have `R = K[x_1, \ldots, x_n]`, otherwise it is a certain
  357. localization thereof), `I` any ideal of `R` and `G` a standard basis for
  358. `I`, then for any `f \in R`, we have `f \in I` if and only if
  359. `NF(f | G) = 0`.
  360. This is the generalized Mora algorithm for computing weak normal forms with
  361. respect to arbitrary monomial orders [SCA, algorithm 2.3.9].
  362. If ``phantom`` is not ``None``, it should be a pair of "phantom" arguments
  363. on which to perform the same computations as on ``f``, ``G``, both results
  364. are then returned.
  365. """
  366. from itertools import repeat
  367. h = f
  368. T = list(G)
  369. if phantom is not None:
  370. # "phantom" variables with suffix p
  371. hp = phantom[0]
  372. Tp = list(phantom[1])
  373. phantom = True
  374. else:
  375. Tp = repeat([])
  376. phantom = False
  377. while h:
  378. # TODO better data structure!!!
  379. Th = [(g, sdm_ecart(g), gp) for g, gp in zip(T, Tp)
  380. if sdm_monomial_divides(sdm_LM(g), sdm_LM(h))]
  381. if not Th:
  382. break
  383. g, _, gp = min(Th, key=lambda x: x[1])
  384. if sdm_ecart(g) > sdm_ecart(h):
  385. T.append(h)
  386. if phantom:
  387. Tp.append(hp)
  388. if phantom:
  389. h, hp = sdm_spoly(h, g, O, K, phantom=(hp, gp))
  390. else:
  391. h = sdm_spoly(h, g, O, K)
  392. if phantom:
  393. return h, hp
  394. return h
  395. def sdm_nf_buchberger(f, G, O, K, phantom=None):
  396. r"""
  397. Compute a weak normal form of ``f`` with respect to ``G`` and order ``O``.
  398. The ground field is assumed to be ``K``, and monomials ordered according to
  399. ``O``.
  400. This is the standard Buchberger algorithm for computing weak normal forms with
  401. respect to *global* monomial orders [SCA, algorithm 1.6.10].
  402. If ``phantom`` is not ``None``, it should be a pair of "phantom" arguments
  403. on which to perform the same computations as on ``f``, ``G``, both results
  404. are then returned.
  405. """
  406. from itertools import repeat
  407. h = f
  408. T = list(G)
  409. if phantom is not None:
  410. # "phantom" variables with suffix p
  411. hp = phantom[0]
  412. Tp = list(phantom[1])
  413. phantom = True
  414. else:
  415. Tp = repeat([])
  416. phantom = False
  417. while h:
  418. try:
  419. g, gp = next((g, gp) for g, gp in zip(T, Tp)
  420. if sdm_monomial_divides(sdm_LM(g), sdm_LM(h)))
  421. except StopIteration:
  422. break
  423. if phantom:
  424. h, hp = sdm_spoly(h, g, O, K, phantom=(hp, gp))
  425. else:
  426. h = sdm_spoly(h, g, O, K)
  427. if phantom:
  428. return h, hp
  429. return h
  430. def sdm_nf_buchberger_reduced(f, G, O, K):
  431. r"""
  432. Compute a reduced normal form of ``f`` with respect to ``G`` and order ``O``.
  433. The ground field is assumed to be ``K``, and monomials ordered according to
  434. ``O``.
  435. In contrast to weak normal forms, reduced normal forms *are* unique, but
  436. their computation is more expensive.
  437. This is the standard Buchberger algorithm for computing reduced normal forms
  438. with respect to *global* monomial orders [SCA, algorithm 1.6.11].
  439. The ``pantom`` option is not supported, so this normal form cannot be used
  440. as a normal form for the "extended" groebner algorithm.
  441. """
  442. h = sdm_zero()
  443. g = f
  444. while g:
  445. g = sdm_nf_buchberger(g, G, O, K)
  446. if g:
  447. h = sdm_add(h, [sdm_LT(g)], O, K)
  448. g = g[1:]
  449. return h
  450. def sdm_groebner(G, NF, O, K, extended=False):
  451. """
  452. Compute a minimal standard basis of ``G`` with respect to order ``O``.
  453. The algorithm uses a normal form ``NF``, for example ``sdm_nf_mora``.
  454. The ground field is assumed to be ``K``, and monomials ordered according
  455. to ``O``.
  456. Let `N` denote the submodule generated by elements of `G`. A standard
  457. basis for `N` is a subset `S` of `N`, such that `in(S) = in(N)`, where for
  458. any subset `X` of `F`, `in(X)` denotes the submodule generated by the
  459. initial forms of elements of `X`. [SCA, defn 2.3.2]
  460. A standard basis is called minimal if no subset of it is a standard basis.
  461. One may show that standard bases are always generating sets.
  462. Minimal standard bases are not unique. This algorithm computes a
  463. deterministic result, depending on the particular order of `G`.
  464. If ``extended=True``, also compute the transition matrix from the initial
  465. generators to the groebner basis. That is, return a list of coefficient
  466. vectors, expressing the elements of the groebner basis in terms of the
  467. elements of ``G``.
  468. This functions implements the "sugar" strategy, see
  469. Giovini et al: "One sugar cube, please" OR Selection strategies in
  470. Buchberger algorithm.
  471. """
  472. # The critical pair set.
  473. # A critical pair is stored as (i, j, s, t) where (i, j) defines the pair
  474. # (by indexing S), s is the sugar of the pair, and t is the lcm of their
  475. # leading monomials.
  476. P = []
  477. # The eventual standard basis.
  478. S = []
  479. Sugars = []
  480. def Ssugar(i, j):
  481. """Compute the sugar of the S-poly corresponding to (i, j)."""
  482. LMi = sdm_LM(S[i])
  483. LMj = sdm_LM(S[j])
  484. return max(Sugars[i] - sdm_monomial_deg(LMi),
  485. Sugars[j] - sdm_monomial_deg(LMj)) \
  486. + sdm_monomial_deg(sdm_monomial_lcm(LMi, LMj))
  487. ourkey = lambda p: (p[2], O(p[3]), p[1])
  488. def update(f, sugar, P):
  489. """Add f with sugar ``sugar`` to S, update P."""
  490. if not f:
  491. return P
  492. k = len(S)
  493. S.append(f)
  494. Sugars.append(sugar)
  495. LMf = sdm_LM(f)
  496. def removethis(pair):
  497. i, j, s, t = pair
  498. if LMf[0] != t[0]:
  499. return False
  500. tik = sdm_monomial_lcm(LMf, sdm_LM(S[i]))
  501. tjk = sdm_monomial_lcm(LMf, sdm_LM(S[j]))
  502. return tik != t and tjk != t and sdm_monomial_divides(tik, t) and \
  503. sdm_monomial_divides(tjk, t)
  504. # apply the chain criterion
  505. P = [p for p in P if not removethis(p)]
  506. # new-pair set
  507. N = [(i, k, Ssugar(i, k), sdm_monomial_lcm(LMf, sdm_LM(S[i])))
  508. for i in range(k) if LMf[0] == sdm_LM(S[i])[0]]
  509. # TODO apply the product criterion?
  510. N.sort(key=ourkey)
  511. remove = set()
  512. for i, p in enumerate(N):
  513. for j in range(i + 1, len(N)):
  514. if sdm_monomial_divides(p[3], N[j][3]):
  515. remove.add(j)
  516. # TODO mergesort?
  517. P.extend(reversed([p for i, p in enumerate(N) if i not in remove]))
  518. P.sort(key=ourkey, reverse=True)
  519. # NOTE reverse-sort, because we want to pop from the end
  520. return P
  521. # Figure out the number of generators in the ground ring.
  522. try:
  523. # NOTE: we look for the first non-zero vector, take its first monomial
  524. # the number of generators in the ring is one less than the length
  525. # (since the zeroth entry is for the module generators)
  526. numgens = len(next(x[0] for x in G if x)[0]) - 1
  527. except StopIteration:
  528. # No non-zero elements in G ...
  529. if extended:
  530. return [], []
  531. return []
  532. # This list will store expressions of the elements of S in terms of the
  533. # initial generators
  534. coefficients = []
  535. # First add all the elements of G to S
  536. for i, f in enumerate(G):
  537. P = update(f, sdm_deg(f), P)
  538. if extended and f:
  539. coefficients.append(sdm_from_dict({(i,) + (0,)*numgens: K(1)}, O))
  540. # Now carry out the buchberger algorithm.
  541. while P:
  542. i, j, s, t = P.pop()
  543. f, g = S[i], S[j]
  544. if extended:
  545. sp, coeff = sdm_spoly(f, g, O, K,
  546. phantom=(coefficients[i], coefficients[j]))
  547. h, hcoeff = NF(sp, S, O, K, phantom=(coeff, coefficients))
  548. if h:
  549. coefficients.append(hcoeff)
  550. else:
  551. h = NF(sdm_spoly(f, g, O, K), S, O, K)
  552. P = update(h, Ssugar(i, j), P)
  553. # Finally interreduce the standard basis.
  554. # (TODO again, better data structures)
  555. S = {(tuple(f), i) for i, f in enumerate(S)}
  556. for (a, ai), (b, bi) in permutations(S, 2):
  557. A = sdm_LM(a)
  558. B = sdm_LM(b)
  559. if sdm_monomial_divides(A, B) and (b, bi) in S and (a, ai) in S:
  560. S.remove((b, bi))
  561. L = sorted(((list(f), i) for f, i in S), key=lambda p: O(sdm_LM(p[0])),
  562. reverse=True)
  563. res = [x[0] for x in L]
  564. if extended:
  565. return res, [coefficients[i] for _, i in L]
  566. return res