pde.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. """
  2. This module contains pdsolve() and different helper functions that it
  3. uses. It is heavily inspired by the ode module and hence the basic
  4. infrastructure remains the same.
  5. **Functions in this module**
  6. These are the user functions in this module:
  7. - pdsolve() - Solves PDE's
  8. - classify_pde() - Classifies PDEs into possible hints for dsolve().
  9. - pde_separate() - Separate variables in partial differential equation either by
  10. additive or multiplicative separation approach.
  11. These are the helper functions in this module:
  12. - pde_separate_add() - Helper function for searching additive separable solutions.
  13. - pde_separate_mul() - Helper function for searching multiplicative
  14. separable solutions.
  15. **Currently implemented solver methods**
  16. The following methods are implemented for solving partial differential
  17. equations. See the docstrings of the various pde_hint() functions for
  18. more information on each (run help(pde)):
  19. - 1st order linear homogeneous partial differential equations
  20. with constant coefficients.
  21. - 1st order linear general partial differential equations
  22. with constant coefficients.
  23. - 1st order linear partial differential equations with
  24. variable coefficients.
  25. """
  26. from functools import reduce
  27. from itertools import combinations_with_replacement
  28. from sympy.simplify import simplify # type: ignore
  29. from sympy.core import Add, S
  30. from sympy.core.function import Function, expand, AppliedUndef, Subs
  31. from sympy.core.relational import Equality, Eq
  32. from sympy.core.symbol import Symbol, Wild, symbols
  33. from sympy.functions import exp
  34. from sympy.integrals.integrals import Integral
  35. from sympy.utilities.iterables import has_dups, is_sequence
  36. from sympy.utilities.misc import filldedent
  37. from sympy.solvers.deutils import _preprocess, ode_order, _desolve
  38. from sympy.solvers.solvers import solve
  39. from sympy.simplify.radsimp import collect
  40. import operator
  41. allhints = (
  42. "1st_linear_constant_coeff_homogeneous",
  43. "1st_linear_constant_coeff",
  44. "1st_linear_constant_coeff_Integral",
  45. "1st_linear_variable_coeff"
  46. )
  47. def pdsolve(eq, func=None, hint='default', dict=False, solvefun=None, **kwargs):
  48. """
  49. Solves any (supported) kind of partial differential equation.
  50. **Usage**
  51. pdsolve(eq, f(x,y), hint) -> Solve partial differential equation
  52. eq for function f(x,y), using method hint.
  53. **Details**
  54. ``eq`` can be any supported partial differential equation (see
  55. the pde docstring for supported methods). This can either
  56. be an Equality, or an expression, which is assumed to be
  57. equal to 0.
  58. ``f(x,y)`` is a function of two variables whose derivatives in that
  59. variable make up the partial differential equation. In many
  60. cases it is not necessary to provide this; it will be autodetected
  61. (and an error raised if it couldn't be detected).
  62. ``hint`` is the solving method that you want pdsolve to use. Use
  63. classify_pde(eq, f(x,y)) to get all of the possible hints for
  64. a PDE. The default hint, 'default', will use whatever hint
  65. is returned first by classify_pde(). See Hints below for
  66. more options that you can use for hint.
  67. ``solvefun`` is the convention used for arbitrary functions returned
  68. by the PDE solver. If not set by the user, it is set by default
  69. to be F.
  70. **Hints**
  71. Aside from the various solving methods, there are also some
  72. meta-hints that you can pass to pdsolve():
  73. "default":
  74. This uses whatever hint is returned first by
  75. classify_pde(). This is the default argument to
  76. pdsolve().
  77. "all":
  78. To make pdsolve apply all relevant classification hints,
  79. use pdsolve(PDE, func, hint="all"). This will return a
  80. dictionary of hint:solution terms. If a hint causes
  81. pdsolve to raise the NotImplementedError, value of that
  82. hint's key will be the exception object raised. The
  83. dictionary will also include some special keys:
  84. - order: The order of the PDE. See also ode_order() in
  85. deutils.py
  86. - default: The solution that would be returned by
  87. default. This is the one produced by the hint that
  88. appears first in the tuple returned by classify_pde().
  89. "all_Integral":
  90. This is the same as "all", except if a hint also has a
  91. corresponding "_Integral" hint, it only returns the
  92. "_Integral" hint. This is useful if "all" causes
  93. pdsolve() to hang because of a difficult or impossible
  94. integral. This meta-hint will also be much faster than
  95. "all", because integrate() is an expensive routine.
  96. See also the classify_pde() docstring for more info on hints,
  97. and the pde docstring for a list of all supported hints.
  98. **Tips**
  99. - You can declare the derivative of an unknown function this way:
  100. >>> from sympy import Function, Derivative
  101. >>> from sympy.abc import x, y # x and y are the independent variables
  102. >>> f = Function("f")(x, y) # f is a function of x and y
  103. >>> # fx will be the partial derivative of f with respect to x
  104. >>> fx = Derivative(f, x)
  105. >>> # fy will be the partial derivative of f with respect to y
  106. >>> fy = Derivative(f, y)
  107. - See test_pde.py for many tests, which serves also as a set of
  108. examples for how to use pdsolve().
  109. - pdsolve always returns an Equality class (except for the case
  110. when the hint is "all" or "all_Integral"). Note that it is not possible
  111. to get an explicit solution for f(x, y) as in the case of ODE's
  112. - Do help(pde.pde_hintname) to get help more information on a
  113. specific hint
  114. Examples
  115. ========
  116. >>> from sympy.solvers.pde import pdsolve
  117. >>> from sympy import Function, Eq
  118. >>> from sympy.abc import x, y
  119. >>> f = Function('f')
  120. >>> u = f(x, y)
  121. >>> ux = u.diff(x)
  122. >>> uy = u.diff(y)
  123. >>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0)
  124. >>> pdsolve(eq)
  125. Eq(f(x, y), F(3*x - 2*y)*exp(-2*x/13 - 3*y/13))
  126. """
  127. if not solvefun:
  128. solvefun = Function('F')
  129. # See the docstring of _desolve for more details.
  130. hints = _desolve(eq, func=func, hint=hint, simplify=True,
  131. type='pde', **kwargs)
  132. eq = hints.pop('eq', False)
  133. all_ = hints.pop('all', False)
  134. if all_:
  135. # TODO : 'best' hint should be implemented when adequate
  136. # number of hints are added.
  137. pdedict = {}
  138. failed_hints = {}
  139. gethints = classify_pde(eq, dict=True)
  140. pdedict.update({'order': gethints['order'],
  141. 'default': gethints['default']})
  142. for hint in hints:
  143. try:
  144. rv = _helper_simplify(eq, hint, hints[hint]['func'],
  145. hints[hint]['order'], hints[hint][hint], solvefun)
  146. except NotImplementedError as detail:
  147. failed_hints[hint] = detail
  148. else:
  149. pdedict[hint] = rv
  150. pdedict.update(failed_hints)
  151. return pdedict
  152. else:
  153. return _helper_simplify(eq, hints['hint'], hints['func'],
  154. hints['order'], hints[hints['hint']], solvefun)
  155. def _helper_simplify(eq, hint, func, order, match, solvefun):
  156. """Helper function of pdsolve that calls the respective
  157. pde functions to solve for the partial differential
  158. equations. This minimizes the computation in
  159. calling _desolve multiple times.
  160. """
  161. if hint.endswith("_Integral"):
  162. solvefunc = globals()[
  163. "pde_" + hint[:-len("_Integral")]]
  164. else:
  165. solvefunc = globals()["pde_" + hint]
  166. return _handle_Integral(solvefunc(eq, func, order,
  167. match, solvefun), func, order, hint)
  168. def _handle_Integral(expr, func, order, hint):
  169. r"""
  170. Converts a solution with integrals in it into an actual solution.
  171. Simplifies the integral mainly using doit()
  172. """
  173. if hint.endswith("_Integral"):
  174. return expr
  175. elif hint == "1st_linear_constant_coeff":
  176. return simplify(expr.doit())
  177. else:
  178. return expr
  179. def classify_pde(eq, func=None, dict=False, *, prep=True, **kwargs):
  180. """
  181. Returns a tuple of possible pdsolve() classifications for a PDE.
  182. The tuple is ordered so that first item is the classification that
  183. pdsolve() uses to solve the PDE by default. In general,
  184. classifications near the beginning of the list will produce
  185. better solutions faster than those near the end, though there are
  186. always exceptions. To make pdsolve use a different classification,
  187. use pdsolve(PDE, func, hint=<classification>). See also the pdsolve()
  188. docstring for different meta-hints you can use.
  189. If ``dict`` is true, classify_pde() will return a dictionary of
  190. hint:match expression terms. This is intended for internal use by
  191. pdsolve(). Note that because dictionaries are ordered arbitrarily,
  192. this will most likely not be in the same order as the tuple.
  193. You can get help on different hints by doing help(pde.pde_hintname),
  194. where hintname is the name of the hint without "_Integral".
  195. See sympy.pde.allhints or the sympy.pde docstring for a list of all
  196. supported hints that can be returned from classify_pde.
  197. Examples
  198. ========
  199. >>> from sympy.solvers.pde import classify_pde
  200. >>> from sympy import Function, Eq
  201. >>> from sympy.abc import x, y
  202. >>> f = Function('f')
  203. >>> u = f(x, y)
  204. >>> ux = u.diff(x)
  205. >>> uy = u.diff(y)
  206. >>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0)
  207. >>> classify_pde(eq)
  208. ('1st_linear_constant_coeff_homogeneous',)
  209. """
  210. if func and len(func.args) != 2:
  211. raise NotImplementedError("Right now only partial "
  212. "differential equations of two variables are supported")
  213. if prep or func is None:
  214. prep, func_ = _preprocess(eq, func)
  215. if func is None:
  216. func = func_
  217. if isinstance(eq, Equality):
  218. if eq.rhs != 0:
  219. return classify_pde(eq.lhs - eq.rhs, func)
  220. eq = eq.lhs
  221. f = func.func
  222. x = func.args[0]
  223. y = func.args[1]
  224. fx = f(x,y).diff(x)
  225. fy = f(x,y).diff(y)
  226. # TODO : For now pde.py uses support offered by the ode_order function
  227. # to find the order with respect to a multi-variable function. An
  228. # improvement could be to classify the order of the PDE on the basis of
  229. # individual variables.
  230. order = ode_order(eq, f(x,y))
  231. # hint:matchdict or hint:(tuple of matchdicts)
  232. # Also will contain "default":<default hint> and "order":order items.
  233. matching_hints = {'order': order}
  234. if not order:
  235. if dict:
  236. matching_hints["default"] = None
  237. return matching_hints
  238. else:
  239. return ()
  240. eq = expand(eq)
  241. a = Wild('a', exclude = [f(x,y)])
  242. b = Wild('b', exclude = [f(x,y), fx, fy, x, y])
  243. c = Wild('c', exclude = [f(x,y), fx, fy, x, y])
  244. d = Wild('d', exclude = [f(x,y), fx, fy, x, y])
  245. e = Wild('e', exclude = [f(x,y), fx, fy])
  246. n = Wild('n', exclude = [x, y])
  247. # Try removing the smallest power of f(x,y)
  248. # from the highest partial derivatives of f(x,y)
  249. reduced_eq = None
  250. if eq.is_Add:
  251. var = set(combinations_with_replacement((x,y), order))
  252. dummyvar = var.copy()
  253. power = None
  254. for i in var:
  255. coeff = eq.coeff(f(x,y).diff(*i))
  256. if coeff != 1:
  257. match = coeff.match(a*f(x,y)**n)
  258. if match and match[a]:
  259. power = match[n]
  260. dummyvar.remove(i)
  261. break
  262. dummyvar.remove(i)
  263. for i in dummyvar:
  264. coeff = eq.coeff(f(x,y).diff(*i))
  265. if coeff != 1:
  266. match = coeff.match(a*f(x,y)**n)
  267. if match and match[a] and match[n] < power:
  268. power = match[n]
  269. if power:
  270. den = f(x,y)**power
  271. reduced_eq = Add(*[arg/den for arg in eq.args])
  272. if not reduced_eq:
  273. reduced_eq = eq
  274. if order == 1:
  275. reduced_eq = collect(reduced_eq, f(x, y))
  276. r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e)
  277. if r:
  278. if not r[e]:
  279. ## Linear first-order homogeneous partial-differential
  280. ## equation with constant coefficients
  281. r.update({'b': b, 'c': c, 'd': d})
  282. matching_hints["1st_linear_constant_coeff_homogeneous"] = r
  283. else:
  284. if r[b]**2 + r[c]**2 != 0:
  285. ## Linear first-order general partial-differential
  286. ## equation with constant coefficients
  287. r.update({'b': b, 'c': c, 'd': d, 'e': e})
  288. matching_hints["1st_linear_constant_coeff"] = r
  289. matching_hints[
  290. "1st_linear_constant_coeff_Integral"] = r
  291. else:
  292. b = Wild('b', exclude=[f(x, y), fx, fy])
  293. c = Wild('c', exclude=[f(x, y), fx, fy])
  294. d = Wild('d', exclude=[f(x, y), fx, fy])
  295. r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e)
  296. if r:
  297. r.update({'b': b, 'c': c, 'd': d, 'e': e})
  298. matching_hints["1st_linear_variable_coeff"] = r
  299. # Order keys based on allhints.
  300. retlist = []
  301. for i in allhints:
  302. if i in matching_hints:
  303. retlist.append(i)
  304. if dict:
  305. # Dictionaries are ordered arbitrarily, so make note of which
  306. # hint would come first for pdsolve(). Use an ordered dict in Py 3.
  307. matching_hints["default"] = None
  308. matching_hints["ordered_hints"] = tuple(retlist)
  309. for i in allhints:
  310. if i in matching_hints:
  311. matching_hints["default"] = i
  312. break
  313. return matching_hints
  314. else:
  315. return tuple(retlist)
  316. def checkpdesol(pde, sol, func=None, solve_for_func=True):
  317. """
  318. Checks if the given solution satisfies the partial differential
  319. equation.
  320. pde is the partial differential equation which can be given in the
  321. form of an equation or an expression. sol is the solution for which
  322. the pde is to be checked. This can also be given in an equation or
  323. an expression form. If the function is not provided, the helper
  324. function _preprocess from deutils is used to identify the function.
  325. If a sequence of solutions is passed, the same sort of container will be
  326. used to return the result for each solution.
  327. The following methods are currently being implemented to check if the
  328. solution satisfies the PDE:
  329. 1. Directly substitute the solution in the PDE and check. If the
  330. solution hasn't been solved for f, then it will solve for f
  331. provided solve_for_func hasn't been set to False.
  332. If the solution satisfies the PDE, then a tuple (True, 0) is returned.
  333. Otherwise a tuple (False, expr) where expr is the value obtained
  334. after substituting the solution in the PDE. However if a known solution
  335. returns False, it may be due to the inability of doit() to simplify it to zero.
  336. Examples
  337. ========
  338. >>> from sympy import Function, symbols
  339. >>> from sympy.solvers.pde import checkpdesol, pdsolve
  340. >>> x, y = symbols('x y')
  341. >>> f = Function('f')
  342. >>> eq = 2*f(x,y) + 3*f(x,y).diff(x) + 4*f(x,y).diff(y)
  343. >>> sol = pdsolve(eq)
  344. >>> assert checkpdesol(eq, sol)[0]
  345. >>> eq = x*f(x,y) + f(x,y).diff(x)
  346. >>> checkpdesol(eq, sol)
  347. (False, (x*F(4*x - 3*y) - 6*F(4*x - 3*y)/25 + 4*Subs(Derivative(F(_xi_1), _xi_1), _xi_1, 4*x - 3*y))*exp(-6*x/25 - 8*y/25))
  348. """
  349. # Converting the pde into an equation
  350. if not isinstance(pde, Equality):
  351. pde = Eq(pde, 0)
  352. # If no function is given, try finding the function present.
  353. if func is None:
  354. try:
  355. _, func = _preprocess(pde.lhs)
  356. except ValueError:
  357. funcs = [s.atoms(AppliedUndef) for s in (
  358. sol if is_sequence(sol, set) else [sol])]
  359. funcs = set().union(funcs)
  360. if len(funcs) != 1:
  361. raise ValueError(
  362. 'must pass func arg to checkpdesol for this case.')
  363. func = funcs.pop()
  364. # If the given solution is in the form of a list or a set
  365. # then return a list or set of tuples.
  366. if is_sequence(sol, set):
  367. return type(sol)([checkpdesol(
  368. pde, i, func=func,
  369. solve_for_func=solve_for_func) for i in sol])
  370. # Convert solution into an equation
  371. if not isinstance(sol, Equality):
  372. sol = Eq(func, sol)
  373. elif sol.rhs == func:
  374. sol = sol.reversed
  375. # Try solving for the function
  376. solved = sol.lhs == func and not sol.rhs.has(func)
  377. if solve_for_func and not solved:
  378. solved = solve(sol, func)
  379. if solved:
  380. if len(solved) == 1:
  381. return checkpdesol(pde, Eq(func, solved[0]),
  382. func=func, solve_for_func=False)
  383. else:
  384. return checkpdesol(pde, [Eq(func, t) for t in solved],
  385. func=func, solve_for_func=False)
  386. # try direct substitution of the solution into the PDE and simplify
  387. if sol.lhs == func:
  388. pde = pde.lhs - pde.rhs
  389. s = simplify(pde.subs(func, sol.rhs).doit())
  390. return s is S.Zero, s
  391. raise NotImplementedError(filldedent('''
  392. Unable to test if %s is a solution to %s.''' % (sol, pde)))
  393. def pde_1st_linear_constant_coeff_homogeneous(eq, func, order, match, solvefun):
  394. r"""
  395. Solves a first order linear homogeneous
  396. partial differential equation with constant coefficients.
  397. The general form of this partial differential equation is
  398. .. math:: a \frac{\partial f(x,y)}{\partial x}
  399. + b \frac{\partial f(x,y)}{\partial y} + c f(x,y) = 0
  400. where `a`, `b` and `c` are constants.
  401. The general solution is of the form:
  402. .. math::
  403. f(x, y) = F(- a y + b x ) e^{- \frac{c (a x + b y)}{a^2 + b^2}}
  404. and can be found in SymPy with ``pdsolve``::
  405. >>> from sympy.solvers import pdsolve
  406. >>> from sympy.abc import x, y, a, b, c
  407. >>> from sympy import Function, pprint
  408. >>> f = Function('f')
  409. >>> u = f(x,y)
  410. >>> ux = u.diff(x)
  411. >>> uy = u.diff(y)
  412. >>> genform = a*ux + b*uy + c*u
  413. >>> pprint(genform)
  414. d d
  415. a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y)
  416. dx dy
  417. >>> pprint(pdsolve(genform))
  418. -c*(a*x + b*y)
  419. ---------------
  420. 2 2
  421. a + b
  422. f(x, y) = F(-a*y + b*x)*e
  423. Examples
  424. ========
  425. >>> from sympy import pdsolve
  426. >>> from sympy import Function, pprint
  427. >>> from sympy.abc import x,y
  428. >>> f = Function('f')
  429. >>> pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y))
  430. Eq(f(x, y), F(x - y)*exp(-x/2 - y/2))
  431. >>> pprint(pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y)))
  432. x y
  433. - - - -
  434. 2 2
  435. f(x, y) = F(x - y)*e
  436. References
  437. ==========
  438. - Viktor Grigoryan, "Partial Differential Equations"
  439. Math 124A - Fall 2010, pp.7
  440. """
  441. # TODO : For now homogeneous first order linear PDE's having
  442. # two variables are implemented. Once there is support for
  443. # solving systems of ODE's, this can be extended to n variables.
  444. f = func.func
  445. x = func.args[0]
  446. y = func.args[1]
  447. b = match[match['b']]
  448. c = match[match['c']]
  449. d = match[match['d']]
  450. return Eq(f(x,y), exp(-S(d)/(b**2 + c**2)*(b*x + c*y))*solvefun(c*x - b*y))
  451. def pde_1st_linear_constant_coeff(eq, func, order, match, solvefun):
  452. r"""
  453. Solves a first order linear partial differential equation
  454. with constant coefficients.
  455. The general form of this partial differential equation is
  456. .. math:: a \frac{\partial f(x,y)}{\partial x}
  457. + b \frac{\partial f(x,y)}{\partial y}
  458. + c f(x,y) = G(x,y)
  459. where `a`, `b` and `c` are constants and `G(x, y)` can be an arbitrary
  460. function in `x` and `y`.
  461. The general solution of the PDE is:
  462. .. math::
  463. f(x, y) = \left. \left[F(\eta) + \frac{1}{a^2 + b^2}
  464. \int\limits^{a x + b y} G\left(\frac{a \xi + b \eta}{a^2 + b^2},
  465. \frac{- a \eta + b \xi}{a^2 + b^2} \right)
  466. e^{\frac{c \xi}{a^2 + b^2}}\, d\xi\right]
  467. e^{- \frac{c \xi}{a^2 + b^2}}
  468. \right|_{\substack{\eta=- a y + b x\\ \xi=a x + b y }}\, ,
  469. where `F(\eta)` is an arbitrary single-valued function. The solution
  470. can be found in SymPy with ``pdsolve``::
  471. >>> from sympy.solvers import pdsolve
  472. >>> from sympy.abc import x, y, a, b, c
  473. >>> from sympy import Function, pprint
  474. >>> f = Function('f')
  475. >>> G = Function('G')
  476. >>> u = f(x,y)
  477. >>> ux = u.diff(x)
  478. >>> uy = u.diff(y)
  479. >>> genform = a*ux + b*uy + c*u - G(x,y)
  480. >>> pprint(genform)
  481. d d
  482. a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y) - G(x, y)
  483. dx dy
  484. >>> pprint(pdsolve(genform, hint='1st_linear_constant_coeff_Integral'))
  485. // a*x + b*y \
  486. || / |
  487. || | |
  488. || | c*xi |
  489. || | ------- |
  490. || | 2 2 |
  491. || | /a*xi + b*eta -a*eta + b*xi\ a + b |
  492. || | G|------------, -------------|*e d(xi)|
  493. || | | 2 2 2 2 | |
  494. || | \ a + b a + b / |
  495. || | |
  496. || / |
  497. || |
  498. f(x, y) = ||F(eta) + -------------------------------------------------------|*
  499. || 2 2 |
  500. \\ a + b /
  501. <BLANKLINE>
  502. \|
  503. ||
  504. ||
  505. ||
  506. ||
  507. ||
  508. ||
  509. ||
  510. ||
  511. -c*xi ||
  512. -------||
  513. 2 2||
  514. a + b ||
  515. e ||
  516. ||
  517. /|eta=-a*y + b*x, xi=a*x + b*y
  518. Examples
  519. ========
  520. >>> from sympy.solvers.pde import pdsolve
  521. >>> from sympy import Function, pprint, exp
  522. >>> from sympy.abc import x,y
  523. >>> f = Function('f')
  524. >>> eq = -2*f(x,y).diff(x) + 4*f(x,y).diff(y) + 5*f(x,y) - exp(x + 3*y)
  525. >>> pdsolve(eq)
  526. Eq(f(x, y), (F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y))
  527. References
  528. ==========
  529. - Viktor Grigoryan, "Partial Differential Equations"
  530. Math 124A - Fall 2010, pp.7
  531. """
  532. # TODO : For now homogeneous first order linear PDE's having
  533. # two variables are implemented. Once there is support for
  534. # solving systems of ODE's, this can be extended to n variables.
  535. xi, eta = symbols("xi eta")
  536. f = func.func
  537. x = func.args[0]
  538. y = func.args[1]
  539. b = match[match['b']]
  540. c = match[match['c']]
  541. d = match[match['d']]
  542. e = -match[match['e']]
  543. expterm = exp(-S(d)/(b**2 + c**2)*xi)
  544. functerm = solvefun(eta)
  545. solvedict = solve((b*x + c*y - xi, c*x - b*y - eta), x, y)
  546. # Integral should remain as it is in terms of xi,
  547. # doit() should be done in _handle_Integral.
  548. genterm = (1/S(b**2 + c**2))*Integral(
  549. (1/expterm*e).subs(solvedict), (xi, b*x + c*y))
  550. return Eq(f(x,y), Subs(expterm*(functerm + genterm),
  551. (eta, xi), (c*x - b*y, b*x + c*y)))
  552. def pde_1st_linear_variable_coeff(eq, func, order, match, solvefun):
  553. r"""
  554. Solves a first order linear partial differential equation
  555. with variable coefficients. The general form of this partial
  556. differential equation is
  557. .. math:: a(x, y) \frac{\partial f(x, y)}{\partial x}
  558. + b(x, y) \frac{\partial f(x, y)}{\partial y}
  559. + c(x, y) f(x, y) = G(x, y)
  560. where `a(x, y)`, `b(x, y)`, `c(x, y)` and `G(x, y)` are arbitrary
  561. functions in `x` and `y`. This PDE is converted into an ODE by
  562. making the following transformation:
  563. 1. `\xi` as `x`
  564. 2. `\eta` as the constant in the solution to the differential
  565. equation `\frac{dy}{dx} = -\frac{b}{a}`
  566. Making the previous substitutions reduces it to the linear ODE
  567. .. math:: a(\xi, \eta)\frac{du}{d\xi} + c(\xi, \eta)u - G(\xi, \eta) = 0
  568. which can be solved using ``dsolve``.
  569. >>> from sympy.abc import x, y
  570. >>> from sympy import Function, pprint
  571. >>> a, b, c, G, f= [Function(i) for i in ['a', 'b', 'c', 'G', 'f']]
  572. >>> u = f(x,y)
  573. >>> ux = u.diff(x)
  574. >>> uy = u.diff(y)
  575. >>> genform = a(x, y)*u + b(x, y)*ux + c(x, y)*uy - G(x,y)
  576. >>> pprint(genform)
  577. d d
  578. -G(x, y) + a(x, y)*f(x, y) + b(x, y)*--(f(x, y)) + c(x, y)*--(f(x, y))
  579. dx dy
  580. Examples
  581. ========
  582. >>> from sympy.solvers.pde import pdsolve
  583. >>> from sympy import Function, pprint
  584. >>> from sympy.abc import x,y
  585. >>> f = Function('f')
  586. >>> eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2
  587. >>> pdsolve(eq)
  588. Eq(f(x, y), F(x*y)*exp(y**2/2) + 1)
  589. References
  590. ==========
  591. - Viktor Grigoryan, "Partial Differential Equations"
  592. Math 124A - Fall 2010, pp.7
  593. """
  594. from sympy.integrals.integrals import integrate
  595. from sympy.solvers.ode import dsolve
  596. xi, eta = symbols("xi eta")
  597. f = func.func
  598. x = func.args[0]
  599. y = func.args[1]
  600. b = match[match['b']]
  601. c = match[match['c']]
  602. d = match[match['d']]
  603. e = -match[match['e']]
  604. if not d:
  605. # To deal with cases like b*ux = e or c*uy = e
  606. if not (b and c):
  607. if c:
  608. try:
  609. tsol = integrate(e/c, y)
  610. except NotImplementedError:
  611. raise NotImplementedError("Unable to find a solution"
  612. " due to inability of integrate")
  613. else:
  614. return Eq(f(x,y), solvefun(x) + tsol)
  615. if b:
  616. try:
  617. tsol = integrate(e/b, x)
  618. except NotImplementedError:
  619. raise NotImplementedError("Unable to find a solution"
  620. " due to inability of integrate")
  621. else:
  622. return Eq(f(x,y), solvefun(y) + tsol)
  623. if not c:
  624. # To deal with cases when c is 0, a simpler method is used.
  625. # The PDE reduces to b*(u.diff(x)) + d*u = e, which is a linear ODE in x
  626. plode = f(x).diff(x)*b + d*f(x) - e
  627. sol = dsolve(plode, f(x))
  628. syms = sol.free_symbols - plode.free_symbols - {x, y}
  629. rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, y)
  630. return Eq(f(x, y), rhs)
  631. if not b:
  632. # To deal with cases when b is 0, a simpler method is used.
  633. # The PDE reduces to c*(u.diff(y)) + d*u = e, which is a linear ODE in y
  634. plode = f(y).diff(y)*c + d*f(y) - e
  635. sol = dsolve(plode, f(y))
  636. syms = sol.free_symbols - plode.free_symbols - {x, y}
  637. rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, x)
  638. return Eq(f(x, y), rhs)
  639. dummy = Function('d')
  640. h = (c/b).subs(y, dummy(x))
  641. sol = dsolve(dummy(x).diff(x) - h, dummy(x))
  642. if isinstance(sol, list):
  643. sol = sol[0]
  644. solsym = sol.free_symbols - h.free_symbols - {x, y}
  645. if len(solsym) == 1:
  646. solsym = solsym.pop()
  647. etat = (solve(sol, solsym)[0]).subs(dummy(x), y)
  648. ysub = solve(eta - etat, y)[0]
  649. deq = (b*(f(x).diff(x)) + d*f(x) - e).subs(y, ysub)
  650. final = (dsolve(deq, f(x), hint='1st_linear')).rhs
  651. if isinstance(final, list):
  652. final = final[0]
  653. finsyms = final.free_symbols - deq.free_symbols - {x, y}
  654. rhs = _simplify_variable_coeff(final, finsyms, solvefun, etat)
  655. return Eq(f(x, y), rhs)
  656. else:
  657. raise NotImplementedError("Cannot solve the partial differential equation due"
  658. " to inability of constantsimp")
  659. def _simplify_variable_coeff(sol, syms, func, funcarg):
  660. r"""
  661. Helper function to replace constants by functions in 1st_linear_variable_coeff
  662. """
  663. eta = Symbol("eta")
  664. if len(syms) == 1:
  665. sym = syms.pop()
  666. final = sol.subs(sym, func(funcarg))
  667. else:
  668. for key, sym in enumerate(syms):
  669. final = sol.subs(sym, func(funcarg))
  670. return simplify(final.subs(eta, funcarg))
  671. def pde_separate(eq, fun, sep, strategy='mul'):
  672. """Separate variables in partial differential equation either by additive
  673. or multiplicative separation approach. It tries to rewrite an equation so
  674. that one of the specified variables occurs on a different side of the
  675. equation than the others.
  676. :param eq: Partial differential equation
  677. :param fun: Original function F(x, y, z)
  678. :param sep: List of separated functions [X(x), u(y, z)]
  679. :param strategy: Separation strategy. You can choose between additive
  680. separation ('add') and multiplicative separation ('mul') which is
  681. default.
  682. Examples
  683. ========
  684. >>> from sympy import E, Eq, Function, pde_separate, Derivative as D
  685. >>> from sympy.abc import x, t
  686. >>> u, X, T = map(Function, 'uXT')
  687. >>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
  688. >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='add')
  689. [exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
  690. >>> eq = Eq(D(u(x, t), x, 2), D(u(x, t), t, 2))
  691. >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='mul')
  692. [Derivative(X(x), (x, 2))/X(x), Derivative(T(t), (t, 2))/T(t)]
  693. See Also
  694. ========
  695. pde_separate_add, pde_separate_mul
  696. """
  697. do_add = False
  698. if strategy == 'add':
  699. do_add = True
  700. elif strategy == 'mul':
  701. do_add = False
  702. else:
  703. raise ValueError('Unknown strategy: %s' % strategy)
  704. if isinstance(eq, Equality):
  705. if eq.rhs != 0:
  706. return pde_separate(Eq(eq.lhs - eq.rhs, 0), fun, sep, strategy)
  707. else:
  708. return pde_separate(Eq(eq, 0), fun, sep, strategy)
  709. if eq.rhs != 0:
  710. raise ValueError("Value should be 0")
  711. # Handle arguments
  712. orig_args = list(fun.args)
  713. subs_args = []
  714. for s in sep:
  715. for j in range(0, len(s.args)):
  716. subs_args.append(s.args[j])
  717. if do_add:
  718. functions = reduce(operator.add, sep)
  719. else:
  720. functions = reduce(operator.mul, sep)
  721. # Check whether variables match
  722. if len(subs_args) != len(orig_args):
  723. raise ValueError("Variable counts do not match")
  724. # Check for duplicate arguments like [X(x), u(x, y)]
  725. if has_dups(subs_args):
  726. raise ValueError("Duplicate substitution arguments detected")
  727. # Check whether the variables match
  728. if set(orig_args) != set(subs_args):
  729. raise ValueError("Arguments do not match")
  730. # Substitute original function with separated...
  731. result = eq.lhs.subs(fun, functions).doit()
  732. # Divide by terms when doing multiplicative separation
  733. if not do_add:
  734. eq = 0
  735. for i in result.args:
  736. eq += i/functions
  737. result = eq
  738. svar = subs_args[0]
  739. dvar = subs_args[1:]
  740. return _separate(result, svar, dvar)
  741. def pde_separate_add(eq, fun, sep):
  742. """
  743. Helper function for searching additive separable solutions.
  744. Consider an equation of two independent variables x, y and a dependent
  745. variable w, we look for the product of two functions depending on different
  746. arguments:
  747. `w(x, y, z) = X(x) + y(y, z)`
  748. Examples
  749. ========
  750. >>> from sympy import E, Eq, Function, pde_separate_add, Derivative as D
  751. >>> from sympy.abc import x, t
  752. >>> u, X, T = map(Function, 'uXT')
  753. >>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
  754. >>> pde_separate_add(eq, u(x, t), [X(x), T(t)])
  755. [exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
  756. """
  757. return pde_separate(eq, fun, sep, strategy='add')
  758. def pde_separate_mul(eq, fun, sep):
  759. """
  760. Helper function for searching multiplicative separable solutions.
  761. Consider an equation of two independent variables x, y and a dependent
  762. variable w, we look for the product of two functions depending on different
  763. arguments:
  764. `w(x, y, z) = X(x)*u(y, z)`
  765. Examples
  766. ========
  767. >>> from sympy import Function, Eq, pde_separate_mul, Derivative as D
  768. >>> from sympy.abc import x, y
  769. >>> u, X, Y = map(Function, 'uXY')
  770. >>> eq = Eq(D(u(x, y), x, 2), D(u(x, y), y, 2))
  771. >>> pde_separate_mul(eq, u(x, y), [X(x), Y(y)])
  772. [Derivative(X(x), (x, 2))/X(x), Derivative(Y(y), (y, 2))/Y(y)]
  773. """
  774. return pde_separate(eq, fun, sep, strategy='mul')
  775. def _separate(eq, dep, others):
  776. """Separate expression into two parts based on dependencies of variables."""
  777. # FIRST PASS
  778. # Extract derivatives depending our separable variable...
  779. terms = set()
  780. for term in eq.args:
  781. if term.is_Mul:
  782. for i in term.args:
  783. if i.is_Derivative and not i.has(*others):
  784. terms.add(term)
  785. continue
  786. elif term.is_Derivative and not term.has(*others):
  787. terms.add(term)
  788. # Find the factor that we need to divide by
  789. div = set()
  790. for term in terms:
  791. ext, sep = term.expand().as_independent(dep)
  792. # Failed?
  793. if sep.has(*others):
  794. return None
  795. div.add(ext)
  796. # FIXME: Find lcm() of all the divisors and divide with it, instead of
  797. # current hack :(
  798. # https://github.com/sympy/sympy/issues/4597
  799. if len(div) > 0:
  800. final = 0
  801. for term in eq.args:
  802. eqn = 0
  803. for i in div:
  804. eqn += term / i
  805. final += simplify(eqn)
  806. eq = final
  807. # SECOND PASS - separate the derivatives
  808. div = set()
  809. lhs = rhs = 0
  810. for term in eq.args:
  811. # Check, whether we have already term with independent variable...
  812. if not term.has(*others):
  813. lhs += term
  814. continue
  815. # ...otherwise, try to separate
  816. temp, sep = term.expand().as_independent(dep)
  817. # Failed?
  818. if sep.has(*others):
  819. return None
  820. # Extract the divisors
  821. div.add(sep)
  822. rhs -= term.expand()
  823. # Do the division
  824. fulldiv = reduce(operator.add, div)
  825. lhs = simplify(lhs/fulldiv).expand()
  826. rhs = simplify(rhs/fulldiv).expand()
  827. # ...and check whether we were successful :)
  828. if lhs.has(*others) or rhs.has(dep):
  829. return None
  830. return [lhs, rhs]