bivariate.py 17 KB

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