polyclasses.py 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186
  1. """OO layer for several polynomial representations. """
  2. from __future__ import annotations
  3. from sympy.external.gmpy import GROUND_TYPES
  4. from sympy.utilities.exceptions import sympy_deprecation_warning
  5. from sympy.core.numbers import oo
  6. from sympy.core.sympify import CantSympify
  7. from sympy.polys.polyutils import PicklableWithSlots, _sort_factors
  8. from sympy.polys.domains import Domain, ZZ, QQ
  9. from sympy.polys.polyerrors import (
  10. CoercionFailed,
  11. ExactQuotientFailed,
  12. DomainError,
  13. NotInvertible,
  14. )
  15. from sympy.polys.densebasic import (
  16. ninf,
  17. dmp_validate,
  18. dup_normal, dmp_normal,
  19. dup_convert, dmp_convert,
  20. dmp_from_sympy,
  21. dup_strip,
  22. dmp_degree_in,
  23. dmp_degree_list,
  24. dmp_negative_p,
  25. dmp_ground_LC,
  26. dmp_ground_TC,
  27. dmp_ground_nth,
  28. dmp_one, dmp_ground,
  29. dmp_zero, dmp_zero_p, dmp_one_p, dmp_ground_p,
  30. dup_from_dict, dmp_from_dict,
  31. dmp_to_dict,
  32. dmp_deflate,
  33. dmp_inject, dmp_eject,
  34. dmp_terms_gcd,
  35. dmp_list_terms, dmp_exclude,
  36. dup_slice, dmp_slice_in, dmp_permute,
  37. dmp_to_tuple,)
  38. from sympy.polys.densearith import (
  39. dmp_add_ground,
  40. dmp_sub_ground,
  41. dmp_mul_ground,
  42. dmp_quo_ground,
  43. dmp_exquo_ground,
  44. dmp_abs,
  45. dmp_neg,
  46. dmp_add,
  47. dmp_sub,
  48. dmp_mul,
  49. dmp_sqr,
  50. dmp_pow,
  51. dmp_pdiv,
  52. dmp_prem,
  53. dmp_pquo,
  54. dmp_pexquo,
  55. dmp_div,
  56. dmp_rem,
  57. dmp_quo,
  58. dmp_exquo,
  59. dmp_add_mul, dmp_sub_mul,
  60. dmp_max_norm,
  61. dmp_l1_norm,
  62. dmp_l2_norm_squared)
  63. from sympy.polys.densetools import (
  64. dmp_clear_denoms,
  65. dmp_integrate_in,
  66. dmp_diff_in,
  67. dmp_eval_in,
  68. dup_revert,
  69. dmp_ground_trunc,
  70. dmp_ground_content,
  71. dmp_ground_primitive,
  72. dmp_ground_monic,
  73. dmp_compose,
  74. dup_decompose,
  75. dup_shift,
  76. dmp_shift,
  77. dup_transform,
  78. dmp_lift)
  79. from sympy.polys.euclidtools import (
  80. dup_half_gcdex, dup_gcdex, dup_invert,
  81. dmp_subresultants,
  82. dmp_resultant,
  83. dmp_discriminant,
  84. dmp_inner_gcd,
  85. dmp_gcd,
  86. dmp_lcm,
  87. dmp_cancel)
  88. from sympy.polys.sqfreetools import (
  89. dup_gff_list,
  90. dmp_norm,
  91. dmp_sqf_p,
  92. dmp_sqf_norm,
  93. dmp_sqf_part,
  94. dmp_sqf_list, dmp_sqf_list_include)
  95. from sympy.polys.factortools import (
  96. dup_cyclotomic_p, dmp_irreducible_p,
  97. dmp_factor_list, dmp_factor_list_include)
  98. from sympy.polys.rootisolation import (
  99. dup_isolate_real_roots_sqf,
  100. dup_isolate_real_roots,
  101. dup_isolate_all_roots_sqf,
  102. dup_isolate_all_roots,
  103. dup_refine_real_root,
  104. dup_count_real_roots,
  105. dup_count_complex_roots,
  106. dup_sturm,
  107. dup_cauchy_upper_bound,
  108. dup_cauchy_lower_bound,
  109. dup_mignotte_sep_bound_squared)
  110. from sympy.polys.polyerrors import (
  111. UnificationFailed,
  112. PolynomialError)
  113. if GROUND_TYPES == 'flint':
  114. import flint
  115. def _supported_flint_domain(D):
  116. return D.is_ZZ or D.is_QQ or D.is_FF and D._is_flint
  117. else:
  118. flint = None
  119. def _supported_flint_domain(D):
  120. return False
  121. class DMP(CantSympify):
  122. """Dense Multivariate Polynomials over `K`. """
  123. __slots__ = ()
  124. lev: int
  125. dom: Domain
  126. def __new__(cls, rep, dom, lev=None):
  127. if lev is None:
  128. rep, lev = dmp_validate(rep)
  129. elif not isinstance(rep, list):
  130. raise CoercionFailed("expected list, got %s" % type(rep))
  131. return cls.new(rep, dom, lev)
  132. @classmethod
  133. def new(cls, rep, dom, lev):
  134. # It would be too slow to call _validate_args always at runtime.
  135. # Ideally this checking would be handled by a static type checker.
  136. #
  137. #cls._validate_args(rep, dom, lev)
  138. if flint is not None:
  139. if lev == 0 and _supported_flint_domain(dom):
  140. return DUP_Flint._new(rep, dom, lev)
  141. return DMP_Python._new(rep, dom, lev)
  142. @property
  143. def rep(f):
  144. """Get the representation of ``f``. """
  145. sympy_deprecation_warning("""
  146. Accessing the ``DMP.rep`` attribute is deprecated. The internal
  147. representation of ``DMP`` instances can now be ``DUP_Flint`` when the
  148. ground types are ``flint``. In this case the ``DMP`` instance does not
  149. have a ``rep`` attribute. Use ``DMP.to_list()`` instead. Using
  150. ``DMP.to_list()`` also works in previous versions of SymPy.
  151. """,
  152. deprecated_since_version="1.13",
  153. active_deprecations_target="dmp-rep",
  154. )
  155. return f.to_list()
  156. def to_best(f):
  157. """Convert to DUP_Flint if possible.
  158. This method should be used when the domain or level is changed and it
  159. potentially becomes possible to convert from DMP_Python to DUP_Flint.
  160. """
  161. if flint is not None:
  162. if isinstance(f, DMP_Python) and f.lev == 0 and _supported_flint_domain(f.dom):
  163. return DUP_Flint.new(f._rep, f.dom, f.lev)
  164. return f
  165. @classmethod
  166. def _validate_args(cls, rep, dom, lev):
  167. assert isinstance(dom, Domain)
  168. assert isinstance(lev, int) and lev >= 0
  169. def validate_rep(rep, lev):
  170. assert isinstance(rep, list)
  171. if lev == 0:
  172. assert all(dom.of_type(c) for c in rep)
  173. else:
  174. for r in rep:
  175. validate_rep(r, lev - 1)
  176. validate_rep(rep, lev)
  177. @classmethod
  178. def from_dict(cls, rep, lev, dom):
  179. rep = dmp_from_dict(rep, lev, dom)
  180. return cls.new(rep, dom, lev)
  181. @classmethod
  182. def from_list(cls, rep, lev, dom):
  183. """Create an instance of ``cls`` given a list of native coefficients. """
  184. return cls.new(dmp_convert(rep, lev, None, dom), dom, lev)
  185. @classmethod
  186. def from_sympy_list(cls, rep, lev, dom):
  187. """Create an instance of ``cls`` given a list of SymPy coefficients. """
  188. return cls.new(dmp_from_sympy(rep, lev, dom), dom, lev)
  189. @classmethod
  190. def from_monoms_coeffs(cls, monoms, coeffs, lev, dom):
  191. return cls(dict(list(zip(monoms, coeffs))), dom, lev)
  192. def convert(f, dom):
  193. """Convert ``f`` to a ``DMP`` over the new domain. """
  194. if f.dom == dom:
  195. return f
  196. elif f.lev or flint is None:
  197. return f._convert(dom)
  198. elif isinstance(f, DUP_Flint):
  199. if _supported_flint_domain(dom):
  200. return f._convert(dom)
  201. else:
  202. return f.to_DMP_Python()._convert(dom)
  203. elif isinstance(f, DMP_Python):
  204. if _supported_flint_domain(dom):
  205. return f._convert(dom).to_DUP_Flint()
  206. else:
  207. return f._convert(dom)
  208. else:
  209. raise RuntimeError("unreachable code")
  210. def _convert(f, dom):
  211. raise NotImplementedError
  212. @classmethod
  213. def zero(cls, lev, dom):
  214. return DMP(dmp_zero(lev), dom, lev)
  215. @classmethod
  216. def one(cls, lev, dom):
  217. return DMP(dmp_one(lev, dom), dom, lev)
  218. def _one(f):
  219. raise NotImplementedError
  220. def __repr__(f):
  221. return "%s(%s, %s)" % (f.__class__.__name__, f.to_list(), f.dom)
  222. def __hash__(f):
  223. return hash((f.__class__.__name__, f.to_tuple(), f.lev, f.dom))
  224. def __getnewargs__(self):
  225. return self.to_list(), self.dom, self.lev
  226. def ground_new(f, coeff):
  227. """Construct a new ground instance of ``f``. """
  228. raise NotImplementedError
  229. def unify_DMP(f, g):
  230. """Unify and return ``DMP`` instances of ``f`` and ``g``. """
  231. if not isinstance(g, DMP) or f.lev != g.lev:
  232. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  233. if f.dom != g.dom:
  234. dom = f.dom.unify(g.dom)
  235. f = f.convert(dom)
  236. g = g.convert(dom)
  237. return f, g
  238. def to_dict(f, zero=False):
  239. """Convert ``f`` to a dict representation with native coefficients. """
  240. return dmp_to_dict(f.to_list(), f.lev, f.dom, zero=zero)
  241. def to_sympy_dict(f, zero=False):
  242. """Convert ``f`` to a dict representation with SymPy coefficients. """
  243. rep = f.to_dict(zero=zero)
  244. for k, v in rep.items():
  245. rep[k] = f.dom.to_sympy(v)
  246. return rep
  247. def to_sympy_list(f):
  248. """Convert ``f`` to a list representation with SymPy coefficients. """
  249. def sympify_nested_list(rep):
  250. out = []
  251. for val in rep:
  252. if isinstance(val, list):
  253. out.append(sympify_nested_list(val))
  254. else:
  255. out.append(f.dom.to_sympy(val))
  256. return out
  257. return sympify_nested_list(f.to_list())
  258. def to_list(f):
  259. """Convert ``f`` to a list representation with native coefficients. """
  260. raise NotImplementedError
  261. def to_tuple(f):
  262. """
  263. Convert ``f`` to a tuple representation with native coefficients.
  264. This is needed for hashing.
  265. """
  266. raise NotImplementedError
  267. def to_ring(f):
  268. """Make the ground domain a ring. """
  269. return f.convert(f.dom.get_ring())
  270. def to_field(f):
  271. """Make the ground domain a field. """
  272. return f.convert(f.dom.get_field())
  273. def to_exact(f):
  274. """Make the ground domain exact. """
  275. return f.convert(f.dom.get_exact())
  276. def slice(f, m, n, j=0):
  277. """Take a continuous subsequence of terms of ``f``. """
  278. if not f.lev and not j:
  279. return f._slice(m, n)
  280. else:
  281. return f._slice_lev(m, n, j)
  282. def _slice(f, m, n):
  283. raise NotImplementedError
  284. def _slice_lev(f, m, n, j):
  285. raise NotImplementedError
  286. def coeffs(f, order=None):
  287. """Returns all non-zero coefficients from ``f`` in lex order. """
  288. return [ c for _, c in f.terms(order=order) ]
  289. def monoms(f, order=None):
  290. """Returns all non-zero monomials from ``f`` in lex order. """
  291. return [ m for m, _ in f.terms(order=order) ]
  292. def terms(f, order=None):
  293. """Returns all non-zero terms from ``f`` in lex order. """
  294. if f.is_zero:
  295. zero_monom = (0,)*(f.lev + 1)
  296. return [(zero_monom, f.dom.zero)]
  297. else:
  298. return f._terms(order=order)
  299. def _terms(f, order=None):
  300. raise NotImplementedError
  301. def all_coeffs(f):
  302. """Returns all coefficients from ``f``. """
  303. if f.lev:
  304. raise PolynomialError('multivariate polynomials not supported')
  305. if not f:
  306. return [f.dom.zero]
  307. else:
  308. return list(f.to_list())
  309. def all_monoms(f):
  310. """Returns all monomials from ``f``. """
  311. if f.lev:
  312. raise PolynomialError('multivariate polynomials not supported')
  313. n = f.degree()
  314. if n < 0:
  315. return [(0,)]
  316. else:
  317. return [ (n - i,) for i, c in enumerate(f.to_list()) ]
  318. def all_terms(f):
  319. """Returns all terms from a ``f``. """
  320. if f.lev:
  321. raise PolynomialError('multivariate polynomials not supported')
  322. n = f.degree()
  323. if n < 0:
  324. return [((0,), f.dom.zero)]
  325. else:
  326. return [ ((n - i,), c) for i, c in enumerate(f.to_list()) ]
  327. def lift(f):
  328. """Convert algebraic coefficients to rationals. """
  329. return f._lift().to_best()
  330. def _lift(f):
  331. raise NotImplementedError
  332. def deflate(f):
  333. """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """
  334. raise NotImplementedError
  335. def inject(f, front=False):
  336. """Inject ground domain generators into ``f``. """
  337. raise NotImplementedError
  338. def eject(f, dom, front=False):
  339. """Eject selected generators into the ground domain. """
  340. raise NotImplementedError
  341. def exclude(f):
  342. r"""
  343. Remove useless generators from ``f``.
  344. Returns the removed generators and the new excluded ``f``.
  345. Examples
  346. ========
  347. >>> from sympy.polys.polyclasses import DMP
  348. >>> from sympy.polys.domains import ZZ
  349. >>> DMP([[[ZZ(1)]], [[ZZ(1)], [ZZ(2)]]], ZZ).exclude()
  350. ([2], DMP_Python([[1], [1, 2]], ZZ))
  351. """
  352. J, F = f._exclude()
  353. return J, F.to_best()
  354. def _exclude(f):
  355. raise NotImplementedError
  356. def permute(f, P):
  357. r"""
  358. Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`.
  359. Examples
  360. ========
  361. >>> from sympy.polys.polyclasses import DMP
  362. >>> from sympy.polys.domains import ZZ
  363. >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 0, 2])
  364. DMP_Python([[[2], []], [[1, 0], []]], ZZ)
  365. >>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 2, 0])
  366. DMP_Python([[[1], []], [[2, 0], []]], ZZ)
  367. """
  368. return f._permute(P)
  369. def _permute(f, P):
  370. raise NotImplementedError
  371. def terms_gcd(f):
  372. """Remove GCD of terms from the polynomial ``f``. """
  373. raise NotImplementedError
  374. def abs(f):
  375. """Make all coefficients in ``f`` positive. """
  376. raise NotImplementedError
  377. def neg(f):
  378. """Negate all coefficients in ``f``. """
  379. raise NotImplementedError
  380. def add_ground(f, c):
  381. """Add an element of the ground domain to ``f``. """
  382. return f._add_ground(f.dom.convert(c))
  383. def sub_ground(f, c):
  384. """Subtract an element of the ground domain from ``f``. """
  385. return f._sub_ground(f.dom.convert(c))
  386. def mul_ground(f, c):
  387. """Multiply ``f`` by a an element of the ground domain. """
  388. return f._mul_ground(f.dom.convert(c))
  389. def quo_ground(f, c):
  390. """Quotient of ``f`` by a an element of the ground domain. """
  391. return f._quo_ground(f.dom.convert(c))
  392. def exquo_ground(f, c):
  393. """Exact quotient of ``f`` by a an element of the ground domain. """
  394. return f._exquo_ground(f.dom.convert(c))
  395. def add(f, g):
  396. """Add two multivariate polynomials ``f`` and ``g``. """
  397. F, G = f.unify_DMP(g)
  398. return F._add(G)
  399. def sub(f, g):
  400. """Subtract two multivariate polynomials ``f`` and ``g``. """
  401. F, G = f.unify_DMP(g)
  402. return F._sub(G)
  403. def mul(f, g):
  404. """Multiply two multivariate polynomials ``f`` and ``g``. """
  405. F, G = f.unify_DMP(g)
  406. return F._mul(G)
  407. def sqr(f):
  408. """Square a multivariate polynomial ``f``. """
  409. return f._sqr()
  410. def pow(f, n):
  411. """Raise ``f`` to a non-negative power ``n``. """
  412. if not isinstance(n, int):
  413. raise TypeError("``int`` expected, got %s" % type(n))
  414. return f._pow(n)
  415. def pdiv(f, g):
  416. """Polynomial pseudo-division of ``f`` and ``g``. """
  417. F, G = f.unify_DMP(g)
  418. return F._pdiv(G)
  419. def prem(f, g):
  420. """Polynomial pseudo-remainder of ``f`` and ``g``. """
  421. F, G = f.unify_DMP(g)
  422. return F._prem(G)
  423. def pquo(f, g):
  424. """Polynomial pseudo-quotient of ``f`` and ``g``. """
  425. F, G = f.unify_DMP(g)
  426. return F._pquo(G)
  427. def pexquo(f, g):
  428. """Polynomial exact pseudo-quotient of ``f`` and ``g``. """
  429. F, G = f.unify_DMP(g)
  430. return F._pexquo(G)
  431. def div(f, g):
  432. """Polynomial division with remainder of ``f`` and ``g``. """
  433. F, G = f.unify_DMP(g)
  434. return F._div(G)
  435. def rem(f, g):
  436. """Computes polynomial remainder of ``f`` and ``g``. """
  437. F, G = f.unify_DMP(g)
  438. return F._rem(G)
  439. def quo(f, g):
  440. """Computes polynomial quotient of ``f`` and ``g``. """
  441. F, G = f.unify_DMP(g)
  442. return F._quo(G)
  443. def exquo(f, g):
  444. """Computes polynomial exact quotient of ``f`` and ``g``. """
  445. F, G = f.unify_DMP(g)
  446. return F._exquo(G)
  447. def _add_ground(f, c):
  448. raise NotImplementedError
  449. def _sub_ground(f, c):
  450. raise NotImplementedError
  451. def _mul_ground(f, c):
  452. raise NotImplementedError
  453. def _quo_ground(f, c):
  454. raise NotImplementedError
  455. def _exquo_ground(f, c):
  456. raise NotImplementedError
  457. def _add(f, g):
  458. raise NotImplementedError
  459. def _sub(f, g):
  460. raise NotImplementedError
  461. def _mul(f, g):
  462. raise NotImplementedError
  463. def _sqr(f):
  464. raise NotImplementedError
  465. def _pow(f, n):
  466. raise NotImplementedError
  467. def _pdiv(f, g):
  468. raise NotImplementedError
  469. def _prem(f, g):
  470. raise NotImplementedError
  471. def _pquo(f, g):
  472. raise NotImplementedError
  473. def _pexquo(f, g):
  474. raise NotImplementedError
  475. def _div(f, g):
  476. raise NotImplementedError
  477. def _rem(f, g):
  478. raise NotImplementedError
  479. def _quo(f, g):
  480. raise NotImplementedError
  481. def _exquo(f, g):
  482. raise NotImplementedError
  483. def degree(f, j=0):
  484. """Returns the leading degree of ``f`` in ``x_j``. """
  485. if not isinstance(j, int):
  486. raise TypeError("``int`` expected, got %s" % type(j))
  487. return f._degree(j)
  488. def _degree(f, j):
  489. raise NotImplementedError
  490. def degree_list(f):
  491. """Returns a list of degrees of ``f``. """
  492. raise NotImplementedError
  493. def total_degree(f):
  494. """Returns the total degree of ``f``. """
  495. raise NotImplementedError
  496. def homogenize(f, s):
  497. """Return homogeneous polynomial of ``f``"""
  498. td = f.total_degree()
  499. result = {}
  500. new_symbol = (s == len(f.terms()[0][0]))
  501. for term in f.terms():
  502. d = sum(term[0])
  503. if d < td:
  504. i = td - d
  505. else:
  506. i = 0
  507. if new_symbol:
  508. result[term[0] + (i,)] = term[1]
  509. else:
  510. l = list(term[0])
  511. l[s] += i
  512. result[tuple(l)] = term[1]
  513. return DMP.from_dict(result, f.lev + int(new_symbol), f.dom)
  514. def homogeneous_order(f):
  515. """Returns the homogeneous order of ``f``. """
  516. if f.is_zero:
  517. return -oo
  518. monoms = f.monoms()
  519. tdeg = sum(monoms[0])
  520. for monom in monoms:
  521. _tdeg = sum(monom)
  522. if _tdeg != tdeg:
  523. return None
  524. return tdeg
  525. def LC(f):
  526. """Returns the leading coefficient of ``f``. """
  527. raise NotImplementedError
  528. def TC(f):
  529. """Returns the trailing coefficient of ``f``. """
  530. raise NotImplementedError
  531. def nth(f, *N):
  532. """Returns the ``n``-th coefficient of ``f``. """
  533. if all(isinstance(n, int) for n in N):
  534. return f._nth(N)
  535. else:
  536. raise TypeError("a sequence of integers expected")
  537. def _nth(f, N):
  538. raise NotImplementedError
  539. def max_norm(f):
  540. """Returns maximum norm of ``f``. """
  541. raise NotImplementedError
  542. def l1_norm(f):
  543. """Returns l1 norm of ``f``. """
  544. raise NotImplementedError
  545. def l2_norm_squared(f):
  546. """Return squared l2 norm of ``f``. """
  547. raise NotImplementedError
  548. def clear_denoms(f):
  549. """Clear denominators, but keep the ground domain. """
  550. raise NotImplementedError
  551. def integrate(f, m=1, j=0):
  552. """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """
  553. if not isinstance(m, int):
  554. raise TypeError("``int`` expected, got %s" % type(m))
  555. if not isinstance(j, int):
  556. raise TypeError("``int`` expected, got %s" % type(j))
  557. return f._integrate(m, j)
  558. def _integrate(f, m, j):
  559. raise NotImplementedError
  560. def diff(f, m=1, j=0):
  561. """Computes the ``m``-th order derivative of ``f`` in ``x_j``. """
  562. if not isinstance(m, int):
  563. raise TypeError("``int`` expected, got %s" % type(m))
  564. if not isinstance(j, int):
  565. raise TypeError("``int`` expected, got %s" % type(j))
  566. return f._diff(m, j)
  567. def _diff(f, m, j):
  568. raise NotImplementedError
  569. def eval(f, a, j=0):
  570. """Evaluates ``f`` at the given point ``a`` in ``x_j``. """
  571. if not isinstance(j, int):
  572. raise TypeError("``int`` expected, got %s" % type(j))
  573. elif not (0 <= j <= f.lev):
  574. raise ValueError("invalid variable index %s" % j)
  575. if f.lev:
  576. return f._eval_lev(a, j)
  577. else:
  578. return f._eval(a)
  579. def _eval(f, a):
  580. raise NotImplementedError
  581. def _eval_lev(f, a, j):
  582. raise NotImplementedError
  583. def half_gcdex(f, g):
  584. """Half extended Euclidean algorithm, if univariate. """
  585. F, G = f.unify_DMP(g)
  586. if F.lev:
  587. raise ValueError('univariate polynomial expected')
  588. return F._half_gcdex(G)
  589. def _half_gcdex(f, g):
  590. raise NotImplementedError
  591. def gcdex(f, g):
  592. """Extended Euclidean algorithm, if univariate. """
  593. F, G = f.unify_DMP(g)
  594. if F.lev:
  595. raise ValueError('univariate polynomial expected')
  596. if not F.dom.is_Field:
  597. raise DomainError('ground domain must be a field')
  598. return F._gcdex(G)
  599. def _gcdex(f, g):
  600. raise NotImplementedError
  601. def invert(f, g):
  602. """Invert ``f`` modulo ``g``, if possible. """
  603. F, G = f.unify_DMP(g)
  604. if F.lev:
  605. raise ValueError('univariate polynomial expected')
  606. return F._invert(G)
  607. def _invert(f, g):
  608. raise NotImplementedError
  609. def revert(f, n):
  610. """Compute ``f**(-1)`` mod ``x**n``. """
  611. if f.lev:
  612. raise ValueError('univariate polynomial expected')
  613. return f._revert(n)
  614. def _revert(f, n):
  615. raise NotImplementedError
  616. def subresultants(f, g):
  617. """Computes subresultant PRS sequence of ``f`` and ``g``. """
  618. F, G = f.unify_DMP(g)
  619. return F._subresultants(G)
  620. def _subresultants(f, g):
  621. raise NotImplementedError
  622. def resultant(f, g, includePRS=False):
  623. """Computes resultant of ``f`` and ``g`` via PRS. """
  624. F, G = f.unify_DMP(g)
  625. if includePRS:
  626. return F._resultant_includePRS(G)
  627. else:
  628. return F._resultant(G)
  629. def _resultant(f, g, includePRS=False):
  630. raise NotImplementedError
  631. def discriminant(f):
  632. """Computes discriminant of ``f``. """
  633. raise NotImplementedError
  634. def cofactors(f, g):
  635. """Returns GCD of ``f`` and ``g`` and their cofactors. """
  636. F, G = f.unify_DMP(g)
  637. return F._cofactors(G)
  638. def _cofactors(f, g):
  639. raise NotImplementedError
  640. def gcd(f, g):
  641. """Returns polynomial GCD of ``f`` and ``g``. """
  642. F, G = f.unify_DMP(g)
  643. return F._gcd(G)
  644. def _gcd(f, g):
  645. raise NotImplementedError
  646. def lcm(f, g):
  647. """Returns polynomial LCM of ``f`` and ``g``. """
  648. F, G = f.unify_DMP(g)
  649. return F._lcm(G)
  650. def _lcm(f, g):
  651. raise NotImplementedError
  652. def cancel(f, g, include=True):
  653. """Cancel common factors in a rational function ``f/g``. """
  654. F, G = f.unify_DMP(g)
  655. if include:
  656. return F._cancel_include(G)
  657. else:
  658. return F._cancel(G)
  659. def _cancel(f, g):
  660. raise NotImplementedError
  661. def _cancel_include(f, g):
  662. raise NotImplementedError
  663. def trunc(f, p):
  664. """Reduce ``f`` modulo a constant ``p``. """
  665. return f._trunc(f.dom.convert(p))
  666. def _trunc(f, p):
  667. raise NotImplementedError
  668. def monic(f):
  669. """Divides all coefficients by ``LC(f)``. """
  670. raise NotImplementedError
  671. def content(f):
  672. """Returns GCD of polynomial coefficients. """
  673. raise NotImplementedError
  674. def primitive(f):
  675. """Returns content and a primitive form of ``f``. """
  676. raise NotImplementedError
  677. def compose(f, g):
  678. """Computes functional composition of ``f`` and ``g``. """
  679. F, G = f.unify_DMP(g)
  680. return F._compose(G)
  681. def _compose(f, g):
  682. raise NotImplementedError
  683. def decompose(f):
  684. """Computes functional decomposition of ``f``. """
  685. if f.lev:
  686. raise ValueError('univariate polynomial expected')
  687. return f._decompose()
  688. def _decompose(f):
  689. raise NotImplementedError
  690. def shift(f, a):
  691. """Efficiently compute Taylor shift ``f(x + a)``. """
  692. if f.lev:
  693. raise ValueError('univariate polynomial expected')
  694. return f._shift(f.dom.convert(a))
  695. def shift_list(f, a):
  696. """Efficiently compute Taylor shift ``f(X + A)``. """
  697. a = [f.dom.convert(ai) for ai in a]
  698. return f._shift_list(a)
  699. def _shift(f, a):
  700. raise NotImplementedError
  701. def transform(f, p, q):
  702. """Evaluate functional transformation ``q**n * f(p/q)``."""
  703. if f.lev:
  704. raise ValueError('univariate polynomial expected')
  705. P, Q = p.unify_DMP(q)
  706. F, P = f.unify_DMP(P)
  707. F, Q = F.unify_DMP(Q)
  708. return F._transform(P, Q)
  709. def _transform(f, p, q):
  710. raise NotImplementedError
  711. def sturm(f):
  712. """Computes the Sturm sequence of ``f``. """
  713. if f.lev:
  714. raise ValueError('univariate polynomial expected')
  715. return f._sturm()
  716. def _sturm(f):
  717. raise NotImplementedError
  718. def cauchy_upper_bound(f):
  719. """Computes the Cauchy upper bound on the roots of ``f``. """
  720. if f.lev:
  721. raise ValueError('univariate polynomial expected')
  722. return f._cauchy_upper_bound()
  723. def _cauchy_upper_bound(f):
  724. raise NotImplementedError
  725. def cauchy_lower_bound(f):
  726. """Computes the Cauchy lower bound on the nonzero roots of ``f``. """
  727. if f.lev:
  728. raise ValueError('univariate polynomial expected')
  729. return f._cauchy_lower_bound()
  730. def _cauchy_lower_bound(f):
  731. raise NotImplementedError
  732. def mignotte_sep_bound_squared(f):
  733. """Computes the squared Mignotte bound on root separations of ``f``. """
  734. if f.lev:
  735. raise ValueError('univariate polynomial expected')
  736. return f._mignotte_sep_bound_squared()
  737. def _mignotte_sep_bound_squared(f):
  738. raise NotImplementedError
  739. def gff_list(f):
  740. """Computes greatest factorial factorization of ``f``. """
  741. if f.lev:
  742. raise ValueError('univariate polynomial expected')
  743. return f._gff_list()
  744. def _gff_list(f):
  745. raise NotImplementedError
  746. def norm(f):
  747. """Computes ``Norm(f)``."""
  748. raise NotImplementedError
  749. def sqf_norm(f):
  750. """Computes square-free norm of ``f``. """
  751. raise NotImplementedError
  752. def sqf_part(f):
  753. """Computes square-free part of ``f``. """
  754. raise NotImplementedError
  755. def sqf_list(f, all=False):
  756. """Returns a list of square-free factors of ``f``. """
  757. raise NotImplementedError
  758. def sqf_list_include(f, all=False):
  759. """Returns a list of square-free factors of ``f``. """
  760. raise NotImplementedError
  761. def factor_list(f):
  762. """Returns a list of irreducible factors of ``f``. """
  763. raise NotImplementedError
  764. def factor_list_include(f):
  765. """Returns a list of irreducible factors of ``f``. """
  766. raise NotImplementedError
  767. def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False):
  768. """Compute isolating intervals for roots of ``f``. """
  769. if f.lev:
  770. raise PolynomialError("Cannot isolate roots of a multivariate polynomial")
  771. if all and sqf:
  772. return f._isolate_all_roots_sqf(eps=eps, inf=inf, sup=sup, fast=fast)
  773. elif all and not sqf:
  774. return f._isolate_all_roots(eps=eps, inf=inf, sup=sup, fast=fast)
  775. elif not all and sqf:
  776. return f._isolate_real_roots_sqf(eps=eps, inf=inf, sup=sup, fast=fast)
  777. else:
  778. return f._isolate_real_roots(eps=eps, inf=inf, sup=sup, fast=fast)
  779. def _isolate_all_roots(f, eps, inf, sup, fast):
  780. raise NotImplementedError
  781. def _isolate_all_roots_sqf(f, eps, inf, sup, fast):
  782. raise NotImplementedError
  783. def _isolate_real_roots(f, eps, inf, sup, fast):
  784. raise NotImplementedError
  785. def _isolate_real_roots_sqf(f, eps, inf, sup, fast):
  786. raise NotImplementedError
  787. def refine_root(f, s, t, eps=None, steps=None, fast=False):
  788. """
  789. Refine an isolating interval to the given precision.
  790. ``eps`` should be a rational number.
  791. """
  792. if f.lev:
  793. raise PolynomialError(
  794. "Cannot refine a root of a multivariate polynomial")
  795. return f._refine_real_root(s, t, eps=eps, steps=steps, fast=fast)
  796. def _refine_real_root(f, s, t, eps, steps, fast):
  797. raise NotImplementedError
  798. def count_real_roots(f, inf=None, sup=None):
  799. """Return the number of real roots of ``f`` in ``[inf, sup]``. """
  800. raise NotImplementedError
  801. def count_complex_roots(f, inf=None, sup=None):
  802. """Return the number of complex roots of ``f`` in ``[inf, sup]``. """
  803. raise NotImplementedError
  804. @property
  805. def is_zero(f):
  806. """Returns ``True`` if ``f`` is a zero polynomial. """
  807. raise NotImplementedError
  808. @property
  809. def is_one(f):
  810. """Returns ``True`` if ``f`` is a unit polynomial. """
  811. raise NotImplementedError
  812. @property
  813. def is_ground(f):
  814. """Returns ``True`` if ``f`` is an element of the ground domain. """
  815. raise NotImplementedError
  816. @property
  817. def is_sqf(f):
  818. """Returns ``True`` if ``f`` is a square-free polynomial. """
  819. raise NotImplementedError
  820. @property
  821. def is_monic(f):
  822. """Returns ``True`` if the leading coefficient of ``f`` is one. """
  823. raise NotImplementedError
  824. @property
  825. def is_primitive(f):
  826. """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """
  827. raise NotImplementedError
  828. @property
  829. def is_linear(f):
  830. """Returns ``True`` if ``f`` is linear in all its variables. """
  831. raise NotImplementedError
  832. @property
  833. def is_quadratic(f):
  834. """Returns ``True`` if ``f`` is quadratic in all its variables. """
  835. raise NotImplementedError
  836. @property
  837. def is_monomial(f):
  838. """Returns ``True`` if ``f`` is zero or has only one term. """
  839. raise NotImplementedError
  840. @property
  841. def is_homogeneous(f):
  842. """Returns ``True`` if ``f`` is a homogeneous polynomial. """
  843. raise NotImplementedError
  844. @property
  845. def is_irreducible(f):
  846. """Returns ``True`` if ``f`` has no factors over its domain. """
  847. raise NotImplementedError
  848. @property
  849. def is_cyclotomic(f):
  850. """Returns ``True`` if ``f`` is a cyclotomic polynomial. """
  851. raise NotImplementedError
  852. def __abs__(f):
  853. return f.abs()
  854. def __neg__(f):
  855. return f.neg()
  856. def __add__(f, g):
  857. if isinstance(g, DMP):
  858. return f.add(g)
  859. else:
  860. try:
  861. return f.add_ground(g)
  862. except CoercionFailed:
  863. return NotImplemented
  864. def __radd__(f, g):
  865. return f.__add__(g)
  866. def __sub__(f, g):
  867. if isinstance(g, DMP):
  868. return f.sub(g)
  869. else:
  870. try:
  871. return f.sub_ground(g)
  872. except CoercionFailed:
  873. return NotImplemented
  874. def __rsub__(f, g):
  875. return (-f).__add__(g)
  876. def __mul__(f, g):
  877. if isinstance(g, DMP):
  878. return f.mul(g)
  879. else:
  880. try:
  881. return f.mul_ground(g)
  882. except CoercionFailed:
  883. return NotImplemented
  884. def __rmul__(f, g):
  885. return f.__mul__(g)
  886. def __truediv__(f, g):
  887. if isinstance(g, DMP):
  888. return f.exquo(g)
  889. else:
  890. try:
  891. return f.mul_ground(g)
  892. except CoercionFailed:
  893. return NotImplemented
  894. def __rtruediv__(f, g):
  895. if isinstance(g, DMP):
  896. return g.exquo(f)
  897. else:
  898. try:
  899. return f._one().mul_ground(g).exquo(f)
  900. except CoercionFailed:
  901. return NotImplemented
  902. def __pow__(f, n):
  903. return f.pow(n)
  904. def __divmod__(f, g):
  905. return f.div(g)
  906. def __mod__(f, g):
  907. return f.rem(g)
  908. def __floordiv__(f, g):
  909. if isinstance(g, DMP):
  910. return f.quo(g)
  911. else:
  912. try:
  913. return f.quo_ground(g)
  914. except TypeError:
  915. return NotImplemented
  916. def __eq__(f, g):
  917. if f is g:
  918. return True
  919. if not isinstance(g, DMP):
  920. return NotImplemented
  921. try:
  922. F, G = f.unify_DMP(g)
  923. except UnificationFailed:
  924. return False
  925. else:
  926. return F._strict_eq(G)
  927. def _strict_eq(f, g):
  928. raise NotImplementedError
  929. def eq(f, g, strict=False):
  930. if not strict:
  931. return f == g
  932. else:
  933. return f._strict_eq(g)
  934. def ne(f, g, strict=False):
  935. return not f.eq(g, strict=strict)
  936. def __lt__(f, g):
  937. F, G = f.unify_DMP(g)
  938. return F.to_list() < G.to_list()
  939. def __le__(f, g):
  940. F, G = f.unify_DMP(g)
  941. return F.to_list() <= G.to_list()
  942. def __gt__(f, g):
  943. F, G = f.unify_DMP(g)
  944. return F.to_list() > G.to_list()
  945. def __ge__(f, g):
  946. F, G = f.unify_DMP(g)
  947. return F.to_list() >= G.to_list()
  948. def __bool__(f):
  949. return not f.is_zero
  950. class DMP_Python(DMP):
  951. """Dense Multivariate Polynomials over `K`. """
  952. __slots__ = ('_rep', 'dom', 'lev')
  953. @classmethod
  954. def _new(cls, rep, dom, lev):
  955. obj = object.__new__(cls)
  956. obj._rep = rep
  957. obj.lev = lev
  958. obj.dom = dom
  959. return obj
  960. def _strict_eq(f, g):
  961. if type(f) != type(g):
  962. return False
  963. return f.lev == g.lev and f.dom == g.dom and f._rep == g._rep
  964. def per(f, rep):
  965. """Create a DMP out of the given representation. """
  966. return f._new(rep, f.dom, f.lev)
  967. def ground_new(f, coeff):
  968. """Construct a new ground instance of ``f``. """
  969. return f._new(dmp_ground(coeff, f.lev), f.dom, f.lev)
  970. def _one(f):
  971. return f.one(f.lev, f.dom)
  972. def unify(f, g):
  973. """Unify representations of two multivariate polynomials. """
  974. # XXX: This function is not really used any more since there is
  975. # unify_DMP now.
  976. if not isinstance(g, DMP) or f.lev != g.lev:
  977. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  978. if f.dom == g.dom:
  979. return f.lev, f.dom, f.per, f._rep, g._rep
  980. else:
  981. lev, dom = f.lev, f.dom.unify(g.dom)
  982. F = dmp_convert(f._rep, lev, f.dom, dom)
  983. G = dmp_convert(g._rep, lev, g.dom, dom)
  984. def per(rep):
  985. return f._new(rep, dom, lev)
  986. return lev, dom, per, F, G
  987. def to_DUP_Flint(f):
  988. """Convert ``f`` to a Flint representation. """
  989. return DUP_Flint._new(f._rep, f.dom, f.lev)
  990. def to_list(f):
  991. """Convert ``f`` to a list representation with native coefficients. """
  992. return list(f._rep)
  993. def to_tuple(f):
  994. """Convert ``f`` to a tuple representation with native coefficients. """
  995. return dmp_to_tuple(f._rep, f.lev)
  996. def _convert(f, dom):
  997. """Convert the ground domain of ``f``. """
  998. return f._new(dmp_convert(f._rep, f.lev, f.dom, dom), dom, f.lev)
  999. def _slice(f, m, n):
  1000. """Take a continuous subsequence of terms of ``f``. """
  1001. rep = dup_slice(f._rep, m, n, f.dom)
  1002. return f._new(rep, f.dom, f.lev)
  1003. def _slice_lev(f, m, n, j):
  1004. """Take a continuous subsequence of terms of ``f``. """
  1005. rep = dmp_slice_in(f._rep, m, n, j, f.lev, f.dom)
  1006. return f._new(rep, f.dom, f.lev)
  1007. def _terms(f, order=None):
  1008. """Returns all non-zero terms from ``f`` in lex order. """
  1009. return dmp_list_terms(f._rep, f.lev, f.dom, order=order)
  1010. def _lift(f):
  1011. """Convert algebraic coefficients to rationals. """
  1012. r = dmp_lift(f._rep, f.lev, f.dom)
  1013. return f._new(r, f.dom.dom, f.lev)
  1014. def deflate(f):
  1015. """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """
  1016. J, F = dmp_deflate(f._rep, f.lev, f.dom)
  1017. return J, f.per(F)
  1018. def inject(f, front=False):
  1019. """Inject ground domain generators into ``f``. """
  1020. F, lev = dmp_inject(f._rep, f.lev, f.dom, front=front)
  1021. # XXX: domain and level changed here
  1022. return f._new(F, f.dom.dom, lev)
  1023. def eject(f, dom, front=False):
  1024. """Eject selected generators into the ground domain. """
  1025. F = dmp_eject(f._rep, f.lev, dom, front=front)
  1026. # XXX: domain and level changed here
  1027. return f._new(F, dom, f.lev - len(dom.symbols))
  1028. def _exclude(f):
  1029. """Remove useless generators from ``f``. """
  1030. J, F, u = dmp_exclude(f._rep, f.lev, f.dom)
  1031. # XXX: level changed here
  1032. return J, f._new(F, f.dom, u)
  1033. def _permute(f, P):
  1034. """Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`. """
  1035. return f.per(dmp_permute(f._rep, P, f.lev, f.dom))
  1036. def terms_gcd(f):
  1037. """Remove GCD of terms from the polynomial ``f``. """
  1038. J, F = dmp_terms_gcd(f._rep, f.lev, f.dom)
  1039. return J, f.per(F)
  1040. def _add_ground(f, c):
  1041. """Add an element of the ground domain to ``f``. """
  1042. return f.per(dmp_add_ground(f._rep, c, f.lev, f.dom))
  1043. def _sub_ground(f, c):
  1044. """Subtract an element of the ground domain from ``f``. """
  1045. return f.per(dmp_sub_ground(f._rep, c, f.lev, f.dom))
  1046. def _mul_ground(f, c):
  1047. """Multiply ``f`` by a an element of the ground domain. """
  1048. return f.per(dmp_mul_ground(f._rep, c, f.lev, f.dom))
  1049. def _quo_ground(f, c):
  1050. """Quotient of ``f`` by a an element of the ground domain. """
  1051. return f.per(dmp_quo_ground(f._rep, c, f.lev, f.dom))
  1052. def _exquo_ground(f, c):
  1053. """Exact quotient of ``f`` by a an element of the ground domain. """
  1054. return f.per(dmp_exquo_ground(f._rep, c, f.lev, f.dom))
  1055. def abs(f):
  1056. """Make all coefficients in ``f`` positive. """
  1057. return f.per(dmp_abs(f._rep, f.lev, f.dom))
  1058. def neg(f):
  1059. """Negate all coefficients in ``f``. """
  1060. return f.per(dmp_neg(f._rep, f.lev, f.dom))
  1061. def _add(f, g):
  1062. """Add two multivariate polynomials ``f`` and ``g``. """
  1063. return f.per(dmp_add(f._rep, g._rep, f.lev, f.dom))
  1064. def _sub(f, g):
  1065. """Subtract two multivariate polynomials ``f`` and ``g``. """
  1066. return f.per(dmp_sub(f._rep, g._rep, f.lev, f.dom))
  1067. def _mul(f, g):
  1068. """Multiply two multivariate polynomials ``f`` and ``g``. """
  1069. return f.per(dmp_mul(f._rep, g._rep, f.lev, f.dom))
  1070. def sqr(f):
  1071. """Square a multivariate polynomial ``f``. """
  1072. return f.per(dmp_sqr(f._rep, f.lev, f.dom))
  1073. def _pow(f, n):
  1074. """Raise ``f`` to a non-negative power ``n``. """
  1075. return f.per(dmp_pow(f._rep, n, f.lev, f.dom))
  1076. def _pdiv(f, g):
  1077. """Polynomial pseudo-division of ``f`` and ``g``. """
  1078. q, r = dmp_pdiv(f._rep, g._rep, f.lev, f.dom)
  1079. return f.per(q), f.per(r)
  1080. def _prem(f, g):
  1081. """Polynomial pseudo-remainder of ``f`` and ``g``. """
  1082. return f.per(dmp_prem(f._rep, g._rep, f.lev, f.dom))
  1083. def _pquo(f, g):
  1084. """Polynomial pseudo-quotient of ``f`` and ``g``. """
  1085. return f.per(dmp_pquo(f._rep, g._rep, f.lev, f.dom))
  1086. def _pexquo(f, g):
  1087. """Polynomial exact pseudo-quotient of ``f`` and ``g``. """
  1088. return f.per(dmp_pexquo(f._rep, g._rep, f.lev, f.dom))
  1089. def _div(f, g):
  1090. """Polynomial division with remainder of ``f`` and ``g``. """
  1091. q, r = dmp_div(f._rep, g._rep, f.lev, f.dom)
  1092. return f.per(q), f.per(r)
  1093. def _rem(f, g):
  1094. """Computes polynomial remainder of ``f`` and ``g``. """
  1095. return f.per(dmp_rem(f._rep, g._rep, f.lev, f.dom))
  1096. def _quo(f, g):
  1097. """Computes polynomial quotient of ``f`` and ``g``. """
  1098. return f.per(dmp_quo(f._rep, g._rep, f.lev, f.dom))
  1099. def _exquo(f, g):
  1100. """Computes polynomial exact quotient of ``f`` and ``g``. """
  1101. return f.per(dmp_exquo(f._rep, g._rep, f.lev, f.dom))
  1102. def _degree(f, j=0):
  1103. """Returns the leading degree of ``f`` in ``x_j``. """
  1104. return dmp_degree_in(f._rep, j, f.lev)
  1105. def degree_list(f):
  1106. """Returns a list of degrees of ``f``. """
  1107. return dmp_degree_list(f._rep, f.lev)
  1108. def total_degree(f):
  1109. """Returns the total degree of ``f``. """
  1110. return max(sum(m) for m in f.monoms())
  1111. def LC(f):
  1112. """Returns the leading coefficient of ``f``. """
  1113. return dmp_ground_LC(f._rep, f.lev, f.dom)
  1114. def TC(f):
  1115. """Returns the trailing coefficient of ``f``. """
  1116. return dmp_ground_TC(f._rep, f.lev, f.dom)
  1117. def _nth(f, N):
  1118. """Returns the ``n``-th coefficient of ``f``. """
  1119. return dmp_ground_nth(f._rep, N, f.lev, f.dom)
  1120. def max_norm(f):
  1121. """Returns maximum norm of ``f``. """
  1122. return dmp_max_norm(f._rep, f.lev, f.dom)
  1123. def l1_norm(f):
  1124. """Returns l1 norm of ``f``. """
  1125. return dmp_l1_norm(f._rep, f.lev, f.dom)
  1126. def l2_norm_squared(f):
  1127. """Return squared l2 norm of ``f``. """
  1128. return dmp_l2_norm_squared(f._rep, f.lev, f.dom)
  1129. def clear_denoms(f):
  1130. """Clear denominators, but keep the ground domain. """
  1131. coeff, F = dmp_clear_denoms(f._rep, f.lev, f.dom)
  1132. return coeff, f.per(F)
  1133. def _integrate(f, m=1, j=0):
  1134. """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """
  1135. return f.per(dmp_integrate_in(f._rep, m, j, f.lev, f.dom))
  1136. def _diff(f, m=1, j=0):
  1137. """Computes the ``m``-th order derivative of ``f`` in ``x_j``. """
  1138. return f.per(dmp_diff_in(f._rep, m, j, f.lev, f.dom))
  1139. def _eval(f, a):
  1140. return dmp_eval_in(f._rep, f.dom.convert(a), 0, f.lev, f.dom)
  1141. def _eval_lev(f, a, j):
  1142. rep = dmp_eval_in(f._rep, f.dom.convert(a), j, f.lev, f.dom)
  1143. return f.new(rep, f.dom, f.lev - 1)
  1144. def _half_gcdex(f, g):
  1145. """Half extended Euclidean algorithm, if univariate. """
  1146. s, h = dup_half_gcdex(f._rep, g._rep, f.dom)
  1147. return f.per(s), f.per(h)
  1148. def _gcdex(f, g):
  1149. """Extended Euclidean algorithm, if univariate. """
  1150. s, t, h = dup_gcdex(f._rep, g._rep, f.dom)
  1151. return f.per(s), f.per(t), f.per(h)
  1152. def _invert(f, g):
  1153. """Invert ``f`` modulo ``g``, if possible. """
  1154. s = dup_invert(f._rep, g._rep, f.dom)
  1155. return f.per(s)
  1156. def _revert(f, n):
  1157. """Compute ``f**(-1)`` mod ``x**n``. """
  1158. return f.per(dup_revert(f._rep, n, f.dom))
  1159. def _subresultants(f, g):
  1160. """Computes subresultant PRS sequence of ``f`` and ``g``. """
  1161. R = dmp_subresultants(f._rep, g._rep, f.lev, f.dom)
  1162. return list(map(f.per, R))
  1163. def _resultant_includePRS(f, g):
  1164. """Computes resultant of ``f`` and ``g`` via PRS. """
  1165. res, R = dmp_resultant(f._rep, g._rep, f.lev, f.dom, includePRS=True)
  1166. if f.lev:
  1167. res = f.new(res, f.dom, f.lev - 1)
  1168. return res, list(map(f.per, R))
  1169. def _resultant(f, g):
  1170. res = dmp_resultant(f._rep, g._rep, f.lev, f.dom)
  1171. if f.lev:
  1172. res = f.new(res, f.dom, f.lev - 1)
  1173. return res
  1174. def discriminant(f):
  1175. """Computes discriminant of ``f``. """
  1176. res = dmp_discriminant(f._rep, f.lev, f.dom)
  1177. if f.lev:
  1178. res = f.new(res, f.dom, f.lev - 1)
  1179. return res
  1180. def _cofactors(f, g):
  1181. """Returns GCD of ``f`` and ``g`` and their cofactors. """
  1182. h, cff, cfg = dmp_inner_gcd(f._rep, g._rep, f.lev, f.dom)
  1183. return f.per(h), f.per(cff), f.per(cfg)
  1184. def _gcd(f, g):
  1185. """Returns polynomial GCD of ``f`` and ``g``. """
  1186. return f.per(dmp_gcd(f._rep, g._rep, f.lev, f.dom))
  1187. def _lcm(f, g):
  1188. """Returns polynomial LCM of ``f`` and ``g``. """
  1189. return f.per(dmp_lcm(f._rep, g._rep, f.lev, f.dom))
  1190. def _cancel(f, g):
  1191. """Cancel common factors in a rational function ``f/g``. """
  1192. cF, cG, F, G = dmp_cancel(f._rep, g._rep, f.lev, f.dom, include=False)
  1193. return cF, cG, f.per(F), f.per(G)
  1194. def _cancel_include(f, g):
  1195. """Cancel common factors in a rational function ``f/g``. """
  1196. F, G = dmp_cancel(f._rep, g._rep, f.lev, f.dom, include=True)
  1197. return f.per(F), f.per(G)
  1198. def _trunc(f, p):
  1199. """Reduce ``f`` modulo a constant ``p``. """
  1200. return f.per(dmp_ground_trunc(f._rep, p, f.lev, f.dom))
  1201. def monic(f):
  1202. """Divides all coefficients by ``LC(f)``. """
  1203. return f.per(dmp_ground_monic(f._rep, f.lev, f.dom))
  1204. def content(f):
  1205. """Returns GCD of polynomial coefficients. """
  1206. return dmp_ground_content(f._rep, f.lev, f.dom)
  1207. def primitive(f):
  1208. """Returns content and a primitive form of ``f``. """
  1209. cont, F = dmp_ground_primitive(f._rep, f.lev, f.dom)
  1210. return cont, f.per(F)
  1211. def _compose(f, g):
  1212. """Computes functional composition of ``f`` and ``g``. """
  1213. return f.per(dmp_compose(f._rep, g._rep, f.lev, f.dom))
  1214. def _decompose(f):
  1215. """Computes functional decomposition of ``f``. """
  1216. return list(map(f.per, dup_decompose(f._rep, f.dom)))
  1217. def _shift(f, a):
  1218. """Efficiently compute Taylor shift ``f(x + a)``. """
  1219. return f.per(dup_shift(f._rep, a, f.dom))
  1220. def _shift_list(f, a):
  1221. """Efficiently compute Taylor shift ``f(X + A)``. """
  1222. return f.per(dmp_shift(f._rep, a, f.lev, f.dom))
  1223. def _transform(f, p, q):
  1224. """Evaluate functional transformation ``q**n * f(p/q)``."""
  1225. return f.per(dup_transform(f._rep, p._rep, q._rep, f.dom))
  1226. def _sturm(f):
  1227. """Computes the Sturm sequence of ``f``. """
  1228. return list(map(f.per, dup_sturm(f._rep, f.dom)))
  1229. def _cauchy_upper_bound(f):
  1230. """Computes the Cauchy upper bound on the roots of ``f``. """
  1231. return dup_cauchy_upper_bound(f._rep, f.dom)
  1232. def _cauchy_lower_bound(f):
  1233. """Computes the Cauchy lower bound on the nonzero roots of ``f``. """
  1234. return dup_cauchy_lower_bound(f._rep, f.dom)
  1235. def _mignotte_sep_bound_squared(f):
  1236. """Computes the squared Mignotte bound on root separations of ``f``. """
  1237. return dup_mignotte_sep_bound_squared(f._rep, f.dom)
  1238. def _gff_list(f):
  1239. """Computes greatest factorial factorization of ``f``. """
  1240. return [ (f.per(g), k) for g, k in dup_gff_list(f._rep, f.dom) ]
  1241. def norm(f):
  1242. """Computes ``Norm(f)``."""
  1243. r = dmp_norm(f._rep, f.lev, f.dom)
  1244. return f.new(r, f.dom.dom, f.lev)
  1245. def sqf_norm(f):
  1246. """Computes square-free norm of ``f``. """
  1247. s, g, r = dmp_sqf_norm(f._rep, f.lev, f.dom)
  1248. return s, f.per(g), f.new(r, f.dom.dom, f.lev)
  1249. def sqf_part(f):
  1250. """Computes square-free part of ``f``. """
  1251. return f.per(dmp_sqf_part(f._rep, f.lev, f.dom))
  1252. def sqf_list(f, all=False):
  1253. """Returns a list of square-free factors of ``f``. """
  1254. coeff, factors = dmp_sqf_list(f._rep, f.lev, f.dom, all)
  1255. return coeff, [ (f.per(g), k) for g, k in factors ]
  1256. def sqf_list_include(f, all=False):
  1257. """Returns a list of square-free factors of ``f``. """
  1258. factors = dmp_sqf_list_include(f._rep, f.lev, f.dom, all)
  1259. return [ (f.per(g), k) for g, k in factors ]
  1260. def factor_list(f):
  1261. """Returns a list of irreducible factors of ``f``. """
  1262. coeff, factors = dmp_factor_list(f._rep, f.lev, f.dom)
  1263. return coeff, [ (f.per(g), k) for g, k in factors ]
  1264. def factor_list_include(f):
  1265. """Returns a list of irreducible factors of ``f``. """
  1266. factors = dmp_factor_list_include(f._rep, f.lev, f.dom)
  1267. return [ (f.per(g), k) for g, k in factors ]
  1268. def _isolate_real_roots(f, eps, inf, sup, fast):
  1269. return dup_isolate_real_roots(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  1270. def _isolate_real_roots_sqf(f, eps, inf, sup, fast):
  1271. return dup_isolate_real_roots_sqf(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  1272. def _isolate_all_roots(f, eps, inf, sup, fast):
  1273. return dup_isolate_all_roots(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  1274. def _isolate_all_roots_sqf(f, eps, inf, sup, fast):
  1275. return dup_isolate_all_roots_sqf(f._rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
  1276. def _refine_real_root(f, s, t, eps, steps, fast):
  1277. return dup_refine_real_root(f._rep, s, t, f.dom, eps=eps, steps=steps, fast=fast)
  1278. def count_real_roots(f, inf=None, sup=None):
  1279. """Return the number of real roots of ``f`` in ``[inf, sup]``. """
  1280. return dup_count_real_roots(f._rep, f.dom, inf=inf, sup=sup)
  1281. def count_complex_roots(f, inf=None, sup=None):
  1282. """Return the number of complex roots of ``f`` in ``[inf, sup]``. """
  1283. return dup_count_complex_roots(f._rep, f.dom, inf=inf, sup=sup)
  1284. @property
  1285. def is_zero(f):
  1286. """Returns ``True`` if ``f`` is a zero polynomial. """
  1287. return dmp_zero_p(f._rep, f.lev)
  1288. @property
  1289. def is_one(f):
  1290. """Returns ``True`` if ``f`` is a unit polynomial. """
  1291. return dmp_one_p(f._rep, f.lev, f.dom)
  1292. @property
  1293. def is_ground(f):
  1294. """Returns ``True`` if ``f`` is an element of the ground domain. """
  1295. return dmp_ground_p(f._rep, None, f.lev)
  1296. @property
  1297. def is_sqf(f):
  1298. """Returns ``True`` if ``f`` is a square-free polynomial. """
  1299. return dmp_sqf_p(f._rep, f.lev, f.dom)
  1300. @property
  1301. def is_monic(f):
  1302. """Returns ``True`` if the leading coefficient of ``f`` is one. """
  1303. return f.dom.is_one(dmp_ground_LC(f._rep, f.lev, f.dom))
  1304. @property
  1305. def is_primitive(f):
  1306. """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """
  1307. return f.dom.is_one(dmp_ground_content(f._rep, f.lev, f.dom))
  1308. @property
  1309. def is_linear(f):
  1310. """Returns ``True`` if ``f`` is linear in all its variables. """
  1311. return all(sum(monom) <= 1 for monom in dmp_to_dict(f._rep, f.lev, f.dom).keys())
  1312. @property
  1313. def is_quadratic(f):
  1314. """Returns ``True`` if ``f`` is quadratic in all its variables. """
  1315. return all(sum(monom) <= 2 for monom in dmp_to_dict(f._rep, f.lev, f.dom).keys())
  1316. @property
  1317. def is_monomial(f):
  1318. """Returns ``True`` if ``f`` is zero or has only one term. """
  1319. return len(f.to_dict()) <= 1
  1320. @property
  1321. def is_homogeneous(f):
  1322. """Returns ``True`` if ``f`` is a homogeneous polynomial. """
  1323. return f.homogeneous_order() is not None
  1324. @property
  1325. def is_irreducible(f):
  1326. """Returns ``True`` if ``f`` has no factors over its domain. """
  1327. return dmp_irreducible_p(f._rep, f.lev, f.dom)
  1328. @property
  1329. def is_cyclotomic(f):
  1330. """Returns ``True`` if ``f`` is a cyclotomic polynomial. """
  1331. if not f.lev:
  1332. return dup_cyclotomic_p(f._rep, f.dom)
  1333. else:
  1334. return False
  1335. class DUP_Flint(DMP):
  1336. """Dense Multivariate Polynomials over `K`. """
  1337. lev = 0
  1338. __slots__ = ('_rep', 'dom', '_cls')
  1339. def __reduce__(self):
  1340. return self.__class__, (self.to_list(), self.dom, self.lev)
  1341. @classmethod
  1342. def _new(cls, rep, dom, lev):
  1343. rep = cls._flint_poly(rep[::-1], dom, lev)
  1344. return cls.from_rep(rep, dom)
  1345. def to_list(f):
  1346. """Convert ``f`` to a list representation with native coefficients. """
  1347. return f._rep.coeffs()[::-1]
  1348. @classmethod
  1349. def _flint_poly(cls, rep, dom, lev):
  1350. assert _supported_flint_domain(dom)
  1351. assert lev == 0
  1352. flint_cls = cls._get_flint_poly_cls(dom)
  1353. return flint_cls(rep)
  1354. @classmethod
  1355. def _get_flint_poly_cls(cls, dom):
  1356. if dom.is_ZZ:
  1357. return flint.fmpz_poly
  1358. elif dom.is_QQ:
  1359. return flint.fmpq_poly
  1360. elif dom.is_FF:
  1361. return dom._poly_ctx
  1362. else:
  1363. raise RuntimeError("Domain %s is not supported with flint" % dom)
  1364. @classmethod
  1365. def from_rep(cls, rep, dom):
  1366. """Create a DMP from the given representation. """
  1367. if dom.is_ZZ:
  1368. assert isinstance(rep, flint.fmpz_poly)
  1369. _cls = flint.fmpz_poly
  1370. elif dom.is_QQ:
  1371. assert isinstance(rep, flint.fmpq_poly)
  1372. _cls = flint.fmpq_poly
  1373. elif dom.is_FF:
  1374. assert isinstance(rep, (flint.nmod_poly, flint.fmpz_mod_poly))
  1375. c = dom.characteristic()
  1376. __cls = type(rep)
  1377. _cls = lambda e: __cls(e, c)
  1378. else:
  1379. raise RuntimeError("Domain %s is not supported with flint" % dom)
  1380. obj = object.__new__(cls)
  1381. obj.dom = dom
  1382. obj._rep = rep
  1383. obj._cls = _cls
  1384. return obj
  1385. def _strict_eq(f, g):
  1386. if type(f) != type(g):
  1387. return False
  1388. return f.dom == g.dom and f._rep == g._rep
  1389. def ground_new(f, coeff):
  1390. """Construct a new ground instance of ``f``. """
  1391. return f.from_rep(f._cls([coeff]), f.dom)
  1392. def _one(f):
  1393. return f.ground_new(f.dom.one)
  1394. def unify(f, g):
  1395. """Unify representations of two polynomials. """
  1396. raise RuntimeError
  1397. def to_DMP_Python(f):
  1398. """Convert ``f`` to a Python native representation. """
  1399. return DMP_Python._new(f.to_list(), f.dom, f.lev)
  1400. def to_tuple(f):
  1401. """Convert ``f`` to a tuple representation with native coefficients. """
  1402. return tuple(f.to_list())
  1403. def _convert(f, dom):
  1404. """Convert the ground domain of ``f``. """
  1405. if dom == QQ and f.dom == ZZ:
  1406. return f.from_rep(flint.fmpq_poly(f._rep), dom)
  1407. elif _supported_flint_domain(dom) and _supported_flint_domain(f.dom):
  1408. # XXX: python-flint should provide a faster way to do this.
  1409. return f.to_DMP_Python()._convert(dom).to_DUP_Flint()
  1410. else:
  1411. raise RuntimeError(f"DUP_Flint: Cannot convert {f.dom} to {dom}")
  1412. def _slice(f, m, n):
  1413. """Take a continuous subsequence of terms of ``f``. """
  1414. coeffs = f._rep.coeffs()[m:n]
  1415. return f.from_rep(f._cls(coeffs), f.dom)
  1416. def _slice_lev(f, m, n, j):
  1417. """Take a continuous subsequence of terms of ``f``. """
  1418. # Only makes sense for multivariate polynomials
  1419. raise NotImplementedError
  1420. def _terms(f, order=None):
  1421. """Returns all non-zero terms from ``f`` in lex order. """
  1422. if order is None or order.alias == 'lex':
  1423. terms = [ ((n,), c) for n, c in enumerate(f._rep.coeffs()) if c ]
  1424. return terms[::-1]
  1425. else:
  1426. # XXX: InverseOrder (ilex) comes here. We could handle that case
  1427. # efficiently by reversing the coefficients but it is not clear
  1428. # how to test if the order is InverseOrder.
  1429. #
  1430. # Otherwise why would the order ever be different for univariate
  1431. # polynomials?
  1432. return f.to_DMP_Python()._terms(order=order)
  1433. def _lift(f):
  1434. """Convert algebraic coefficients to rationals. """
  1435. # This is for algebraic number fields which DUP_Flint does not support
  1436. raise NotImplementedError
  1437. def deflate(f):
  1438. """Reduce degree of `f` by mapping `x_i^m` to `y_i`. """
  1439. # XXX: Check because otherwise this segfaults with python-flint:
  1440. #
  1441. # >>> flint.fmpz_poly([]).deflation()
  1442. # Exception (fmpz_poly_deflate). Division by zero.
  1443. # Aborted (core dumped
  1444. #
  1445. if f.is_zero:
  1446. return (1,), f
  1447. g, n = f._rep.deflation()
  1448. return (n,), f.from_rep(g, f.dom)
  1449. def inject(f, front=False):
  1450. """Inject ground domain generators into ``f``. """
  1451. # Ground domain would need to be a poly ring
  1452. raise NotImplementedError
  1453. def eject(f, dom, front=False):
  1454. """Eject selected generators into the ground domain. """
  1455. # Only makes sense for multivariate polynomials
  1456. raise NotImplementedError
  1457. def _exclude(f):
  1458. """Remove useless generators from ``f``. """
  1459. # Only makes sense for multivariate polynomials
  1460. raise NotImplementedError
  1461. def _permute(f, P):
  1462. """Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`. """
  1463. # Only makes sense for multivariate polynomials
  1464. raise NotImplementedError
  1465. def terms_gcd(f):
  1466. """Remove GCD of terms from the polynomial ``f``. """
  1467. # XXX: python-flint should have primitive, content, etc methods.
  1468. J, F = f.to_DMP_Python().terms_gcd()
  1469. return J, F.to_DUP_Flint()
  1470. def _add_ground(f, c):
  1471. """Add an element of the ground domain to ``f``. """
  1472. return f.from_rep(f._rep + c, f.dom)
  1473. def _sub_ground(f, c):
  1474. """Subtract an element of the ground domain from ``f``. """
  1475. return f.from_rep(f._rep - c, f.dom)
  1476. def _mul_ground(f, c):
  1477. """Multiply ``f`` by a an element of the ground domain. """
  1478. return f.from_rep(f._rep * c, f.dom)
  1479. def _quo_ground(f, c):
  1480. """Quotient of ``f`` by a an element of the ground domain. """
  1481. return f.from_rep(f._rep // c, f.dom)
  1482. def _exquo_ground(f, c):
  1483. """Exact quotient of ``f`` by an element of the ground domain. """
  1484. q, r = divmod(f._rep, c)
  1485. if r:
  1486. raise ExactQuotientFailed(f, c)
  1487. return f.from_rep(q, f.dom)
  1488. def abs(f):
  1489. """Make all coefficients in ``f`` positive. """
  1490. return f.to_DMP_Python().abs().to_DUP_Flint()
  1491. def neg(f):
  1492. """Negate all coefficients in ``f``. """
  1493. return f.from_rep(-f._rep, f.dom)
  1494. def _add(f, g):
  1495. """Add two multivariate polynomials ``f`` and ``g``. """
  1496. return f.from_rep(f._rep + g._rep, f.dom)
  1497. def _sub(f, g):
  1498. """Subtract two multivariate polynomials ``f`` and ``g``. """
  1499. return f.from_rep(f._rep - g._rep, f.dom)
  1500. def _mul(f, g):
  1501. """Multiply two multivariate polynomials ``f`` and ``g``. """
  1502. return f.from_rep(f._rep * g._rep, f.dom)
  1503. def sqr(f):
  1504. """Square a multivariate polynomial ``f``. """
  1505. return f.from_rep(f._rep ** 2, f.dom)
  1506. def _pow(f, n):
  1507. """Raise ``f`` to a non-negative power ``n``. """
  1508. return f.from_rep(f._rep ** n, f.dom)
  1509. def _pdiv(f, g):
  1510. """Polynomial pseudo-division of ``f`` and ``g``. """
  1511. d = f.degree() - g.degree() + 1
  1512. q, r = divmod(g.LC()**d * f._rep, g._rep)
  1513. return f.from_rep(q, f.dom), f.from_rep(r, f.dom)
  1514. def _prem(f, g):
  1515. """Polynomial pseudo-remainder of ``f`` and ``g``. """
  1516. d = f.degree() - g.degree() + 1
  1517. q = (g.LC()**d * f._rep) % g._rep
  1518. return f.from_rep(q, f.dom)
  1519. def _pquo(f, g):
  1520. """Polynomial pseudo-quotient of ``f`` and ``g``. """
  1521. d = f.degree() - g.degree() + 1
  1522. r = (g.LC()**d * f._rep) // g._rep
  1523. return f.from_rep(r, f.dom)
  1524. def _pexquo(f, g):
  1525. """Polynomial exact pseudo-quotient of ``f`` and ``g``. """
  1526. d = f.degree() - g.degree() + 1
  1527. q, r = divmod(g.LC()**d * f._rep, g._rep)
  1528. if r:
  1529. raise ExactQuotientFailed(f, g)
  1530. return f.from_rep(q, f.dom)
  1531. def _div(f, g):
  1532. """Polynomial division with remainder of ``f`` and ``g``. """
  1533. if f.dom.is_Field:
  1534. q, r = divmod(f._rep, g._rep)
  1535. return f.from_rep(q, f.dom), f.from_rep(r, f.dom)
  1536. else:
  1537. # XXX: python-flint defines division in ZZ[x] differently
  1538. q, r = f.to_DMP_Python()._div(g.to_DMP_Python())
  1539. return q.to_DUP_Flint(), r.to_DUP_Flint()
  1540. def _rem(f, g):
  1541. """Computes polynomial remainder of ``f`` and ``g``. """
  1542. return f.from_rep(f._rep % g._rep, f.dom)
  1543. def _quo(f, g):
  1544. """Computes polynomial quotient of ``f`` and ``g``. """
  1545. return f.from_rep(f._rep // g._rep, f.dom)
  1546. def _exquo(f, g):
  1547. """Computes polynomial exact quotient of ``f`` and ``g``. """
  1548. q, r = f._div(g)
  1549. if r:
  1550. raise ExactQuotientFailed(f, g)
  1551. return q
  1552. def _degree(f, j=0):
  1553. """Returns the leading degree of ``f`` in ``x_j``. """
  1554. d = f._rep.degree()
  1555. if d == -1:
  1556. d = ninf
  1557. return d
  1558. def degree_list(f):
  1559. """Returns a list of degrees of ``f``. """
  1560. return ( f._degree() ,)
  1561. def total_degree(f):
  1562. """Returns the total degree of ``f``. """
  1563. return f._degree()
  1564. def LC(f):
  1565. """Returns the leading coefficient of ``f``. """
  1566. return f._rep[f._rep.degree()]
  1567. def TC(f):
  1568. """Returns the trailing coefficient of ``f``. """
  1569. return f._rep[0]
  1570. def _nth(f, N):
  1571. """Returns the ``n``-th coefficient of ``f``. """
  1572. [n] = N
  1573. return f._rep[n]
  1574. def max_norm(f):
  1575. """Returns maximum norm of ``f``. """
  1576. return f.to_DMP_Python().max_norm()
  1577. def l1_norm(f):
  1578. """Returns l1 norm of ``f``. """
  1579. return f.to_DMP_Python().l1_norm()
  1580. def l2_norm_squared(f):
  1581. """Return squared l2 norm of ``f``. """
  1582. return f.to_DMP_Python().l2_norm_squared()
  1583. def clear_denoms(f):
  1584. """Clear denominators, but keep the ground domain. """
  1585. R = f.dom
  1586. if R.is_QQ:
  1587. denom = f._rep.denom()
  1588. numer = f.from_rep(f._cls(f._rep.numer()), f.dom)
  1589. return denom, numer
  1590. elif R.is_ZZ or R.is_FiniteField:
  1591. return R.one, f
  1592. else:
  1593. raise NotImplementedError
  1594. def _integrate(f, m=1, j=0):
  1595. """Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """
  1596. assert j == 0
  1597. if f.dom.is_Field:
  1598. rep = f._rep
  1599. for i in range(m):
  1600. rep = rep.integral()
  1601. return f.from_rep(rep, f.dom)
  1602. else:
  1603. return f.to_DMP_Python()._integrate(m=m, j=j).to_DUP_Flint()
  1604. def _diff(f, m=1, j=0):
  1605. """Computes the ``m``-th order derivative of ``f``. """
  1606. assert j == 0
  1607. rep = f._rep
  1608. for i in range(m):
  1609. rep = rep.derivative()
  1610. return f.from_rep(rep, f.dom)
  1611. def _eval(f, a):
  1612. # XXX: This method is called with many different input types. Ideally
  1613. # we could use e.g. fmpz_poly.__call__ here but more thought needs to
  1614. # go into which types this is supposed to be called with and what types
  1615. # it should return.
  1616. return f.to_DMP_Python()._eval(a)
  1617. def _eval_lev(f, a, j):
  1618. # Only makes sense for multivariate polynomials
  1619. raise NotImplementedError
  1620. def _half_gcdex(f, g):
  1621. """Half extended Euclidean algorithm. """
  1622. s, h = f.to_DMP_Python()._half_gcdex(g.to_DMP_Python())
  1623. return s.to_DUP_Flint(), h.to_DUP_Flint()
  1624. def _gcdex(f, g):
  1625. """Extended Euclidean algorithm. """
  1626. h, s, t = f._rep.xgcd(g._rep)
  1627. return f.from_rep(s, f.dom), f.from_rep(t, f.dom), f.from_rep(h, f.dom)
  1628. def _invert(f, g):
  1629. """Invert ``f`` modulo ``g``, if possible. """
  1630. R = f.dom
  1631. if R.is_Field:
  1632. gcd, F_inv, _ = f._rep.xgcd(g._rep)
  1633. # XXX: Should be gcd != 1 but nmod_poly does not compare equal to
  1634. # other types.
  1635. if gcd != 0*gcd + 1:
  1636. raise NotInvertible("zero divisor")
  1637. return f.from_rep(F_inv, R)
  1638. else:
  1639. # fmpz_poly does not have xgcd or invert and this is not well
  1640. # defined in general.
  1641. return f.to_DMP_Python()._invert(g.to_DMP_Python()).to_DUP_Flint()
  1642. def _revert(f, n):
  1643. """Compute ``f**(-1)`` mod ``x**n``. """
  1644. # XXX: Use fmpz_series etc for reversion?
  1645. # Maybe python-flint should provide revert for fmpz_poly...
  1646. return f.to_DMP_Python()._revert(n).to_DUP_Flint()
  1647. def _subresultants(f, g):
  1648. """Computes subresultant PRS sequence of ``f`` and ``g``. """
  1649. # XXX: Maybe _fmpz_poly_pseudo_rem_cohen could be used...
  1650. R = f.to_DMP_Python()._subresultants(g.to_DMP_Python())
  1651. return [ g.to_DUP_Flint() for g in R ]
  1652. def _resultant_includePRS(f, g):
  1653. """Computes resultant of ``f`` and ``g`` via PRS. """
  1654. # XXX: Maybe _fmpz_poly_pseudo_rem_cohen could be used...
  1655. res, R = f.to_DMP_Python()._resultant_includePRS(g.to_DMP_Python())
  1656. return res, [ g.to_DUP_Flint() for g in R ]
  1657. def _resultant(f, g):
  1658. """Computes resultant of ``f`` and ``g``. """
  1659. # XXX: Use fmpz_mpoly etc when possible...
  1660. return f.to_DMP_Python()._resultant(g.to_DMP_Python())
  1661. def discriminant(f):
  1662. """Computes discriminant of ``f``. """
  1663. # XXX: Use fmpz_mpoly etc when possible...
  1664. return f.to_DMP_Python().discriminant()
  1665. def _cofactors(f, g):
  1666. """Returns GCD of ``f`` and ``g`` and their cofactors. """
  1667. h = f.gcd(g)
  1668. return h, f.exquo(h), g.exquo(h)
  1669. def _gcd(f, g):
  1670. """Returns polynomial GCD of ``f`` and ``g``. """
  1671. return f.from_rep(f._rep.gcd(g._rep), f.dom)
  1672. def _lcm(f, g):
  1673. """Returns polynomial LCM of ``f`` and ``g``. """
  1674. # XXX: python-flint should have a lcm method
  1675. if not (f and g):
  1676. return f.ground_new(f.dom.zero)
  1677. l = f._mul(g)._exquo(f._gcd(g))
  1678. if l.dom.is_Field:
  1679. l = l.monic()
  1680. elif l.LC() < 0:
  1681. l = l.neg()
  1682. return l
  1683. def _cancel(f, g):
  1684. """Cancel common factors in a rational function ``f/g``. """
  1685. assert f.dom == g.dom
  1686. R = f.dom
  1687. # Think carefully about how to handle denominators and coefficient
  1688. # canonicalisation if more domains are permitted...
  1689. assert R.is_ZZ or R.is_QQ or R.is_FiniteField
  1690. if R.is_FiniteField:
  1691. h = f._gcd(g)
  1692. F, G = f.exquo(h), g.exquo(h)
  1693. return R.one, R.one, F, G
  1694. if R.is_QQ:
  1695. cG, F = f.clear_denoms()
  1696. cF, G = g.clear_denoms()
  1697. else:
  1698. cG, F = R.one, f
  1699. cF, G = R.one, g
  1700. cH = cF.gcd(cG)
  1701. cF, cG = cF // cH, cG // cH
  1702. H = F._gcd(G)
  1703. F, G = F.exquo(H), G.exquo(H)
  1704. f_neg = F.LC() < 0
  1705. g_neg = G.LC() < 0
  1706. if f_neg and g_neg:
  1707. F, G = F.neg(), G.neg()
  1708. elif f_neg:
  1709. cF, F = -cF, F.neg()
  1710. elif g_neg:
  1711. cF, G = -cF, G.neg()
  1712. return cF, cG, F, G
  1713. def _cancel_include(f, g):
  1714. """Cancel common factors in a rational function ``f/g``. """
  1715. cF, cG, F, G = f._cancel(g)
  1716. return F._mul_ground(cF), G._mul_ground(cG)
  1717. def _trunc(f, p):
  1718. """Reduce ``f`` modulo a constant ``p``. """
  1719. return f.to_DMP_Python()._trunc(p).to_DUP_Flint()
  1720. def monic(f):
  1721. """Divides all coefficients by ``LC(f)``. """
  1722. # XXX: python-flint should add monic
  1723. return f._exquo_ground(f.LC())
  1724. def content(f):
  1725. """Returns GCD of polynomial coefficients. """
  1726. # XXX: python-flint should have a content method
  1727. return f.to_DMP_Python().content()
  1728. def primitive(f):
  1729. """Returns content and a primitive form of ``f``. """
  1730. cont = f.content()
  1731. if f.is_zero:
  1732. return f.dom.zero, f
  1733. prim = f._exquo_ground(cont)
  1734. return cont, prim
  1735. def _compose(f, g):
  1736. """Computes functional composition of ``f`` and ``g``. """
  1737. return f.from_rep(f._rep(g._rep), f.dom)
  1738. def _decompose(f):
  1739. """Computes functional decomposition of ``f``. """
  1740. return [ g.to_DUP_Flint() for g in f.to_DMP_Python()._decompose() ]
  1741. def _shift(f, a):
  1742. """Efficiently compute Taylor shift ``f(x + a)``. """
  1743. x_plus_a = f._cls([a, f.dom.one])
  1744. return f.from_rep(f._rep(x_plus_a), f.dom)
  1745. def _transform(f, p, q):
  1746. """Evaluate functional transformation ``q**n * f(p/q)``."""
  1747. F, P, Q = f.to_DMP_Python(), p.to_DMP_Python(), q.to_DMP_Python()
  1748. return F.transform(P, Q).to_DUP_Flint()
  1749. def _sturm(f):
  1750. """Computes the Sturm sequence of ``f``. """
  1751. return [ g.to_DUP_Flint() for g in f.to_DMP_Python()._sturm() ]
  1752. def _cauchy_upper_bound(f):
  1753. """Computes the Cauchy upper bound on the roots of ``f``. """
  1754. return f.to_DMP_Python()._cauchy_upper_bound()
  1755. def _cauchy_lower_bound(f):
  1756. """Computes the Cauchy lower bound on the nonzero roots of ``f``. """
  1757. return f.to_DMP_Python()._cauchy_lower_bound()
  1758. def _mignotte_sep_bound_squared(f):
  1759. """Computes the squared Mignotte bound on root separations of ``f``. """
  1760. return f.to_DMP_Python()._mignotte_sep_bound_squared()
  1761. def _gff_list(f):
  1762. """Computes greatest factorial factorization of ``f``. """
  1763. F = f.to_DMP_Python()
  1764. return [ (g.to_DUP_Flint(), k) for g, k in F.gff_list() ]
  1765. def norm(f):
  1766. """Computes ``Norm(f)``."""
  1767. # This is for algebraic number fields which DUP_Flint does not support
  1768. raise NotImplementedError
  1769. def sqf_norm(f):
  1770. """Computes square-free norm of ``f``. """
  1771. # This is for algebraic number fields which DUP_Flint does not support
  1772. raise NotImplementedError
  1773. def sqf_part(f):
  1774. """Computes square-free part of ``f``. """
  1775. return f._exquo(f._gcd(f._diff()))
  1776. def sqf_list(f, all=False):
  1777. """Returns a list of square-free factors of ``f``. """
  1778. # XXX: python-flint should provide square free factorisation.
  1779. coeff, factors = f.to_DMP_Python().sqf_list(all=all)
  1780. return coeff, [ (g.to_DUP_Flint(), k) for g, k in factors ]
  1781. def sqf_list_include(f, all=False):
  1782. """Returns a list of square-free factors of ``f``. """
  1783. factors = f.to_DMP_Python().sqf_list_include(all=all)
  1784. return [ (g.to_DUP_Flint(), k) for g, k in factors ]
  1785. def factor_list(f):
  1786. """Returns a list of irreducible factors of ``f``. """
  1787. if f.dom.is_ZZ or f.dom.is_FF:
  1788. # python-flint matches polys here
  1789. coeff, factors = f._rep.factor()
  1790. factors = [ (f.from_rep(g, f.dom), k) for g, k in factors ]
  1791. elif f.dom.is_QQ:
  1792. # python-flint returns monic factors over QQ whereas polys returns
  1793. # denominator free factors.
  1794. coeff, factors = f._rep.factor()
  1795. factors_monic = [ (f.from_rep(g, f.dom), k) for g, k in factors ]
  1796. # Absorb the denominators into coeff
  1797. factors = []
  1798. for g, k in factors_monic:
  1799. d, g = g.clear_denoms()
  1800. coeff /= d**k
  1801. factors.append((g, k))
  1802. else:
  1803. # Check carefully when adding more domains here...
  1804. raise RuntimeError("Domain %s is not supported with flint" % f.dom)
  1805. # We need to match the way that polys orders the factors
  1806. factors = f._sort_factors(factors)
  1807. return coeff, factors
  1808. def factor_list_include(f):
  1809. """Returns a list of irreducible factors of ``f``. """
  1810. # XXX: factor_list_include seems to be broken in general:
  1811. #
  1812. # >>> Poly(2*(x - 1)**3, x).factor_list_include()
  1813. # [(Poly(2*x - 2, x, domain='ZZ'), 3)]
  1814. #
  1815. # Let's not try to implement it here.
  1816. factors = f.to_DMP_Python().factor_list_include()
  1817. return [ (g.to_DUP_Flint(), k) for g, k in factors ]
  1818. def _sort_factors(f, factors):
  1819. """Sort a list of factors to canonical order. """
  1820. # Convert the factors to lists and use _sort_factors from polys
  1821. factors = [ (g.to_list(), k) for g, k in factors ]
  1822. factors = _sort_factors(factors, multiple=True)
  1823. to_dup_flint = lambda g: f.from_rep(f._cls(g[::-1]), f.dom)
  1824. return [ (to_dup_flint(g), k) for g, k in factors ]
  1825. def _isolate_real_roots(f, eps, inf, sup, fast):
  1826. return f.to_DMP_Python()._isolate_real_roots(eps, inf, sup, fast)
  1827. def _isolate_real_roots_sqf(f, eps, inf, sup, fast):
  1828. return f.to_DMP_Python()._isolate_real_roots_sqf(eps, inf, sup, fast)
  1829. def _isolate_all_roots(f, eps, inf, sup, fast):
  1830. # fmpz_poly and fmpq_poly have a complex_roots method that could be
  1831. # used here. It probably makes more sense to add analogous methods in
  1832. # python-flint though.
  1833. return f.to_DMP_Python()._isolate_all_roots(eps, inf, sup, fast)
  1834. def _isolate_all_roots_sqf(f, eps, inf, sup, fast):
  1835. return f.to_DMP_Python()._isolate_all_roots_sqf(eps, inf, sup, fast)
  1836. def _refine_real_root(f, s, t, eps, steps, fast):
  1837. return f.to_DMP_Python()._refine_real_root(s, t, eps, steps, fast)
  1838. def count_real_roots(f, inf=None, sup=None):
  1839. """Return the number of real roots of ``f`` in ``[inf, sup]``. """
  1840. return f.to_DMP_Python().count_real_roots(inf=inf, sup=sup)
  1841. def count_complex_roots(f, inf=None, sup=None):
  1842. """Return the number of complex roots of ``f`` in ``[inf, sup]``. """
  1843. return f.to_DMP_Python().count_complex_roots(inf=inf, sup=sup)
  1844. @property
  1845. def is_zero(f):
  1846. """Returns ``True`` if ``f`` is a zero polynomial. """
  1847. return not f._rep
  1848. @property
  1849. def is_one(f):
  1850. """Returns ``True`` if ``f`` is a unit polynomial. """
  1851. return f._rep == f.dom.one
  1852. @property
  1853. def is_ground(f):
  1854. """Returns ``True`` if ``f`` is an element of the ground domain. """
  1855. return f._rep.degree() <= 0
  1856. @property
  1857. def is_linear(f):
  1858. """Returns ``True`` if ``f`` is linear in all its variables. """
  1859. return f._rep.degree() <= 1
  1860. @property
  1861. def is_quadratic(f):
  1862. """Returns ``True`` if ``f`` is quadratic in all its variables. """
  1863. return f._rep.degree() <= 2
  1864. @property
  1865. def is_monomial(f):
  1866. """Returns ``True`` if ``f`` is zero or has only one term. """
  1867. fr = f._rep
  1868. return fr.degree() < 0 or not any(fr[n] for n in range(fr.degree()))
  1869. @property
  1870. def is_monic(f):
  1871. """Returns ``True`` if the leading coefficient of ``f`` is one. """
  1872. return f.LC() == f.dom.one
  1873. @property
  1874. def is_primitive(f):
  1875. """Returns ``True`` if the GCD of the coefficients of ``f`` is one. """
  1876. return f.to_DMP_Python().is_primitive
  1877. @property
  1878. def is_homogeneous(f):
  1879. """Returns ``True`` if ``f`` is a homogeneous polynomial. """
  1880. return f.to_DMP_Python().is_homogeneous
  1881. @property
  1882. def is_sqf(f):
  1883. """Returns ``True`` if ``f`` is a square-free polynomial. """
  1884. g = f._rep.gcd(f._rep.derivative())
  1885. return g.degree() <= 0
  1886. @property
  1887. def is_irreducible(f):
  1888. """Returns ``True`` if ``f`` has no factors over its domain. """
  1889. _, factors = f._rep.factor()
  1890. if len(factors) == 0:
  1891. return True
  1892. elif len(factors) == 1:
  1893. return factors[0][1] == 1
  1894. else:
  1895. return False
  1896. @property
  1897. def is_cyclotomic(f):
  1898. """Returns ``True`` if ``f`` is a cyclotomic polynomial. """
  1899. if f.dom.is_QQ:
  1900. try:
  1901. f = f.convert(ZZ)
  1902. except CoercionFailed:
  1903. return False
  1904. if f.dom.is_ZZ:
  1905. return bool(f._rep.is_cyclotomic())
  1906. else:
  1907. # This is what dup_cyclotomic_p does...
  1908. return False
  1909. def init_normal_DMF(num, den, lev, dom):
  1910. return DMF(dmp_normal(num, lev, dom),
  1911. dmp_normal(den, lev, dom), dom, lev)
  1912. class DMF(PicklableWithSlots, CantSympify):
  1913. """Dense Multivariate Fractions over `K`. """
  1914. __slots__ = ('num', 'den', 'lev', 'dom')
  1915. def __init__(self, rep, dom, lev=None):
  1916. num, den, lev = self._parse(rep, dom, lev)
  1917. num, den = dmp_cancel(num, den, lev, dom)
  1918. self.num = num
  1919. self.den = den
  1920. self.lev = lev
  1921. self.dom = dom
  1922. @classmethod
  1923. def new(cls, rep, dom, lev=None):
  1924. num, den, lev = cls._parse(rep, dom, lev)
  1925. obj = object.__new__(cls)
  1926. obj.num = num
  1927. obj.den = den
  1928. obj.lev = lev
  1929. obj.dom = dom
  1930. return obj
  1931. def ground_new(self, rep):
  1932. return self.new(rep, self.dom, self.lev)
  1933. @classmethod
  1934. def _parse(cls, rep, dom, lev=None):
  1935. if isinstance(rep, tuple):
  1936. num, den = rep
  1937. if lev is not None:
  1938. if isinstance(num, dict):
  1939. num = dmp_from_dict(num, lev, dom)
  1940. if isinstance(den, dict):
  1941. den = dmp_from_dict(den, lev, dom)
  1942. else:
  1943. num, num_lev = dmp_validate(num)
  1944. den, den_lev = dmp_validate(den)
  1945. if num_lev == den_lev:
  1946. lev = num_lev
  1947. else:
  1948. raise ValueError('inconsistent number of levels')
  1949. if dmp_zero_p(den, lev):
  1950. raise ZeroDivisionError('fraction denominator')
  1951. if dmp_zero_p(num, lev):
  1952. den = dmp_one(lev, dom)
  1953. else:
  1954. if dmp_negative_p(den, lev, dom):
  1955. num = dmp_neg(num, lev, dom)
  1956. den = dmp_neg(den, lev, dom)
  1957. else:
  1958. num = rep
  1959. if lev is not None:
  1960. if isinstance(num, dict):
  1961. num = dmp_from_dict(num, lev, dom)
  1962. elif not isinstance(num, list):
  1963. num = dmp_ground(dom.convert(num), lev)
  1964. else:
  1965. num, lev = dmp_validate(num)
  1966. den = dmp_one(lev, dom)
  1967. return num, den, lev
  1968. def __repr__(f):
  1969. return "%s((%s, %s), %s)" % (f.__class__.__name__, f.num, f.den, f.dom)
  1970. def __hash__(f):
  1971. return hash((f.__class__.__name__, dmp_to_tuple(f.num, f.lev),
  1972. dmp_to_tuple(f.den, f.lev), f.lev, f.dom))
  1973. def poly_unify(f, g):
  1974. """Unify a multivariate fraction and a polynomial. """
  1975. if not isinstance(g, DMP) or f.lev != g.lev:
  1976. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  1977. if f.dom == g.dom:
  1978. return (f.lev, f.dom, f.per, (f.num, f.den), g._rep)
  1979. else:
  1980. lev, dom = f.lev, f.dom.unify(g.dom)
  1981. F = (dmp_convert(f.num, lev, f.dom, dom),
  1982. dmp_convert(f.den, lev, f.dom, dom))
  1983. G = dmp_convert(g._rep, lev, g.dom, dom)
  1984. def per(num, den, cancel=True, kill=False, lev=lev):
  1985. if kill:
  1986. if not lev:
  1987. return num/den
  1988. else:
  1989. lev = lev - 1
  1990. if cancel:
  1991. num, den = dmp_cancel(num, den, lev, dom)
  1992. return f.__class__.new((num, den), dom, lev)
  1993. return lev, dom, per, F, G
  1994. def frac_unify(f, g):
  1995. """Unify representations of two multivariate fractions. """
  1996. if not isinstance(g, DMF) or f.lev != g.lev:
  1997. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  1998. if f.dom == g.dom:
  1999. return (f.lev, f.dom, f.per, (f.num, f.den),
  2000. (g.num, g.den))
  2001. else:
  2002. lev, dom = f.lev, f.dom.unify(g.dom)
  2003. F = (dmp_convert(f.num, lev, f.dom, dom),
  2004. dmp_convert(f.den, lev, f.dom, dom))
  2005. G = (dmp_convert(g.num, lev, g.dom, dom),
  2006. dmp_convert(g.den, lev, g.dom, dom))
  2007. def per(num, den, cancel=True, kill=False, lev=lev):
  2008. if kill:
  2009. if not lev:
  2010. return num/den
  2011. else:
  2012. lev = lev - 1
  2013. if cancel:
  2014. num, den = dmp_cancel(num, den, lev, dom)
  2015. return f.__class__.new((num, den), dom, lev)
  2016. return lev, dom, per, F, G
  2017. def per(f, num, den, cancel=True, kill=False):
  2018. """Create a DMF out of the given representation. """
  2019. lev, dom = f.lev, f.dom
  2020. if kill:
  2021. if not lev:
  2022. return num/den
  2023. else:
  2024. lev -= 1
  2025. if cancel:
  2026. num, den = dmp_cancel(num, den, lev, dom)
  2027. return f.__class__.new((num, den), dom, lev)
  2028. def half_per(f, rep, kill=False):
  2029. """Create a DMP out of the given representation. """
  2030. lev = f.lev
  2031. if kill:
  2032. if not lev:
  2033. return rep
  2034. else:
  2035. lev -= 1
  2036. return DMP(rep, f.dom, lev)
  2037. @classmethod
  2038. def zero(cls, lev, dom):
  2039. return cls.new(0, dom, lev)
  2040. @classmethod
  2041. def one(cls, lev, dom):
  2042. return cls.new(1, dom, lev)
  2043. def numer(f):
  2044. """Returns the numerator of ``f``. """
  2045. return f.half_per(f.num)
  2046. def denom(f):
  2047. """Returns the denominator of ``f``. """
  2048. return f.half_per(f.den)
  2049. def cancel(f):
  2050. """Remove common factors from ``f.num`` and ``f.den``. """
  2051. return f.per(f.num, f.den)
  2052. def neg(f):
  2053. """Negate all coefficients in ``f``. """
  2054. return f.per(dmp_neg(f.num, f.lev, f.dom), f.den, cancel=False)
  2055. def add_ground(f, c):
  2056. """Add an element of the ground domain to ``f``. """
  2057. return f + f.ground_new(c)
  2058. def add(f, g):
  2059. """Add two multivariate fractions ``f`` and ``g``. """
  2060. if isinstance(g, DMP):
  2061. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  2062. num, den = dmp_add_mul(F_num, F_den, G, lev, dom), F_den
  2063. else:
  2064. lev, dom, per, F, G = f.frac_unify(g)
  2065. (F_num, F_den), (G_num, G_den) = F, G
  2066. num = dmp_add(dmp_mul(F_num, G_den, lev, dom),
  2067. dmp_mul(F_den, G_num, lev, dom), lev, dom)
  2068. den = dmp_mul(F_den, G_den, lev, dom)
  2069. return per(num, den)
  2070. def sub(f, g):
  2071. """Subtract two multivariate fractions ``f`` and ``g``. """
  2072. if isinstance(g, DMP):
  2073. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  2074. num, den = dmp_sub_mul(F_num, F_den, G, lev, dom), F_den
  2075. else:
  2076. lev, dom, per, F, G = f.frac_unify(g)
  2077. (F_num, F_den), (G_num, G_den) = F, G
  2078. num = dmp_sub(dmp_mul(F_num, G_den, lev, dom),
  2079. dmp_mul(F_den, G_num, lev, dom), lev, dom)
  2080. den = dmp_mul(F_den, G_den, lev, dom)
  2081. return per(num, den)
  2082. def mul(f, g):
  2083. """Multiply two multivariate fractions ``f`` and ``g``. """
  2084. if isinstance(g, DMP):
  2085. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  2086. num, den = dmp_mul(F_num, G, lev, dom), F_den
  2087. else:
  2088. lev, dom, per, F, G = f.frac_unify(g)
  2089. (F_num, F_den), (G_num, G_den) = F, G
  2090. num = dmp_mul(F_num, G_num, lev, dom)
  2091. den = dmp_mul(F_den, G_den, lev, dom)
  2092. return per(num, den)
  2093. def pow(f, n):
  2094. """Raise ``f`` to a non-negative power ``n``. """
  2095. if isinstance(n, int):
  2096. num, den = f.num, f.den
  2097. if n < 0:
  2098. num, den, n = den, num, -n
  2099. return f.per(dmp_pow(num, n, f.lev, f.dom),
  2100. dmp_pow(den, n, f.lev, f.dom), cancel=False)
  2101. else:
  2102. raise TypeError("``int`` expected, got %s" % type(n))
  2103. def quo(f, g):
  2104. """Computes quotient of fractions ``f`` and ``g``. """
  2105. if isinstance(g, DMP):
  2106. lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
  2107. num, den = F_num, dmp_mul(F_den, G, lev, dom)
  2108. else:
  2109. lev, dom, per, F, G = f.frac_unify(g)
  2110. (F_num, F_den), (G_num, G_den) = F, G
  2111. num = dmp_mul(F_num, G_den, lev, dom)
  2112. den = dmp_mul(F_den, G_num, lev, dom)
  2113. return per(num, den)
  2114. exquo = quo
  2115. def invert(f, check=True):
  2116. """Computes inverse of a fraction ``f``. """
  2117. return f.per(f.den, f.num, cancel=False)
  2118. @property
  2119. def is_zero(f):
  2120. """Returns ``True`` if ``f`` is a zero fraction. """
  2121. return dmp_zero_p(f.num, f.lev)
  2122. @property
  2123. def is_one(f):
  2124. """Returns ``True`` if ``f`` is a unit fraction. """
  2125. return dmp_one_p(f.num, f.lev, f.dom) and \
  2126. dmp_one_p(f.den, f.lev, f.dom)
  2127. def __neg__(f):
  2128. return f.neg()
  2129. def __add__(f, g):
  2130. if isinstance(g, (DMP, DMF)):
  2131. return f.add(g)
  2132. elif g in f.dom:
  2133. return f.add_ground(f.dom.convert(g))
  2134. try:
  2135. return f.add(f.half_per(g))
  2136. except (TypeError, CoercionFailed, NotImplementedError):
  2137. return NotImplemented
  2138. def __radd__(f, g):
  2139. return f.__add__(g)
  2140. def __sub__(f, g):
  2141. if isinstance(g, (DMP, DMF)):
  2142. return f.sub(g)
  2143. try:
  2144. return f.sub(f.half_per(g))
  2145. except (TypeError, CoercionFailed, NotImplementedError):
  2146. return NotImplemented
  2147. def __rsub__(f, g):
  2148. return (-f).__add__(g)
  2149. def __mul__(f, g):
  2150. if isinstance(g, (DMP, DMF)):
  2151. return f.mul(g)
  2152. try:
  2153. return f.mul(f.half_per(g))
  2154. except (TypeError, CoercionFailed, NotImplementedError):
  2155. return NotImplemented
  2156. def __rmul__(f, g):
  2157. return f.__mul__(g)
  2158. def __pow__(f, n):
  2159. return f.pow(n)
  2160. def __truediv__(f, g):
  2161. if isinstance(g, (DMP, DMF)):
  2162. return f.quo(g)
  2163. try:
  2164. return f.quo(f.half_per(g))
  2165. except (TypeError, CoercionFailed, NotImplementedError):
  2166. return NotImplemented
  2167. def __rtruediv__(self, g):
  2168. return self.invert(check=False)*g
  2169. def __eq__(f, g):
  2170. try:
  2171. if isinstance(g, DMP):
  2172. _, _, _, (F_num, F_den), G = f.poly_unify(g)
  2173. if f.lev == g.lev:
  2174. return dmp_one_p(F_den, f.lev, f.dom) and F_num == G
  2175. else:
  2176. _, _, _, F, G = f.frac_unify(g)
  2177. if f.lev == g.lev:
  2178. return F == G
  2179. except UnificationFailed:
  2180. pass
  2181. return False
  2182. def __ne__(f, g):
  2183. try:
  2184. if isinstance(g, DMP):
  2185. _, _, _, (F_num, F_den), G = f.poly_unify(g)
  2186. if f.lev == g.lev:
  2187. return not (dmp_one_p(F_den, f.lev, f.dom) and F_num == G)
  2188. else:
  2189. _, _, _, F, G = f.frac_unify(g)
  2190. if f.lev == g.lev:
  2191. return F != G
  2192. except UnificationFailed:
  2193. pass
  2194. return True
  2195. def __lt__(f, g):
  2196. _, _, _, F, G = f.frac_unify(g)
  2197. return F < G
  2198. def __le__(f, g):
  2199. _, _, _, F, G = f.frac_unify(g)
  2200. return F <= G
  2201. def __gt__(f, g):
  2202. _, _, _, F, G = f.frac_unify(g)
  2203. return F > G
  2204. def __ge__(f, g):
  2205. _, _, _, F, G = f.frac_unify(g)
  2206. return F >= G
  2207. def __bool__(f):
  2208. return not dmp_zero_p(f.num, f.lev)
  2209. def init_normal_ANP(rep, mod, dom):
  2210. return ANP(dup_normal(rep, dom),
  2211. dup_normal(mod, dom), dom)
  2212. class ANP(CantSympify):
  2213. """Dense Algebraic Number Polynomials over a field. """
  2214. __slots__ = ('_rep', '_mod', 'dom')
  2215. def __new__(cls, rep, mod, dom):
  2216. if isinstance(rep, DMP):
  2217. pass
  2218. elif type(rep) is dict: # don't use isinstance
  2219. rep = DMP(dup_from_dict(rep, dom), dom, 0)
  2220. else:
  2221. if isinstance(rep, list):
  2222. rep = [dom.convert(a) for a in rep]
  2223. else:
  2224. rep = [dom.convert(rep)]
  2225. rep = DMP(dup_strip(rep), dom, 0)
  2226. if isinstance(mod, DMP):
  2227. pass
  2228. elif isinstance(mod, dict):
  2229. mod = DMP(dup_from_dict(mod, dom), dom, 0)
  2230. else:
  2231. mod = DMP(dup_strip(mod), dom, 0)
  2232. return cls.new(rep, mod, dom)
  2233. @classmethod
  2234. def new(cls, rep, mod, dom):
  2235. if not (rep.dom == mod.dom == dom):
  2236. raise RuntimeError("Inconsistent domain")
  2237. obj = super().__new__(cls)
  2238. obj._rep = rep
  2239. obj._mod = mod
  2240. obj.dom = dom
  2241. return obj
  2242. # XXX: It should be possible to use __getnewargs__ rather than __reduce__
  2243. # but it doesn't work for some reason. Probably this would be easier if
  2244. # python-flint supported pickling for polynomial types.
  2245. def __reduce__(self):
  2246. return ANP, (self.rep, self.mod, self.dom)
  2247. @property
  2248. def rep(self):
  2249. return self._rep.to_list()
  2250. @property
  2251. def mod(self):
  2252. return self.mod_to_list()
  2253. def to_DMP(self):
  2254. return self._rep
  2255. def mod_to_DMP(self):
  2256. return self._mod
  2257. def per(f, rep):
  2258. return f.new(rep, f._mod, f.dom)
  2259. def __repr__(f):
  2260. return "%s(%s, %s, %s)" % (f.__class__.__name__, f._rep.to_list(), f._mod.to_list(), f.dom)
  2261. def __hash__(f):
  2262. return hash((f.__class__.__name__, f.to_tuple(), f._mod.to_tuple(), f.dom))
  2263. def convert(f, dom):
  2264. """Convert ``f`` to a ``ANP`` over a new domain. """
  2265. if f.dom == dom:
  2266. return f
  2267. else:
  2268. return f.new(f._rep.convert(dom), f._mod.convert(dom), dom)
  2269. def unify(f, g):
  2270. """Unify representations of two algebraic numbers. """
  2271. # XXX: This unify method is not used any more because unify_ANP is used
  2272. # instead.
  2273. if not isinstance(g, ANP) or f.mod != g.mod:
  2274. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  2275. if f.dom == g.dom:
  2276. return f.dom, f.per, f.rep, g.rep, f.mod
  2277. else:
  2278. dom = f.dom.unify(g.dom)
  2279. F = dup_convert(f.rep, f.dom, dom)
  2280. G = dup_convert(g.rep, g.dom, dom)
  2281. if dom != f.dom and dom != g.dom:
  2282. mod = dup_convert(f.mod, f.dom, dom)
  2283. else:
  2284. if dom == f.dom:
  2285. mod = f.mod
  2286. else:
  2287. mod = g.mod
  2288. per = lambda rep: ANP(rep, mod, dom)
  2289. return dom, per, F, G, mod
  2290. def unify_ANP(f, g):
  2291. """Unify and return ``DMP`` instances of ``f`` and ``g``. """
  2292. if not isinstance(g, ANP) or f._mod != g._mod:
  2293. raise UnificationFailed("Cannot unify %s with %s" % (f, g))
  2294. # The domain is almost always QQ but there are some tests involving ZZ
  2295. if f.dom != g.dom:
  2296. dom = f.dom.unify(g.dom)
  2297. f = f.convert(dom)
  2298. g = g.convert(dom)
  2299. return f._rep, g._rep, f._mod, f.dom
  2300. @classmethod
  2301. def zero(cls, mod, dom):
  2302. return ANP(0, mod, dom)
  2303. @classmethod
  2304. def one(cls, mod, dom):
  2305. return ANP(1, mod, dom)
  2306. def to_dict(f):
  2307. """Convert ``f`` to a dict representation with native coefficients. """
  2308. return f._rep.to_dict()
  2309. def to_sympy_dict(f):
  2310. """Convert ``f`` to a dict representation with SymPy coefficients. """
  2311. rep = dmp_to_dict(f.rep, 0, f.dom)
  2312. for k, v in rep.items():
  2313. rep[k] = f.dom.to_sympy(v)
  2314. return rep
  2315. def to_list(f):
  2316. """Convert ``f`` to a list representation with native coefficients. """
  2317. return f._rep.to_list()
  2318. def mod_to_list(f):
  2319. """Return ``f.mod`` as a list with native coefficients. """
  2320. return f._mod.to_list()
  2321. def to_sympy_list(f):
  2322. """Convert ``f`` to a list representation with SymPy coefficients. """
  2323. return [ f.dom.to_sympy(c) for c in f.to_list() ]
  2324. def to_tuple(f):
  2325. """
  2326. Convert ``f`` to a tuple representation with native coefficients.
  2327. This is needed for hashing.
  2328. """
  2329. return f._rep.to_tuple()
  2330. @classmethod
  2331. def from_list(cls, rep, mod, dom):
  2332. return ANP(dup_strip(list(map(dom.convert, rep))), mod, dom)
  2333. def add_ground(f, c):
  2334. """Add an element of the ground domain to ``f``. """
  2335. return f.per(f._rep.add_ground(c))
  2336. def sub_ground(f, c):
  2337. """Subtract an element of the ground domain from ``f``. """
  2338. return f.per(f._rep.sub_ground(c))
  2339. def mul_ground(f, c):
  2340. """Multiply ``f`` by an element of the ground domain. """
  2341. return f.per(f._rep.mul_ground(c))
  2342. def quo_ground(f, c):
  2343. """Quotient of ``f`` by an element of the ground domain. """
  2344. return f.per(f._rep.quo_ground(c))
  2345. def neg(f):
  2346. return f.per(f._rep.neg())
  2347. def add(f, g):
  2348. F, G, mod, dom = f.unify_ANP(g)
  2349. return f.new(F.add(G), mod, dom)
  2350. def sub(f, g):
  2351. F, G, mod, dom = f.unify_ANP(g)
  2352. return f.new(F.sub(G), mod, dom)
  2353. def mul(f, g):
  2354. F, G, mod, dom = f.unify_ANP(g)
  2355. return f.new(F.mul(G).rem(mod), mod, dom)
  2356. def pow(f, n):
  2357. """Raise ``f`` to a non-negative power ``n``. """
  2358. if not isinstance(n, int):
  2359. raise TypeError("``int`` expected, got %s" % type(n))
  2360. mod = f._mod
  2361. F = f._rep
  2362. if n < 0:
  2363. F, n = F.invert(mod), -n
  2364. # XXX: Need a pow_mod method for DMP
  2365. return f.new(F.pow(n).rem(f._mod), mod, f.dom)
  2366. def exquo(f, g):
  2367. F, G, mod, dom = f.unify_ANP(g)
  2368. return f.new(F.mul(G.invert(mod)).rem(mod), mod, dom)
  2369. def div(f, g):
  2370. return f.exquo(g), f.zero(f._mod, f.dom)
  2371. def quo(f, g):
  2372. return f.exquo(g)
  2373. def rem(f, g):
  2374. F, G, mod, dom = f.unify_ANP(g)
  2375. s, h = F.half_gcdex(G)
  2376. if h.is_one:
  2377. return f.zero(mod, dom)
  2378. else:
  2379. raise NotInvertible("zero divisor")
  2380. def LC(f):
  2381. """Returns the leading coefficient of ``f``. """
  2382. return f._rep.LC()
  2383. def TC(f):
  2384. """Returns the trailing coefficient of ``f``. """
  2385. return f._rep.TC()
  2386. @property
  2387. def is_zero(f):
  2388. """Returns ``True`` if ``f`` is a zero algebraic number. """
  2389. return f._rep.is_zero
  2390. @property
  2391. def is_one(f):
  2392. """Returns ``True`` if ``f`` is a unit algebraic number. """
  2393. return f._rep.is_one
  2394. @property
  2395. def is_ground(f):
  2396. """Returns ``True`` if ``f`` is an element of the ground domain. """
  2397. return f._rep.is_ground
  2398. def __pos__(f):
  2399. return f
  2400. def __neg__(f):
  2401. return f.neg()
  2402. def __add__(f, g):
  2403. if isinstance(g, ANP):
  2404. return f.add(g)
  2405. try:
  2406. g = f.dom.convert(g)
  2407. except CoercionFailed:
  2408. return NotImplemented
  2409. else:
  2410. return f.add_ground(g)
  2411. def __radd__(f, g):
  2412. return f.__add__(g)
  2413. def __sub__(f, g):
  2414. if isinstance(g, ANP):
  2415. return f.sub(g)
  2416. try:
  2417. g = f.dom.convert(g)
  2418. except CoercionFailed:
  2419. return NotImplemented
  2420. else:
  2421. return f.sub_ground(g)
  2422. def __rsub__(f, g):
  2423. return (-f).__add__(g)
  2424. def __mul__(f, g):
  2425. if isinstance(g, ANP):
  2426. return f.mul(g)
  2427. try:
  2428. g = f.dom.convert(g)
  2429. except CoercionFailed:
  2430. return NotImplemented
  2431. else:
  2432. return f.mul_ground(g)
  2433. def __rmul__(f, g):
  2434. return f.__mul__(g)
  2435. def __pow__(f, n):
  2436. return f.pow(n)
  2437. def __divmod__(f, g):
  2438. return f.div(g)
  2439. def __mod__(f, g):
  2440. return f.rem(g)
  2441. def __truediv__(f, g):
  2442. if isinstance(g, ANP):
  2443. return f.quo(g)
  2444. try:
  2445. g = f.dom.convert(g)
  2446. except CoercionFailed:
  2447. return NotImplemented
  2448. else:
  2449. return f.quo_ground(g)
  2450. def __eq__(f, g):
  2451. try:
  2452. F, G, _, _ = f.unify_ANP(g)
  2453. except UnificationFailed:
  2454. return NotImplemented
  2455. return F == G
  2456. def __ne__(f, g):
  2457. try:
  2458. F, G, _, _ = f.unify_ANP(g)
  2459. except UnificationFailed:
  2460. return NotImplemented
  2461. return F != G
  2462. def __lt__(f, g):
  2463. F, G, _, _ = f.unify_ANP(g)
  2464. return F < G
  2465. def __le__(f, g):
  2466. F, G, _, _ = f.unify_ANP(g)
  2467. return F <= G
  2468. def __gt__(f, g):
  2469. F, G, _, _ = f.unify_ANP(g)
  2470. return F > G
  2471. def __ge__(f, g):
  2472. F, G, _, _ = f.unify_ANP(g)
  2473. return F >= G
  2474. def __bool__(f):
  2475. return bool(f._rep)