extensions.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. """Finite extensions of ring domains."""
  2. from sympy.polys.domains.domain import Domain
  3. from sympy.polys.domains.domainelement import DomainElement
  4. from sympy.polys.polyerrors import (CoercionFailed, NotInvertible,
  5. GeneratorsError)
  6. from sympy.polys.polytools import Poly
  7. from sympy.printing.defaults import DefaultPrinting
  8. class ExtensionElement(DomainElement, DefaultPrinting):
  9. """
  10. Element of a finite extension.
  11. A class of univariate polynomials modulo the ``modulus``
  12. of the extension ``ext``. It is represented by the
  13. unique polynomial ``rep`` of lowest degree. Both
  14. ``rep`` and the representation ``mod`` of ``modulus``
  15. are of class DMP.
  16. """
  17. __slots__ = ('rep', 'ext')
  18. def __init__(self, rep, ext):
  19. self.rep = rep
  20. self.ext = ext
  21. def parent(f):
  22. return f.ext
  23. def __bool__(f):
  24. return bool(f.rep)
  25. def __pos__(f):
  26. return f
  27. def __neg__(f):
  28. return ExtElem(-f.rep, f.ext)
  29. def _get_rep(f, g):
  30. if isinstance(g, ExtElem):
  31. if g.ext == f.ext:
  32. return g.rep
  33. else:
  34. return None
  35. else:
  36. try:
  37. g = f.ext.convert(g)
  38. return g.rep
  39. except CoercionFailed:
  40. return None
  41. def __add__(f, g):
  42. rep = f._get_rep(g)
  43. if rep is not None:
  44. return ExtElem(f.rep + rep, f.ext)
  45. else:
  46. return NotImplemented
  47. __radd__ = __add__
  48. def __sub__(f, g):
  49. rep = f._get_rep(g)
  50. if rep is not None:
  51. return ExtElem(f.rep - rep, f.ext)
  52. else:
  53. return NotImplemented
  54. def __rsub__(f, g):
  55. rep = f._get_rep(g)
  56. if rep is not None:
  57. return ExtElem(rep - f.rep, f.ext)
  58. else:
  59. return NotImplemented
  60. def __mul__(f, g):
  61. rep = f._get_rep(g)
  62. if rep is not None:
  63. return ExtElem((f.rep * rep) % f.ext.mod, f.ext)
  64. else:
  65. return NotImplemented
  66. __rmul__ = __mul__
  67. def _divcheck(f):
  68. """Raise if division is not implemented for this divisor"""
  69. if not f:
  70. raise NotInvertible('Zero divisor')
  71. elif f.ext.is_Field:
  72. return True
  73. elif f.rep.is_ground and f.ext.domain.is_unit(f.rep.rep[0]):
  74. return True
  75. else:
  76. # Some cases like (2*x + 2)/2 over ZZ will fail here. It is
  77. # unclear how to implement division in general if the ground
  78. # domain is not a field so for now it was decided to restrict the
  79. # implementation to division by invertible constants.
  80. msg = (f"Can not invert {f} in {f.ext}. "
  81. "Only division by invertible constants is implemented.")
  82. raise NotImplementedError(msg)
  83. def inverse(f):
  84. """Multiplicative inverse.
  85. Raises
  86. ======
  87. NotInvertible
  88. If the element is a zero divisor.
  89. """
  90. f._divcheck()
  91. if f.ext.is_Field:
  92. invrep = f.rep.invert(f.ext.mod)
  93. else:
  94. R = f.ext.ring
  95. invrep = R.exquo(R.one, f.rep)
  96. return ExtElem(invrep, f.ext)
  97. def __truediv__(f, g):
  98. rep = f._get_rep(g)
  99. if rep is None:
  100. return NotImplemented
  101. g = ExtElem(rep, f.ext)
  102. try:
  103. ginv = g.inverse()
  104. except NotInvertible:
  105. raise ZeroDivisionError(f"{f} / {g}")
  106. return f * ginv
  107. __floordiv__ = __truediv__
  108. def __rtruediv__(f, g):
  109. try:
  110. g = f.ext.convert(g)
  111. except CoercionFailed:
  112. return NotImplemented
  113. return g / f
  114. __rfloordiv__ = __rtruediv__
  115. def __mod__(f, g):
  116. rep = f._get_rep(g)
  117. if rep is None:
  118. return NotImplemented
  119. g = ExtElem(rep, f.ext)
  120. try:
  121. g._divcheck()
  122. except NotInvertible:
  123. raise ZeroDivisionError(f"{f} % {g}")
  124. # Division where defined is always exact so there is no remainder
  125. return f.ext.zero
  126. def __rmod__(f, g):
  127. try:
  128. g = f.ext.convert(g)
  129. except CoercionFailed:
  130. return NotImplemented
  131. return g % f
  132. def __pow__(f, n):
  133. if not isinstance(n, int):
  134. raise TypeError("exponent of type 'int' expected")
  135. if n < 0:
  136. try:
  137. f, n = f.inverse(), -n
  138. except NotImplementedError:
  139. raise ValueError("negative powers are not defined")
  140. b = f.rep
  141. m = f.ext.mod
  142. r = f.ext.one.rep
  143. while n > 0:
  144. if n % 2:
  145. r = (r*b) % m
  146. b = (b*b) % m
  147. n //= 2
  148. return ExtElem(r, f.ext)
  149. def __eq__(f, g):
  150. if isinstance(g, ExtElem):
  151. return f.rep == g.rep and f.ext == g.ext
  152. else:
  153. return NotImplemented
  154. def __ne__(f, g):
  155. return not f == g
  156. def __hash__(f):
  157. return hash((f.rep, f.ext))
  158. def __str__(f):
  159. from sympy.printing.str import sstr
  160. return sstr(f.rep)
  161. __repr__ = __str__
  162. @property
  163. def is_ground(f):
  164. return f.rep.is_ground
  165. def to_ground(f):
  166. [c] = f.rep.to_list()
  167. return c
  168. ExtElem = ExtensionElement
  169. class MonogenicFiniteExtension(Domain):
  170. r"""
  171. Finite extension generated by an integral element.
  172. The generator is defined by a monic univariate
  173. polynomial derived from the argument ``mod``.
  174. A shorter alias is ``FiniteExtension``.
  175. Examples
  176. ========
  177. Quadratic integer ring $\mathbb{Z}[\sqrt2]$:
  178. >>> from sympy import Symbol, Poly
  179. >>> from sympy.polys.agca.extensions import FiniteExtension
  180. >>> x = Symbol('x')
  181. >>> R = FiniteExtension(Poly(x**2 - 2)); R
  182. ZZ[x]/(x**2 - 2)
  183. >>> R.rank
  184. 2
  185. >>> R(1 + x)*(3 - 2*x)
  186. x - 1
  187. Finite field $GF(5^3)$ defined by the primitive
  188. polynomial $x^3 + x^2 + 2$ (over $\mathbb{Z}_5$).
  189. >>> F = FiniteExtension(Poly(x**3 + x**2 + 2, modulus=5)); F
  190. GF(5)[x]/(x**3 + x**2 + 2)
  191. >>> F.basis
  192. (1, x, x**2)
  193. >>> F(x + 3)/(x**2 + 2)
  194. -2*x**2 + x + 2
  195. Function field of an elliptic curve:
  196. >>> t = Symbol('t')
  197. >>> FiniteExtension(Poly(t**2 - x**3 - x + 1, t, field=True))
  198. ZZ(x)[t]/(t**2 - x**3 - x + 1)
  199. """
  200. is_FiniteExtension = True
  201. dtype = ExtensionElement
  202. def __init__(self, mod):
  203. if not (isinstance(mod, Poly) and mod.is_univariate):
  204. raise TypeError("modulus must be a univariate Poly")
  205. # Using auto=True (default) potentially changes the ground domain to a
  206. # field whereas auto=False raises if division is not exact. We'll let
  207. # the caller decide whether or not they want to put the ground domain
  208. # over a field. In most uses mod is already monic.
  209. mod = mod.monic(auto=False)
  210. self.rank = mod.degree()
  211. self.modulus = mod
  212. self.mod = mod.rep # DMP representation
  213. self.domain = dom = mod.domain
  214. self.ring = mod.rep.ring or dom.old_poly_ring(*mod.gens)
  215. self.zero = self.convert(self.ring.zero)
  216. self.one = self.convert(self.ring.one)
  217. gen = self.ring.gens[0]
  218. self.symbol = self.ring.symbols[0]
  219. self.generator = self.convert(gen)
  220. self.basis = tuple(self.convert(gen**i) for i in range(self.rank))
  221. # XXX: It might be necessary to check mod.is_irreducible here
  222. self.is_Field = self.domain.is_Field
  223. def new(self, arg):
  224. rep = self.ring.convert(arg)
  225. return ExtElem(rep % self.mod, self)
  226. def __eq__(self, other):
  227. if not isinstance(other, FiniteExtension):
  228. return False
  229. return self.modulus == other.modulus
  230. def __hash__(self):
  231. return hash((self.__class__.__name__, self.modulus))
  232. def __str__(self):
  233. return "%s/(%s)" % (self.ring, self.modulus.as_expr())
  234. __repr__ = __str__
  235. def convert(self, f, base=None):
  236. rep = self.ring.convert(f, base)
  237. return ExtElem(rep % self.mod, self)
  238. def convert_from(self, f, base):
  239. rep = self.ring.convert(f, base)
  240. return ExtElem(rep % self.mod, self)
  241. def to_sympy(self, f):
  242. return self.ring.to_sympy(f.rep)
  243. def from_sympy(self, f):
  244. return self.convert(f)
  245. def set_domain(self, K):
  246. mod = self.modulus.set_domain(K)
  247. return self.__class__(mod)
  248. def drop(self, *symbols):
  249. if self.symbol in symbols:
  250. raise GeneratorsError('Can not drop generator from FiniteExtension')
  251. K = self.domain.drop(*symbols)
  252. return self.set_domain(K)
  253. def quo(self, f, g):
  254. return self.exquo(f, g)
  255. def exquo(self, f, g):
  256. rep = self.ring.exquo(f.rep, g.rep)
  257. return ExtElem(rep % self.mod, self)
  258. def is_negative(self, a):
  259. return False
  260. def is_unit(self, a):
  261. if self.is_Field:
  262. return bool(a)
  263. elif a.is_ground:
  264. return self.domain.is_unit(a.to_ground())
  265. FiniteExtension = MonogenicFiniteExtension