bivariate.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. from sympy.core.add import Add
  2. from sympy.core.exprtools import factor_terms
  3. from sympy.core.function import expand_log, _mexpand
  4. from sympy.core.power import Pow
  5. from sympy.core.singleton import S
  6. from sympy.core.sorting import ordered
  7. from sympy.core.symbol import Dummy
  8. from sympy.functions.elementary.exponential import (LambertW, exp, log)
  9. from sympy.functions.elementary.miscellaneous import root
  10. from sympy.polys.polyroots import roots
  11. from sympy.polys.polytools import Poly, factor
  12. from sympy.simplify.simplify import separatevars
  13. from sympy.simplify.radsimp import collect
  14. from sympy.simplify.simplify import powsimp
  15. from sympy.solvers.solvers import solve, _invert
  16. from sympy.utilities.iterables import uniq
  17. def _filtered_gens(poly, symbol):
  18. """process the generators of ``poly``, returning the set of generators that
  19. have ``symbol``. If there are two generators that are inverses of each other,
  20. prefer the one that has no denominator.
  21. Examples
  22. ========
  23. >>> from sympy.solvers.bivariate import _filtered_gens
  24. >>> from sympy import Poly, exp
  25. >>> from sympy.abc import x
  26. >>> _filtered_gens(Poly(x + 1/x + exp(x)), x)
  27. {x, exp(x)}
  28. """
  29. gens = {g for g in poly.gens if symbol in g.free_symbols}
  30. for g in list(gens):
  31. ag = 1/g
  32. if g in gens and ag in gens:
  33. if ag.as_numer_denom()[1] is not S.One:
  34. g = ag
  35. gens.remove(g)
  36. return gens
  37. def _mostfunc(lhs, func, X=None):
  38. """Returns the term in lhs which contains the most of the
  39. func-type things e.g. log(log(x)) wins over log(x) if both terms appear.
  40. ``func`` can be a function (exp, log, etc...) or any other SymPy object,
  41. like Pow.
  42. If ``X`` is not ``None``, then the function returns the term composed with the
  43. most ``func`` having the specified variable.
  44. Examples
  45. ========
  46. >>> from sympy.solvers.bivariate import _mostfunc
  47. >>> from sympy import exp
  48. >>> from sympy.abc import x, y
  49. >>> _mostfunc(exp(x) + exp(exp(x) + 2), exp)
  50. exp(exp(x) + 2)
  51. >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp)
  52. exp(exp(y) + 2)
  53. >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x)
  54. exp(x)
  55. >>> _mostfunc(x, exp, x) is None
  56. True
  57. >>> _mostfunc(exp(x) + exp(x*y), exp, x)
  58. exp(x)
  59. """
  60. fterms = [tmp for tmp in lhs.atoms(func) if (not X or
  61. X.is_Symbol and X in tmp.free_symbols or
  62. not X.is_Symbol and tmp.has(X))]
  63. if len(fterms) == 1:
  64. return fterms[0]
  65. elif fterms:
  66. return max(list(ordered(fterms)), key=lambda x: x.count(func))
  67. return None
  68. def _linab(arg, symbol):
  69. """Return ``a, b, X`` assuming ``arg`` can be written as ``a*X + b``
  70. where ``X`` is a symbol-dependent factor and ``a`` and ``b`` are
  71. independent of ``symbol``.
  72. Examples
  73. ========
  74. >>> from sympy.solvers.bivariate import _linab
  75. >>> from sympy.abc import x, y
  76. >>> from sympy import exp, S
  77. >>> _linab(S(2), x)
  78. (2, 0, 1)
  79. >>> _linab(2*x, x)
  80. (2, 0, x)
  81. >>> _linab(y + y*x + 2*x, x)
  82. (y + 2, y, x)
  83. >>> _linab(3 + 2*exp(x), x)
  84. (2, 3, exp(x))
  85. """
  86. arg = factor_terms(arg.expand())
  87. ind, dep = arg.as_independent(symbol)
  88. if arg.is_Mul and dep.is_Add:
  89. a, b, x = _linab(dep, symbol)
  90. return ind*a, ind*b, x
  91. if not arg.is_Add:
  92. b = 0
  93. a, x = ind, dep
  94. else:
  95. b = ind
  96. a, x = separatevars(dep).as_independent(symbol, as_Add=False)
  97. if x.could_extract_minus_sign():
  98. a = -a
  99. x = -x
  100. return a, b, x
  101. def _lambert(eq, x):
  102. """
  103. Given an expression assumed to be in the form
  104. ``F(X, a..f) = a*log(b*X + c) + d*X + f = 0``
  105. where X = g(x) and x = g^-1(X), return the Lambert solution,
  106. ``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``.
  107. """
  108. eq = _mexpand(expand_log(eq))
  109. mainlog = _mostfunc(eq, log, x)
  110. if not mainlog:
  111. return [] # violated assumptions
  112. other = eq.subs(mainlog, 0)
  113. if isinstance(-other, log):
  114. eq = (eq - other).subs(mainlog, mainlog.args[0])
  115. mainlog = mainlog.args[0]
  116. if not isinstance(mainlog, log):
  117. return [] # violated assumptions
  118. other = -(-other).args[0]
  119. eq += other
  120. if x not in other.free_symbols:
  121. return [] # violated assumptions
  122. d, f, X2 = _linab(other, x)
  123. logterm = collect(eq - other, mainlog)
  124. a = logterm.as_coefficient(mainlog)
  125. if a is None or x in a.free_symbols:
  126. return [] # violated assumptions
  127. logarg = mainlog.args[0]
  128. b, c, X1 = _linab(logarg, x)
  129. if X1 != X2:
  130. return [] # violated assumptions
  131. # invert the generator X1 so we have x(u)
  132. u = Dummy('rhs')
  133. xusolns = solve(X1 - u, x)
  134. # There are infinitely many branches for LambertW
  135. # but only branches for k = -1 and 0 might be real. The k = 0
  136. # branch is real and the k = -1 branch is real if the LambertW argumen
  137. # in in range [-1/e, 0]. Since `solve` does not return infinite
  138. # solutions we will only include the -1 branch if it tests as real.
  139. # Otherwise, inclusion of any LambertW in the solution indicates to
  140. # the user that there are imaginary solutions corresponding to
  141. # different k values.
  142. lambert_real_branches = [-1, 0]
  143. sol = []
  144. # solution of the given Lambert equation is like
  145. # sol = -c/b + (a/d)*LambertW(arg, k),
  146. # where arg = d/(a*b)*exp((c*d-b*f)/a/b) and k in lambert_real_branches.
  147. # Instead of considering the single arg, `d/(a*b)*exp((c*d-b*f)/a/b)`,
  148. # the individual `p` roots obtained when writing `exp((c*d-b*f)/a/b)`
  149. # as `exp(A/p) = exp(A)**(1/p)`, where `p` is an Integer, are used.
  150. # calculating args for LambertW
  151. num, den = ((c*d-b*f)/a/b).as_numer_denom()
  152. p, den = den.as_coeff_Mul()
  153. e = exp(num/den)
  154. t = Dummy('t')
  155. args = [d/(a*b)*t for t in roots(t**p - e, t).keys()]
  156. # calculating solutions from args
  157. for arg in args:
  158. for k in lambert_real_branches:
  159. w = LambertW(arg, k)
  160. if k and not w.is_real:
  161. continue
  162. rhs = -c/b + (a/d)*w
  163. for xu in xusolns:
  164. sol.append(xu.subs(u, rhs))
  165. return sol
  166. def _solve_lambert(f, symbol, gens):
  167. """Return solution to ``f`` if it is a Lambert-type expression
  168. else raise NotImplementedError.
  169. For ``f(X, a..f) = a*log(b*X + c) + d*X - f = 0`` the solution
  170. for ``X`` is ``X = -c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(f/a))``.
  171. There are a variety of forms for `f(X, a..f)` as enumerated below:
  172. 1a1)
  173. if B**B = R for R not in [0, 1] (since those cases would already
  174. be solved before getting here) then log of both sides gives
  175. log(B) + log(log(B)) = log(log(R)) and
  176. X = log(B), a = 1, b = 1, c = 0, d = 1, f = log(log(R))
  177. 1a2)
  178. if B*(b*log(B) + c)**a = R then log of both sides gives
  179. log(B) + a*log(b*log(B) + c) = log(R) and
  180. X = log(B), d=1, f=log(R)
  181. 1b)
  182. if a*log(b*B + c) + d*B = R and
  183. X = B, f = R
  184. 2a)
  185. if (b*B + c)*exp(d*B + g) = R then log of both sides gives
  186. log(b*B + c) + d*B + g = log(R) and
  187. X = B, a = 1, f = log(R) - g
  188. 2b)
  189. if g*exp(d*B + h) - b*B = c then the log form is
  190. log(g) + d*B + h - log(b*B + c) = 0 and
  191. X = B, a = -1, f = -h - log(g)
  192. 3)
  193. if d*p**(a*B + g) - b*B = c then the log form is
  194. log(d) + (a*B + g)*log(p) - log(b*B + c) = 0 and
  195. X = B, a = -1, d = a*log(p), f = -log(d) - g*log(p)
  196. """
  197. def _solve_even_degree_expr(expr, t, symbol):
  198. """Return the unique solutions of equations derived from
  199. ``expr`` by replacing ``t`` with ``+/- symbol``.
  200. Parameters
  201. ==========
  202. expr : Expr
  203. The expression which includes a dummy variable t to be
  204. replaced with +symbol and -symbol.
  205. symbol : Symbol
  206. The symbol for which a solution is being sought.
  207. Returns
  208. =======
  209. List of unique solution of the two equations generated by
  210. replacing ``t`` with positive and negative ``symbol``.
  211. Notes
  212. =====
  213. If ``expr = 2*log(t) + x/2` then solutions for
  214. ``2*log(x) + x/2 = 0`` and ``2*log(-x) + x/2 = 0`` are
  215. returned by this function. Though this may seem
  216. counter-intuitive, one must note that the ``expr`` being
  217. solved here has been derived from a different expression. For
  218. an expression like ``eq = x**2*g(x) = 1``, if we take the
  219. log of both sides we obtain ``log(x**2) + log(g(x)) = 0``. If
  220. x is positive then this simplifies to
  221. ``2*log(x) + log(g(x)) = 0``; the Lambert-solving routines will
  222. return solutions for this, but we must also consider the
  223. solutions for ``2*log(-x) + log(g(x))`` since those must also
  224. be a solution of ``eq`` which has the same value when the ``x``
  225. in ``x**2`` is negated. If `g(x)` does not have even powers of
  226. symbol then we do not want to replace the ``x`` there with
  227. ``-x``. So the role of the ``t`` in the expression received by
  228. this function is to mark where ``+/-x`` should be inserted
  229. before obtaining the Lambert solutions.
  230. """
  231. nlhs, plhs = [
  232. expr.xreplace({t: sgn*symbol}) for sgn in (-1, 1)]
  233. sols = _solve_lambert(nlhs, symbol, gens)
  234. if plhs != nlhs:
  235. sols.extend(_solve_lambert(plhs, symbol, gens))
  236. # uniq is needed for a case like
  237. # 2*log(t) - log(-z**2) + log(z + log(x) + log(z))
  238. # where subtituting t with +/-x gives all the same solution;
  239. # uniq, rather than list(set()), is used to maintain canonical
  240. # order
  241. return list(uniq(sols))
  242. nrhs, lhs = f.as_independent(symbol, as_Add=True)
  243. rhs = -nrhs
  244. lamcheck = [tmp for tmp in gens
  245. if (tmp.func in [exp, log] or
  246. (tmp.is_Pow and symbol in tmp.exp.free_symbols))]
  247. if not lamcheck:
  248. raise NotImplementedError()
  249. if lhs.is_Add or lhs.is_Mul:
  250. # replacing all even_degrees of symbol with dummy variable t
  251. # since these will need special handling; non-Add/Mul do not
  252. # need this handling
  253. t = Dummy('t', **symbol.assumptions0)
  254. lhs = lhs.replace(
  255. lambda i: # find symbol**even
  256. i.is_Pow and i.base == symbol and i.exp.is_even,
  257. lambda i: # replace t**even
  258. t**i.exp)
  259. if lhs.is_Add and lhs.has(t):
  260. t_indep = lhs.subs(t, 0)
  261. t_term = lhs - t_indep
  262. _rhs = rhs - t_indep
  263. if not t_term.is_Add and _rhs and not (
  264. t_term.has(S.ComplexInfinity, S.NaN)):
  265. eq = expand_log(log(t_term) - log(_rhs))
  266. return _solve_even_degree_expr(eq, t, symbol)
  267. elif lhs.is_Mul and rhs:
  268. # this needs to happen whether t is present or not
  269. lhs = expand_log(log(lhs), force=True)
  270. rhs = log(rhs)
  271. if lhs.has(t) and lhs.is_Add:
  272. # it expanded from Mul to Add
  273. eq = lhs - rhs
  274. return _solve_even_degree_expr(eq, t, symbol)
  275. # restore symbol in lhs
  276. lhs = lhs.xreplace({t: symbol})
  277. lhs = powsimp(factor(lhs, deep=True))
  278. # make sure we have inverted as completely as possible
  279. r = Dummy()
  280. i, lhs = _invert(lhs - r, symbol)
  281. rhs = i.xreplace({r: rhs})
  282. # For the first forms:
  283. #
  284. # 1a1) B**B = R will arrive here as B*log(B) = log(R)
  285. # lhs is Mul so take log of both sides:
  286. # log(B) + log(log(B)) = log(log(R))
  287. # 1a2) B*(b*log(B) + c)**a = R will arrive unchanged so
  288. # lhs is Mul, so take log of both sides:
  289. # log(B) + a*log(b*log(B) + c) = log(R)
  290. # 1b) d*log(a*B + b) + c*B = R will arrive unchanged so
  291. # lhs is Add, so isolate c*B and expand log of both sides:
  292. # log(c) + log(B) = log(R - d*log(a*B + b))
  293. soln = []
  294. if not soln:
  295. mainlog = _mostfunc(lhs, log, symbol)
  296. if mainlog:
  297. if lhs.is_Mul and rhs != 0:
  298. soln = _lambert(log(lhs) - log(rhs), symbol)
  299. elif lhs.is_Add:
  300. other = lhs.subs(mainlog, 0)
  301. if other and not other.is_Add and [
  302. tmp for tmp in other.atoms(Pow)
  303. if symbol in tmp.free_symbols]:
  304. if not rhs:
  305. diff = log(other) - log(other - lhs)
  306. else:
  307. diff = log(lhs - other) - log(rhs - other)
  308. soln = _lambert(expand_log(diff), symbol)
  309. else:
  310. #it's ready to go
  311. soln = _lambert(lhs - rhs, symbol)
  312. # For the next forms,
  313. #
  314. # collect on main exp
  315. # 2a) (b*B + c)*exp(d*B + g) = R
  316. # lhs is mul, so take log of both sides:
  317. # log(b*B + c) + d*B = log(R) - g
  318. # 2b) g*exp(d*B + h) - b*B = R
  319. # lhs is add, so add b*B to both sides,
  320. # take the log of both sides and rearrange to give
  321. # log(R + b*B) - d*B = log(g) + h
  322. if not soln:
  323. mainexp = _mostfunc(lhs, exp, symbol)
  324. if mainexp:
  325. lhs = collect(lhs, mainexp)
  326. if lhs.is_Mul and rhs != 0:
  327. soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
  328. elif lhs.is_Add:
  329. # move all but mainexp-containing term to rhs
  330. other = lhs.subs(mainexp, 0)
  331. mainterm = lhs - other
  332. rhs = rhs - other
  333. if (mainterm.could_extract_minus_sign() and
  334. rhs.could_extract_minus_sign()):
  335. mainterm *= -1
  336. rhs *= -1
  337. diff = log(mainterm) - log(rhs)
  338. soln = _lambert(expand_log(diff), symbol)
  339. # For the last form:
  340. #
  341. # 3) d*p**(a*B + g) - b*B = c
  342. # collect on main pow, add b*B to both sides,
  343. # take log of both sides and rearrange to give
  344. # a*B*log(p) - log(b*B + c) = -log(d) - g*log(p)
  345. if not soln:
  346. mainpow = _mostfunc(lhs, Pow, symbol)
  347. if mainpow and symbol in mainpow.exp.free_symbols:
  348. lhs = collect(lhs, mainpow)
  349. if lhs.is_Mul and rhs != 0:
  350. # b*B = 0
  351. soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
  352. elif lhs.is_Add:
  353. # move all but mainpow-containing term to rhs
  354. other = lhs.subs(mainpow, 0)
  355. mainterm = lhs - other
  356. rhs = rhs - other
  357. diff = log(mainterm) - log(rhs)
  358. soln = _lambert(expand_log(diff), symbol)
  359. if not soln:
  360. raise NotImplementedError('%s does not appear to have a solution in '
  361. 'terms of LambertW' % f)
  362. return list(ordered(soln))
  363. def bivariate_type(f, x, y, *, first=True):
  364. """Given an expression, f, 3 tests will be done to see what type
  365. of composite bivariate it might be, options for u(x, y) are::
  366. x*y
  367. x+y
  368. x*y+x
  369. x*y+y
  370. If it matches one of these types, ``u(x, y)``, ``P(u)`` and dummy
  371. variable ``u`` will be returned. Solving ``P(u)`` for ``u`` and
  372. equating the solutions to ``u(x, y)`` and then solving for ``x`` or
  373. ``y`` is equivalent to solving the original expression for ``x`` or
  374. ``y``. If ``x`` and ``y`` represent two functions in the same
  375. variable, e.g. ``x = g(t)`` and ``y = h(t)``, then if ``u(x, y) - p``
  376. can be solved for ``t`` then these represent the solutions to
  377. ``P(u) = 0`` when ``p`` are the solutions of ``P(u) = 0``.
  378. Only positive values of ``u`` are considered.
  379. Examples
  380. ========
  381. >>> from sympy import solve
  382. >>> from sympy.solvers.bivariate import bivariate_type
  383. >>> from sympy.abc import x, y
  384. >>> eq = (x**2 - 3).subs(x, x + y)
  385. >>> bivariate_type(eq, x, y)
  386. (x + y, _u**2 - 3, _u)
  387. >>> uxy, pu, u = _
  388. >>> usol = solve(pu, u); usol
  389. [sqrt(3)]
  390. >>> [solve(uxy - s) for s in solve(pu, u)]
  391. [[{x: -y + sqrt(3)}]]
  392. >>> all(eq.subs(s).equals(0) for sol in _ for s in sol)
  393. True
  394. """
  395. u = Dummy('u', positive=True)
  396. if first:
  397. p = Poly(f, x, y)
  398. f = p.as_expr()
  399. _x = Dummy()
  400. _y = Dummy()
  401. rv = bivariate_type(Poly(f.subs({x: _x, y: _y}), _x, _y), _x, _y, first=False)
  402. if rv:
  403. reps = {_x: x, _y: y}
  404. return rv[0].xreplace(reps), rv[1].xreplace(reps), rv[2]
  405. return
  406. p = f
  407. f = p.as_expr()
  408. # f(x*y)
  409. args = Add.make_args(p.as_expr())
  410. new = []
  411. for a in args:
  412. a = _mexpand(a.subs(x, u/y))
  413. free = a.free_symbols
  414. if x in free or y in free:
  415. break
  416. new.append(a)
  417. else:
  418. return x*y, Add(*new), u
  419. def ok(f, v, c):
  420. new = _mexpand(f.subs(v, c))
  421. free = new.free_symbols
  422. return None if (x in free or y in free) else new
  423. # f(a*x + b*y)
  424. new = []
  425. d = p.degree(x)
  426. if p.degree(y) == d:
  427. a = root(p.coeff_monomial(x**d), d)
  428. b = root(p.coeff_monomial(y**d), d)
  429. new = ok(f, x, (u - b*y)/a)
  430. if new is not None:
  431. return a*x + b*y, new, u
  432. # f(a*x*y + b*y)
  433. new = []
  434. d = p.degree(x)
  435. if p.degree(y) == d:
  436. for itry in range(2):
  437. a = root(p.coeff_monomial(x**d*y**d), d)
  438. b = root(p.coeff_monomial(y**d), d)
  439. new = ok(f, x, (u - b*y)/a/y)
  440. if new is not None:
  441. return a*x*y + b*y, new, u
  442. x, y = y, x