lie_group.py 38 KB

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