complexes.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  1. from typing import Tuple as tTuple
  2. from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic
  3. from sympy.core.expr import Expr
  4. from sympy.core.exprtools import factor_terms
  5. from sympy.core.function import (Function, Derivative, ArgumentIndexError,
  6. AppliedUndef, expand_mul)
  7. from sympy.core.logic import fuzzy_not, fuzzy_or
  8. from sympy.core.numbers import pi, I, oo
  9. from sympy.core.power import Pow
  10. from sympy.core.relational import Eq
  11. from sympy.functions.elementary.exponential import exp, exp_polar, log
  12. from sympy.functions.elementary.integers import ceiling
  13. from sympy.functions.elementary.miscellaneous import sqrt
  14. from sympy.functions.elementary.piecewise import Piecewise
  15. from sympy.functions.elementary.trigonometric import atan, atan2
  16. ###############################################################################
  17. ######################### REAL and IMAGINARY PARTS ############################
  18. ###############################################################################
  19. class re(Function):
  20. """
  21. Returns real part of expression. This function performs only
  22. elementary analysis and so it will fail to decompose properly
  23. more complicated expressions. If completely simplified result
  24. is needed then use ``Basic.as_real_imag()`` or perform complex
  25. expansion on instance of this function.
  26. Examples
  27. ========
  28. >>> from sympy import re, im, I, E, symbols
  29. >>> x, y = symbols('x y', real=True)
  30. >>> re(2*E)
  31. 2*E
  32. >>> re(2*I + 17)
  33. 17
  34. >>> re(2*I)
  35. 0
  36. >>> re(im(x) + x*I + 2)
  37. 2
  38. >>> re(5 + I + 2)
  39. 7
  40. Parameters
  41. ==========
  42. arg : Expr
  43. Real or complex expression.
  44. Returns
  45. =======
  46. expr : Expr
  47. Real part of expression.
  48. See Also
  49. ========
  50. im
  51. """
  52. args: tTuple[Expr]
  53. is_extended_real = True
  54. unbranched = True # implicitly works on the projection to C
  55. _singularities = True # non-holomorphic
  56. @classmethod
  57. def eval(cls, arg):
  58. if arg is S.NaN:
  59. return S.NaN
  60. elif arg is S.ComplexInfinity:
  61. return S.NaN
  62. elif arg.is_extended_real:
  63. return arg
  64. elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real:
  65. return S.Zero
  66. elif arg.is_Matrix:
  67. return arg.as_real_imag()[0]
  68. elif arg.is_Function and isinstance(arg, conjugate):
  69. return re(arg.args[0])
  70. else:
  71. included, reverted, excluded = [], [], []
  72. args = Add.make_args(arg)
  73. for term in args:
  74. coeff = term.as_coefficient(S.ImaginaryUnit)
  75. if coeff is not None:
  76. if not coeff.is_extended_real:
  77. reverted.append(coeff)
  78. elif not term.has(S.ImaginaryUnit) and term.is_extended_real:
  79. excluded.append(term)
  80. else:
  81. # Try to do some advanced expansion. If
  82. # impossible, don't try to do re(arg) again
  83. # (because this is what we are trying to do now).
  84. real_imag = term.as_real_imag(ignore=arg)
  85. if real_imag:
  86. excluded.append(real_imag[0])
  87. else:
  88. included.append(term)
  89. if len(args) != len(included):
  90. a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
  91. return cls(a) - im(b) + c
  92. def as_real_imag(self, deep=True, **hints):
  93. """
  94. Returns the real number with a zero imaginary part.
  95. """
  96. return (self, S.Zero)
  97. def _eval_derivative(self, x):
  98. if x.is_extended_real or self.args[0].is_extended_real:
  99. return re(Derivative(self.args[0], x, evaluate=True))
  100. if x.is_imaginary or self.args[0].is_imaginary:
  101. return -S.ImaginaryUnit \
  102. * im(Derivative(self.args[0], x, evaluate=True))
  103. def _eval_rewrite_as_im(self, arg, **kwargs):
  104. return self.args[0] - S.ImaginaryUnit*im(self.args[0])
  105. def _eval_is_algebraic(self):
  106. return self.args[0].is_algebraic
  107. def _eval_is_zero(self):
  108. # is_imaginary implies nonzero
  109. return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero])
  110. def _eval_is_finite(self):
  111. if self.args[0].is_finite:
  112. return True
  113. def _eval_is_complex(self):
  114. if self.args[0].is_finite:
  115. return True
  116. class im(Function):
  117. """
  118. Returns imaginary part of expression. This function performs only
  119. elementary analysis and so it will fail to decompose properly more
  120. complicated expressions. If completely simplified result is needed then
  121. use ``Basic.as_real_imag()`` or perform complex expansion on instance of
  122. this function.
  123. Examples
  124. ========
  125. >>> from sympy import re, im, E, I
  126. >>> from sympy.abc import x, y
  127. >>> im(2*E)
  128. 0
  129. >>> im(2*I + 17)
  130. 2
  131. >>> im(x*I)
  132. re(x)
  133. >>> im(re(x) + y)
  134. im(y)
  135. >>> im(2 + 3*I)
  136. 3
  137. Parameters
  138. ==========
  139. arg : Expr
  140. Real or complex expression.
  141. Returns
  142. =======
  143. expr : Expr
  144. Imaginary part of expression.
  145. See Also
  146. ========
  147. re
  148. """
  149. args: tTuple[Expr]
  150. is_extended_real = True
  151. unbranched = True # implicitly works on the projection to C
  152. _singularities = True # non-holomorphic
  153. @classmethod
  154. def eval(cls, arg):
  155. if arg is S.NaN:
  156. return S.NaN
  157. elif arg is S.ComplexInfinity:
  158. return S.NaN
  159. elif arg.is_extended_real:
  160. return S.Zero
  161. elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real:
  162. return -S.ImaginaryUnit * arg
  163. elif arg.is_Matrix:
  164. return arg.as_real_imag()[1]
  165. elif arg.is_Function and isinstance(arg, conjugate):
  166. return -im(arg.args[0])
  167. else:
  168. included, reverted, excluded = [], [], []
  169. args = Add.make_args(arg)
  170. for term in args:
  171. coeff = term.as_coefficient(S.ImaginaryUnit)
  172. if coeff is not None:
  173. if not coeff.is_extended_real:
  174. reverted.append(coeff)
  175. else:
  176. excluded.append(coeff)
  177. elif term.has(S.ImaginaryUnit) or not term.is_extended_real:
  178. # Try to do some advanced expansion. If
  179. # impossible, don't try to do im(arg) again
  180. # (because this is what we are trying to do now).
  181. real_imag = term.as_real_imag(ignore=arg)
  182. if real_imag:
  183. excluded.append(real_imag[1])
  184. else:
  185. included.append(term)
  186. if len(args) != len(included):
  187. a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
  188. return cls(a) + re(b) + c
  189. def as_real_imag(self, deep=True, **hints):
  190. """
  191. Return the imaginary part with a zero real part.
  192. """
  193. return (self, S.Zero)
  194. def _eval_derivative(self, x):
  195. if x.is_extended_real or self.args[0].is_extended_real:
  196. return im(Derivative(self.args[0], x, evaluate=True))
  197. if x.is_imaginary or self.args[0].is_imaginary:
  198. return -S.ImaginaryUnit \
  199. * re(Derivative(self.args[0], x, evaluate=True))
  200. def _eval_rewrite_as_re(self, arg, **kwargs):
  201. return -S.ImaginaryUnit*(self.args[0] - re(self.args[0]))
  202. def _eval_is_algebraic(self):
  203. return self.args[0].is_algebraic
  204. def _eval_is_zero(self):
  205. return self.args[0].is_extended_real
  206. def _eval_is_finite(self):
  207. if self.args[0].is_finite:
  208. return True
  209. def _eval_is_complex(self):
  210. if self.args[0].is_finite:
  211. return True
  212. ###############################################################################
  213. ############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################
  214. ###############################################################################
  215. class sign(Function):
  216. """
  217. Returns the complex sign of an expression:
  218. Explanation
  219. ===========
  220. If the expression is real the sign will be:
  221. * $1$ if expression is positive
  222. * $0$ if expression is equal to zero
  223. * $-1$ if expression is negative
  224. If the expression is imaginary the sign will be:
  225. * $I$ if im(expression) is positive
  226. * $-I$ if im(expression) is negative
  227. Otherwise an unevaluated expression will be returned. When evaluated, the
  228. result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``.
  229. Examples
  230. ========
  231. >>> from sympy import sign, I
  232. >>> sign(-1)
  233. -1
  234. >>> sign(0)
  235. 0
  236. >>> sign(-3*I)
  237. -I
  238. >>> sign(1 + I)
  239. sign(1 + I)
  240. >>> _.evalf()
  241. 0.707106781186548 + 0.707106781186548*I
  242. Parameters
  243. ==========
  244. arg : Expr
  245. Real or imaginary expression.
  246. Returns
  247. =======
  248. expr : Expr
  249. Complex sign of expression.
  250. See Also
  251. ========
  252. Abs, conjugate
  253. """
  254. is_complex = True
  255. _singularities = True
  256. def doit(self, **hints):
  257. s = super().doit()
  258. if s == self and self.args[0].is_zero is False:
  259. return self.args[0] / Abs(self.args[0])
  260. return s
  261. @classmethod
  262. def eval(cls, arg):
  263. # handle what we can
  264. if arg.is_Mul:
  265. c, args = arg.as_coeff_mul()
  266. unk = []
  267. s = sign(c)
  268. for a in args:
  269. if a.is_extended_negative:
  270. s = -s
  271. elif a.is_extended_positive:
  272. pass
  273. else:
  274. if a.is_imaginary:
  275. ai = im(a)
  276. if ai.is_comparable: # i.e. a = I*real
  277. s *= S.ImaginaryUnit
  278. if ai.is_extended_negative:
  279. # can't use sign(ai) here since ai might not be
  280. # a Number
  281. s = -s
  282. else:
  283. unk.append(a)
  284. else:
  285. unk.append(a)
  286. if c is S.One and len(unk) == len(args):
  287. return None
  288. return s * cls(arg._new_rawargs(*unk))
  289. if arg is S.NaN:
  290. return S.NaN
  291. if arg.is_zero: # it may be an Expr that is zero
  292. return S.Zero
  293. if arg.is_extended_positive:
  294. return S.One
  295. if arg.is_extended_negative:
  296. return S.NegativeOne
  297. if arg.is_Function:
  298. if isinstance(arg, sign):
  299. return arg
  300. if arg.is_imaginary:
  301. if arg.is_Pow and arg.exp is S.Half:
  302. # we catch this because non-trivial sqrt args are not expanded
  303. # e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1)
  304. return S.ImaginaryUnit
  305. arg2 = -S.ImaginaryUnit * arg
  306. if arg2.is_extended_positive:
  307. return S.ImaginaryUnit
  308. if arg2.is_extended_negative:
  309. return -S.ImaginaryUnit
  310. def _eval_Abs(self):
  311. if fuzzy_not(self.args[0].is_zero):
  312. return S.One
  313. def _eval_conjugate(self):
  314. return sign(conjugate(self.args[0]))
  315. def _eval_derivative(self, x):
  316. if self.args[0].is_extended_real:
  317. from sympy.functions.special.delta_functions import DiracDelta
  318. return 2 * Derivative(self.args[0], x, evaluate=True) \
  319. * DiracDelta(self.args[0])
  320. elif self.args[0].is_imaginary:
  321. from sympy.functions.special.delta_functions import DiracDelta
  322. return 2 * Derivative(self.args[0], x, evaluate=True) \
  323. * DiracDelta(-S.ImaginaryUnit * self.args[0])
  324. def _eval_is_nonnegative(self):
  325. if self.args[0].is_nonnegative:
  326. return True
  327. def _eval_is_nonpositive(self):
  328. if self.args[0].is_nonpositive:
  329. return True
  330. def _eval_is_imaginary(self):
  331. return self.args[0].is_imaginary
  332. def _eval_is_integer(self):
  333. return self.args[0].is_extended_real
  334. def _eval_is_zero(self):
  335. return self.args[0].is_zero
  336. def _eval_power(self, other):
  337. if (
  338. fuzzy_not(self.args[0].is_zero) and
  339. other.is_integer and
  340. other.is_even
  341. ):
  342. return S.One
  343. def _eval_nseries(self, x, n, logx, cdir=0):
  344. arg0 = self.args[0]
  345. x0 = arg0.subs(x, 0)
  346. if x0 != 0:
  347. return self.func(x0)
  348. if cdir != 0:
  349. cdir = arg0.dir(x, cdir)
  350. return -S.One if re(cdir) < 0 else S.One
  351. def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
  352. if arg.is_extended_real:
  353. return Piecewise((1, arg > 0), (-1, arg < 0), (0, True))
  354. def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
  355. from sympy.functions.special.delta_functions import Heaviside
  356. if arg.is_extended_real:
  357. return Heaviside(arg) * 2 - 1
  358. def _eval_rewrite_as_Abs(self, arg, **kwargs):
  359. return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))
  360. def _eval_simplify(self, **kwargs):
  361. return self.func(factor_terms(self.args[0])) # XXX include doit?
  362. class Abs(Function):
  363. """
  364. Return the absolute value of the argument.
  365. Explanation
  366. ===========
  367. This is an extension of the built-in function ``abs()`` to accept symbolic
  368. values. If you pass a SymPy expression to the built-in ``abs()``, it will
  369. pass it automatically to ``Abs()``.
  370. Examples
  371. ========
  372. >>> from sympy import Abs, Symbol, S, I
  373. >>> Abs(-1)
  374. 1
  375. >>> x = Symbol('x', real=True)
  376. >>> Abs(-x)
  377. Abs(x)
  378. >>> Abs(x**2)
  379. x**2
  380. >>> abs(-x) # The Python built-in
  381. Abs(x)
  382. >>> Abs(3*x + 2*I)
  383. sqrt(9*x**2 + 4)
  384. >>> Abs(8*I)
  385. 8
  386. Note that the Python built-in will return either an Expr or int depending on
  387. the argument::
  388. >>> type(abs(-1))
  389. <... 'int'>
  390. >>> type(abs(S.NegativeOne))
  391. <class 'sympy.core.numbers.One'>
  392. Abs will always return a SymPy object.
  393. Parameters
  394. ==========
  395. arg : Expr
  396. Real or complex expression.
  397. Returns
  398. =======
  399. expr : Expr
  400. Absolute value returned can be an expression or integer depending on
  401. input arg.
  402. See Also
  403. ========
  404. sign, conjugate
  405. """
  406. args: tTuple[Expr]
  407. is_extended_real = True
  408. is_extended_negative = False
  409. is_extended_nonnegative = True
  410. unbranched = True
  411. _singularities = True # non-holomorphic
  412. def fdiff(self, argindex=1):
  413. """
  414. Get the first derivative of the argument to Abs().
  415. """
  416. if argindex == 1:
  417. return sign(self.args[0])
  418. else:
  419. raise ArgumentIndexError(self, argindex)
  420. @classmethod
  421. def eval(cls, arg):
  422. from sympy.simplify.simplify import signsimp
  423. if hasattr(arg, '_eval_Abs'):
  424. obj = arg._eval_Abs()
  425. if obj is not None:
  426. return obj
  427. if not isinstance(arg, Expr):
  428. raise TypeError("Bad argument type for Abs(): %s" % type(arg))
  429. # handle what we can
  430. arg = signsimp(arg, evaluate=False)
  431. n, d = arg.as_numer_denom()
  432. if d.free_symbols and not n.free_symbols:
  433. return cls(n)/cls(d)
  434. if arg.is_Mul:
  435. known = []
  436. unk = []
  437. for t in arg.args:
  438. if t.is_Pow and t.exp.is_integer and t.exp.is_negative:
  439. bnew = cls(t.base)
  440. if isinstance(bnew, cls):
  441. unk.append(t)
  442. else:
  443. known.append(Pow(bnew, t.exp))
  444. else:
  445. tnew = cls(t)
  446. if isinstance(tnew, cls):
  447. unk.append(t)
  448. else:
  449. known.append(tnew)
  450. known = Mul(*known)
  451. unk = cls(Mul(*unk), evaluate=False) if unk else S.One
  452. return known*unk
  453. if arg is S.NaN:
  454. return S.NaN
  455. if arg is S.ComplexInfinity:
  456. return S.Infinity
  457. if arg.is_Pow:
  458. base, exponent = arg.as_base_exp()
  459. if base.is_extended_real:
  460. if exponent.is_integer:
  461. if exponent.is_even:
  462. return arg
  463. if base is S.NegativeOne:
  464. return S.One
  465. return Abs(base)**exponent
  466. if base.is_extended_nonnegative:
  467. return base**re(exponent)
  468. if base.is_extended_negative:
  469. return (-base)**re(exponent)*exp(-S.Pi*im(exponent))
  470. return
  471. elif not base.has(Symbol): # complex base
  472. # express base**exponent as exp(exponent*log(base))
  473. a, b = log(base).as_real_imag()
  474. z = a + I*b
  475. return exp(re(exponent*z))
  476. if isinstance(arg, exp):
  477. return exp(re(arg.args[0]))
  478. if isinstance(arg, AppliedUndef):
  479. if arg.is_positive:
  480. return arg
  481. elif arg.is_negative:
  482. return -arg
  483. return
  484. if arg.is_Add and arg.has(S.Infinity, S.NegativeInfinity):
  485. if any(a.is_infinite for a in arg.as_real_imag()):
  486. return S.Infinity
  487. if arg.is_zero:
  488. return S.Zero
  489. if arg.is_extended_nonnegative:
  490. return arg
  491. if arg.is_extended_nonpositive:
  492. return -arg
  493. if arg.is_imaginary:
  494. arg2 = -S.ImaginaryUnit * arg
  495. if arg2.is_extended_nonnegative:
  496. return arg2
  497. if arg.is_extended_real:
  498. return
  499. # reject result if all new conjugates are just wrappers around
  500. # an expression that was already in the arg
  501. conj = signsimp(arg.conjugate(), evaluate=False)
  502. new_conj = conj.atoms(conjugate) - arg.atoms(conjugate)
  503. if new_conj and all(arg.has(i.args[0]) for i in new_conj):
  504. return
  505. if arg != conj and arg != -conj:
  506. ignore = arg.atoms(Abs)
  507. abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore})
  508. unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None]
  509. if not unk or not all(conj.has(conjugate(u)) for u in unk):
  510. return sqrt(expand_mul(arg*conj))
  511. def _eval_is_real(self):
  512. if self.args[0].is_finite:
  513. return True
  514. def _eval_is_integer(self):
  515. if self.args[0].is_extended_real:
  516. return self.args[0].is_integer
  517. def _eval_is_extended_nonzero(self):
  518. return fuzzy_not(self._args[0].is_zero)
  519. def _eval_is_zero(self):
  520. return self._args[0].is_zero
  521. def _eval_is_extended_positive(self):
  522. is_z = self.is_zero
  523. if is_z is not None:
  524. return not is_z
  525. def _eval_is_rational(self):
  526. if self.args[0].is_extended_real:
  527. return self.args[0].is_rational
  528. def _eval_is_even(self):
  529. if self.args[0].is_extended_real:
  530. return self.args[0].is_even
  531. def _eval_is_odd(self):
  532. if self.args[0].is_extended_real:
  533. return self.args[0].is_odd
  534. def _eval_is_algebraic(self):
  535. return self.args[0].is_algebraic
  536. def _eval_power(self, exponent):
  537. if self.args[0].is_extended_real and exponent.is_integer:
  538. if exponent.is_even:
  539. return self.args[0]**exponent
  540. elif exponent is not S.NegativeOne and exponent.is_Integer:
  541. return self.args[0]**(exponent - 1)*self
  542. return
  543. def _eval_nseries(self, x, n, logx, cdir=0):
  544. direction = self.args[0].leadterm(x)[0]
  545. if direction.has(log(x)):
  546. direction = direction.subs(log(x), logx)
  547. s = self.args[0]._eval_nseries(x, n=n, logx=logx)
  548. return (sign(direction)*s).expand()
  549. def _eval_derivative(self, x):
  550. if self.args[0].is_extended_real or self.args[0].is_imaginary:
  551. return Derivative(self.args[0], x, evaluate=True) \
  552. * sign(conjugate(self.args[0]))
  553. rv = (re(self.args[0]) * Derivative(re(self.args[0]), x,
  554. evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]),
  555. x, evaluate=True)) / Abs(self.args[0])
  556. return rv.rewrite(sign)
  557. def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
  558. # Note this only holds for real arg (since Heaviside is not defined
  559. # for complex arguments).
  560. from sympy.functions.special.delta_functions import Heaviside
  561. if arg.is_extended_real:
  562. return arg*(Heaviside(arg) - Heaviside(-arg))
  563. def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
  564. if arg.is_extended_real:
  565. return Piecewise((arg, arg >= 0), (-arg, True))
  566. elif arg.is_imaginary:
  567. return Piecewise((I*arg, I*arg >= 0), (-I*arg, True))
  568. def _eval_rewrite_as_sign(self, arg, **kwargs):
  569. return arg/sign(arg)
  570. def _eval_rewrite_as_conjugate(self, arg, **kwargs):
  571. return (arg*conjugate(arg))**S.Half
  572. class arg(Function):
  573. r"""
  574. Returns the argument (in radians) of a complex number. The argument is
  575. evaluated in consistent convention with ``atan2`` where the branch-cut is
  576. taken along the negative real axis and ``arg(z)`` is in the interval
  577. $(-\pi,\pi]$. For a positive number, the argument is always 0; the
  578. argument of a negative number is $\pi$; and the argument of 0
  579. is undefined and returns ``nan``. So the ``arg`` function will never nest
  580. greater than 3 levels since at the 4th application, the result must be
  581. nan; for a real number, nan is returned on the 3rd application.
  582. Examples
  583. ========
  584. >>> from sympy import arg, I, sqrt, Dummy
  585. >>> from sympy.abc import x
  586. >>> arg(2.0)
  587. 0
  588. >>> arg(I)
  589. pi/2
  590. >>> arg(sqrt(2) + I*sqrt(2))
  591. pi/4
  592. >>> arg(sqrt(3)/2 + I/2)
  593. pi/6
  594. >>> arg(4 + 3*I)
  595. atan(3/4)
  596. >>> arg(0.8 + 0.6*I)
  597. 0.643501108793284
  598. >>> arg(arg(arg(arg(x))))
  599. nan
  600. >>> real = Dummy(real=True)
  601. >>> arg(arg(arg(real)))
  602. nan
  603. Parameters
  604. ==========
  605. arg : Expr
  606. Real or complex expression.
  607. Returns
  608. =======
  609. value : Expr
  610. Returns arc tangent of arg measured in radians.
  611. """
  612. is_extended_real = True
  613. is_real = True
  614. is_finite = True
  615. _singularities = True # non-holomorphic
  616. @classmethod
  617. def eval(cls, arg):
  618. a = arg
  619. for i in range(3):
  620. if isinstance(a, cls):
  621. a = a.args[0]
  622. else:
  623. if i == 2 and a.is_extended_real:
  624. return S.NaN
  625. break
  626. else:
  627. return S.NaN
  628. if isinstance(arg, exp_polar):
  629. return periodic_argument(arg, oo)
  630. if not arg.is_Atom:
  631. c, arg_ = factor_terms(arg).as_coeff_Mul()
  632. if arg_.is_Mul:
  633. arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
  634. sign(a) for a in arg_.args])
  635. arg_ = sign(c)*arg_
  636. else:
  637. arg_ = arg
  638. if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):
  639. return
  640. x, y = arg_.as_real_imag()
  641. rv = atan2(y, x)
  642. if rv.is_number:
  643. return rv
  644. if arg_ != arg:
  645. return cls(arg_, evaluate=False)
  646. def _eval_derivative(self, t):
  647. x, y = self.args[0].as_real_imag()
  648. return (x * Derivative(y, t, evaluate=True) - y *
  649. Derivative(x, t, evaluate=True)) / (x**2 + y**2)
  650. def _eval_rewrite_as_atan2(self, arg, **kwargs):
  651. x, y = self.args[0].as_real_imag()
  652. return atan2(y, x)
  653. class conjugate(Function):
  654. """
  655. Returns the *complex conjugate* [1]_ of an argument.
  656. In mathematics, the complex conjugate of a complex number
  657. is given by changing the sign of the imaginary part.
  658. Thus, the conjugate of the complex number
  659. :math:`a + ib` (where $a$ and $b$ are real numbers) is :math:`a - ib`
  660. Examples
  661. ========
  662. >>> from sympy import conjugate, I
  663. >>> conjugate(2)
  664. 2
  665. >>> conjugate(I)
  666. -I
  667. >>> conjugate(3 + 2*I)
  668. 3 - 2*I
  669. >>> conjugate(5 - I)
  670. 5 + I
  671. Parameters
  672. ==========
  673. arg : Expr
  674. Real or complex expression.
  675. Returns
  676. =======
  677. arg : Expr
  678. Complex conjugate of arg as real, imaginary or mixed expression.
  679. See Also
  680. ========
  681. sign, Abs
  682. References
  683. ==========
  684. .. [1] https://en.wikipedia.org/wiki/Complex_conjugation
  685. """
  686. _singularities = True # non-holomorphic
  687. @classmethod
  688. def eval(cls, arg):
  689. obj = arg._eval_conjugate()
  690. if obj is not None:
  691. return obj
  692. def inverse(self):
  693. return conjugate
  694. def _eval_Abs(self):
  695. return Abs(self.args[0], evaluate=True)
  696. def _eval_adjoint(self):
  697. return transpose(self.args[0])
  698. def _eval_conjugate(self):
  699. return self.args[0]
  700. def _eval_derivative(self, x):
  701. if x.is_real:
  702. return conjugate(Derivative(self.args[0], x, evaluate=True))
  703. elif x.is_imaginary:
  704. return -conjugate(Derivative(self.args[0], x, evaluate=True))
  705. def _eval_transpose(self):
  706. return adjoint(self.args[0])
  707. def _eval_is_algebraic(self):
  708. return self.args[0].is_algebraic
  709. class transpose(Function):
  710. """
  711. Linear map transposition.
  712. Examples
  713. ========
  714. >>> from sympy import transpose, Matrix, MatrixSymbol
  715. >>> A = MatrixSymbol('A', 25, 9)
  716. >>> transpose(A)
  717. A.T
  718. >>> B = MatrixSymbol('B', 9, 22)
  719. >>> transpose(B)
  720. B.T
  721. >>> transpose(A*B)
  722. B.T*A.T
  723. >>> M = Matrix([[4, 5], [2, 1], [90, 12]])
  724. >>> M
  725. Matrix([
  726. [ 4, 5],
  727. [ 2, 1],
  728. [90, 12]])
  729. >>> transpose(M)
  730. Matrix([
  731. [4, 2, 90],
  732. [5, 1, 12]])
  733. Parameters
  734. ==========
  735. arg : Matrix
  736. Matrix or matrix expression to take the transpose of.
  737. Returns
  738. =======
  739. value : Matrix
  740. Transpose of arg.
  741. """
  742. @classmethod
  743. def eval(cls, arg):
  744. obj = arg._eval_transpose()
  745. if obj is not None:
  746. return obj
  747. def _eval_adjoint(self):
  748. return conjugate(self.args[0])
  749. def _eval_conjugate(self):
  750. return adjoint(self.args[0])
  751. def _eval_transpose(self):
  752. return self.args[0]
  753. class adjoint(Function):
  754. """
  755. Conjugate transpose or Hermite conjugation.
  756. Examples
  757. ========
  758. >>> from sympy import adjoint, MatrixSymbol
  759. >>> A = MatrixSymbol('A', 10, 5)
  760. >>> adjoint(A)
  761. Adjoint(A)
  762. Parameters
  763. ==========
  764. arg : Matrix
  765. Matrix or matrix expression to take the adjoint of.
  766. Returns
  767. =======
  768. value : Matrix
  769. Represents the conjugate transpose or Hermite
  770. conjugation of arg.
  771. """
  772. @classmethod
  773. def eval(cls, arg):
  774. obj = arg._eval_adjoint()
  775. if obj is not None:
  776. return obj
  777. obj = arg._eval_transpose()
  778. if obj is not None:
  779. return conjugate(obj)
  780. def _eval_adjoint(self):
  781. return self.args[0]
  782. def _eval_conjugate(self):
  783. return transpose(self.args[0])
  784. def _eval_transpose(self):
  785. return conjugate(self.args[0])
  786. def _latex(self, printer, exp=None, *args):
  787. arg = printer._print(self.args[0])
  788. tex = r'%s^{\dagger}' % arg
  789. if exp:
  790. tex = r'\left(%s\right)^{%s}' % (tex, exp)
  791. return tex
  792. def _pretty(self, printer, *args):
  793. from sympy.printing.pretty.stringpict import prettyForm
  794. pform = printer._print(self.args[0], *args)
  795. if printer._use_unicode:
  796. pform = pform**prettyForm('\N{DAGGER}')
  797. else:
  798. pform = pform**prettyForm('+')
  799. return pform
  800. ###############################################################################
  801. ############### HANDLING OF POLAR NUMBERS #####################################
  802. ###############################################################################
  803. class polar_lift(Function):
  804. """
  805. Lift argument to the Riemann surface of the logarithm, using the
  806. standard branch.
  807. Examples
  808. ========
  809. >>> from sympy import Symbol, polar_lift, I
  810. >>> p = Symbol('p', polar=True)
  811. >>> x = Symbol('x')
  812. >>> polar_lift(4)
  813. 4*exp_polar(0)
  814. >>> polar_lift(-4)
  815. 4*exp_polar(I*pi)
  816. >>> polar_lift(-I)
  817. exp_polar(-I*pi/2)
  818. >>> polar_lift(I + 2)
  819. polar_lift(2 + I)
  820. >>> polar_lift(4*x)
  821. 4*polar_lift(x)
  822. >>> polar_lift(4*p)
  823. 4*p
  824. Parameters
  825. ==========
  826. arg : Expr
  827. Real or complex expression.
  828. See Also
  829. ========
  830. sympy.functions.elementary.exponential.exp_polar
  831. periodic_argument
  832. """
  833. is_polar = True
  834. is_comparable = False # Cannot be evalf'd.
  835. @classmethod
  836. def eval(cls, arg):
  837. from sympy.functions.elementary.complexes import arg as argument
  838. if arg.is_number:
  839. ar = argument(arg)
  840. # In general we want to affirm that something is known,
  841. # e.g. `not ar.has(argument) and not ar.has(atan)`
  842. # but for now we will just be more restrictive and
  843. # see that it has evaluated to one of the known values.
  844. if ar in (0, pi/2, -pi/2, pi):
  845. return exp_polar(I*ar)*abs(arg)
  846. if arg.is_Mul:
  847. args = arg.args
  848. else:
  849. args = [arg]
  850. included = []
  851. excluded = []
  852. positive = []
  853. for arg in args:
  854. if arg.is_polar:
  855. included += [arg]
  856. elif arg.is_positive:
  857. positive += [arg]
  858. else:
  859. excluded += [arg]
  860. if len(excluded) < len(args):
  861. if excluded:
  862. return Mul(*(included + positive))*polar_lift(Mul(*excluded))
  863. elif included:
  864. return Mul(*(included + positive))
  865. else:
  866. return Mul(*positive)*exp_polar(0)
  867. def _eval_evalf(self, prec):
  868. """ Careful! any evalf of polar numbers is flaky """
  869. return self.args[0]._eval_evalf(prec)
  870. def _eval_Abs(self):
  871. return Abs(self.args[0], evaluate=True)
  872. class periodic_argument(Function):
  873. r"""
  874. Represent the argument on a quotient of the Riemann surface of the
  875. logarithm. That is, given a period $P$, always return a value in
  876. $(-P/2, P/2]$, by using $\exp(PI) = 1$.
  877. Examples
  878. ========
  879. >>> from sympy import exp_polar, periodic_argument
  880. >>> from sympy import I, pi
  881. >>> periodic_argument(exp_polar(10*I*pi), 2*pi)
  882. 0
  883. >>> periodic_argument(exp_polar(5*I*pi), 4*pi)
  884. pi
  885. >>> from sympy import exp_polar, periodic_argument
  886. >>> from sympy import I, pi
  887. >>> periodic_argument(exp_polar(5*I*pi), 2*pi)
  888. pi
  889. >>> periodic_argument(exp_polar(5*I*pi), 3*pi)
  890. -pi
  891. >>> periodic_argument(exp_polar(5*I*pi), pi)
  892. 0
  893. Parameters
  894. ==========
  895. ar : Expr
  896. A polar number.
  897. period : Expr
  898. The period $P$.
  899. See Also
  900. ========
  901. sympy.functions.elementary.exponential.exp_polar
  902. polar_lift : Lift argument to the Riemann surface of the logarithm
  903. principal_branch
  904. """
  905. @classmethod
  906. def _getunbranched(cls, ar):
  907. if ar.is_Mul:
  908. args = ar.args
  909. else:
  910. args = [ar]
  911. unbranched = 0
  912. for a in args:
  913. if not a.is_polar:
  914. unbranched += arg(a)
  915. elif isinstance(a, exp_polar):
  916. unbranched += a.exp.as_real_imag()[1]
  917. elif a.is_Pow:
  918. re, im = a.exp.as_real_imag()
  919. unbranched += re*unbranched_argument(
  920. a.base) + im*log(abs(a.base))
  921. elif isinstance(a, polar_lift):
  922. unbranched += arg(a.args[0])
  923. else:
  924. return None
  925. return unbranched
  926. @classmethod
  927. def eval(cls, ar, period):
  928. # Our strategy is to evaluate the argument on the Riemann surface of the
  929. # logarithm, and then reduce.
  930. # NOTE evidently this means it is a rather bad idea to use this with
  931. # period != 2*pi and non-polar numbers.
  932. if not period.is_extended_positive:
  933. return None
  934. if period == oo and isinstance(ar, principal_branch):
  935. return periodic_argument(*ar.args)
  936. if isinstance(ar, polar_lift) and period >= 2*pi:
  937. return periodic_argument(ar.args[0], period)
  938. if ar.is_Mul:
  939. newargs = [x for x in ar.args if not x.is_positive]
  940. if len(newargs) != len(ar.args):
  941. return periodic_argument(Mul(*newargs), period)
  942. unbranched = cls._getunbranched(ar)
  943. if unbranched is None:
  944. return None
  945. if unbranched.has(periodic_argument, atan2, atan):
  946. return None
  947. if period == oo:
  948. return unbranched
  949. if period != oo:
  950. n = ceiling(unbranched/period - S.Half)*period
  951. if not n.has(ceiling):
  952. return unbranched - n
  953. def _eval_evalf(self, prec):
  954. z, period = self.args
  955. if period == oo:
  956. unbranched = periodic_argument._getunbranched(z)
  957. if unbranched is None:
  958. return self
  959. return unbranched._eval_evalf(prec)
  960. ub = periodic_argument(z, oo)._eval_evalf(prec)
  961. return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec)
  962. def unbranched_argument(arg):
  963. '''
  964. Returns periodic argument of arg with period as infinity.
  965. Examples
  966. ========
  967. >>> from sympy import exp_polar, unbranched_argument
  968. >>> from sympy import I, pi
  969. >>> unbranched_argument(exp_polar(15*I*pi))
  970. 15*pi
  971. >>> unbranched_argument(exp_polar(7*I*pi))
  972. 7*pi
  973. See also
  974. ========
  975. periodic_argument
  976. '''
  977. return periodic_argument(arg, oo)
  978. class principal_branch(Function):
  979. """
  980. Represent a polar number reduced to its principal branch on a quotient
  981. of the Riemann surface of the logarithm.
  982. Explanation
  983. ===========
  984. This is a function of two arguments. The first argument is a polar
  985. number `z`, and the second one a positive real number or infinity, `p`.
  986. The result is ``z mod exp_polar(I*p)``.
  987. Examples
  988. ========
  989. >>> from sympy import exp_polar, principal_branch, oo, I, pi
  990. >>> from sympy.abc import z
  991. >>> principal_branch(z, oo)
  992. z
  993. >>> principal_branch(exp_polar(2*pi*I)*3, 2*pi)
  994. 3*exp_polar(0)
  995. >>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi)
  996. 3*principal_branch(z, 2*pi)
  997. Parameters
  998. ==========
  999. x : Expr
  1000. A polar number.
  1001. period : Expr
  1002. Positive real number or infinity.
  1003. See Also
  1004. ========
  1005. sympy.functions.elementary.exponential.exp_polar
  1006. polar_lift : Lift argument to the Riemann surface of the logarithm
  1007. periodic_argument
  1008. """
  1009. is_polar = True
  1010. is_comparable = False # cannot always be evalf'd
  1011. @classmethod
  1012. def eval(self, x, period):
  1013. if isinstance(x, polar_lift):
  1014. return principal_branch(x.args[0], period)
  1015. if period == oo:
  1016. return x
  1017. ub = periodic_argument(x, oo)
  1018. barg = periodic_argument(x, period)
  1019. if ub != barg and not ub.has(periodic_argument) \
  1020. and not barg.has(periodic_argument):
  1021. pl = polar_lift(x)
  1022. def mr(expr):
  1023. if not isinstance(expr, Symbol):
  1024. return polar_lift(expr)
  1025. return expr
  1026. pl = pl.replace(polar_lift, mr)
  1027. # Recompute unbranched argument
  1028. ub = periodic_argument(pl, oo)
  1029. if not pl.has(polar_lift):
  1030. if ub != barg:
  1031. res = exp_polar(I*(barg - ub))*pl
  1032. else:
  1033. res = pl
  1034. if not res.is_polar and not res.has(exp_polar):
  1035. res *= exp_polar(0)
  1036. return res
  1037. if not x.free_symbols:
  1038. c, m = x, ()
  1039. else:
  1040. c, m = x.as_coeff_mul(*x.free_symbols)
  1041. others = []
  1042. for y in m:
  1043. if y.is_positive:
  1044. c *= y
  1045. else:
  1046. others += [y]
  1047. m = tuple(others)
  1048. arg = periodic_argument(c, period)
  1049. if arg.has(periodic_argument):
  1050. return None
  1051. if arg.is_number and (unbranched_argument(c) != arg or
  1052. (arg == 0 and m != () and c != 1)):
  1053. if arg == 0:
  1054. return abs(c)*principal_branch(Mul(*m), period)
  1055. return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c)
  1056. if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \
  1057. and m == ():
  1058. return exp_polar(arg*I)*abs(c)
  1059. def _eval_evalf(self, prec):
  1060. z, period = self.args
  1061. p = periodic_argument(z, period)._eval_evalf(prec)
  1062. if abs(p) > pi or p == -pi:
  1063. return self # Cannot evalf for this argument.
  1064. return (abs(z)*exp(I*p))._eval_evalf(prec)
  1065. def _polarify(eq, lift, pause=False):
  1066. from sympy.integrals.integrals import Integral
  1067. if eq.is_polar:
  1068. return eq
  1069. if eq.is_number and not pause:
  1070. return polar_lift(eq)
  1071. if isinstance(eq, Symbol) and not pause and lift:
  1072. return polar_lift(eq)
  1073. elif eq.is_Atom:
  1074. return eq
  1075. elif eq.is_Add:
  1076. r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args])
  1077. if lift:
  1078. return polar_lift(r)
  1079. return r
  1080. elif eq.is_Pow and eq.base == S.Exp1:
  1081. return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False))
  1082. elif eq.is_Function:
  1083. return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args])
  1084. elif isinstance(eq, Integral):
  1085. # Don't lift the integration variable
  1086. func = _polarify(eq.function, lift, pause=pause)
  1087. limits = []
  1088. for limit in eq.args[1:]:
  1089. var = _polarify(limit[0], lift=False, pause=pause)
  1090. rest = _polarify(limit[1:], lift=lift, pause=pause)
  1091. limits.append((var,) + rest)
  1092. return Integral(*((func,) + tuple(limits)))
  1093. else:
  1094. return eq.func(*[_polarify(arg, lift, pause=pause)
  1095. if isinstance(arg, Expr) else arg for arg in eq.args])
  1096. def polarify(eq, subs=True, lift=False):
  1097. """
  1098. Turn all numbers in eq into their polar equivalents (under the standard
  1099. choice of argument).
  1100. Note that no attempt is made to guess a formal convention of adding
  1101. polar numbers, expressions like $1 + x$ will generally not be altered.
  1102. Note also that this function does not promote ``exp(x)`` to ``exp_polar(x)``.
  1103. If ``subs`` is ``True``, all symbols which are not already polar will be
  1104. substituted for polar dummies; in this case the function behaves much
  1105. like :func:`~.posify`.
  1106. If ``lift`` is ``True``, both addition statements and non-polar symbols are
  1107. changed to their ``polar_lift()``ed versions.
  1108. Note that ``lift=True`` implies ``subs=False``.
  1109. Examples
  1110. ========
  1111. >>> from sympy import polarify, sin, I
  1112. >>> from sympy.abc import x, y
  1113. >>> expr = (-x)**y
  1114. >>> expr.expand()
  1115. (-x)**y
  1116. >>> polarify(expr)
  1117. ((_x*exp_polar(I*pi))**_y, {_x: x, _y: y})
  1118. >>> polarify(expr)[0].expand()
  1119. _x**_y*exp_polar(_y*I*pi)
  1120. >>> polarify(x, lift=True)
  1121. polar_lift(x)
  1122. >>> polarify(x*(1+y), lift=True)
  1123. polar_lift(x)*polar_lift(y + 1)
  1124. Adds are treated carefully:
  1125. >>> polarify(1 + sin((1 + I)*x))
  1126. (sin(_x*polar_lift(1 + I)) + 1, {_x: x})
  1127. """
  1128. if lift:
  1129. subs = False
  1130. eq = _polarify(sympify(eq), lift)
  1131. if not subs:
  1132. return eq
  1133. reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols}
  1134. eq = eq.subs(reps)
  1135. return eq, {r: s for s, r in reps.items()}
  1136. def _unpolarify(eq, exponents_only, pause=False):
  1137. if not isinstance(eq, Basic) or eq.is_Atom:
  1138. return eq
  1139. if not pause:
  1140. if isinstance(eq, exp_polar):
  1141. return exp(_unpolarify(eq.exp, exponents_only))
  1142. if isinstance(eq, principal_branch) and eq.args[1] == 2*pi:
  1143. return _unpolarify(eq.args[0], exponents_only)
  1144. if (
  1145. eq.is_Add or eq.is_Mul or eq.is_Boolean or
  1146. eq.is_Relational and (
  1147. eq.rel_op in ('==', '!=') and 0 in eq.args or
  1148. eq.rel_op not in ('==', '!='))
  1149. ):
  1150. return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args])
  1151. if isinstance(eq, polar_lift):
  1152. return _unpolarify(eq.args[0], exponents_only)
  1153. if eq.is_Pow:
  1154. expo = _unpolarify(eq.exp, exponents_only)
  1155. base = _unpolarify(eq.base, exponents_only,
  1156. not (expo.is_integer and not pause))
  1157. return base**expo
  1158. if eq.is_Function and getattr(eq.func, 'unbranched', False):
  1159. return eq.func(*[_unpolarify(x, exponents_only, exponents_only)
  1160. for x in eq.args])
  1161. return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args])
  1162. def unpolarify(eq, subs=None, exponents_only=False):
  1163. """
  1164. If `p` denotes the projection from the Riemann surface of the logarithm to
  1165. the complex line, return a simplified version `eq'` of `eq` such that
  1166. `p(eq') = p(eq)`.
  1167. Also apply the substitution subs in the end. (This is a convenience, since
  1168. ``unpolarify``, in a certain sense, undoes :func:`polarify`.)
  1169. Examples
  1170. ========
  1171. >>> from sympy import unpolarify, polar_lift, sin, I
  1172. >>> unpolarify(polar_lift(I + 2))
  1173. 2 + I
  1174. >>> unpolarify(sin(polar_lift(I + 7)))
  1175. sin(7 + I)
  1176. """
  1177. if isinstance(eq, bool):
  1178. return eq
  1179. eq = sympify(eq)
  1180. if subs is not None:
  1181. return unpolarify(eq.subs(subs))
  1182. changed = True
  1183. pause = False
  1184. if exponents_only:
  1185. pause = True
  1186. while changed:
  1187. changed = False
  1188. res = _unpolarify(eq, exponents_only, pause)
  1189. if res != eq:
  1190. changed = True
  1191. eq = res
  1192. if isinstance(res, bool):
  1193. return res
  1194. # Finally, replacing Exp(0) by 1 is always correct.
  1195. # So is polar_lift(0) -> 0.
  1196. return res.subs({exp_polar(0): 1, polar_lift(0): 0})