polyclasses.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  1. """OO layer for several polynomial representations. """
  2. from sympy.core.numbers import oo
  3. from sympy.core.sympify import CantSympify
  4. from sympy.polys.polyerrors import CoercionFailed, NotReversible, NotInvertible
  5. from sympy.polys.polyutils import PicklableWithSlots
  6. class GenericPoly(PicklableWithSlots):
  7. """Base class for low-level polynomial representations. """
  8. def ground_to_ring(f):
  9. """Make the ground domain a ring. """
  10. return f.set_domain(f.dom.get_ring())
  11. def ground_to_field(f):
  12. """Make the ground domain a field. """
  13. return f.set_domain(f.dom.get_field())
  14. def ground_to_exact(f):
  15. """Make the ground domain exact. """
  16. return f.set_domain(f.dom.get_exact())
  17. @classmethod
  18. def _perify_factors(per, result, include):
  19. if include:
  20. coeff, factors = result
  21. factors = [ (per(g), k) for g, k in factors ]
  22. if include:
  23. return coeff, factors
  24. else:
  25. return factors
  26. from sympy.polys.densebasic import (
  27. dmp_validate,
  28. dup_normal, dmp_normal,
  29. dup_convert, dmp_convert,
  30. dmp_from_sympy,
  31. dup_strip,
  32. dup_degree, dmp_degree_in,
  33. dmp_degree_list,
  34. dmp_negative_p,
  35. dup_LC, dmp_ground_LC,
  36. dup_TC, dmp_ground_TC,
  37. dmp_ground_nth,
  38. dmp_one, dmp_ground,
  39. dmp_zero_p, dmp_one_p, dmp_ground_p,
  40. dup_from_dict, dmp_from_dict,
  41. dmp_to_dict,
  42. dmp_deflate,
  43. dmp_inject, dmp_eject,
  44. dmp_terms_gcd,
  45. dmp_list_terms, dmp_exclude,
  46. dmp_slice_in, dmp_permute,
  47. dmp_to_tuple,)
  48. from sympy.polys.densearith import (
  49. dmp_add_ground,
  50. dmp_sub_ground,
  51. dmp_mul_ground,
  52. dmp_quo_ground,
  53. dmp_exquo_ground,
  54. dmp_abs,
  55. dup_neg, dmp_neg,
  56. dup_add, dmp_add,
  57. dup_sub, dmp_sub,
  58. dup_mul, dmp_mul,
  59. dmp_sqr,
  60. dup_pow, dmp_pow,
  61. dmp_pdiv,
  62. dmp_prem,
  63. dmp_pquo,
  64. dmp_pexquo,
  65. dmp_div,
  66. dup_rem, dmp_rem,
  67. dmp_quo,
  68. dmp_exquo,
  69. dmp_add_mul, dmp_sub_mul,
  70. dmp_max_norm,
  71. dmp_l1_norm,
  72. dmp_l2_norm_squared)
  73. from sympy.polys.densetools import (
  74. dmp_clear_denoms,
  75. dmp_integrate_in,
  76. dmp_diff_in,
  77. dmp_eval_in,
  78. dup_revert,
  79. dmp_ground_trunc,
  80. dmp_ground_content,
  81. dmp_ground_primitive,
  82. dmp_ground_monic,
  83. dmp_compose,
  84. dup_decompose,
  85. dup_shift,
  86. dup_transform,
  87. dmp_lift)
  88. from sympy.polys.euclidtools import (
  89. dup_half_gcdex, dup_gcdex, dup_invert,
  90. dmp_subresultants,
  91. dmp_resultant,
  92. dmp_discriminant,
  93. dmp_inner_gcd,
  94. dmp_gcd,
  95. dmp_lcm,
  96. dmp_cancel)
  97. from sympy.polys.sqfreetools import (
  98. dup_gff_list,
  99. dmp_norm,
  100. dmp_sqf_p,
  101. dmp_sqf_norm,
  102. dmp_sqf_part,
  103. dmp_sqf_list, dmp_sqf_list_include)
  104. from sympy.polys.factortools import (
  105. dup_cyclotomic_p, dmp_irreducible_p,
  106. dmp_factor_list, dmp_factor_list_include)
  107. from sympy.polys.rootisolation import (
  108. dup_isolate_real_roots_sqf,
  109. dup_isolate_real_roots,
  110. dup_isolate_all_roots_sqf,
  111. dup_isolate_all_roots,
  112. dup_refine_real_root,
  113. dup_count_real_roots,
  114. dup_count_complex_roots,
  115. dup_sturm,
  116. dup_cauchy_upper_bound,
  117. dup_cauchy_lower_bound,
  118. dup_mignotte_sep_bound_squared)
  119. from sympy.polys.polyerrors import (
  120. UnificationFailed,
  121. PolynomialError)
  122. def init_normal_DMP(rep, lev, dom):
  123. return DMP(dmp_normal(rep, lev, dom), dom, lev)
  124. class DMP(PicklableWithSlots, CantSympify):
  125. """Dense Multivariate Polynomials over `K`. """
  126. __slots__ = ('rep', 'lev', 'dom', 'ring')
  127. def __init__(self, rep, dom, lev=None, ring=None):
  128. if lev is not None:
  129. # Not possible to check with isinstance
  130. if type(rep) is dict:
  131. rep = dmp_from_dict(rep, lev, dom)
  132. elif not isinstance(rep, list):
  133. rep = dmp_ground(dom.convert(rep), lev)
  134. else:
  135. rep, lev = dmp_validate(rep)
  136. self.rep = rep
  137. self.lev = lev
  138. self.dom = dom
  139. self.ring = ring
  140. def __repr__(f):
  141. return "%s(%s, %s, %s)" % (f.__class__.__name__, f.rep, f.dom, f.ring)
  142. def __hash__(f):
  143. return hash((f.__class__.__name__, f.to_tuple(), f.lev, f.dom, f.ring))
  144. def unify(f, g):
  145. """Unify representations of two multivariate polynomials. """
  146. if not isinstance(g, DMP) or f.lev != g.lev:
  147. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  148. if f.dom == g.dom and f.ring == g.ring:
  149. return f.lev, f.dom, f.per, f.rep, g.rep
  150. else:
  151. lev, dom = f.lev, f.dom.unify(g.dom)
  152. ring = f.ring
  153. if g.ring is not None:
  154. if ring is not None:
  155. ring = ring.unify(g.ring)
  156. else:
  157. ring = g.ring
  158. F = dmp_convert(f.rep, lev, f.dom, dom)
  159. G = dmp_convert(g.rep, lev, g.dom, dom)
  160. def per(rep, dom=dom, lev=lev, kill=False):
  161. if kill:
  162. if not lev:
  163. return rep
  164. else:
  165. lev -= 1
  166. return DMP(rep, dom, lev, ring)
  167. return lev, dom, per, F, G
  168. def per(f, rep, dom=None, kill=False, ring=None):
  169. """Create a DMP out of the given representation. """
  170. lev = f.lev
  171. if kill:
  172. if not lev:
  173. return rep
  174. else:
  175. lev -= 1
  176. if dom is None:
  177. dom = f.dom
  178. if ring is None:
  179. ring = f.ring
  180. return DMP(rep, dom, lev, ring)
  181. @classmethod
  182. def zero(cls, lev, dom, ring=None):
  183. return DMP(0, dom, lev, ring)
  184. @classmethod
  185. def one(cls, lev, dom, ring=None):
  186. return DMP(1, dom, lev, ring)
  187. @classmethod
  188. def from_list(cls, rep, lev, dom):
  189. """Create an instance of ``cls`` given a list of native coefficients. """
  190. return cls(dmp_convert(rep, lev, None, dom), dom, lev)
  191. @classmethod
  192. def from_sympy_list(cls, rep, lev, dom):
  193. """Create an instance of ``cls`` given a list of SymPy coefficients. """
  194. return cls(dmp_from_sympy(rep, lev, dom), dom, lev)
  195. def to_dict(f, zero=False):
  196. """Convert ``f`` to a dict representation with native coefficients. """
  197. return dmp_to_dict(f.rep, f.lev, f.dom, zero=zero)
  198. def to_sympy_dict(f, zero=False):
  199. """Convert ``f`` to a dict representation with SymPy coefficients. """
  200. rep = dmp_to_dict(f.rep, f.lev, f.dom, zero=zero)
  201. for k, v in rep.items():
  202. rep[k] = f.dom.to_sympy(v)
  203. return rep
  204. def to_list(f):
  205. """Convert ``f`` to a list representation with native coefficients. """
  206. return f.rep
  207. def to_sympy_list(f):
  208. """Convert ``f`` to a list representation with SymPy coefficients. """
  209. def sympify_nested_list(rep):
  210. out = []
  211. for val in rep:
  212. if isinstance(val, list):
  213. out.append(sympify_nested_list(val))
  214. else:
  215. out.append(f.dom.to_sympy(val))
  216. return out
  217. return sympify_nested_list(f.rep)
  218. def to_tuple(f):
  219. """
  220. Convert ``f`` to a tuple representation with native coefficients.
  221. This is needed for hashing.
  222. """
  223. return dmp_to_tuple(f.rep, f.lev)
  224. @classmethod
  225. def from_dict(cls, rep, lev, dom):
  226. """Construct and instance of ``cls`` from a ``dict`` representation. """
  227. return cls(dmp_from_dict(rep, lev, dom), dom, lev)
  228. @classmethod
  229. def from_monoms_coeffs(cls, monoms, coeffs, lev, dom, ring=None):
  230. return DMP(dict(list(zip(monoms, coeffs))), dom, lev, ring)
  231. def to_ring(f):
  232. """Make the ground domain a ring. """
  233. return f.convert(f.dom.get_ring())
  234. def to_field(f):
  235. """Make the ground domain a field. """
  236. return f.convert(f.dom.get_field())
  237. def to_exact(f):
  238. """Make the ground domain exact. """
  239. return f.convert(f.dom.get_exact())
  240. def convert(f, dom):
  241. """Convert the ground domain of ``f``. """
  242. if f.dom == dom:
  243. return f
  244. else:
  245. return DMP(dmp_convert(f.rep, f.lev, f.dom, dom), dom, f.lev)
  246. def slice(f, m, n, j=0):
  247. """Take a continuous subsequence of terms of ``f``. """
  248. return f.per(dmp_slice_in(f.rep, m, n, j, f.lev, f.dom))
  249. def coeffs(f, order=None):
  250. """Returns all non-zero coefficients from ``f`` in lex order. """
  251. return [ c for _, c in dmp_list_terms(f.rep, f.lev, f.dom, order=order) ]
  252. def monoms(f, order=None):
  253. """Returns all non-zero monomials from ``f`` in lex order. """
  254. return [ m for m, _ in dmp_list_terms(f.rep, f.lev, f.dom, order=order) ]
  255. def terms(f, order=None):
  256. """Returns all non-zero terms from ``f`` in lex order. """
  257. return dmp_list_terms(f.rep, f.lev, f.dom, order=order)
  258. def all_coeffs(f):
  259. """Returns all coefficients from ``f``. """
  260. if not f.lev:
  261. if not f:
  262. return [f.dom.zero]
  263. else:
  264. return [ c for c in f.rep ]
  265. else:
  266. raise PolynomialError('multivariate polynomials not supported')
  267. def all_monoms(f):
  268. """Returns all monomials from ``f``. """
  269. if not f.lev:
  270. n = dup_degree(f.rep)
  271. if n < 0:
  272. return [(0,)]
  273. else:
  274. return [ (n - i,) for i, c in enumerate(f.rep) ]
  275. else:
  276. raise PolynomialError('multivariate polynomials not supported')
  277. def all_terms(f):
  278. """Returns all terms from a ``f``. """
  279. if not f.lev:
  280. n = dup_degree(f.rep)
  281. if n < 0:
  282. return [((0,), f.dom.zero)]
  283. else:
  284. return [ ((n - i,), c) for i, c in enumerate(f.rep) ]
  285. else:
  286. raise PolynomialError('multivariate polynomials not supported')
  287. def lift(f):
  288. """Convert algebraic coefficients to rationals. """
  289. return f.per(dmp_lift(f.rep, f.lev, f.dom), dom=f.dom.dom)
  290. def deflate(f):
  291. """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """
  292. J, F = dmp_deflate(f.rep, f.lev, f.dom)
  293. return J, f.per(F)
  294. def inject(f, front=False):
  295. """Inject ground domain generators into ``f``. """
  296. F, lev = dmp_inject(f.rep, f.lev, f.dom, front=front)
  297. return f.__class__(F, f.dom.dom, lev)
  298. def eject(f, dom, front=False):
  299. """Eject selected generators into the ground domain. """
  300. F = dmp_eject(f.rep, f.lev, dom, front=front)
  301. return f.__class__(F, dom, f.lev - len(dom.symbols))
  302. def exclude(f):
  303. r"""
  304. Remove useless generators from ``f``.
  305. Returns the removed generators and the new excluded ``f``.
  306. Examples
  307. ========
  308. >>> from sympy.polys.polyclasses import DMP
  309. >>> from sympy.polys.domains import ZZ
  310. >>> DMP([[[ZZ(1)]], [[ZZ(1)], [ZZ(2)]]], ZZ).exclude()
  311. ([2], DMP([[1], [1, 2]], ZZ, None))
  312. """
  313. J, F, u = dmp_exclude(f.rep, f.lev, f.dom)
  314. return J, f.__class__(F, f.dom, u)
  315. def permute(f, P):
  316. r"""
  317. Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`.
  318. Examples
  319. ========
  320. >>> from sympy.polys.polyclasses import DMP
  321. >>> from sympy.polys.domains import ZZ
  322. >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 0, 2])
  323. DMP([[[2], []], [[1, 0], []]], ZZ, None)
  324. >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 2, 0])
  325. DMP([[[1], []], [[2, 0], []]], ZZ, None)
  326. """
  327. return f.per(dmp_permute(f.rep, P, f.lev, f.dom))
  328. def terms_gcd(f):
  329. """Remove GCD of terms from the polynomial ``f``. """
  330. J, F = dmp_terms_gcd(f.rep, f.lev, f.dom)
  331. return J, f.per(F)
  332. def add_ground(f, c):
  333. """Add an element of the ground domain to ``f``. """
  334. return f.per(dmp_add_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
  335. def sub_ground(f, c):
  336. """Subtract an element of the ground domain from ``f``. """
  337. return f.per(dmp_sub_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
  338. def mul_ground(f, c):
  339. """Multiply ``f`` by a an element of the ground domain. """
  340. return f.per(dmp_mul_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
  341. def quo_ground(f, c):
  342. """Quotient of ``f`` by a an element of the ground domain. """
  343. return f.per(dmp_quo_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
  344. def exquo_ground(f, c):
  345. """Exact quotient of ``f`` by a an element of the ground domain. """
  346. return f.per(dmp_exquo_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
  347. def abs(f):
  348. """Make all coefficients in ``f`` positive. """
  349. return f.per(dmp_abs(f.rep, f.lev, f.dom))
  350. def neg(f):
  351. """Negate all coefficients in ``f``. """
  352. return f.per(dmp_neg(f.rep, f.lev, f.dom))
  353. def add(f, g):
  354. """Add two multivariate polynomials ``f`` and ``g``. """
  355. lev, dom, per, F, G = f.unify(g)
  356. return per(dmp_add(F, G, lev, dom))
  357. def sub(f, g):
  358. """Subtract two multivariate polynomials ``f`` and ``g``. """
  359. lev, dom, per, F, G = f.unify(g)
  360. return per(dmp_sub(F, G, lev, dom))
  361. def mul(f, g):
  362. """Multiply two multivariate polynomials ``f`` and ``g``. """
  363. lev, dom, per, F, G = f.unify(g)
  364. return per(dmp_mul(F, G, lev, dom))
  365. def sqr(f):
  366. """Square a multivariate polynomial ``f``. """
  367. return f.per(dmp_sqr(f.rep, f.lev, f.dom))
  368. def pow(f, n):
  369. """Raise ``f`` to a non-negative power ``n``. """
  370. if isinstance(n, int):
  371. return f.per(dmp_pow(f.rep, n, f.lev, f.dom))
  372. else:
  373. raise TypeError("``int`` expected, got %s" % type(n))
  374. def pdiv(f, g):
  375. """Polynomial pseudo-division of ``f`` and ``g``. """
  376. lev, dom, per, F, G = f.unify(g)
  377. q, r = dmp_pdiv(F, G, lev, dom)
  378. return per(q), per(r)
  379. def prem(f, g):
  380. """Polynomial pseudo-remainder of ``f`` and ``g``. """
  381. lev, dom, per, F, G = f.unify(g)
  382. return per(dmp_prem(F, G, lev, dom))
  383. def pquo(f, g):
  384. """Polynomial pseudo-quotient of ``f`` and ``g``. """
  385. lev, dom, per, F, G = f.unify(g)
  386. return per(dmp_pquo(F, G, lev, dom))
  387. def pexquo(f, g):
  388. """Polynomial exact pseudo-quotient of ``f`` and ``g``. """
  389. lev, dom, per, F, G = f.unify(g)
  390. return per(dmp_pexquo(F, G, lev, dom))
  391. def div(f, g):
  392. """Polynomial division with remainder of ``f`` and ``g``. """
  393. lev, dom, per, F, G = f.unify(g)
  394. q, r = dmp_div(F, G, lev, dom)
  395. return per(q), per(r)
  396. def rem(f, g):
  397. """Computes polynomial remainder of ``f`` and ``g``. """
  398. lev, dom, per, F, G = f.unify(g)
  399. return per(dmp_rem(F, G, lev, dom))
  400. def quo(f, g):
  401. """Computes polynomial quotient of ``f`` and ``g``. """
  402. lev, dom, per, F, G = f.unify(g)
  403. return per(dmp_quo(F, G, lev, dom))
  404. def exquo(f, g):
  405. """Computes polynomial exact quotient of ``f`` and ``g``. """
  406. lev, dom, per, F, G = f.unify(g)
  407. res = per(dmp_exquo(F, G, lev, dom))
  408. if f.ring and res not in f.ring:
  409. from sympy.polys.polyerrors import ExactQuotientFailed
  410. raise ExactQuotientFailed(f, g, f.ring)
  411. return res
  412. def degree(f, j=0):
  413. """Returns the leading degree of ``f`` in ``x_j``. """
  414. if isinstance(j, int):
  415. return dmp_degree_in(f.rep, j, f.lev)
  416. else:
  417. raise TypeError("``int`` expected, got %s" % type(j))
  418. def degree_list(f):
  419. """Returns a list of degrees of ``f``. """
  420. return dmp_degree_list(f.rep, f.lev)
  421. def total_degree(f):
  422. """Returns the total degree of ``f``. """
  423. return max(sum(m) for m in f.monoms())
  424. def homogenize(f, s):
  425. """Return homogeneous polynomial of ``f``"""
  426. td = f.total_degree()
  427. result = {}
  428. new_symbol = (s == len(f.terms()[0][0]))
  429. for term in f.terms():
  430. d = sum(term[0])
  431. if d < td:
  432. i = td - d
  433. else:
  434. i = 0
  435. if new_symbol:
  436. result[term[0] + (i,)] = term[1]
  437. else:
  438. l = list(term[0])
  439. l[s] += i
  440. result[tuple(l)] = term[1]
  441. return DMP(result, f.dom, f.lev + int(new_symbol), f.ring)
  442. def homogeneous_order(f):
  443. """Returns the homogeneous order of ``f``. """
  444. if f.is_zero:
  445. return -oo
  446. monoms = f.monoms()
  447. tdeg = sum(monoms[0])
  448. for monom in monoms:
  449. _tdeg = sum(monom)
  450. if _tdeg != tdeg:
  451. return None
  452. return tdeg
  453. def LC(f):
  454. """Returns the leading coefficient of ``f``. """
  455. return dmp_ground_LC(f.rep, f.lev, f.dom)
  456. def TC(f):
  457. """Returns the trailing coefficient of ``f``. """
  458. return dmp_ground_TC(f.rep, f.lev, f.dom)
  459. def nth(f, *N):
  460. """Returns the ``n``-th coefficient of ``f``. """
  461. if all(isinstance(n, int) for n in N):
  462. return dmp_ground_nth(f.rep, N, f.lev, f.dom)
  463. else:
  464. raise TypeError("a sequence of integers expected")
  465. def max_norm(f):
  466. """Returns maximum norm of ``f``. """
  467. return dmp_max_norm(f.rep, f.lev, f.dom)
  468. def l1_norm(f):
  469. """Returns l1 norm of ``f``. """
  470. return dmp_l1_norm(f.rep, f.lev, f.dom)
  471. def l2_norm_squared(f):
  472. """Return squared l2 norm of ``f``. """
  473. return dmp_l2_norm_squared(f.rep, f.lev, f.dom)
  474. def clear_denoms(f):
  475. """Clear denominators, but keep the ground domain. """
  476. coeff, F = dmp_clear_denoms(f.rep, f.lev, f.dom)
  477. return coeff, f.per(F)
  478. def integrate(f, m=1, j=0):
  479. """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """
  480. if not isinstance(m, int):
  481. raise TypeError("``int`` expected, got %s" % type(m))
  482. if not isinstance(j, int):
  483. raise TypeError("``int`` expected, got %s" % type(j))
  484. return f.per(dmp_integrate_in(f.rep, m, j, f.lev, f.dom))
  485. def diff(f, m=1, j=0):
  486. """Computes the ``m``-th order derivative of ``f`` in ``x_j``. """
  487. if not isinstance(m, int):
  488. raise TypeError("``int`` expected, got %s" % type(m))
  489. if not isinstance(j, int):
  490. raise TypeError("``int`` expected, got %s" % type(j))
  491. return f.per(dmp_diff_in(f.rep, m, j, f.lev, f.dom))
  492. def eval(f, a, j=0):
  493. """Evaluates ``f`` at the given point ``a`` in ``x_j``. """
  494. if not isinstance(j, int):
  495. raise TypeError("``int`` expected, got %s" % type(j))
  496. return f.per(dmp_eval_in(f.rep,
  497. f.dom.convert(a), j, f.lev, f.dom), kill=True)
  498. def half_gcdex(f, g):
  499. """Half extended Euclidean algorithm, if univariate. """
  500. lev, dom, per, F, G = f.unify(g)
  501. if not lev:
  502. s, h = dup_half_gcdex(F, G, dom)
  503. return per(s), per(h)
  504. else:
  505. raise ValueError('univariate polynomial expected')
  506. def gcdex(f, g):
  507. """Extended Euclidean algorithm, if univariate. """
  508. lev, dom, per, F, G = f.unify(g)
  509. if not lev:
  510. s, t, h = dup_gcdex(F, G, dom)
  511. return per(s), per(t), per(h)
  512. else:
  513. raise ValueError('univariate polynomial expected')
  514. def invert(f, g):
  515. """Invert ``f`` modulo ``g``, if possible. """
  516. lev, dom, per, F, G = f.unify(g)
  517. if not lev:
  518. return per(dup_invert(F, G, dom))
  519. else:
  520. raise ValueError('univariate polynomial expected')
  521. def revert(f, n):
  522. """Compute ``f**(-1)`` mod ``x**n``. """
  523. if not f.lev:
  524. return f.per(dup_revert(f.rep, n, f.dom))
  525. else:
  526. raise ValueError('univariate polynomial expected')
  527. def subresultants(f, g):
  528. """Computes subresultant PRS sequence of ``f`` and ``g``. """
  529. lev, dom, per, F, G = f.unify(g)
  530. R = dmp_subresultants(F, G, lev, dom)
  531. return list(map(per, R))
  532. def resultant(f, g, includePRS=False):
  533. """Computes resultant of ``f`` and ``g`` via PRS. """
  534. lev, dom, per, F, G = f.unify(g)
  535. if includePRS:
  536. res, R = dmp_resultant(F, G, lev, dom, includePRS=includePRS)
  537. return per(res, kill=True), list(map(per, R))
  538. return per(dmp_resultant(F, G, lev, dom), kill=True)
  539. def discriminant(f):
  540. """Computes discriminant of ``f``. """
  541. return f.per(dmp_discriminant(f.rep, f.lev, f.dom), kill=True)
  542. def cofactors(f, g):
  543. """Returns GCD of ``f`` and ``g`` and their cofactors. """
  544. lev, dom, per, F, G = f.unify(g)
  545. h, cff, cfg = dmp_inner_gcd(F, G, lev, dom)
  546. return per(h), per(cff), per(cfg)
  547. def gcd(f, g):
  548. """Returns polynomial GCD of ``f`` and ``g``. """
  549. lev, dom, per, F, G = f.unify(g)
  550. return per(dmp_gcd(F, G, lev, dom))
  551. def lcm(f, g):
  552. """Returns polynomial LCM of ``f`` and ``g``. """
  553. lev, dom, per, F, G = f.unify(g)
  554. return per(dmp_lcm(F, G, lev, dom))
  555. def cancel(f, g, include=True):
  556. """Cancel common factors in a rational function ``f/g``. """
  557. lev, dom, per, F, G = f.unify(g)
  558. if include:
  559. F, G = dmp_cancel(F, G, lev, dom, include=True)
  560. else:
  561. cF, cG, F, G = dmp_cancel(F, G, lev, dom, include=False)
  562. F, G = per(F), per(G)
  563. if include:
  564. return F, G
  565. else:
  566. return cF, cG, F, G
  567. def trunc(f, p):
  568. """Reduce ``f`` modulo a constant ``p``. """
  569. return f.per(dmp_ground_trunc(f.rep, f.dom.convert(p), f.lev, f.dom))
  570. def monic(f):
  571. """Divides all coefficients by ``LC(f)``. """
  572. return f.per(dmp_ground_monic(f.rep, f.lev, f.dom))
  573. def content(f):
  574. """Returns GCD of polynomial coefficients. """
  575. return dmp_ground_content(f.rep, f.lev, f.dom)
  576. def primitive(f):
  577. """Returns content and a primitive form of ``f``. """
  578. cont, F = dmp_ground_primitive(f.rep, f.lev, f.dom)
  579. return cont, f.per(F)
  580. def compose(f, g):
  581. """Computes functional composition of ``f`` and ``g``. """
  582. lev, dom, per, F, G = f.unify(g)
  583. return per(dmp_compose(F, G, lev, dom))
  584. def decompose(f):
  585. """Computes functional decomposition of ``f``. """
  586. if not f.lev:
  587. return list(map(f.per, dup_decompose(f.rep, f.dom)))
  588. else:
  589. raise ValueError('univariate polynomial expected')
  590. def shift(f, a):
  591. """Efficiently compute Taylor shift ``f(x + a)``. """
  592. if not f.lev:
  593. return f.per(dup_shift(f.rep, f.dom.convert(a), f.dom))
  594. else:
  595. raise ValueError('univariate polynomial expected')
  596. def transform(f, p, q):
  597. """Evaluate functional transformation ``q**n * f(p/q)``."""
  598. if f.lev:
  599. raise ValueError('univariate polynomial expected')
  600. lev, dom, per, P, Q = p.unify(q)
  601. lev, dom, per, F, P = f.unify(per(P, dom, lev))
  602. lev, dom, per, F, Q = per(F, dom, lev).unify(per(Q, dom, lev))
  603. if not lev:
  604. return per(dup_transform(F, P, Q, dom))
  605. else:
  606. raise ValueError('univariate polynomial expected')
  607. def sturm(f):
  608. """Computes the Sturm sequence of ``f``. """
  609. if not f.lev:
  610. return list(map(f.per, dup_sturm(f.rep, f.dom)))
  611. else:
  612. raise ValueError('univariate polynomial expected')
  613. def cauchy_upper_bound(f):
  614. """Computes the Cauchy upper bound on the roots of ``f``. """
  615. if not f.lev:
  616. return dup_cauchy_upper_bound(f.rep, f.dom)
  617. else:
  618. raise ValueError('univariate polynomial expected')
  619. def cauchy_lower_bound(f):
  620. """Computes the Cauchy lower bound on the nonzero roots of ``f``. """
  621. if not f.lev:
  622. return dup_cauchy_lower_bound(f.rep, f.dom)
  623. else:
  624. raise ValueError('univariate polynomial expected')
  625. def mignotte_sep_bound_squared(f):
  626. """Computes the squared Mignotte bound on root separations of ``f``. """
  627. if not f.lev:
  628. return dup_mignotte_sep_bound_squared(f.rep, f.dom)
  629. else:
  630. raise ValueError('univariate polynomial expected')
  631. def gff_list(f):
  632. """Computes greatest factorial factorization of ``f``. """
  633. if not f.lev:
  634. return [ (f.per(g), k) for g, k in dup_gff_list(f.rep, f.dom) ]
  635. else:
  636. raise ValueError('univariate polynomial expected')
  637. def norm(f):
  638. """Computes ``Norm(f)``."""
  639. r = dmp_norm(f.rep, f.lev, f.dom)
  640. return f.per(r, dom=f.dom.dom)
  641. def sqf_norm(f):
  642. """Computes square-free norm of ``f``. """
  643. s, g, r = dmp_sqf_norm(f.rep, f.lev, f.dom)
  644. return s, f.per(g), f.per(r, dom=f.dom.dom)
  645. def sqf_part(f):
  646. """Computes square-free part of ``f``. """
  647. return f.per(dmp_sqf_part(f.rep, f.lev, f.dom))
  648. def sqf_list(f, all=False):
  649. """Returns a list of square-free factors of ``f``. """
  650. coeff, factors = dmp_sqf_list(f.rep, f.lev, f.dom, all)
  651. return coeff, [ (f.per(g), k) for g, k in factors ]
  652. def sqf_list_include(f, all=False):
  653. """Returns a list of square-free factors of ``f``. """
  654. factors = dmp_sqf_list_include(f.rep, f.lev, f.dom, all)
  655. return [ (f.per(g), k) for g, k in factors ]
  656. def factor_list(f):
  657. """Returns a list of irreducible factors of ``f``. """
  658. coeff, factors = dmp_factor_list(f.rep, f.lev, f.dom)
  659. return coeff, [ (f.per(g), k) for g, k in factors ]
  660. def factor_list_include(f):
  661. """Returns a list of irreducible factors of ``f``. """
  662. factors = dmp_factor_list_include(f.rep, f.lev, f.dom)
  663. return [ (f.per(g), k) for g, k in factors ]
  664. def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False):
  665. """Compute isolating intervals for roots of ``f``. """
  666. if not f.lev:
  667. if not all:
  668. if not sqf:
  669. return dup_isolate_real_roots(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  670. else:
  671. return dup_isolate_real_roots_sqf(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  672. else:
  673. if not sqf:
  674. return dup_isolate_all_roots(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  675. else:
  676. return dup_isolate_all_roots_sqf(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  677. else:
  678. raise PolynomialError(
  679. "Cannot isolate roots of a multivariate polynomial")
  680. def refine_root(f, s, t, eps=None, steps=None, fast=False):
  681. """
  682. Refine an isolating interval to the given precision.
  683. ``eps`` should be a rational number.
  684. """
  685. if not f.lev:
  686. return dup_refine_real_root(f.rep, s, t, f.dom, eps=eps, steps=steps, fast=fast)
  687. else:
  688. raise PolynomialError(
  689. "Cannot refine a root of a multivariate polynomial")
  690. def count_real_roots(f, inf=None, sup=None):
  691. """Return the number of real roots of ``f`` in ``[inf, sup]``. """
  692. return dup_count_real_roots(f.rep, f.dom, inf=inf, sup=sup)
  693. def count_complex_roots(f, inf=None, sup=None):
  694. """Return the number of complex roots of ``f`` in ``[inf, sup]``. """
  695. return dup_count_complex_roots(f.rep, f.dom, inf=inf, sup=sup)
  696. @property
  697. def is_zero(f):
  698. """Returns ``True`` if ``f`` is a zero polynomial. """
  699. return dmp_zero_p(f.rep, f.lev)
  700. @property
  701. def is_one(f):
  702. """Returns ``True`` if ``f`` is a unit polynomial. """
  703. return dmp_one_p(f.rep, f.lev, f.dom)
  704. @property
  705. def is_ground(f):
  706. """Returns ``True`` if ``f`` is an element of the ground domain. """
  707. return dmp_ground_p(f.rep, None, f.lev)
  708. @property
  709. def is_sqf(f):
  710. """Returns ``True`` if ``f`` is a square-free polynomial. """
  711. return dmp_sqf_p(f.rep, f.lev, f.dom)
  712. @property
  713. def is_monic(f):
  714. """Returns ``True`` if the leading coefficient of ``f`` is one. """
  715. return f.dom.is_one(dmp_ground_LC(f.rep, f.lev, f.dom))
  716. @property
  717. def is_primitive(f):
  718. """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """
  719. return f.dom.is_one(dmp_ground_content(f.rep, f.lev, f.dom))
  720. @property
  721. def is_linear(f):
  722. """Returns ``True`` if ``f`` is linear in all its variables. """
  723. return all(sum(monom) <= 1 for monom in dmp_to_dict(f.rep, f.lev, f.dom).keys())
  724. @property
  725. def is_quadratic(f):
  726. """Returns ``True`` if ``f`` is quadratic in all its variables. """
  727. return all(sum(monom) <= 2 for monom in dmp_to_dict(f.rep, f.lev, f.dom).keys())
  728. @property
  729. def is_monomial(f):
  730. """Returns ``True`` if ``f`` is zero or has only one term. """
  731. return len(f.to_dict()) <= 1
  732. @property
  733. def is_homogeneous(f):
  734. """Returns ``True`` if ``f`` is a homogeneous polynomial. """
  735. return f.homogeneous_order() is not None
  736. @property
  737. def is_irreducible(f):
  738. """Returns ``True`` if ``f`` has no factors over its domain. """
  739. return dmp_irreducible_p(f.rep, f.lev, f.dom)
  740. @property
  741. def is_cyclotomic(f):
  742. """Returns ``True`` if ``f`` is a cyclotomic polynomial. """
  743. if not f.lev:
  744. return dup_cyclotomic_p(f.rep, f.dom)
  745. else:
  746. return False
  747. def __abs__(f):
  748. return f.abs()
  749. def __neg__(f):
  750. return f.neg()
  751. def __add__(f, g):
  752. if not isinstance(g, DMP):
  753. try:
  754. g = f.per(dmp_ground(f.dom.convert(g), f.lev))
  755. except TypeError:
  756. return NotImplemented
  757. except (CoercionFailed, NotImplementedError):
  758. if f.ring is not None:
  759. try:
  760. g = f.ring.convert(g)
  761. except (CoercionFailed, NotImplementedError):
  762. return NotImplemented
  763. return f.add(g)
  764. def __radd__(f, g):
  765. return f.__add__(g)
  766. def __sub__(f, g):
  767. if not isinstance(g, DMP):
  768. try:
  769. g = f.per(dmp_ground(f.dom.convert(g), f.lev))
  770. except TypeError:
  771. return NotImplemented
  772. except (CoercionFailed, NotImplementedError):
  773. if f.ring is not None:
  774. try:
  775. g = f.ring.convert(g)
  776. except (CoercionFailed, NotImplementedError):
  777. return NotImplemented
  778. return f.sub(g)
  779. def __rsub__(f, g):
  780. return (-f).__add__(g)
  781. def __mul__(f, g):
  782. if isinstance(g, DMP):
  783. return f.mul(g)
  784. else:
  785. try:
  786. return f.mul_ground(g)
  787. except TypeError:
  788. return NotImplemented
  789. except (CoercionFailed, NotImplementedError):
  790. if f.ring is not None:
  791. try:
  792. return f.mul(f.ring.convert(g))
  793. except (CoercionFailed, NotImplementedError):
  794. pass
  795. return NotImplemented
  796. def __truediv__(f, g):
  797. if isinstance(g, DMP):
  798. return f.exquo(g)
  799. else:
  800. try:
  801. return f.mul_ground(g)
  802. except TypeError:
  803. return NotImplemented
  804. except (CoercionFailed, NotImplementedError):
  805. if f.ring is not None:
  806. try:
  807. return f.exquo(f.ring.convert(g))
  808. except (CoercionFailed, NotImplementedError):
  809. pass
  810. return NotImplemented
  811. def __rtruediv__(f, g):
  812. if isinstance(g, DMP):
  813. return g.exquo(f)
  814. elif f.ring is not None:
  815. try:
  816. return f.ring.convert(g).exquo(f)
  817. except (CoercionFailed, NotImplementedError):
  818. pass
  819. return NotImplemented
  820. def __rmul__(f, g):
  821. return f.__mul__(g)
  822. def __pow__(f, n):
  823. return f.pow(n)
  824. def __divmod__(f, g):
  825. return f.div(g)
  826. def __mod__(f, g):
  827. return f.rem(g)
  828. def __floordiv__(f, g):
  829. if isinstance(g, DMP):
  830. return f.quo(g)
  831. else:
  832. try:
  833. return f.quo_ground(g)
  834. except TypeError:
  835. return NotImplemented
  836. def __eq__(f, g):
  837. try:
  838. _, _, _, F, G = f.unify(g)
  839. if f.lev == g.lev:
  840. return F == G
  841. except UnificationFailed:
  842. pass
  843. return False
  844. def __ne__(f, g):
  845. return not f == g
  846. def eq(f, g, strict=False):
  847. if not strict:
  848. return f == g
  849. else:
  850. return f._strict_eq(g)
  851. def ne(f, g, strict=False):
  852. return not f.eq(g, strict=strict)
  853. def _strict_eq(f, g):
  854. return isinstance(g, f.__class__) and f.lev == g.lev \
  855. and f.dom == g.dom \
  856. and f.rep == g.rep
  857. def __lt__(f, g):
  858. _, _, _, F, G = f.unify(g)
  859. return F < G
  860. def __le__(f, g):
  861. _, _, _, F, G = f.unify(g)
  862. return F <= G
  863. def __gt__(f, g):
  864. _, _, _, F, G = f.unify(g)
  865. return F > G
  866. def __ge__(f, g):
  867. _, _, _, F, G = f.unify(g)
  868. return F >= G
  869. def __bool__(f):
  870. return not dmp_zero_p(f.rep, f.lev)
  871. def init_normal_DMF(num, den, lev, dom):
  872. return DMF(dmp_normal(num, lev, dom),
  873. dmp_normal(den, lev, dom), dom, lev)
  874. class DMF(PicklableWithSlots, CantSympify):
  875. """Dense Multivariate Fractions over `K`. """
  876. __slots__ = ('num', 'den', 'lev', 'dom', 'ring')
  877. def __init__(self, rep, dom, lev=None, ring=None):
  878. num, den, lev = self._parse(rep, dom, lev)
  879. num, den = dmp_cancel(num, den, lev, dom)
  880. self.num = num
  881. self.den = den
  882. self.lev = lev
  883. self.dom = dom
  884. self.ring = ring
  885. @classmethod
  886. def new(cls, rep, dom, lev=None, ring=None):
  887. num, den, lev = cls._parse(rep, dom, lev)
  888. obj = object.__new__(cls)
  889. obj.num = num
  890. obj.den = den
  891. obj.lev = lev
  892. obj.dom = dom
  893. obj.ring = ring
  894. return obj
  895. @classmethod
  896. def _parse(cls, rep, dom, lev=None):
  897. if isinstance(rep, tuple):
  898. num, den = rep
  899. if lev is not None:
  900. if isinstance(num, dict):
  901. num = dmp_from_dict(num, lev, dom)
  902. if isinstance(den, dict):
  903. den = dmp_from_dict(den, lev, dom)
  904. else:
  905. num, num_lev = dmp_validate(num)
  906. den, den_lev = dmp_validate(den)
  907. if num_lev == den_lev:
  908. lev = num_lev
  909. else:
  910. raise ValueError('inconsistent number of levels')
  911. if dmp_zero_p(den, lev):
  912. raise ZeroDivisionError('fraction denominator')
  913. if dmp_zero_p(num, lev):
  914. den = dmp_one(lev, dom)
  915. else:
  916. if dmp_negative_p(den, lev, dom):
  917. num = dmp_neg(num, lev, dom)
  918. den = dmp_neg(den, lev, dom)
  919. else:
  920. num = rep
  921. if lev is not None:
  922. if isinstance(num, dict):
  923. num = dmp_from_dict(num, lev, dom)
  924. elif not isinstance(num, list):
  925. num = dmp_ground(dom.convert(num), lev)
  926. else:
  927. num, lev = dmp_validate(num)
  928. den = dmp_one(lev, dom)
  929. return num, den, lev
  930. def __repr__(f):
  931. return "%s((%s, %s), %s, %s)" % (f.__class__.__name__, f.num, f.den,
  932. f.dom, f.ring)
  933. def __hash__(f):
  934. return hash((f.__class__.__name__, dmp_to_tuple(f.num, f.lev),
  935. dmp_to_tuple(f.den, f.lev), f.lev, f.dom, f.ring))
  936. def poly_unify(f, g):
  937. """Unify a multivariate fraction and a polynomial. """
  938. if not isinstance(g, DMP) or f.lev != g.lev:
  939. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  940. if f.dom == g.dom and f.ring == g.ring:
  941. return (f.lev, f.dom, f.per, (f.num, f.den), g.rep)
  942. else:
  943. lev, dom = f.lev, f.dom.unify(g.dom)
  944. ring = f.ring
  945. if g.ring is not None:
  946. if ring is not None:
  947. ring = ring.unify(g.ring)
  948. else:
  949. ring = g.ring
  950. F = (dmp_convert(f.num, lev, f.dom, dom),
  951. dmp_convert(f.den, lev, f.dom, dom))
  952. G = dmp_convert(g.rep, lev, g.dom, dom)
  953. def per(num, den, cancel=True, kill=False, lev=lev):
  954. if kill:
  955. if not lev:
  956. return num/den
  957. else:
  958. lev = lev - 1
  959. if cancel:
  960. num, den = dmp_cancel(num, den, lev, dom)
  961. return f.__class__.new((num, den), dom, lev, ring=ring)
  962. return lev, dom, per, F, G
  963. def frac_unify(f, g):
  964. """Unify representations of two multivariate fractions. """
  965. if not isinstance(g, DMF) or f.lev != g.lev:
  966. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  967. if f.dom == g.dom and f.ring == g.ring:
  968. return (f.lev, f.dom, f.per, (f.num, f.den),
  969. (g.num, g.den))
  970. else:
  971. lev, dom = f.lev, f.dom.unify(g.dom)
  972. ring = f.ring
  973. if g.ring is not None:
  974. if ring is not None:
  975. ring = ring.unify(g.ring)
  976. else:
  977. ring = g.ring
  978. F = (dmp_convert(f.num, lev, f.dom, dom),
  979. dmp_convert(f.den, lev, f.dom, dom))
  980. G = (dmp_convert(g.num, lev, g.dom, dom),
  981. dmp_convert(g.den, lev, g.dom, dom))
  982. def per(num, den, cancel=True, kill=False, lev=lev):
  983. if kill:
  984. if not lev:
  985. return num/den
  986. else:
  987. lev = lev - 1
  988. if cancel:
  989. num, den = dmp_cancel(num, den, lev, dom)
  990. return f.__class__.new((num, den), dom, lev, ring=ring)
  991. return lev, dom, per, F, G
  992. def per(f, num, den, cancel=True, kill=False, ring=None):
  993. """Create a DMF out of the given representation. """
  994. lev, dom = f.lev, f.dom
  995. if kill:
  996. if not lev:
  997. return num/den
  998. else:
  999. lev -= 1
  1000. if cancel:
  1001. num, den = dmp_cancel(num, den, lev, dom)
  1002. if ring is None:
  1003. ring = f.ring
  1004. return f.__class__.new((num, den), dom, lev, ring=ring)
  1005. def half_per(f, rep, kill=False):
  1006. """Create a DMP out of the given representation. """
  1007. lev = f.lev
  1008. if kill:
  1009. if not lev:
  1010. return rep
  1011. else:
  1012. lev -= 1
  1013. return DMP(rep, f.dom, lev)
  1014. @classmethod
  1015. def zero(cls, lev, dom, ring=None):
  1016. return cls.new(0, dom, lev, ring=ring)
  1017. @classmethod
  1018. def one(cls, lev, dom, ring=None):
  1019. return cls.new(1, dom, lev, ring=ring)
  1020. def numer(f):
  1021. """Returns the numerator of ``f``. """
  1022. return f.half_per(f.num)
  1023. def denom(f):
  1024. """Returns the denominator of ``f``. """
  1025. return f.half_per(f.den)
  1026. def cancel(f):
  1027. """Remove common factors from ``f.num`` and ``f.den``. """
  1028. return f.per(f.num, f.den)
  1029. def neg(f):
  1030. """Negate all coefficients in ``f``. """
  1031. return f.per(dmp_neg(f.num, f.lev, f.dom), f.den, cancel=False)
  1032. def add(f, g):
  1033. """Add two multivariate fractions ``f`` and ``g``. """
  1034. if isinstance(g, DMP):
  1035. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  1036. num, den = dmp_add_mul(F_num, F_den, G, lev, dom), F_den
  1037. else:
  1038. lev, dom, per, F, G = f.frac_unify(g)
  1039. (F_num, F_den), (G_num, G_den) = F, G
  1040. num = dmp_add(dmp_mul(F_num, G_den, lev, dom),
  1041. dmp_mul(F_den, G_num, lev, dom), lev, dom)
  1042. den = dmp_mul(F_den, G_den, lev, dom)
  1043. return per(num, den)
  1044. def sub(f, g):
  1045. """Subtract two multivariate fractions ``f`` and ``g``. """
  1046. if isinstance(g, DMP):
  1047. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  1048. num, den = dmp_sub_mul(F_num, F_den, G, lev, dom), F_den
  1049. else:
  1050. lev, dom, per, F, G = f.frac_unify(g)
  1051. (F_num, F_den), (G_num, G_den) = F, G
  1052. num = dmp_sub(dmp_mul(F_num, G_den, lev, dom),
  1053. dmp_mul(F_den, G_num, lev, dom), lev, dom)
  1054. den = dmp_mul(F_den, G_den, lev, dom)
  1055. return per(num, den)
  1056. def mul(f, g):
  1057. """Multiply two multivariate fractions ``f`` and ``g``. """
  1058. if isinstance(g, DMP):
  1059. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  1060. num, den = dmp_mul(F_num, G, lev, dom), F_den
  1061. else:
  1062. lev, dom, per, F, G = f.frac_unify(g)
  1063. (F_num, F_den), (G_num, G_den) = F, G
  1064. num = dmp_mul(F_num, G_num, lev, dom)
  1065. den = dmp_mul(F_den, G_den, lev, dom)
  1066. return per(num, den)
  1067. def pow(f, n):
  1068. """Raise ``f`` to a non-negative power ``n``. """
  1069. if isinstance(n, int):
  1070. num, den = f.num, f.den
  1071. if n < 0:
  1072. num, den, n = den, num, -n
  1073. return f.per(dmp_pow(num, n, f.lev, f.dom),
  1074. dmp_pow(den, n, f.lev, f.dom), cancel=False)
  1075. else:
  1076. raise TypeError("``int`` expected, got %s" % type(n))
  1077. def quo(f, g):
  1078. """Computes quotient of fractions ``f`` and ``g``. """
  1079. if isinstance(g, DMP):
  1080. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  1081. num, den = F_num, dmp_mul(F_den, G, lev, dom)
  1082. else:
  1083. lev, dom, per, F, G = f.frac_unify(g)
  1084. (F_num, F_den), (G_num, G_den) = F, G
  1085. num = dmp_mul(F_num, G_den, lev, dom)
  1086. den = dmp_mul(F_den, G_num, lev, dom)
  1087. res = per(num, den)
  1088. if f.ring is not None and res not in f.ring:
  1089. from sympy.polys.polyerrors import ExactQuotientFailed
  1090. raise ExactQuotientFailed(f, g, f.ring)
  1091. return res
  1092. exquo = quo
  1093. def invert(f, check=True):
  1094. """Computes inverse of a fraction ``f``. """
  1095. if check and f.ring is not None and not f.ring.is_unit(f):
  1096. raise NotReversible(f, f.ring)
  1097. res = f.per(f.den, f.num, cancel=False)
  1098. return res
  1099. @property
  1100. def is_zero(f):
  1101. """Returns ``True`` if ``f`` is a zero fraction. """
  1102. return dmp_zero_p(f.num, f.lev)
  1103. @property
  1104. def is_one(f):
  1105. """Returns ``True`` if ``f`` is a unit fraction. """
  1106. return dmp_one_p(f.num, f.lev, f.dom) and \
  1107. dmp_one_p(f.den, f.lev, f.dom)
  1108. def __neg__(f):
  1109. return f.neg()
  1110. def __add__(f, g):
  1111. if isinstance(g, (DMP, DMF)):
  1112. return f.add(g)
  1113. try:
  1114. return f.add(f.half_per(g))
  1115. except TypeError:
  1116. return NotImplemented
  1117. except (CoercionFailed, NotImplementedError):
  1118. if f.ring is not None:
  1119. try:
  1120. return f.add(f.ring.convert(g))
  1121. except (CoercionFailed, NotImplementedError):
  1122. pass
  1123. return NotImplemented
  1124. def __radd__(f, g):
  1125. return f.__add__(g)
  1126. def __sub__(f, g):
  1127. if isinstance(g, (DMP, DMF)):
  1128. return f.sub(g)
  1129. try:
  1130. return f.sub(f.half_per(g))
  1131. except TypeError:
  1132. return NotImplemented
  1133. except (CoercionFailed, NotImplementedError):
  1134. if f.ring is not None:
  1135. try:
  1136. return f.sub(f.ring.convert(g))
  1137. except (CoercionFailed, NotImplementedError):
  1138. pass
  1139. return NotImplemented
  1140. def __rsub__(f, g):
  1141. return (-f).__add__(g)
  1142. def __mul__(f, g):
  1143. if isinstance(g, (DMP, DMF)):
  1144. return f.mul(g)
  1145. try:
  1146. return f.mul(f.half_per(g))
  1147. except TypeError:
  1148. return NotImplemented
  1149. except (CoercionFailed, NotImplementedError):
  1150. if f.ring is not None:
  1151. try:
  1152. return f.mul(f.ring.convert(g))
  1153. except (CoercionFailed, NotImplementedError):
  1154. pass
  1155. return NotImplemented
  1156. def __rmul__(f, g):
  1157. return f.__mul__(g)
  1158. def __pow__(f, n):
  1159. return f.pow(n)
  1160. def __truediv__(f, g):
  1161. if isinstance(g, (DMP, DMF)):
  1162. return f.quo(g)
  1163. try:
  1164. return f.quo(f.half_per(g))
  1165. except TypeError:
  1166. return NotImplemented
  1167. except (CoercionFailed, NotImplementedError):
  1168. if f.ring is not None:
  1169. try:
  1170. return f.quo(f.ring.convert(g))
  1171. except (CoercionFailed, NotImplementedError):
  1172. pass
  1173. return NotImplemented
  1174. def __rtruediv__(self, g):
  1175. r = self.invert(check=False)*g
  1176. if self.ring and r not in self.ring:
  1177. from sympy.polys.polyerrors import ExactQuotientFailed
  1178. raise ExactQuotientFailed(g, self, self.ring)
  1179. return r
  1180. def __eq__(f, g):
  1181. try:
  1182. if isinstance(g, DMP):
  1183. _, _, _, (F_num, F_den), G = f.poly_unify(g)
  1184. if f.lev == g.lev:
  1185. return dmp_one_p(F_den, f.lev, f.dom) and F_num == G
  1186. else:
  1187. _, _, _, F, G = f.frac_unify(g)
  1188. if f.lev == g.lev:
  1189. return F == G
  1190. except UnificationFailed:
  1191. pass
  1192. return False
  1193. def __ne__(f, g):
  1194. try:
  1195. if isinstance(g, DMP):
  1196. _, _, _, (F_num, F_den), G = f.poly_unify(g)
  1197. if f.lev == g.lev:
  1198. return not (dmp_one_p(F_den, f.lev, f.dom) and F_num == G)
  1199. else:
  1200. _, _, _, F, G = f.frac_unify(g)
  1201. if f.lev == g.lev:
  1202. return F != G
  1203. except UnificationFailed:
  1204. pass
  1205. return True
  1206. def __lt__(f, g):
  1207. _, _, _, F, G = f.frac_unify(g)
  1208. return F < G
  1209. def __le__(f, g):
  1210. _, _, _, F, G = f.frac_unify(g)
  1211. return F <= G
  1212. def __gt__(f, g):
  1213. _, _, _, F, G = f.frac_unify(g)
  1214. return F > G
  1215. def __ge__(f, g):
  1216. _, _, _, F, G = f.frac_unify(g)
  1217. return F >= G
  1218. def __bool__(f):
  1219. return not dmp_zero_p(f.num, f.lev)
  1220. def init_normal_ANP(rep, mod, dom):
  1221. return ANP(dup_normal(rep, dom),
  1222. dup_normal(mod, dom), dom)
  1223. class ANP(PicklableWithSlots, CantSympify):
  1224. """Dense Algebraic Number Polynomials over a field. """
  1225. __slots__ = ('rep', 'mod', 'dom')
  1226. def __init__(self, rep, mod, dom):
  1227. # Not possible to check with isinstance
  1228. if type(rep) is dict:
  1229. self.rep = dup_from_dict(rep, dom)
  1230. else:
  1231. if isinstance(rep, list):
  1232. rep = [dom.convert(a) for a in rep]
  1233. else:
  1234. rep = [dom.convert(rep)]
  1235. self.rep = dup_strip(rep)
  1236. if isinstance(mod, DMP):
  1237. self.mod = mod.rep
  1238. else:
  1239. if isinstance(mod, dict):
  1240. self.mod = dup_from_dict(mod, dom)
  1241. else:
  1242. self.mod = dup_strip(mod)
  1243. self.dom = dom
  1244. def __repr__(f):
  1245. return "%s(%s, %s, %s)" % (f.__class__.__name__, f.rep, f.mod, f.dom)
  1246. def __hash__(f):
  1247. return hash((f.__class__.__name__, f.to_tuple(), dmp_to_tuple(f.mod, 0), f.dom))
  1248. def unify(f, g):
  1249. """Unify representations of two algebraic numbers. """
  1250. if not isinstance(g, ANP) or f.mod != g.mod:
  1251. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  1252. if f.dom == g.dom:
  1253. return f.dom, f.per, f.rep, g.rep, f.mod
  1254. else:
  1255. dom = f.dom.unify(g.dom)
  1256. F = dup_convert(f.rep, f.dom, dom)
  1257. G = dup_convert(g.rep, g.dom, dom)
  1258. if dom != f.dom and dom != g.dom:
  1259. mod = dup_convert(f.mod, f.dom, dom)
  1260. else:
  1261. if dom == f.dom:
  1262. mod = f.mod
  1263. else:
  1264. mod = g.mod
  1265. per = lambda rep: ANP(rep, mod, dom)
  1266. return dom, per, F, G, mod
  1267. def per(f, rep, mod=None, dom=None):
  1268. return ANP(rep, mod or f.mod, dom or f.dom)
  1269. @classmethod
  1270. def zero(cls, mod, dom):
  1271. return ANP(0, mod, dom)
  1272. @classmethod
  1273. def one(cls, mod, dom):
  1274. return ANP(1, mod, dom)
  1275. def to_dict(f):
  1276. """Convert ``f`` to a dict representation with native coefficients. """
  1277. return dmp_to_dict(f.rep, 0, f.dom)
  1278. def to_sympy_dict(f):
  1279. """Convert ``f`` to a dict representation with SymPy coefficients. """
  1280. rep = dmp_to_dict(f.rep, 0, f.dom)
  1281. for k, v in rep.items():
  1282. rep[k] = f.dom.to_sympy(v)
  1283. return rep
  1284. def to_list(f):
  1285. """Convert ``f`` to a list representation with native coefficients. """
  1286. return f.rep
  1287. def to_sympy_list(f):
  1288. """Convert ``f`` to a list representation with SymPy coefficients. """
  1289. return [ f.dom.to_sympy(c) for c in f.rep ]
  1290. def to_tuple(f):
  1291. """
  1292. Convert ``f`` to a tuple representation with native coefficients.
  1293. This is needed for hashing.
  1294. """
  1295. return dmp_to_tuple(f.rep, 0)
  1296. @classmethod
  1297. def from_list(cls, rep, mod, dom):
  1298. return ANP(dup_strip(list(map(dom.convert, rep))), mod, dom)
  1299. def neg(f):
  1300. return f.per(dup_neg(f.rep, f.dom))
  1301. def add(f, g):
  1302. dom, per, F, G, mod = f.unify(g)
  1303. return per(dup_add(F, G, dom))
  1304. def sub(f, g):
  1305. dom, per, F, G, mod = f.unify(g)
  1306. return per(dup_sub(F, G, dom))
  1307. def mul(f, g):
  1308. dom, per, F, G, mod = f.unify(g)
  1309. return per(dup_rem(dup_mul(F, G, dom), mod, dom))
  1310. def pow(f, n):
  1311. """Raise ``f`` to a non-negative power ``n``. """
  1312. if isinstance(n, int):
  1313. if n < 0:
  1314. F, n = dup_invert(f.rep, f.mod, f.dom), -n
  1315. else:
  1316. F = f.rep
  1317. return f.per(dup_rem(dup_pow(F, n, f.dom), f.mod, f.dom))
  1318. else:
  1319. raise TypeError("``int`` expected, got %s" % type(n))
  1320. def div(f, g):
  1321. dom, per, F, G, mod = f.unify(g)
  1322. return (per(dup_rem(dup_mul(F, dup_invert(G, mod, dom), dom), mod, dom)), f.zero(mod, dom))
  1323. def rem(f, g):
  1324. dom, _, _, G, mod = f.unify(g)
  1325. s, h = dup_half_gcdex(G, mod, dom)
  1326. if h == [dom.one]:
  1327. return f.zero(mod, dom)
  1328. else:
  1329. raise NotInvertible("zero divisor")
  1330. def quo(f, g):
  1331. dom, per, F, G, mod = f.unify(g)
  1332. return per(dup_rem(dup_mul(F, dup_invert(G, mod, dom), dom), mod, dom))
  1333. exquo = quo
  1334. def LC(f):
  1335. """Returns the leading coefficient of ``f``. """
  1336. return dup_LC(f.rep, f.dom)
  1337. def TC(f):
  1338. """Returns the trailing coefficient of ``f``. """
  1339. return dup_TC(f.rep, f.dom)
  1340. @property
  1341. def is_zero(f):
  1342. """Returns ``True`` if ``f`` is a zero algebraic number. """
  1343. return not f
  1344. @property
  1345. def is_one(f):
  1346. """Returns ``True`` if ``f`` is a unit algebraic number. """
  1347. return f.rep == [f.dom.one]
  1348. @property
  1349. def is_ground(f):
  1350. """Returns ``True`` if ``f`` is an element of the ground domain. """
  1351. return not f.rep or len(f.rep) == 1
  1352. def __pos__(f):
  1353. return f
  1354. def __neg__(f):
  1355. return f.neg()
  1356. def __add__(f, g):
  1357. if isinstance(g, ANP):
  1358. return f.add(g)
  1359. else:
  1360. try:
  1361. return f.add(f.per(g))
  1362. except (CoercionFailed, TypeError):
  1363. return NotImplemented
  1364. def __radd__(f, g):
  1365. return f.__add__(g)
  1366. def __sub__(f, g):
  1367. if isinstance(g, ANP):
  1368. return f.sub(g)
  1369. else:
  1370. try:
  1371. return f.sub(f.per(g))
  1372. except (CoercionFailed, TypeError):
  1373. return NotImplemented
  1374. def __rsub__(f, g):
  1375. return (-f).__add__(g)
  1376. def __mul__(f, g):
  1377. if isinstance(g, ANP):
  1378. return f.mul(g)
  1379. else:
  1380. try:
  1381. return f.mul(f.per(g))
  1382. except (CoercionFailed, TypeError):
  1383. return NotImplemented
  1384. def __rmul__(f, g):
  1385. return f.__mul__(g)
  1386. def __pow__(f, n):
  1387. return f.pow(n)
  1388. def __divmod__(f, g):
  1389. return f.div(g)
  1390. def __mod__(f, g):
  1391. return f.rem(g)
  1392. def __truediv__(f, g):
  1393. if isinstance(g, ANP):
  1394. return f.quo(g)
  1395. else:
  1396. try:
  1397. return f.quo(f.per(g))
  1398. except (CoercionFailed, TypeError):
  1399. return NotImplemented
  1400. def __eq__(f, g):
  1401. try:
  1402. _, _, F, G, _ = f.unify(g)
  1403. return F == G
  1404. except UnificationFailed:
  1405. return False
  1406. def __ne__(f, g):
  1407. try:
  1408. _, _, F, G, _ = f.unify(g)
  1409. return F != G
  1410. except UnificationFailed:
  1411. return True
  1412. def __lt__(f, g):
  1413. _, _, F, G, _ = f.unify(g)
  1414. return F < G
  1415. def __le__(f, g):
  1416. _, _, F, G, _ = f.unify(g)
  1417. return F <= G
  1418. def __gt__(f, g):
  1419. _, _, F, G, _ = f.unify(g)
  1420. return F > G
  1421. def __ge__(f, g):
  1422. _, _, F, G, _ = f.unify(g)
  1423. return F >= G
  1424. def __bool__(f):
  1425. return bool(f.rep)