domain.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  1. """Implementation of :class:`Domain` class. """
  2. from __future__ import annotations
  3. from typing import Any
  4. from sympy.core.numbers import AlgebraicNumber
  5. from sympy.core import Basic, sympify
  6. from sympy.core.sorting import ordered
  7. from sympy.external.gmpy import GROUND_TYPES
  8. from sympy.polys.domains.domainelement import DomainElement
  9. from sympy.polys.orderings import lex
  10. from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError
  11. from sympy.polys.polyutils import _unify_gens, _not_a_coeff
  12. from sympy.utilities import public
  13. from sympy.utilities.iterables import is_sequence
  14. @public
  15. class Domain:
  16. """Superclass for all domains in the polys domains system.
  17. See :ref:`polys-domainsintro` for an introductory explanation of the
  18. domains system.
  19. The :py:class:`~.Domain` class is an abstract base class for all of the
  20. concrete domain types. There are many different :py:class:`~.Domain`
  21. subclasses each of which has an associated ``dtype`` which is a class
  22. representing the elements of the domain. The coefficients of a
  23. :py:class:`~.Poly` are elements of a domain which must be a subclass of
  24. :py:class:`~.Domain`.
  25. Examples
  26. ========
  27. The most common example domains are the integers :ref:`ZZ` and the
  28. rationals :ref:`QQ`.
  29. >>> from sympy import Poly, symbols, Domain
  30. >>> x, y = symbols('x, y')
  31. >>> p = Poly(x**2 + y)
  32. >>> p
  33. Poly(x**2 + y, x, y, domain='ZZ')
  34. >>> p.domain
  35. ZZ
  36. >>> isinstance(p.domain, Domain)
  37. True
  38. >>> Poly(x**2 + y/2)
  39. Poly(x**2 + 1/2*y, x, y, domain='QQ')
  40. The domains can be used directly in which case the domain object e.g.
  41. (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of
  42. ``dtype``.
  43. >>> from sympy import ZZ, QQ
  44. >>> ZZ(2)
  45. 2
  46. >>> ZZ.dtype # doctest: +SKIP
  47. <class 'int'>
  48. >>> type(ZZ(2)) # doctest: +SKIP
  49. <class 'int'>
  50. >>> QQ(1, 2)
  51. 1/2
  52. >>> type(QQ(1, 2)) # doctest: +SKIP
  53. <class 'sympy.polys.domains.pythonrational.PythonRational'>
  54. The corresponding domain elements can be used with the arithmetic
  55. operations ``+,-,*,**`` and depending on the domain some combination of
  56. ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor
  57. division) and ``%`` (modulo division) can be used but ``/`` (true
  58. division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements
  59. can be used with ``/`` but ``//`` and ``%`` should not be used. Some
  60. domains have a :py:meth:`~.Domain.gcd` method.
  61. >>> ZZ(2) + ZZ(3)
  62. 5
  63. >>> ZZ(5) // ZZ(2)
  64. 2
  65. >>> ZZ(5) % ZZ(2)
  66. 1
  67. >>> QQ(1, 2) / QQ(2, 3)
  68. 3/4
  69. >>> ZZ.gcd(ZZ(4), ZZ(2))
  70. 2
  71. >>> QQ.gcd(QQ(2,7), QQ(5,3))
  72. 1/21
  73. >>> ZZ.is_Field
  74. False
  75. >>> QQ.is_Field
  76. True
  77. There are also many other domains including:
  78. 1. :ref:`GF(p)` for finite fields of prime order.
  79. 2. :ref:`RR` for real (floating point) numbers.
  80. 3. :ref:`CC` for complex (floating point) numbers.
  81. 4. :ref:`QQ(a)` for algebraic number fields.
  82. 5. :ref:`K[x]` for polynomial rings.
  83. 6. :ref:`K(x)` for rational function fields.
  84. 7. :ref:`EX` for arbitrary expressions.
  85. Each domain is represented by a domain object and also an implementation
  86. class (``dtype``) for the elements of the domain. For example the
  87. :ref:`K[x]` domains are represented by a domain object which is an
  88. instance of :py:class:`~.PolynomialRing` and the elements are always
  89. instances of :py:class:`~.PolyElement`. The implementation class
  90. represents particular types of mathematical expressions in a way that is
  91. more efficient than a normal SymPy expression which is of type
  92. :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and
  93. :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr`
  94. to a domain element and vice versa.
  95. >>> from sympy import Symbol, ZZ, Expr
  96. >>> x = Symbol('x')
  97. >>> K = ZZ[x] # polynomial ring domain
  98. >>> K
  99. ZZ[x]
  100. >>> type(K) # class of the domain
  101. <class 'sympy.polys.domains.polynomialring.PolynomialRing'>
  102. >>> K.dtype # doctest: +SKIP
  103. <class 'sympy.polys.rings.PolyElement'>
  104. >>> p_expr = x**2 + 1 # Expr
  105. >>> p_expr
  106. x**2 + 1
  107. >>> type(p_expr)
  108. <class 'sympy.core.add.Add'>
  109. >>> isinstance(p_expr, Expr)
  110. True
  111. >>> p_domain = K.from_sympy(p_expr)
  112. >>> p_domain # domain element
  113. x**2 + 1
  114. >>> type(p_domain)
  115. <class 'sympy.polys.rings.PolyElement'>
  116. >>> K.to_sympy(p_domain) == p_expr
  117. True
  118. The :py:meth:`~.Domain.convert_from` method is used to convert domain
  119. elements from one domain to another.
  120. >>> from sympy import ZZ, QQ
  121. >>> ez = ZZ(2)
  122. >>> eq = QQ.convert_from(ez, ZZ)
  123. >>> type(ez) # doctest: +SKIP
  124. <class 'int'>
  125. >>> type(eq) # doctest: +SKIP
  126. <class 'sympy.polys.domains.pythonrational.PythonRational'>
  127. Elements from different domains should not be mixed in arithmetic or other
  128. operations: they should be converted to a common domain first. The domain
  129. method :py:meth:`~.Domain.unify` is used to find a domain that can
  130. represent all the elements of two given domains.
  131. >>> from sympy import ZZ, QQ, symbols
  132. >>> x, y = symbols('x, y')
  133. >>> ZZ.unify(QQ)
  134. QQ
  135. >>> ZZ[x].unify(QQ)
  136. QQ[x]
  137. >>> ZZ[x].unify(QQ[y])
  138. QQ[x,y]
  139. If a domain is a :py:class:`~.Ring` then is might have an associated
  140. :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and
  141. :py:meth:`~.Domain.get_ring` methods will find or create the associated
  142. domain.
  143. >>> from sympy import ZZ, QQ, Symbol
  144. >>> x = Symbol('x')
  145. >>> ZZ.has_assoc_Field
  146. True
  147. >>> ZZ.get_field()
  148. QQ
  149. >>> QQ.has_assoc_Ring
  150. True
  151. >>> QQ.get_ring()
  152. ZZ
  153. >>> K = QQ[x]
  154. >>> K
  155. QQ[x]
  156. >>> K.get_field()
  157. QQ(x)
  158. See also
  159. ========
  160. DomainElement: abstract base class for domain elements
  161. construct_domain: construct a minimal domain for some expressions
  162. """
  163. dtype: type | None = None
  164. """The type (class) of the elements of this :py:class:`~.Domain`:
  165. >>> from sympy import ZZ, QQ, Symbol
  166. >>> ZZ.dtype
  167. <class 'int'>
  168. >>> z = ZZ(2)
  169. >>> z
  170. 2
  171. >>> type(z)
  172. <class 'int'>
  173. >>> type(z) == ZZ.dtype
  174. True
  175. Every domain has an associated **dtype** ("datatype") which is the
  176. class of the associated domain elements.
  177. See also
  178. ========
  179. of_type
  180. """
  181. zero: Any = None
  182. """The zero element of the :py:class:`~.Domain`:
  183. >>> from sympy import QQ
  184. >>> QQ.zero
  185. 0
  186. >>> QQ.of_type(QQ.zero)
  187. True
  188. See also
  189. ========
  190. of_type
  191. one
  192. """
  193. one: Any = None
  194. """The one element of the :py:class:`~.Domain`:
  195. >>> from sympy import QQ
  196. >>> QQ.one
  197. 1
  198. >>> QQ.of_type(QQ.one)
  199. True
  200. See also
  201. ========
  202. of_type
  203. zero
  204. """
  205. is_Ring = False
  206. """Boolean flag indicating if the domain is a :py:class:`~.Ring`.
  207. >>> from sympy import ZZ
  208. >>> ZZ.is_Ring
  209. True
  210. Basically every :py:class:`~.Domain` represents a ring so this flag is
  211. not that useful.
  212. See also
  213. ========
  214. is_PID
  215. is_Field
  216. get_ring
  217. has_assoc_Ring
  218. """
  219. is_Field = False
  220. """Boolean flag indicating if the domain is a :py:class:`~.Field`.
  221. >>> from sympy import ZZ, QQ
  222. >>> ZZ.is_Field
  223. False
  224. >>> QQ.is_Field
  225. True
  226. See also
  227. ========
  228. is_PID
  229. is_Ring
  230. get_field
  231. has_assoc_Field
  232. """
  233. has_assoc_Ring = False
  234. """Boolean flag indicating if the domain has an associated
  235. :py:class:`~.Ring`.
  236. >>> from sympy import QQ
  237. >>> QQ.has_assoc_Ring
  238. True
  239. >>> QQ.get_ring()
  240. ZZ
  241. See also
  242. ========
  243. is_Field
  244. get_ring
  245. """
  246. has_assoc_Field = False
  247. """Boolean flag indicating if the domain has an associated
  248. :py:class:`~.Field`.
  249. >>> from sympy import ZZ
  250. >>> ZZ.has_assoc_Field
  251. True
  252. >>> ZZ.get_field()
  253. QQ
  254. See also
  255. ========
  256. is_Field
  257. get_field
  258. """
  259. is_FiniteField = is_FF = False
  260. is_IntegerRing = is_ZZ = False
  261. is_RationalField = is_QQ = False
  262. is_GaussianRing = is_ZZ_I = False
  263. is_GaussianField = is_QQ_I = False
  264. is_RealField = is_RR = False
  265. is_ComplexField = is_CC = False
  266. is_AlgebraicField = is_Algebraic = False
  267. is_PolynomialRing = is_Poly = False
  268. is_FractionField = is_Frac = False
  269. is_SymbolicDomain = is_EX = False
  270. is_SymbolicRawDomain = is_EXRAW = False
  271. is_FiniteExtension = False
  272. is_Exact = True
  273. is_Numerical = False
  274. is_Simple = False
  275. is_Composite = False
  276. is_PID = False
  277. """Boolean flag indicating if the domain is a `principal ideal domain`_.
  278. >>> from sympy import ZZ
  279. >>> ZZ.has_assoc_Field
  280. True
  281. >>> ZZ.get_field()
  282. QQ
  283. .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain
  284. See also
  285. ========
  286. is_Field
  287. get_field
  288. """
  289. has_CharacteristicZero = False
  290. rep: str | None = None
  291. alias: str | None = None
  292. def __init__(self):
  293. raise NotImplementedError
  294. def __str__(self):
  295. return self.rep
  296. def __repr__(self):
  297. return str(self)
  298. def __hash__(self):
  299. return hash((self.__class__.__name__, self.dtype))
  300. def new(self, *args):
  301. return self.dtype(*args)
  302. @property
  303. def tp(self):
  304. """Alias for :py:attr:`~.Domain.dtype`"""
  305. return self.dtype
  306. def __call__(self, *args):
  307. """Construct an element of ``self`` domain from ``args``. """
  308. return self.new(*args)
  309. def normal(self, *args):
  310. return self.dtype(*args)
  311. def convert_from(self, element, base):
  312. """Convert ``element`` to ``self.dtype`` given the base domain. """
  313. if base.alias is not None:
  314. method = "from_" + base.alias
  315. else:
  316. method = "from_" + base.__class__.__name__
  317. _convert = getattr(self, method)
  318. if _convert is not None:
  319. result = _convert(element, base)
  320. if result is not None:
  321. return result
  322. raise CoercionFailed("Cannot convert %s of type %s from %s to %s" % (element, type(element), base, self))
  323. def convert(self, element, base=None):
  324. """Convert ``element`` to ``self.dtype``. """
  325. if base is not None:
  326. if _not_a_coeff(element):
  327. raise CoercionFailed('%s is not in any domain' % element)
  328. return self.convert_from(element, base)
  329. if self.of_type(element):
  330. return element
  331. if _not_a_coeff(element):
  332. raise CoercionFailed('%s is not in any domain' % element)
  333. from sympy.polys.domains import ZZ, QQ, RealField, ComplexField
  334. if ZZ.of_type(element):
  335. return self.convert_from(element, ZZ)
  336. if isinstance(element, int):
  337. return self.convert_from(ZZ(element), ZZ)
  338. if GROUND_TYPES != 'python':
  339. if isinstance(element, ZZ.tp):
  340. return self.convert_from(element, ZZ)
  341. if isinstance(element, QQ.tp):
  342. return self.convert_from(element, QQ)
  343. if isinstance(element, float):
  344. parent = RealField()
  345. return self.convert_from(parent(element), parent)
  346. if isinstance(element, complex):
  347. parent = ComplexField()
  348. return self.convert_from(parent(element), parent)
  349. if type(element).__name__ == 'mpf':
  350. parent = RealField()
  351. return self.convert_from(parent(element), parent)
  352. if type(element).__name__ == 'mpc':
  353. parent = ComplexField()
  354. return self.convert_from(parent(element), parent)
  355. if isinstance(element, DomainElement):
  356. return self.convert_from(element, element.parent())
  357. # TODO: implement this in from_ methods
  358. if self.is_Numerical and getattr(element, 'is_ground', False):
  359. return self.convert(element.LC())
  360. if isinstance(element, Basic):
  361. try:
  362. return self.from_sympy(element)
  363. except (TypeError, ValueError):
  364. pass
  365. else: # TODO: remove this branch
  366. if not is_sequence(element):
  367. try:
  368. element = sympify(element, strict=True)
  369. if isinstance(element, Basic):
  370. return self.from_sympy(element)
  371. except (TypeError, ValueError):
  372. pass
  373. raise CoercionFailed("Cannot convert %s of type %s to %s" % (element, type(element), self))
  374. def of_type(self, element):
  375. """Check if ``a`` is of type ``dtype``. """
  376. return isinstance(element, self.tp)
  377. def __contains__(self, a):
  378. """Check if ``a`` belongs to this domain. """
  379. try:
  380. if _not_a_coeff(a):
  381. raise CoercionFailed
  382. self.convert(a) # this might raise, too
  383. except CoercionFailed:
  384. return False
  385. return True
  386. def to_sympy(self, a):
  387. """Convert domain element *a* to a SymPy expression (Expr).
  388. Explanation
  389. ===========
  390. Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most
  391. public SymPy functions work with objects of type :py:class:`~.Expr`.
  392. The elements of a :py:class:`~.Domain` have a different internal
  393. representation. It is not possible to mix domain elements with
  394. :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and
  395. :py:meth:`~.Domain.from_sympy` methods to convert its domain elements
  396. to and from :py:class:`~.Expr`.
  397. Parameters
  398. ==========
  399. a: domain element
  400. An element of this :py:class:`~.Domain`.
  401. Returns
  402. =======
  403. expr: Expr
  404. A normal SymPy expression of type :py:class:`~.Expr`.
  405. Examples
  406. ========
  407. Construct an element of the :ref:`QQ` domain and then convert it to
  408. :py:class:`~.Expr`.
  409. >>> from sympy import QQ, Expr
  410. >>> q_domain = QQ(2)
  411. >>> q_domain
  412. 2
  413. >>> q_expr = QQ.to_sympy(q_domain)
  414. >>> q_expr
  415. 2
  416. Although the printed forms look similar these objects are not of the
  417. same type.
  418. >>> isinstance(q_domain, Expr)
  419. False
  420. >>> isinstance(q_expr, Expr)
  421. True
  422. Construct an element of :ref:`K[x]` and convert to
  423. :py:class:`~.Expr`.
  424. >>> from sympy import Symbol
  425. >>> x = Symbol('x')
  426. >>> K = QQ[x]
  427. >>> x_domain = K.gens[0] # generator x as a domain element
  428. >>> p_domain = x_domain**2/3 + 1
  429. >>> p_domain
  430. 1/3*x**2 + 1
  431. >>> p_expr = K.to_sympy(p_domain)
  432. >>> p_expr
  433. x**2/3 + 1
  434. The :py:meth:`~.Domain.from_sympy` method is used for the opposite
  435. conversion from a normal SymPy expression to a domain element.
  436. >>> p_domain == p_expr
  437. False
  438. >>> K.from_sympy(p_expr) == p_domain
  439. True
  440. >>> K.to_sympy(p_domain) == p_expr
  441. True
  442. >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain
  443. True
  444. >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr
  445. True
  446. The :py:meth:`~.Domain.from_sympy` method makes it easier to construct
  447. domain elements interactively.
  448. >>> from sympy import Symbol
  449. >>> x = Symbol('x')
  450. >>> K = QQ[x]
  451. >>> K.from_sympy(x**2/3 + 1)
  452. 1/3*x**2 + 1
  453. See also
  454. ========
  455. from_sympy
  456. convert_from
  457. """
  458. raise NotImplementedError
  459. def from_sympy(self, a):
  460. """Convert a SymPy expression to an element of this domain.
  461. Explanation
  462. ===========
  463. See :py:meth:`~.Domain.to_sympy` for explanation and examples.
  464. Parameters
  465. ==========
  466. expr: Expr
  467. A normal SymPy expression of type :py:class:`~.Expr`.
  468. Returns
  469. =======
  470. a: domain element
  471. An element of this :py:class:`~.Domain`.
  472. See also
  473. ========
  474. to_sympy
  475. convert_from
  476. """
  477. raise NotImplementedError
  478. def sum(self, args):
  479. return sum(args, start=self.zero)
  480. def from_FF(K1, a, K0):
  481. """Convert ``ModularInteger(int)`` to ``dtype``. """
  482. return None
  483. def from_FF_python(K1, a, K0):
  484. """Convert ``ModularInteger(int)`` to ``dtype``. """
  485. return None
  486. def from_ZZ_python(K1, a, K0):
  487. """Convert a Python ``int`` object to ``dtype``. """
  488. return None
  489. def from_QQ_python(K1, a, K0):
  490. """Convert a Python ``Fraction`` object to ``dtype``. """
  491. return None
  492. def from_FF_gmpy(K1, a, K0):
  493. """Convert ``ModularInteger(mpz)`` to ``dtype``. """
  494. return None
  495. def from_ZZ_gmpy(K1, a, K0):
  496. """Convert a GMPY ``mpz`` object to ``dtype``. """
  497. return None
  498. def from_QQ_gmpy(K1, a, K0):
  499. """Convert a GMPY ``mpq`` object to ``dtype``. """
  500. return None
  501. def from_RealField(K1, a, K0):
  502. """Convert a real element object to ``dtype``. """
  503. return None
  504. def from_ComplexField(K1, a, K0):
  505. """Convert a complex element to ``dtype``. """
  506. return None
  507. def from_AlgebraicField(K1, a, K0):
  508. """Convert an algebraic number to ``dtype``. """
  509. return None
  510. def from_PolynomialRing(K1, a, K0):
  511. """Convert a polynomial to ``dtype``. """
  512. if a.is_ground:
  513. return K1.convert(a.LC, K0.dom)
  514. def from_FractionField(K1, a, K0):
  515. """Convert a rational function to ``dtype``. """
  516. return None
  517. def from_MonogenicFiniteExtension(K1, a, K0):
  518. """Convert an ``ExtensionElement`` to ``dtype``. """
  519. return K1.convert_from(a.rep, K0.ring)
  520. def from_ExpressionDomain(K1, a, K0):
  521. """Convert a ``EX`` object to ``dtype``. """
  522. return K1.from_sympy(a.ex)
  523. def from_ExpressionRawDomain(K1, a, K0):
  524. """Convert a ``EX`` object to ``dtype``. """
  525. return K1.from_sympy(a)
  526. def from_GlobalPolynomialRing(K1, a, K0):
  527. """Convert a polynomial to ``dtype``. """
  528. if a.degree() <= 0:
  529. return K1.convert(a.LC(), K0.dom)
  530. def from_GeneralizedPolynomialRing(K1, a, K0):
  531. return K1.from_FractionField(a, K0)
  532. def unify_with_symbols(K0, K1, symbols):
  533. if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))):
  534. raise UnificationFailed("Cannot unify %s with %s, given %s generators" % (K0, K1, tuple(symbols)))
  535. return K0.unify(K1)
  536. def unify_composite(K0, K1):
  537. """Unify two domains where at least one is composite."""
  538. K0_ground = K0.dom if K0.is_Composite else K0
  539. K1_ground = K1.dom if K1.is_Composite else K1
  540. K0_symbols = K0.symbols if K0.is_Composite else ()
  541. K1_symbols = K1.symbols if K1.is_Composite else ()
  542. domain = K0_ground.unify(K1_ground)
  543. symbols = _unify_gens(K0_symbols, K1_symbols)
  544. order = K0.order if K0.is_Composite else K1.order
  545. # E.g. ZZ[x].unify(QQ.frac_field(x)) -> ZZ.frac_field(x)
  546. if ((K0.is_FractionField and K1.is_PolynomialRing or
  547. K1.is_FractionField and K0.is_PolynomialRing) and
  548. (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field
  549. and domain.has_assoc_Ring):
  550. domain = domain.get_ring()
  551. if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing):
  552. cls = K0.__class__
  553. else:
  554. cls = K1.__class__
  555. # Here cls might be PolynomialRing, FractionField, GlobalPolynomialRing
  556. # (dense/old Polynomialring) or dense/old FractionField.
  557. from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing
  558. if cls == GlobalPolynomialRing:
  559. return cls(domain, symbols)
  560. return cls(domain, symbols, order)
  561. def unify(K0, K1, symbols=None):
  562. """
  563. Construct a minimal domain that contains elements of ``K0`` and ``K1``.
  564. Known domains (from smallest to largest):
  565. - ``GF(p)``
  566. - ``ZZ``
  567. - ``QQ``
  568. - ``RR(prec, tol)``
  569. - ``CC(prec, tol)``
  570. - ``ALG(a, b, c)``
  571. - ``K[x, y, z]``
  572. - ``K(x, y, z)``
  573. - ``EX``
  574. """
  575. if symbols is not None:
  576. return K0.unify_with_symbols(K1, symbols)
  577. if K0 == K1:
  578. return K0
  579. if not (K0.has_CharacteristicZero and K1.has_CharacteristicZero):
  580. # Reject unification of domains with different characteristics.
  581. if K0.characteristic() != K1.characteristic():
  582. raise UnificationFailed("Cannot unify %s with %s" % (K0, K1))
  583. # We do not get here if K0 == K1. The two domains have the same
  584. # characteristic but are unequal so at least one is composite and
  585. # we are unifying something like GF(3).unify(GF(3)[x]).
  586. return K0.unify_composite(K1)
  587. # From here we know both domains have characteristic zero and it can be
  588. # acceptable to fall back on EX.
  589. if K0.is_EXRAW:
  590. return K0
  591. if K1.is_EXRAW:
  592. return K1
  593. if K0.is_EX:
  594. return K0
  595. if K1.is_EX:
  596. return K1
  597. if K0.is_FiniteExtension or K1.is_FiniteExtension:
  598. if K1.is_FiniteExtension:
  599. K0, K1 = K1, K0
  600. if K1.is_FiniteExtension:
  601. # Unifying two extensions.
  602. # Try to ensure that K0.unify(K1) == K1.unify(K0)
  603. if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus:
  604. K0, K1 = K1, K0
  605. return K1.set_domain(K0)
  606. else:
  607. # Drop the generator from other and unify with the base domain
  608. K1 = K1.drop(K0.symbol)
  609. K1 = K0.domain.unify(K1)
  610. return K0.set_domain(K1)
  611. if K0.is_Composite or K1.is_Composite:
  612. return K0.unify_composite(K1)
  613. if K1.is_ComplexField:
  614. K0, K1 = K1, K0
  615. if K0.is_ComplexField:
  616. if K1.is_ComplexField or K1.is_RealField:
  617. if K0.precision >= K1.precision:
  618. return K0
  619. else:
  620. from sympy.polys.domains.complexfield import ComplexField
  621. return ComplexField(prec=K1.precision)
  622. else:
  623. return K0
  624. if K1.is_RealField:
  625. K0, K1 = K1, K0
  626. if K0.is_RealField:
  627. if K1.is_RealField:
  628. if K0.precision >= K1.precision:
  629. return K0
  630. else:
  631. return K1
  632. elif K1.is_GaussianRing or K1.is_GaussianField:
  633. from sympy.polys.domains.complexfield import ComplexField
  634. return ComplexField(prec=K0.precision)
  635. else:
  636. return K0
  637. if K1.is_AlgebraicField:
  638. K0, K1 = K1, K0
  639. if K0.is_AlgebraicField:
  640. if K1.is_GaussianRing:
  641. K1 = K1.get_field()
  642. if K1.is_GaussianField:
  643. K1 = K1.as_AlgebraicField()
  644. if K1.is_AlgebraicField:
  645. return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext))
  646. else:
  647. return K0
  648. if K0.is_GaussianField:
  649. return K0
  650. if K1.is_GaussianField:
  651. return K1
  652. if K0.is_GaussianRing:
  653. if K1.is_RationalField:
  654. K0 = K0.get_field()
  655. return K0
  656. if K1.is_GaussianRing:
  657. if K0.is_RationalField:
  658. K1 = K1.get_field()
  659. return K1
  660. if K0.is_RationalField:
  661. return K0
  662. if K1.is_RationalField:
  663. return K1
  664. if K0.is_IntegerRing:
  665. return K0
  666. if K1.is_IntegerRing:
  667. return K1
  668. from sympy.polys.domains import EX
  669. return EX
  670. def __eq__(self, other):
  671. """Returns ``True`` if two domains are equivalent. """
  672. # XXX: Remove this.
  673. return isinstance(other, Domain) and self.dtype == other.dtype
  674. def __ne__(self, other):
  675. """Returns ``False`` if two domains are equivalent. """
  676. return not self == other
  677. def map(self, seq):
  678. """Rersively apply ``self`` to all elements of ``seq``. """
  679. result = []
  680. for elt in seq:
  681. if isinstance(elt, list):
  682. result.append(self.map(elt))
  683. else:
  684. result.append(self(elt))
  685. return result
  686. def get_ring(self):
  687. """Returns a ring associated with ``self``. """
  688. raise DomainError('there is no ring associated with %s' % self)
  689. def get_field(self):
  690. """Returns a field associated with ``self``. """
  691. raise DomainError('there is no field associated with %s' % self)
  692. def get_exact(self):
  693. """Returns an exact domain associated with ``self``. """
  694. return self
  695. def __getitem__(self, symbols):
  696. """The mathematical way to make a polynomial ring. """
  697. if hasattr(symbols, '__iter__'):
  698. return self.poly_ring(*symbols)
  699. else:
  700. return self.poly_ring(symbols)
  701. def poly_ring(self, *symbols, order=lex):
  702. """Returns a polynomial ring, i.e. `K[X]`. """
  703. from sympy.polys.domains.polynomialring import PolynomialRing
  704. return PolynomialRing(self, symbols, order)
  705. def frac_field(self, *symbols, order=lex):
  706. """Returns a fraction field, i.e. `K(X)`. """
  707. from sympy.polys.domains.fractionfield import FractionField
  708. return FractionField(self, symbols, order)
  709. def old_poly_ring(self, *symbols, **kwargs):
  710. """Returns a polynomial ring, i.e. `K[X]`. """
  711. from sympy.polys.domains.old_polynomialring import PolynomialRing
  712. return PolynomialRing(self, *symbols, **kwargs)
  713. def old_frac_field(self, *symbols, **kwargs):
  714. """Returns a fraction field, i.e. `K(X)`. """
  715. from sympy.polys.domains.old_fractionfield import FractionField
  716. return FractionField(self, *symbols, **kwargs)
  717. def algebraic_field(self, *extension, alias=None):
  718. r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """
  719. raise DomainError("Cannot create algebraic field over %s" % self)
  720. def alg_field_from_poly(self, poly, alias=None, root_index=-1):
  721. r"""
  722. Convenience method to construct an algebraic extension on a root of a
  723. polynomial, chosen by root index.
  724. Parameters
  725. ==========
  726. poly : :py:class:`~.Poly`
  727. The polynomial whose root generates the extension.
  728. alias : str, optional (default=None)
  729. Symbol name for the generator of the extension.
  730. E.g. "alpha" or "theta".
  731. root_index : int, optional (default=-1)
  732. Specifies which root of the polynomial is desired. The ordering is
  733. as defined by the :py:class:`~.ComplexRootOf` class. The default of
  734. ``-1`` selects the most natural choice in the common cases of
  735. quadratic and cyclotomic fields (the square root on the positive
  736. real or imaginary axis, resp. $\mathrm{e}^{2\pi i/n}$).
  737. Examples
  738. ========
  739. >>> from sympy import QQ, Poly
  740. >>> from sympy.abc import x
  741. >>> f = Poly(x**2 - 2)
  742. >>> K = QQ.alg_field_from_poly(f)
  743. >>> K.ext.minpoly == f
  744. True
  745. >>> g = Poly(8*x**3 - 6*x - 1)
  746. >>> L = QQ.alg_field_from_poly(g, "alpha")
  747. >>> L.ext.minpoly == g
  748. True
  749. >>> L.to_sympy(L([1, 1, 1]))
  750. alpha**2 + alpha + 1
  751. """
  752. from sympy.polys.rootoftools import CRootOf
  753. root = CRootOf(poly, root_index)
  754. alpha = AlgebraicNumber(root, alias=alias)
  755. return self.algebraic_field(alpha, alias=alias)
  756. def cyclotomic_field(self, n, ss=False, alias="zeta", gen=None, root_index=-1):
  757. r"""
  758. Convenience method to construct a cyclotomic field.
  759. Parameters
  760. ==========
  761. n : int
  762. Construct the nth cyclotomic field.
  763. ss : boolean, optional (default=False)
  764. If True, append *n* as a subscript on the alias string.
  765. alias : str, optional (default="zeta")
  766. Symbol name for the generator.
  767. gen : :py:class:`~.Symbol`, optional (default=None)
  768. Desired variable for the cyclotomic polynomial that defines the
  769. field. If ``None``, a dummy variable will be used.
  770. root_index : int, optional (default=-1)
  771. Specifies which root of the polynomial is desired. The ordering is
  772. as defined by the :py:class:`~.ComplexRootOf` class. The default of
  773. ``-1`` selects the root $\mathrm{e}^{2\pi i/n}$.
  774. Examples
  775. ========
  776. >>> from sympy import QQ, latex
  777. >>> K = QQ.cyclotomic_field(5)
  778. >>> K.to_sympy(K([-1, 1]))
  779. 1 - zeta
  780. >>> L = QQ.cyclotomic_field(7, True)
  781. >>> a = L.to_sympy(L([-1, 1]))
  782. >>> print(a)
  783. 1 - zeta7
  784. >>> print(latex(a))
  785. 1 - \zeta_{7}
  786. """
  787. from sympy.polys.specialpolys import cyclotomic_poly
  788. if ss:
  789. alias += str(n)
  790. return self.alg_field_from_poly(cyclotomic_poly(n, gen), alias=alias,
  791. root_index=root_index)
  792. def inject(self, *symbols):
  793. """Inject generators into this domain. """
  794. raise NotImplementedError
  795. def drop(self, *symbols):
  796. """Drop generators from this domain. """
  797. if self.is_Simple:
  798. return self
  799. raise NotImplementedError # pragma: no cover
  800. def is_zero(self, a):
  801. """Returns True if ``a`` is zero. """
  802. return not a
  803. def is_one(self, a):
  804. """Returns True if ``a`` is one. """
  805. return a == self.one
  806. def is_positive(self, a):
  807. """Returns True if ``a`` is positive. """
  808. return a > 0
  809. def is_negative(self, a):
  810. """Returns True if ``a`` is negative. """
  811. return a < 0
  812. def is_nonpositive(self, a):
  813. """Returns True if ``a`` is non-positive. """
  814. return a <= 0
  815. def is_nonnegative(self, a):
  816. """Returns True if ``a`` is non-negative. """
  817. return a >= 0
  818. def canonical_unit(self, a):
  819. if self.is_negative(a):
  820. return -self.one
  821. else:
  822. return self.one
  823. def abs(self, a):
  824. """Absolute value of ``a``, implies ``__abs__``. """
  825. return abs(a)
  826. def neg(self, a):
  827. """Returns ``a`` negated, implies ``__neg__``. """
  828. return -a
  829. def pos(self, a):
  830. """Returns ``a`` positive, implies ``__pos__``. """
  831. return +a
  832. def add(self, a, b):
  833. """Sum of ``a`` and ``b``, implies ``__add__``. """
  834. return a + b
  835. def sub(self, a, b):
  836. """Difference of ``a`` and ``b``, implies ``__sub__``. """
  837. return a - b
  838. def mul(self, a, b):
  839. """Product of ``a`` and ``b``, implies ``__mul__``. """
  840. return a * b
  841. def pow(self, a, b):
  842. """Raise ``a`` to power ``b``, implies ``__pow__``. """
  843. return a ** b
  844. def exquo(self, a, b):
  845. """Exact quotient of *a* and *b*. Analogue of ``a / b``.
  846. Explanation
  847. ===========
  848. This is essentially the same as ``a / b`` except that an error will be
  849. raised if the division is inexact (if there is any remainder) and the
  850. result will always be a domain element. When working in a
  851. :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ`
  852. or :ref:`K[x]`) ``exquo`` should be used instead of ``/``.
  853. The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does
  854. not raise an exception) then ``a == b*q``.
  855. Examples
  856. ========
  857. We can use ``K.exquo`` instead of ``/`` for exact division.
  858. >>> from sympy import ZZ
  859. >>> ZZ.exquo(ZZ(4), ZZ(2))
  860. 2
  861. >>> ZZ.exquo(ZZ(5), ZZ(2))
  862. Traceback (most recent call last):
  863. ...
  864. ExactQuotientFailed: 2 does not divide 5 in ZZ
  865. Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero
  866. divisor) is always exact so in that case ``/`` can be used instead of
  867. :py:meth:`~.Domain.exquo`.
  868. >>> from sympy import QQ
  869. >>> QQ.exquo(QQ(5), QQ(2))
  870. 5/2
  871. >>> QQ(5) / QQ(2)
  872. 5/2
  873. Parameters
  874. ==========
  875. a: domain element
  876. The dividend
  877. b: domain element
  878. The divisor
  879. Returns
  880. =======
  881. q: domain element
  882. The exact quotient
  883. Raises
  884. ======
  885. ExactQuotientFailed: if exact division is not possible.
  886. ZeroDivisionError: when the divisor is zero.
  887. See also
  888. ========
  889. quo: Analogue of ``a // b``
  890. rem: Analogue of ``a % b``
  891. div: Analogue of ``divmod(a, b)``
  892. Notes
  893. =====
  894. Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int``
  895. (or ``mpz``) division as ``a / b`` should not be used as it would give
  896. a ``float`` which is not a domain element.
  897. >>> ZZ(4) / ZZ(2) # doctest: +SKIP
  898. 2.0
  899. >>> ZZ(5) / ZZ(2) # doctest: +SKIP
  900. 2.5
  901. On the other hand with `SYMPY_GROUND_TYPES=flint` elements of :ref:`ZZ`
  902. are ``flint.fmpz`` and division would raise an exception:
  903. >>> ZZ(4) / ZZ(2) # doctest: +SKIP
  904. Traceback (most recent call last):
  905. ...
  906. TypeError: unsupported operand type(s) for /: 'fmpz' and 'fmpz'
  907. Using ``/`` with :ref:`ZZ` will lead to incorrect results so
  908. :py:meth:`~.Domain.exquo` should be used instead.
  909. """
  910. raise NotImplementedError
  911. def quo(self, a, b):
  912. """Quotient of *a* and *b*. Analogue of ``a // b``.
  913. ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See
  914. :py:meth:`~.Domain.div` for more explanation.
  915. See also
  916. ========
  917. rem: Analogue of ``a % b``
  918. div: Analogue of ``divmod(a, b)``
  919. exquo: Analogue of ``a / b``
  920. """
  921. raise NotImplementedError
  922. def rem(self, a, b):
  923. """Modulo division of *a* and *b*. Analogue of ``a % b``.
  924. ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See
  925. :py:meth:`~.Domain.div` for more explanation.
  926. See also
  927. ========
  928. quo: Analogue of ``a // b``
  929. div: Analogue of ``divmod(a, b)``
  930. exquo: Analogue of ``a / b``
  931. """
  932. raise NotImplementedError
  933. def div(self, a, b):
  934. """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)``
  935. Explanation
  936. ===========
  937. This is essentially the same as ``divmod(a, b)`` except that is more
  938. consistent when working over some :py:class:`~.Field` domains such as
  939. :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the
  940. :py:meth:`~.Domain.div` method should be used instead of ``divmod``.
  941. The key invariant is that if ``q, r = K.div(a, b)`` then
  942. ``a == b*q + r``.
  943. The result of ``K.div(a, b)`` is the same as the tuple
  944. ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and
  945. remainder are needed then it is more efficient to use
  946. :py:meth:`~.Domain.div`.
  947. Examples
  948. ========
  949. We can use ``K.div`` instead of ``divmod`` for floor division and
  950. remainder.
  951. >>> from sympy import ZZ, QQ
  952. >>> ZZ.div(ZZ(5), ZZ(2))
  953. (2, 1)
  954. If ``K`` is a :py:class:`~.Field` then the division is always exact
  955. with a remainder of :py:attr:`~.Domain.zero`.
  956. >>> QQ.div(QQ(5), QQ(2))
  957. (5/2, 0)
  958. Parameters
  959. ==========
  960. a: domain element
  961. The dividend
  962. b: domain element
  963. The divisor
  964. Returns
  965. =======
  966. (q, r): tuple of domain elements
  967. The quotient and remainder
  968. Raises
  969. ======
  970. ZeroDivisionError: when the divisor is zero.
  971. See also
  972. ========
  973. quo: Analogue of ``a // b``
  974. rem: Analogue of ``a % b``
  975. exquo: Analogue of ``a / b``
  976. Notes
  977. =====
  978. If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as
  979. the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type
  980. defines ``divmod`` in a way that is undesirable so
  981. :py:meth:`~.Domain.div` should be used instead of ``divmod``.
  982. >>> a = QQ(1)
  983. >>> b = QQ(3, 2)
  984. >>> a # doctest: +SKIP
  985. mpq(1,1)
  986. >>> b # doctest: +SKIP
  987. mpq(3,2)
  988. >>> divmod(a, b) # doctest: +SKIP
  989. (mpz(0), mpq(1,1))
  990. >>> QQ.div(a, b) # doctest: +SKIP
  991. (mpq(2,3), mpq(0,1))
  992. Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so
  993. :py:meth:`~.Domain.div` should be used instead.
  994. """
  995. raise NotImplementedError
  996. def invert(self, a, b):
  997. """Returns inversion of ``a mod b``, implies something. """
  998. raise NotImplementedError
  999. def revert(self, a):
  1000. """Returns ``a**(-1)`` if possible. """
  1001. raise NotImplementedError
  1002. def numer(self, a):
  1003. """Returns numerator of ``a``. """
  1004. raise NotImplementedError
  1005. def denom(self, a):
  1006. """Returns denominator of ``a``. """
  1007. raise NotImplementedError
  1008. def half_gcdex(self, a, b):
  1009. """Half extended GCD of ``a`` and ``b``. """
  1010. s, t, h = self.gcdex(a, b)
  1011. return s, h
  1012. def gcdex(self, a, b):
  1013. """Extended GCD of ``a`` and ``b``. """
  1014. raise NotImplementedError
  1015. def cofactors(self, a, b):
  1016. """Returns GCD and cofactors of ``a`` and ``b``. """
  1017. gcd = self.gcd(a, b)
  1018. cfa = self.quo(a, gcd)
  1019. cfb = self.quo(b, gcd)
  1020. return gcd, cfa, cfb
  1021. def gcd(self, a, b):
  1022. """Returns GCD of ``a`` and ``b``. """
  1023. raise NotImplementedError
  1024. def lcm(self, a, b):
  1025. """Returns LCM of ``a`` and ``b``. """
  1026. raise NotImplementedError
  1027. def log(self, a, b):
  1028. """Returns b-base logarithm of ``a``. """
  1029. raise NotImplementedError
  1030. def sqrt(self, a):
  1031. """Returns a (possibly inexact) square root of ``a``.
  1032. Explanation
  1033. ===========
  1034. There is no universal definition of "inexact square root" for all
  1035. domains. It is not recommended to implement this method for domains
  1036. other then :ref:`ZZ`.
  1037. See also
  1038. ========
  1039. exsqrt
  1040. """
  1041. raise NotImplementedError
  1042. def is_square(self, a):
  1043. """Returns whether ``a`` is a square in the domain.
  1044. Explanation
  1045. ===========
  1046. Returns ``True`` if there is an element ``b`` in the domain such that
  1047. ``b * b == a``, otherwise returns ``False``. For inexact domains like
  1048. :ref:`RR` and :ref:`CC`, a tiny difference in this equality can be
  1049. tolerated.
  1050. See also
  1051. ========
  1052. exsqrt
  1053. """
  1054. raise NotImplementedError
  1055. def exsqrt(self, a):
  1056. """Principal square root of a within the domain if ``a`` is square.
  1057. Explanation
  1058. ===========
  1059. The implementation of this method should return an element ``b`` in the
  1060. domain such that ``b * b == a``, or ``None`` if there is no such ``b``.
  1061. For inexact domains like :ref:`RR` and :ref:`CC`, a tiny difference in
  1062. this equality can be tolerated. The choice of a "principal" square root
  1063. should follow a consistent rule whenever possible.
  1064. See also
  1065. ========
  1066. sqrt, is_square
  1067. """
  1068. raise NotImplementedError
  1069. def evalf(self, a, prec=None, **options):
  1070. """Returns numerical approximation of ``a``. """
  1071. return self.to_sympy(a).evalf(prec, **options)
  1072. n = evalf
  1073. def real(self, a):
  1074. return a
  1075. def imag(self, a):
  1076. return self.zero
  1077. def almosteq(self, a, b, tolerance=None):
  1078. """Check if ``a`` and ``b`` are almost equal. """
  1079. return a == b
  1080. def characteristic(self):
  1081. """Return the characteristic of this domain. """
  1082. raise NotImplementedError('characteristic()')
  1083. __all__ = ['Domain']