lie_group.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. r"""
  2. This module contains the implementation of the internal helper functions for the lie_group hint for
  3. dsolve. These helper functions apply different heuristics on the given equation
  4. and return the solution. These functions are used by :py:meth:`sympy.solvers.ode.single.LieGroup`
  5. References
  6. =========
  7. - `abaco1_simple`, `function_sum` and `chi` are referenced from E.S Cheb-Terrab, L.G.S Duarte
  8. and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using
  9. Symmetry Methods, pp. 7 - pp. 8
  10. - `abaco1_product`, `abaco2_similar`, `abaco2_unique_unknown`, `linear` and `abaco2_unique_general`
  11. are referenced from E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
  12. ODE Patterns, pp. 7 - pp. 12
  13. - `bivariate` from Lie Groups and Differential Equations pp. 327 - pp. 329
  14. """
  15. from itertools import islice
  16. from sympy.core import Add, S, Mul, Pow
  17. from sympy.core.exprtools import factor_terms
  18. from sympy.core.function import Function, AppliedUndef, expand
  19. from sympy.core.relational import Equality, Eq
  20. from sympy.core.symbol import Symbol, Wild, Dummy, symbols
  21. from sympy.functions import exp, log
  22. from sympy.integrals.integrals import integrate
  23. from sympy.polys import Poly
  24. from sympy.polys.polytools import cancel, div
  25. from sympy.simplify import (collect, powsimp, # type: ignore
  26. separatevars, simplify)
  27. from sympy.solvers import solve
  28. from sympy.solvers.pde import pdsolve
  29. from sympy.utilities import numbered_symbols
  30. from sympy.solvers.deutils import _preprocess, ode_order
  31. from .ode import checkinfsol
  32. lie_heuristics = (
  33. "abaco1_simple",
  34. "abaco1_product",
  35. "abaco2_similar",
  36. "abaco2_unique_unknown",
  37. "abaco2_unique_general",
  38. "linear",
  39. "function_sum",
  40. "bivariate",
  41. "chi"
  42. )
  43. def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf):
  44. xi = Function("xi")
  45. eta = Function("eta")
  46. f = func.func
  47. x = func.args[0]
  48. y = match['y']
  49. h = match['h']
  50. tempsol = []
  51. if not inf:
  52. try:
  53. inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match)
  54. except ValueError:
  55. return None
  56. for infsim in inf:
  57. xiinf = (infsim[xi(x, func)]).subs(func, y)
  58. etainf = (infsim[eta(x, func)]).subs(func, y)
  59. # This condition creates recursion while using pdsolve.
  60. # Since the first step while solving a PDE of form
  61. # a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
  62. # is to solve the ODE dy/dx = b/a
  63. if simplify(etainf/xiinf) == h:
  64. continue
  65. rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
  66. r = pdsolve(rpde, func=f(x, y)).rhs
  67. s = pdsolve(rpde - 1, func=f(x, y)).rhs
  68. newcoord = [_lie_group_remove(coord) for coord in [r, s]]
  69. r = Dummy("r")
  70. s = Dummy("s")
  71. C1 = Symbol("C1")
  72. rcoord = newcoord[0]
  73. scoord = newcoord[-1]
  74. try:
  75. sol = solve([r - rcoord, s - scoord], x, y, dict=True)
  76. if sol == []:
  77. continue
  78. except NotImplementedError:
  79. continue
  80. else:
  81. sol = sol[0]
  82. xsub = sol[x]
  83. ysub = sol[y]
  84. num = simplify(scoord.diff(x) + scoord.diff(y)*h)
  85. denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
  86. if num and denom:
  87. diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)]))
  88. sep = separatevars(diffeq, symbols=[r, s], dict=True)
  89. if sep:
  90. # Trying to separate, r and s coordinates
  91. deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
  92. # Substituting and reverting back to original coordinates
  93. deq = deq.subs([(r, rcoord), (s, scoord)])
  94. try:
  95. sdeq = solve(deq, y)
  96. except NotImplementedError:
  97. tempsol.append(deq)
  98. else:
  99. return [Eq(f(x), sol) for sol in sdeq]
  100. elif denom: # (ds/dr) is zero which means s is constant
  101. return [Eq(f(x), solve(scoord - C1, y)[0])]
  102. elif num: # (dr/ds) is zero which means r is constant
  103. return [Eq(f(x), solve(rcoord - C1, y)[0])]
  104. # If nothing works, return solution as it is, without solving for y
  105. if tempsol:
  106. return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol]
  107. return None
  108. def _ode_lie_group( s, func, order, match):
  109. heuristics = lie_heuristics
  110. inf = {}
  111. f = func.func
  112. x = func.args[0]
  113. df = func.diff(x)
  114. xi = Function("xi")
  115. eta = Function("eta")
  116. xis = match['xi']
  117. etas = match['eta']
  118. y = match.pop('y', None)
  119. if y:
  120. h = -simplify(match[match['d']]/match[match['e']])
  121. y = y
  122. else:
  123. y = Dummy("y")
  124. h = s.subs(func, y)
  125. if xis is not None and etas is not None:
  126. inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}]
  127. if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]:
  128. heuristics = ["user_defined"] + list(heuristics)
  129. match = {'h': h, 'y': y}
  130. # This is done so that if any heuristic raises a ValueError
  131. # another heuristic can be used.
  132. sol = None
  133. for heuristic in heuristics:
  134. sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf)
  135. if sol:
  136. return sol
  137. return sol
  138. def infinitesimals(eq, func=None, order=None, hint='default', match=None):
  139. r"""
  140. The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
  141. and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
  142. for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
  143. would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
  144. `y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
  145. A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
  146. becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
  147. They are tangents to the coordinate curves of the new system.
  148. Consider the transformation `(x, y) \to (X, Y)` such that the
  149. differential equation remains invariant. `\xi` and `\eta` are the tangents to
  150. the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
  151. .. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
  152. }\right)|_{\varepsilon=0} = \xi,
  153. \left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
  154. }\right)|_{\varepsilon=0} = \eta,
  155. The infinitesimals can be found by solving the following PDE:
  156. >>> from sympy import Function, Eq, pprint
  157. >>> from sympy.abc import x, y
  158. >>> xi, eta, h = map(Function, ['xi', 'eta', 'h'])
  159. >>> h = h(x, y) # dy/dx = h
  160. >>> eta = eta(x, y)
  161. >>> xi = xi(x, y)
  162. >>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h
  163. ... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
  164. >>> pprint(genform)
  165. /d d \ d 2 d
  166. |--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x
  167. \dy dx / dy dy
  168. <BLANKLINE>
  169. d d
  170. i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
  171. dx dx
  172. Solving the above mentioned PDE is not trivial, and can be solved only by
  173. making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
  174. infinitesimal is found, the attempt to find more heuristics stops. This is done to
  175. optimise the speed of solving the differential equation. If a list of all the
  176. infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
  177. the complete list of infinitesimals. If the infinitesimals for a particular
  178. heuristic needs to be found, it can be passed as a flag to ``hint``.
  179. Examples
  180. ========
  181. >>> from sympy import Function
  182. >>> from sympy.solvers.ode.lie_group import infinitesimals
  183. >>> from sympy.abc import x
  184. >>> f = Function('f')
  185. >>> eq = f(x).diff(x) - x**2*f(x)
  186. >>> infinitesimals(eq)
  187. [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}]
  188. References
  189. ==========
  190. - Solving differential equations by Symmetry Groups,
  191. John Starrett, pp. 1 - pp. 14
  192. """
  193. if isinstance(eq, Equality):
  194. eq = eq.lhs - eq.rhs
  195. if not func:
  196. eq, func = _preprocess(eq)
  197. variables = func.args
  198. if len(variables) != 1:
  199. raise ValueError("ODE's have only one independent variable")
  200. else:
  201. x = variables[0]
  202. if not order:
  203. order = ode_order(eq, func)
  204. if order != 1:
  205. raise NotImplementedError("Infinitesimals for only "
  206. "first order ODE's have been implemented")
  207. else:
  208. df = func.diff(x)
  209. # Matching differential equation of the form a*df + b
  210. a = Wild('a', exclude = [df])
  211. b = Wild('b', exclude = [df])
  212. if match: # Used by lie_group hint
  213. h = match['h']
  214. y = match['y']
  215. else:
  216. match = collect(expand(eq), df).match(a*df + b)
  217. if match:
  218. h = -simplify(match[b]/match[a])
  219. else:
  220. try:
  221. sol = solve(eq, df)
  222. except NotImplementedError:
  223. raise NotImplementedError("Infinitesimals for the "
  224. "first order ODE could not be found")
  225. else:
  226. h = sol[0] # Find infinitesimals for one solution
  227. y = Dummy("y")
  228. h = h.subs(func, y)
  229. u = Dummy("u")
  230. hx = h.diff(x)
  231. hy = h.diff(y)
  232. hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE
  233. match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
  234. if hint == 'all':
  235. xieta = []
  236. for heuristic in lie_heuristics:
  237. function = globals()['lie_heuristic_' + heuristic]
  238. inflist = function(match, comp=True)
  239. if inflist:
  240. xieta.extend([inf for inf in inflist if inf not in xieta])
  241. if xieta:
  242. return xieta
  243. else:
  244. raise NotImplementedError("Infinitesimals could not be found for "
  245. "the given ODE")
  246. elif hint == 'default':
  247. for heuristic in lie_heuristics:
  248. function = globals()['lie_heuristic_' + heuristic]
  249. xieta = function(match, comp=False)
  250. if xieta:
  251. return xieta
  252. raise NotImplementedError("Infinitesimals could not be found for"
  253. " the given ODE")
  254. elif hint not in lie_heuristics:
  255. raise ValueError("Heuristic not recognized: " + hint)
  256. else:
  257. function = globals()['lie_heuristic_' + hint]
  258. xieta = function(match, comp=True)
  259. if xieta:
  260. return xieta
  261. else:
  262. raise ValueError("Infinitesimals could not be found using the"
  263. " given heuristic")
  264. def lie_heuristic_abaco1_simple(match, comp=False):
  265. r"""
  266. The first heuristic uses the following four sets of
  267. assumptions on `\xi` and `\eta`
  268. .. math:: \xi = 0, \eta = f(x)
  269. .. math:: \xi = 0, \eta = f(y)
  270. .. math:: \xi = f(x), \eta = 0
  271. .. math:: \xi = f(y), \eta = 0
  272. The success of this heuristic is determined by algebraic factorisation.
  273. For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
  274. .. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
  275. - \frac{\partial \xi}{\partial x})*h
  276. - \frac{\partial \xi}{\partial y}*h^{2}
  277. - \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
  278. reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
  279. If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
  280. be integrated easily. A similar idea is applied to the other 3 assumptions as well.
  281. References
  282. ==========
  283. - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
  284. Solving of First Order ODEs Using Symmetry Methods, pp. 8
  285. """
  286. xieta = []
  287. y = match['y']
  288. h = match['h']
  289. func = match['func']
  290. x = func.args[0]
  291. hx = match['hx']
  292. hy = match['hy']
  293. xi = Function('xi')(x, func)
  294. eta = Function('eta')(x, func)
  295. hysym = hy.free_symbols
  296. if y not in hysym:
  297. try:
  298. fx = exp(integrate(hy, x))
  299. except NotImplementedError:
  300. pass
  301. else:
  302. inf = {xi: S.Zero, eta: fx}
  303. if not comp:
  304. return [inf]
  305. if comp and inf not in xieta:
  306. xieta.append(inf)
  307. factor = hy/h
  308. facsym = factor.free_symbols
  309. if x not in facsym:
  310. try:
  311. fy = exp(integrate(factor, y))
  312. except NotImplementedError:
  313. pass
  314. else:
  315. inf = {xi: S.Zero, eta: fy.subs(y, func)}
  316. if not comp:
  317. return [inf]
  318. if comp and inf not in xieta:
  319. xieta.append(inf)
  320. factor = -hx/h
  321. facsym = factor.free_symbols
  322. if y not in facsym:
  323. try:
  324. fx = exp(integrate(factor, x))
  325. except NotImplementedError:
  326. pass
  327. else:
  328. inf = {xi: fx, eta: S.Zero}
  329. if not comp:
  330. return [inf]
  331. if comp and inf not in xieta:
  332. xieta.append(inf)
  333. factor = -hx/(h**2)
  334. facsym = factor.free_symbols
  335. if x not in facsym:
  336. try:
  337. fy = exp(integrate(factor, y))
  338. except NotImplementedError:
  339. pass
  340. else:
  341. inf = {xi: fy.subs(y, func), eta: S.Zero}
  342. if not comp:
  343. return [inf]
  344. if comp and inf not in xieta:
  345. xieta.append(inf)
  346. if xieta:
  347. return xieta
  348. def lie_heuristic_abaco1_product(match, comp=False):
  349. r"""
  350. The second heuristic uses the following two assumptions on `\xi` and `\eta`
  351. .. math:: \eta = 0, \xi = f(x)*g(y)
  352. .. math:: \eta = f(x)*g(y), \xi = 0
  353. The first assumption of this heuristic holds good if
  354. `\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
  355. separable in `x` and `y`, then the separated factors containing `x`
  356. is `f(x)`, and `g(y)` is obtained by
  357. .. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
  358. provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
  359. of `y` only.
  360. The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
  361. `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
  362. satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again
  363. interchanged, to get `\eta` as `f(x)*g(y)`
  364. References
  365. ==========
  366. - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
  367. ODE Patterns, pp. 7 - pp. 8
  368. """
  369. xieta = []
  370. y = match['y']
  371. h = match['h']
  372. hinv = match['hinv']
  373. func = match['func']
  374. x = func.args[0]
  375. xi = Function('xi')(x, func)
  376. eta = Function('eta')(x, func)
  377. inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y])
  378. if inf and inf['coeff']:
  379. fx = inf[x]
  380. gy = simplify(fx*((1/(fx*h)).diff(x)))
  381. gysyms = gy.free_symbols
  382. if x not in gysyms:
  383. gy = exp(integrate(gy, y))
  384. inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)}
  385. if not comp:
  386. return [inf]
  387. if comp and inf not in xieta:
  388. xieta.append(inf)
  389. u1 = Dummy("u1")
  390. inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
  391. if inf and inf['coeff']:
  392. fx = inf[x]
  393. gy = simplify(fx*((1/(fx*hinv)).diff(x)))
  394. gysyms = gy.free_symbols
  395. if x not in gysyms:
  396. gy = exp(integrate(gy, y))
  397. etaval = fx*gy
  398. etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y)
  399. inf = {eta: etaval.subs(y, func), xi: S.Zero}
  400. if not comp:
  401. return [inf]
  402. if comp and inf not in xieta:
  403. xieta.append(inf)
  404. if xieta:
  405. return xieta
  406. def lie_heuristic_bivariate(match, comp=False):
  407. r"""
  408. The third heuristic assumes the infinitesimals `\xi` and `\eta`
  409. to be bi-variate polynomials in `x` and `y`. The assumption made here
  410. for the logic below is that `h` is a rational function in `x` and `y`
  411. though that may not be necessary for the infinitesimals to be
  412. bivariate polynomials. The coefficients of the infinitesimals
  413. are found out by substituting them in the PDE and grouping similar terms
  414. that are polynomials and since they form a linear system, solve and check
  415. for non trivial solutions. The degree of the assumed bivariates
  416. are increased till a certain maximum value.
  417. References
  418. ==========
  419. - Lie Groups and Differential Equations
  420. pp. 327 - pp. 329
  421. """
  422. h = match['h']
  423. hx = match['hx']
  424. hy = match['hy']
  425. func = match['func']
  426. x = func.args[0]
  427. y = match['y']
  428. xi = Function('xi')(x, func)
  429. eta = Function('eta')(x, func)
  430. if h.is_rational_function():
  431. # The maximum degree that the infinitesimals can take is
  432. # calculated by this technique.
  433. etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid")
  434. ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
  435. num, denom = cancel(ipde).as_numer_denom()
  436. deg = Poly(num, x, y).total_degree()
  437. deta = Function('deta')(x, y)
  438. dxi = Function('dxi')(x, y)
  439. ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
  440. - dxi*hx - deta*hy)
  441. xieq = Symbol("xi0")
  442. etaeq = Symbol("eta0")
  443. for i in range(deg + 1):
  444. if i:
  445. xieq += Add(*[
  446. Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
  447. for power in range(i + 1)])
  448. etaeq += Add(*[
  449. Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
  450. for power in range(i + 1)])
  451. pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
  452. pden = expand(pden)
  453. # If the individual terms are monomials, the coefficients
  454. # are grouped
  455. if pden.is_polynomial(x, y) and pden.is_Add:
  456. polyy = Poly(pden, x, y).as_dict()
  457. if polyy:
  458. symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
  459. soldict = solve(polyy.values(), *symset)
  460. if isinstance(soldict, list):
  461. soldict = soldict[0]
  462. if any(soldict.values()):
  463. xired = xieq.subs(soldict)
  464. etared = etaeq.subs(soldict)
  465. # Scaling is done by substituting one for the parameters
  466. # This can be any number except zero.
  467. dict_ = {sym: 1 for sym in symset}
  468. inf = {eta: etared.subs(dict_).subs(y, func),
  469. xi: xired.subs(dict_).subs(y, func)}
  470. return [inf]
  471. def lie_heuristic_chi(match, comp=False):
  472. r"""
  473. The aim of the fourth heuristic is to find the function `\chi(x, y)`
  474. that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
  475. - \frac{\partial h}{\partial y}\chi = 0`.
  476. This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition,
  477. `h` should be a rational function in `x` and `y`. The method used here is
  478. to substitute a general binomial for `\chi` up to a certain maximum degree
  479. is reached. The coefficients of the polynomials, are calculated by by collecting
  480. terms of the same order in `x` and `y`.
  481. After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
  482. determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
  483. which would give `-\xi` as the quotient and `\eta` as the remainder.
  484. References
  485. ==========
  486. - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
  487. Solving of First Order ODEs Using Symmetry Methods, pp. 8
  488. """
  489. h = match['h']
  490. hy = match['hy']
  491. func = match['func']
  492. x = func.args[0]
  493. y = match['y']
  494. xi = Function('xi')(x, func)
  495. eta = Function('eta')(x, func)
  496. if h.is_rational_function():
  497. schi, schix, schiy = symbols("schi, schix, schiy")
  498. cpde = schix + h*schiy - hy*schi
  499. num, denom = cancel(cpde).as_numer_denom()
  500. deg = Poly(num, x, y).total_degree()
  501. chi = Function('chi')(x, y)
  502. chix = chi.diff(x)
  503. chiy = chi.diff(y)
  504. cpde = chix + h*chiy - hy*chi
  505. chieq = Symbol("chi")
  506. for i in range(1, deg + 1):
  507. chieq += Add(*[
  508. Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
  509. for power in range(i + 1)])
  510. cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom()
  511. cnum = expand(cnum)
  512. if cnum.is_polynomial(x, y) and cnum.is_Add:
  513. cpoly = Poly(cnum, x, y).as_dict()
  514. if cpoly:
  515. solsyms = chieq.free_symbols - {x, y}
  516. soldict = solve(cpoly.values(), *solsyms)
  517. if isinstance(soldict, list):
  518. soldict = soldict[0]
  519. if any(soldict.values()):
  520. chieq = chieq.subs(soldict)
  521. dict_ = {sym: 1 for sym in solsyms}
  522. chieq = chieq.subs(dict_)
  523. # After finding chi, the main aim is to find out
  524. # eta, xi by the equation eta = xi*h + chi
  525. # One method to set xi, would be rearranging it to
  526. # (eta/h) - xi = (chi/h). This would mean dividing
  527. # chi by h would give -xi as the quotient and eta
  528. # as the remainder. Thanks to Sean Vig for suggesting
  529. # this method.
  530. xic, etac = div(chieq, h)
  531. inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)}
  532. return [inf]
  533. def lie_heuristic_function_sum(match, comp=False):
  534. r"""
  535. This heuristic uses the following two assumptions on `\xi` and `\eta`
  536. .. math:: \eta = 0, \xi = f(x) + g(y)
  537. .. math:: \eta = f(x) + g(y), \xi = 0
  538. The first assumption of this heuristic holds good if
  539. .. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
  540. \partial x^{2}}(h^{-1}))^{-1}]
  541. is separable in `x` and `y`,
  542. 1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
  543. From this `g(y)` can be determined.
  544. 2. The separated factors containing `x` is `f''(x)`.
  545. 3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
  546. `\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
  547. The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
  548. `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
  549. assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates
  550. are again interchanged, to get `\eta` as `f(x) + g(y)`.
  551. For both assumptions, the constant factors are separated among `g(y)`
  552. and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
  553. obtained from 2]. If not possible, then this heuristic fails.
  554. References
  555. ==========
  556. - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
  557. ODE Patterns, pp. 7 - pp. 8
  558. """
  559. xieta = []
  560. h = match['h']
  561. func = match['func']
  562. hinv = match['hinv']
  563. x = func.args[0]
  564. y = match['y']
  565. xi = Function('xi')(x, func)
  566. eta = Function('eta')(x, func)
  567. for odefac in [h, hinv]:
  568. factor = odefac*((1/odefac).diff(x, 2))
  569. sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
  570. if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
  571. k = Dummy("k")
  572. try:
  573. gy = k*integrate(sep[y], y)
  574. except NotImplementedError:
  575. pass
  576. else:
  577. fdd = 1/(k*sep[x]*sep['coeff'])
  578. fx = simplify(fdd/factor - gy)
  579. check = simplify(fx.diff(x, 2) - fdd)
  580. if fx:
  581. if not check:
  582. fx = fx.subs(k, 1)
  583. gy = (gy/k)
  584. else:
  585. sol = solve(check, k)
  586. if sol:
  587. sol = sol[0]
  588. fx = fx.subs(k, sol)
  589. gy = (gy/k)*sol
  590. else:
  591. continue
  592. if odefac == hinv: # Inverse ODE
  593. fx = fx.subs(x, y)
  594. gy = gy.subs(y, x)
  595. etaval = factor_terms(fx + gy)
  596. if etaval.is_Mul:
  597. etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
  598. if odefac == hinv: # Inverse ODE
  599. inf = {eta: etaval.subs(y, func), xi : S.Zero}
  600. else:
  601. inf = {xi: etaval.subs(y, func), eta : S.Zero}
  602. if not comp:
  603. return [inf]
  604. else:
  605. xieta.append(inf)
  606. if xieta:
  607. return xieta
  608. def lie_heuristic_abaco2_similar(match, comp=False):
  609. r"""
  610. This heuristic uses the following two assumptions on `\xi` and `\eta`
  611. .. math:: \eta = g(x), \xi = f(x)
  612. .. math:: \eta = f(y), \xi = g(y)
  613. For the first assumption,
  614. 1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
  615. \partial yy}}` is calculated. Let us say this value is A
  616. 2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
  617. \frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
  618. and `A(x)*f(x)` gives `g(x)`
  619. 3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
  620. \partial Y}} = \gamma` is calculated. If
  621. a] `\gamma` is a function of `x` alone
  622. b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
  623. \partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
  624. then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
  625. The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
  626. `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
  627. satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again
  628. interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
  629. References
  630. ==========
  631. - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
  632. ODE Patterns, pp. 10 - pp. 12
  633. """
  634. h = match['h']
  635. hx = match['hx']
  636. hy = match['hy']
  637. func = match['func']
  638. hinv = match['hinv']
  639. x = func.args[0]
  640. y = match['y']
  641. xi = Function('xi')(x, func)
  642. eta = Function('eta')(x, func)
  643. factor = cancel(h.diff(y)/h.diff(y, 2))
  644. factorx = factor.diff(x)
  645. factory = factor.diff(y)
  646. if not factor.has(x) and not factor.has(y):
  647. A = Wild('A', exclude=[y])
  648. B = Wild('B', exclude=[y])
  649. C = Wild('C', exclude=[x, y])
  650. match = h.match(A + B*exp(y/C))
  651. try:
  652. tau = exp(-integrate(match[A]/match[C]), x)/match[B]
  653. except NotImplementedError:
  654. pass
  655. else:
  656. gx = match[A]*tau
  657. return [{xi: tau, eta: gx}]
  658. else:
  659. gamma = cancel(factorx/factory)
  660. if not gamma.has(y):
  661. tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
  662. if not tauint.has(y):
  663. try:
  664. tau = exp(integrate(tauint, x))
  665. except NotImplementedError:
  666. pass
  667. else:
  668. gx = -tau*gamma
  669. return [{xi: tau, eta: gx}]
  670. factor = cancel(hinv.diff(y)/hinv.diff(y, 2))
  671. factorx = factor.diff(x)
  672. factory = factor.diff(y)
  673. if not factor.has(x) and not factor.has(y):
  674. A = Wild('A', exclude=[y])
  675. B = Wild('B', exclude=[y])
  676. C = Wild('C', exclude=[x, y])
  677. match = h.match(A + B*exp(y/C))
  678. try:
  679. tau = exp(-integrate(match[A]/match[C]), x)/match[B]
  680. except NotImplementedError:
  681. pass
  682. else:
  683. gx = match[A]*tau
  684. return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
  685. else:
  686. gamma = cancel(factorx/factory)
  687. if not gamma.has(y):
  688. tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
  689. hinv + gamma))
  690. if not tauint.has(y):
  691. try:
  692. tau = exp(integrate(tauint, x))
  693. except NotImplementedError:
  694. pass
  695. else:
  696. gx = -tau*gamma
  697. return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
  698. def lie_heuristic_abaco2_unique_unknown(match, comp=False):
  699. r"""
  700. This heuristic assumes the presence of unknown functions or known functions
  701. with non-integer powers.
  702. 1. A list of all functions and non-integer powers containing x and y
  703. 2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
  704. \frac{\partial f}{\partial x}} = R`
  705. If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
  706. a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
  707. `\xi` and `\eta`
  708. b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
  709. If yes, then return `\xi` and `\eta`
  710. If not, then check if
  711. a] :math:`\xi = -R,\eta = 1`
  712. b] :math:`\xi = 1, \eta = -\frac{1}{R}`
  713. are solutions.
  714. References
  715. ==========
  716. - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
  717. ODE Patterns, pp. 10 - pp. 12
  718. """
  719. h = match['h']
  720. hx = match['hx']
  721. hy = match['hy']
  722. func = match['func']
  723. x = func.args[0]
  724. y = match['y']
  725. xi = Function('xi')(x, func)
  726. eta = Function('eta')(x, func)
  727. funclist = []
  728. for atom in h.atoms(Pow):
  729. base, exp = atom.as_base_exp()
  730. if base.has(x) and base.has(y):
  731. if not exp.is_Integer:
  732. funclist.append(atom)
  733. for function in h.atoms(AppliedUndef):
  734. syms = function.free_symbols
  735. if x in syms and y in syms:
  736. funclist.append(function)
  737. for f in funclist:
  738. frac = cancel(f.diff(y)/f.diff(x))
  739. sep = separatevars(frac, dict=True, symbols=[x, y])
  740. if sep and sep['coeff']:
  741. xitry1 = sep[x]
  742. etatry1 = -1/(sep[y]*sep['coeff'])
  743. pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
  744. if not simplify(pde1):
  745. return [{xi: xitry1, eta: etatry1.subs(y, func)}]
  746. xitry2 = 1/etatry1
  747. etatry2 = 1/xitry1
  748. pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
  749. if not simplify(expand(pde2)):
  750. return [{xi: xitry2.subs(y, func), eta: etatry2}]
  751. else:
  752. etatry = -1/frac
  753. pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
  754. if not simplify(pde):
  755. return [{xi: S.One, eta: etatry.subs(y, func)}]
  756. xitry = -frac
  757. pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy
  758. if not simplify(expand(pde)):
  759. return [{xi: xitry.subs(y, func), eta: S.One}]
  760. def lie_heuristic_abaco2_unique_general(match, comp=False):
  761. r"""
  762. This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)`
  763. without making any assumptions on `h`.
  764. The complete sequence of steps is given in the paper mentioned below.
  765. References
  766. ==========
  767. - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
  768. ODE Patterns, pp. 10 - pp. 12
  769. """
  770. hx = match['hx']
  771. hy = match['hy']
  772. func = match['func']
  773. x = func.args[0]
  774. y = match['y']
  775. xi = Function('xi')(x, func)
  776. eta = Function('eta')(x, func)
  777. A = hx.diff(y)
  778. B = hy.diff(y) + hy**2
  779. C = hx.diff(x) - hx**2
  780. if not (A and B and C):
  781. return
  782. Ax = A.diff(x)
  783. Ay = A.diff(y)
  784. Axy = Ax.diff(y)
  785. Axx = Ax.diff(x)
  786. Ayy = Ay.diff(y)
  787. D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay
  788. if not D:
  789. E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A)
  790. if E1:
  791. E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
  792. if not E2:
  793. E3 = simplify(
  794. E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4)
  795. if not E3:
  796. etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1))
  797. if x not in etaval:
  798. try:
  799. etaval = exp(integrate(etaval, y))
  800. except NotImplementedError:
  801. pass
  802. else:
  803. xival = -4*A**3*etaval/E1
  804. if y not in xival:
  805. return [{xi: xival, eta: etaval.subs(y, func)}]
  806. else:
  807. E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
  808. if E1:
  809. E2 = simplify(
  810. 4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2))
  811. if not E2:
  812. E3 = simplify(
  813. -(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D +
  814. (A*hx - 3*Ax)*E1)*E1)
  815. if not E3:
  816. etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D))
  817. if x not in etaval:
  818. try:
  819. etaval = exp(integrate(etaval, y))
  820. except NotImplementedError:
  821. pass
  822. else:
  823. xival = -E1*etaval/D
  824. if y not in xival:
  825. return [{xi: xival, eta: etaval.subs(y, func)}]
  826. def lie_heuristic_linear(match, comp=False):
  827. r"""
  828. This heuristic assumes
  829. 1. `\xi = ax + by + c` and
  830. 2. `\eta = fx + gy + h`
  831. After substituting the following assumptions in the determining PDE, it
  832. reduces to
  833. .. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
  834. - (fx + gy + c)\frac{\partial h}{\partial y}
  835. Solving the reduced PDE obtained, using the method of characteristics, becomes
  836. impractical. The method followed is grouping similar terms and solving the system
  837. of linear equations obtained. The difference between the bivariate heuristic is that
  838. `h` need not be a rational function in this case.
  839. References
  840. ==========
  841. - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
  842. ODE Patterns, pp. 10 - pp. 12
  843. """
  844. h = match['h']
  845. hx = match['hx']
  846. hy = match['hy']
  847. func = match['func']
  848. x = func.args[0]
  849. y = match['y']
  850. xi = Function('xi')(x, func)
  851. eta = Function('eta')(x, func)
  852. coeffdict = {}
  853. symbols = numbered_symbols("c", cls=Dummy)
  854. symlist = [next(symbols) for _ in islice(symbols, 6)]
  855. C0, C1, C2, C3, C4, C5 = symlist
  856. pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
  857. pde, denom = pde.as_numer_denom()
  858. pde = powsimp(expand(pde))
  859. if pde.is_Add:
  860. terms = pde.args
  861. for term in terms:
  862. if term.is_Mul:
  863. rem = Mul(*[m for m in term.args if not m.has(x, y)])
  864. xypart = term/rem
  865. if xypart not in coeffdict:
  866. coeffdict[xypart] = rem
  867. else:
  868. coeffdict[xypart] += rem
  869. else:
  870. if term not in coeffdict:
  871. coeffdict[term] = S.One
  872. else:
  873. coeffdict[term] += S.One
  874. sollist = coeffdict.values()
  875. soldict = solve(sollist, symlist)
  876. if soldict:
  877. if isinstance(soldict, list):
  878. soldict = soldict[0]
  879. subval = soldict.values()
  880. if any(t for t in subval):
  881. onedict = dict(zip(symlist, [1]*6))
  882. xival = C0*x + C1*func + C2
  883. etaval = C3*x + C4*func + C5
  884. xival = xival.subs(soldict)
  885. etaval = etaval.subs(soldict)
  886. xival = xival.subs(onedict)
  887. etaval = etaval.subs(onedict)
  888. return [{xi: xival, eta: etaval}]
  889. def _lie_group_remove(coords):
  890. r"""
  891. This function is strictly meant for internal use by the Lie group ODE solving
  892. method. It replaces arbitrary functions returned by pdsolve as follows:
  893. 1] If coords is an arbitrary function, then its argument is returned.
  894. 2] An arbitrary function in an Add object is replaced by zero.
  895. 3] An arbitrary function in a Mul object is replaced by one.
  896. 4] If there is no arbitrary function coords is returned unchanged.
  897. Examples
  898. ========
  899. >>> from sympy.solvers.ode.lie_group import _lie_group_remove
  900. >>> from sympy import Function
  901. >>> from sympy.abc import x, y
  902. >>> F = Function("F")
  903. >>> eq = x**2*y
  904. >>> _lie_group_remove(eq)
  905. x**2*y
  906. >>> eq = F(x**2*y)
  907. >>> _lie_group_remove(eq)
  908. x**2*y
  909. >>> eq = x*y**2 + F(x**3)
  910. >>> _lie_group_remove(eq)
  911. x*y**2
  912. >>> eq = (F(x**3) + y)*x**4
  913. >>> _lie_group_remove(eq)
  914. x**4*y
  915. """
  916. if isinstance(coords, AppliedUndef):
  917. return coords.args[0]
  918. elif coords.is_Add:
  919. subfunc = coords.atoms(AppliedUndef)
  920. if subfunc:
  921. for func in subfunc:
  922. coords = coords.subs(func, 0)
  923. return coords
  924. elif coords.is_Pow:
  925. base, expr = coords.as_base_exp()
  926. base = _lie_group_remove(base)
  927. expr = _lie_group_remove(expr)
  928. return base**expr
  929. elif coords.is_Mul:
  930. mulargs = []
  931. coordargs = coords.args
  932. for arg in coordargs:
  933. if not isinstance(coords, AppliedUndef):
  934. mulargs.append(_lie_group_remove(arg))
  935. return Mul(*mulargs)
  936. return coords