pde.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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, integrate
  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 could not 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 = [i for i in allhints if i in matching_hints]
  301. if dict:
  302. # Dictionaries are ordered arbitrarily, so make note of which
  303. # hint would come first for pdsolve(). Use an ordered dict in Py 3.
  304. matching_hints["default"] = None
  305. matching_hints["ordered_hints"] = tuple(retlist)
  306. for i in allhints:
  307. if i in matching_hints:
  308. matching_hints["default"] = i
  309. break
  310. return matching_hints
  311. else:
  312. return tuple(retlist)
  313. def checkpdesol(pde, sol, func=None, solve_for_func=True):
  314. """
  315. Checks if the given solution satisfies the partial differential
  316. equation.
  317. pde is the partial differential equation which can be given in the
  318. form of an equation or an expression. sol is the solution for which
  319. the pde is to be checked. This can also be given in an equation or
  320. an expression form. If the function is not provided, the helper
  321. function _preprocess from deutils is used to identify the function.
  322. If a sequence of solutions is passed, the same sort of container will be
  323. used to return the result for each solution.
  324. The following methods are currently being implemented to check if the
  325. solution satisfies the PDE:
  326. 1. Directly substitute the solution in the PDE and check. If the
  327. solution has not been solved for f, then it will solve for f
  328. provided solve_for_func has not been set to False.
  329. If the solution satisfies the PDE, then a tuple (True, 0) is returned.
  330. Otherwise a tuple (False, expr) where expr is the value obtained
  331. after substituting the solution in the PDE. However if a known solution
  332. returns False, it may be due to the inability of doit() to simplify it to zero.
  333. Examples
  334. ========
  335. >>> from sympy import Function, symbols
  336. >>> from sympy.solvers.pde import checkpdesol, pdsolve
  337. >>> x, y = symbols('x y')
  338. >>> f = Function('f')
  339. >>> eq = 2*f(x,y) + 3*f(x,y).diff(x) + 4*f(x,y).diff(y)
  340. >>> sol = pdsolve(eq)
  341. >>> assert checkpdesol(eq, sol)[0]
  342. >>> eq = x*f(x,y) + f(x,y).diff(x)
  343. >>> checkpdesol(eq, sol)
  344. (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))
  345. """
  346. # Converting the pde into an equation
  347. if not isinstance(pde, Equality):
  348. pde = Eq(pde, 0)
  349. # If no function is given, try finding the function present.
  350. if func is None:
  351. try:
  352. _, func = _preprocess(pde.lhs)
  353. except ValueError:
  354. funcs = [s.atoms(AppliedUndef) for s in (
  355. sol if is_sequence(sol, set) else [sol])]
  356. funcs = set().union(funcs)
  357. if len(funcs) != 1:
  358. raise ValueError(
  359. 'must pass func arg to checkpdesol for this case.')
  360. func = funcs.pop()
  361. # If the given solution is in the form of a list or a set
  362. # then return a list or set of tuples.
  363. if is_sequence(sol, set):
  364. return type(sol)([checkpdesol(
  365. pde, i, func=func,
  366. solve_for_func=solve_for_func) for i in sol])
  367. # Convert solution into an equation
  368. if not isinstance(sol, Equality):
  369. sol = Eq(func, sol)
  370. elif sol.rhs == func:
  371. sol = sol.reversed
  372. # Try solving for the function
  373. solved = sol.lhs == func and not sol.rhs.has(func)
  374. if solve_for_func and not solved:
  375. solved = solve(sol, func)
  376. if solved:
  377. if len(solved) == 1:
  378. return checkpdesol(pde, Eq(func, solved[0]),
  379. func=func, solve_for_func=False)
  380. else:
  381. return checkpdesol(pde, [Eq(func, t) for t in solved],
  382. func=func, solve_for_func=False)
  383. # try direct substitution of the solution into the PDE and simplify
  384. if sol.lhs == func:
  385. pde = pde.lhs - pde.rhs
  386. s = simplify(pde.subs(func, sol.rhs).doit())
  387. return s is S.Zero, s
  388. raise NotImplementedError(filldedent('''
  389. Unable to test if %s is a solution to %s.''' % (sol, pde)))
  390. def pde_1st_linear_constant_coeff_homogeneous(eq, func, order, match, solvefun):
  391. r"""
  392. Solves a first order linear homogeneous
  393. partial differential equation with constant coefficients.
  394. The general form of this partial differential equation is
  395. .. math:: a \frac{\partial f(x,y)}{\partial x}
  396. + b \frac{\partial f(x,y)}{\partial y} + c f(x,y) = 0
  397. where `a`, `b` and `c` are constants.
  398. The general solution is of the form:
  399. .. math::
  400. f(x, y) = F(- a y + b x ) e^{- \frac{c (a x + b y)}{a^2 + b^2}}
  401. and can be found in SymPy with ``pdsolve``::
  402. >>> from sympy.solvers import pdsolve
  403. >>> from sympy.abc import x, y, a, b, c
  404. >>> from sympy import Function, pprint
  405. >>> f = Function('f')
  406. >>> u = f(x,y)
  407. >>> ux = u.diff(x)
  408. >>> uy = u.diff(y)
  409. >>> genform = a*ux + b*uy + c*u
  410. >>> pprint(genform)
  411. d d
  412. a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y)
  413. dx dy
  414. >>> pprint(pdsolve(genform))
  415. -c*(a*x + b*y)
  416. ---------------
  417. 2 2
  418. a + b
  419. f(x, y) = F(-a*y + b*x)*e
  420. Examples
  421. ========
  422. >>> from sympy import pdsolve
  423. >>> from sympy import Function, pprint
  424. >>> from sympy.abc import x,y
  425. >>> f = Function('f')
  426. >>> pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y))
  427. Eq(f(x, y), F(x - y)*exp(-x/2 - y/2))
  428. >>> pprint(pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y)))
  429. x y
  430. - - - -
  431. 2 2
  432. f(x, y) = F(x - y)*e
  433. References
  434. ==========
  435. - Viktor Grigoryan, "Partial Differential Equations"
  436. Math 124A - Fall 2010, pp.7
  437. """
  438. # TODO : For now homogeneous first order linear PDE's having
  439. # two variables are implemented. Once there is support for
  440. # solving systems of ODE's, this can be extended to n variables.
  441. f = func.func
  442. x = func.args[0]
  443. y = func.args[1]
  444. b = match[match['b']]
  445. c = match[match['c']]
  446. d = match[match['d']]
  447. return Eq(f(x,y), exp(-S(d)/(b**2 + c**2)*(b*x + c*y))*solvefun(c*x - b*y))
  448. def pde_1st_linear_constant_coeff(eq, func, order, match, solvefun):
  449. r"""
  450. Solves a first order linear partial differential equation
  451. with constant coefficients.
  452. The general form of this partial differential equation is
  453. .. math:: a \frac{\partial f(x,y)}{\partial x}
  454. + b \frac{\partial f(x,y)}{\partial y}
  455. + c f(x,y) = G(x,y)
  456. where `a`, `b` and `c` are constants and `G(x, y)` can be an arbitrary
  457. function in `x` and `y`.
  458. The general solution of the PDE is:
  459. .. math::
  460. f(x, y) = \left. \left[F(\eta) + \frac{1}{a^2 + b^2}
  461. \int\limits^{a x + b y} G\left(\frac{a \xi + b \eta}{a^2 + b^2},
  462. \frac{- a \eta + b \xi}{a^2 + b^2} \right)
  463. e^{\frac{c \xi}{a^2 + b^2}}\, d\xi\right]
  464. e^{- \frac{c \xi}{a^2 + b^2}}
  465. \right|_{\substack{\eta=- a y + b x\\ \xi=a x + b y }}\, ,
  466. where `F(\eta)` is an arbitrary single-valued function. The solution
  467. can be found in SymPy with ``pdsolve``::
  468. >>> from sympy.solvers import pdsolve
  469. >>> from sympy.abc import x, y, a, b, c
  470. >>> from sympy import Function, pprint
  471. >>> f = Function('f')
  472. >>> G = Function('G')
  473. >>> u = f(x,y)
  474. >>> ux = u.diff(x)
  475. >>> uy = u.diff(y)
  476. >>> genform = a*ux + b*uy + c*u - G(x,y)
  477. >>> pprint(genform)
  478. d d
  479. a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y) - G(x, y)
  480. dx dy
  481. >>> pprint(pdsolve(genform, hint='1st_linear_constant_coeff_Integral'))
  482. // a*x + b*y \
  483. || / |
  484. || | |
  485. || | c*xi |
  486. || | ------- |
  487. || | 2 2 |
  488. || | /a*xi + b*eta -a*eta + b*xi\ a + b |
  489. || | G|------------, -------------|*e d(xi)|
  490. || | | 2 2 2 2 | |
  491. || | \ a + b a + b / |
  492. || | |
  493. || / |
  494. || |
  495. f(x, y) = ||F(eta) + -------------------------------------------------------|*
  496. || 2 2 |
  497. \\ a + b /
  498. <BLANKLINE>
  499. \|
  500. ||
  501. ||
  502. ||
  503. ||
  504. ||
  505. ||
  506. ||
  507. ||
  508. -c*xi ||
  509. -------||
  510. 2 2||
  511. a + b ||
  512. e ||
  513. ||
  514. /|eta=-a*y + b*x, xi=a*x + b*y
  515. Examples
  516. ========
  517. >>> from sympy.solvers.pde import pdsolve
  518. >>> from sympy import Function, pprint, exp
  519. >>> from sympy.abc import x,y
  520. >>> f = Function('f')
  521. >>> eq = -2*f(x,y).diff(x) + 4*f(x,y).diff(y) + 5*f(x,y) - exp(x + 3*y)
  522. >>> pdsolve(eq)
  523. Eq(f(x, y), (F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y))
  524. References
  525. ==========
  526. - Viktor Grigoryan, "Partial Differential Equations"
  527. Math 124A - Fall 2010, pp.7
  528. """
  529. # TODO : For now homogeneous first order linear PDE's having
  530. # two variables are implemented. Once there is support for
  531. # solving systems of ODE's, this can be extended to n variables.
  532. xi, eta = symbols("xi eta")
  533. f = func.func
  534. x = func.args[0]
  535. y = func.args[1]
  536. b = match[match['b']]
  537. c = match[match['c']]
  538. d = match[match['d']]
  539. e = -match[match['e']]
  540. expterm = exp(-S(d)/(b**2 + c**2)*xi)
  541. functerm = solvefun(eta)
  542. solvedict = solve((b*x + c*y - xi, c*x - b*y - eta), x, y)
  543. # Integral should remain as it is in terms of xi,
  544. # doit() should be done in _handle_Integral.
  545. genterm = (1/S(b**2 + c**2))*Integral(
  546. (1/expterm*e).subs(solvedict), (xi, b*x + c*y))
  547. return Eq(f(x,y), Subs(expterm*(functerm + genterm),
  548. (eta, xi), (c*x - b*y, b*x + c*y)))
  549. def pde_1st_linear_variable_coeff(eq, func, order, match, solvefun):
  550. r"""
  551. Solves a first order linear partial differential equation
  552. with variable coefficients. The general form of this partial
  553. differential equation is
  554. .. math:: a(x, y) \frac{\partial f(x, y)}{\partial x}
  555. + b(x, y) \frac{\partial f(x, y)}{\partial y}
  556. + c(x, y) f(x, y) = G(x, y)
  557. where `a(x, y)`, `b(x, y)`, `c(x, y)` and `G(x, y)` are arbitrary
  558. functions in `x` and `y`. This PDE is converted into an ODE by
  559. making the following transformation:
  560. 1. `\xi` as `x`
  561. 2. `\eta` as the constant in the solution to the differential
  562. equation `\frac{dy}{dx} = -\frac{b}{a}`
  563. Making the previous substitutions reduces it to the linear ODE
  564. .. math:: a(\xi, \eta)\frac{du}{d\xi} + c(\xi, \eta)u - G(\xi, \eta) = 0
  565. which can be solved using ``dsolve``.
  566. >>> from sympy.abc import x, y
  567. >>> from sympy import Function, pprint
  568. >>> a, b, c, G, f= [Function(i) for i in ['a', 'b', 'c', 'G', 'f']]
  569. >>> u = f(x,y)
  570. >>> ux = u.diff(x)
  571. >>> uy = u.diff(y)
  572. >>> genform = a(x, y)*u + b(x, y)*ux + c(x, y)*uy - G(x,y)
  573. >>> pprint(genform)
  574. d d
  575. -G(x, y) + a(x, y)*f(x, y) + b(x, y)*--(f(x, y)) + c(x, y)*--(f(x, y))
  576. dx dy
  577. Examples
  578. ========
  579. >>> from sympy.solvers.pde import pdsolve
  580. >>> from sympy import Function, pprint
  581. >>> from sympy.abc import x,y
  582. >>> f = Function('f')
  583. >>> eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2
  584. >>> pdsolve(eq)
  585. Eq(f(x, y), F(x*y)*exp(y**2/2) + 1)
  586. References
  587. ==========
  588. - Viktor Grigoryan, "Partial Differential Equations"
  589. Math 124A - Fall 2010, pp.7
  590. """
  591. from sympy.solvers.ode import dsolve
  592. xi, eta = symbols("xi eta")
  593. f = func.func
  594. x = func.args[0]
  595. y = func.args[1]
  596. b = match[match['b']]
  597. c = match[match['c']]
  598. d = match[match['d']]
  599. e = -match[match['e']]
  600. if not d:
  601. # To deal with cases like b*ux = e or c*uy = e
  602. if not (b and c):
  603. if c:
  604. try:
  605. tsol = integrate(e/c, y)
  606. except NotImplementedError:
  607. raise NotImplementedError("Unable to find a solution"
  608. " due to inability of integrate")
  609. else:
  610. return Eq(f(x,y), solvefun(x) + tsol)
  611. if b:
  612. try:
  613. tsol = integrate(e/b, x)
  614. except NotImplementedError:
  615. raise NotImplementedError("Unable to find a solution"
  616. " due to inability of integrate")
  617. else:
  618. return Eq(f(x,y), solvefun(y) + tsol)
  619. if not c:
  620. # To deal with cases when c is 0, a simpler method is used.
  621. # The PDE reduces to b*(u.diff(x)) + d*u = e, which is a linear ODE in x
  622. plode = f(x).diff(x)*b + d*f(x) - e
  623. sol = dsolve(plode, f(x))
  624. syms = sol.free_symbols - plode.free_symbols - {x, y}
  625. rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, y)
  626. return Eq(f(x, y), rhs)
  627. if not b:
  628. # To deal with cases when b is 0, a simpler method is used.
  629. # The PDE reduces to c*(u.diff(y)) + d*u = e, which is a linear ODE in y
  630. plode = f(y).diff(y)*c + d*f(y) - e
  631. sol = dsolve(plode, f(y))
  632. syms = sol.free_symbols - plode.free_symbols - {x, y}
  633. rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, x)
  634. return Eq(f(x, y), rhs)
  635. dummy = Function('d')
  636. h = (c/b).subs(y, dummy(x))
  637. sol = dsolve(dummy(x).diff(x) - h, dummy(x))
  638. if isinstance(sol, list):
  639. sol = sol[0]
  640. solsym = sol.free_symbols - h.free_symbols - {x, y}
  641. if len(solsym) == 1:
  642. solsym = solsym.pop()
  643. etat = (solve(sol, solsym)[0]).subs(dummy(x), y)
  644. ysub = solve(eta - etat, y)[0]
  645. deq = (b*(f(x).diff(x)) + d*f(x) - e).subs(y, ysub)
  646. final = (dsolve(deq, f(x), hint='1st_linear')).rhs
  647. if isinstance(final, list):
  648. final = final[0]
  649. finsyms = final.free_symbols - deq.free_symbols - {x, y}
  650. rhs = _simplify_variable_coeff(final, finsyms, solvefun, etat)
  651. return Eq(f(x, y), rhs)
  652. else:
  653. raise NotImplementedError("Cannot solve the partial differential equation due"
  654. " to inability of constantsimp")
  655. def _simplify_variable_coeff(sol, syms, func, funcarg):
  656. r"""
  657. Helper function to replace constants by functions in 1st_linear_variable_coeff
  658. """
  659. eta = Symbol("eta")
  660. if len(syms) == 1:
  661. sym = syms.pop()
  662. final = sol.subs(sym, func(funcarg))
  663. else:
  664. for key, sym in enumerate(syms):
  665. final = sol.subs(sym, func(funcarg))
  666. return simplify(final.subs(eta, funcarg))
  667. def pde_separate(eq, fun, sep, strategy='mul'):
  668. """Separate variables in partial differential equation either by additive
  669. or multiplicative separation approach. It tries to rewrite an equation so
  670. that one of the specified variables occurs on a different side of the
  671. equation than the others.
  672. :param eq: Partial differential equation
  673. :param fun: Original function F(x, y, z)
  674. :param sep: List of separated functions [X(x), u(y, z)]
  675. :param strategy: Separation strategy. You can choose between additive
  676. separation ('add') and multiplicative separation ('mul') which is
  677. default.
  678. Examples
  679. ========
  680. >>> from sympy import E, Eq, Function, pde_separate, Derivative as D
  681. >>> from sympy.abc import x, t
  682. >>> u, X, T = map(Function, 'uXT')
  683. >>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
  684. >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='add')
  685. [exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
  686. >>> eq = Eq(D(u(x, t), x, 2), D(u(x, t), t, 2))
  687. >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='mul')
  688. [Derivative(X(x), (x, 2))/X(x), Derivative(T(t), (t, 2))/T(t)]
  689. See Also
  690. ========
  691. pde_separate_add, pde_separate_mul
  692. """
  693. do_add = False
  694. if strategy == 'add':
  695. do_add = True
  696. elif strategy == 'mul':
  697. do_add = False
  698. else:
  699. raise ValueError('Unknown strategy: %s' % strategy)
  700. if isinstance(eq, Equality):
  701. if eq.rhs != 0:
  702. return pde_separate(Eq(eq.lhs - eq.rhs, 0), fun, sep, strategy)
  703. else:
  704. return pde_separate(Eq(eq, 0), fun, sep, strategy)
  705. if eq.rhs != 0:
  706. raise ValueError("Value should be 0")
  707. # Handle arguments
  708. orig_args = list(fun.args)
  709. subs_args = [arg for s in sep for arg in s.args]
  710. if do_add:
  711. functions = reduce(operator.add, sep)
  712. else:
  713. functions = reduce(operator.mul, sep)
  714. # Check whether variables match
  715. if len(subs_args) != len(orig_args):
  716. raise ValueError("Variable counts do not match")
  717. # Check for duplicate arguments like [X(x), u(x, y)]
  718. if has_dups(subs_args):
  719. raise ValueError("Duplicate substitution arguments detected")
  720. # Check whether the variables match
  721. if set(orig_args) != set(subs_args):
  722. raise ValueError("Arguments do not match")
  723. # Substitute original function with separated...
  724. result = eq.lhs.subs(fun, functions).doit()
  725. # Divide by terms when doing multiplicative separation
  726. if not do_add:
  727. eq = 0
  728. for i in result.args:
  729. eq += i/functions
  730. result = eq
  731. svar = subs_args[0]
  732. dvar = subs_args[1:]
  733. return _separate(result, svar, dvar)
  734. def pde_separate_add(eq, fun, sep):
  735. """
  736. Helper function for searching additive separable solutions.
  737. Consider an equation of two independent variables x, y and a dependent
  738. variable w, we look for the product of two functions depending on different
  739. arguments:
  740. `w(x, y, z) = X(x) + y(y, z)`
  741. Examples
  742. ========
  743. >>> from sympy import E, Eq, Function, pde_separate_add, Derivative as D
  744. >>> from sympy.abc import x, t
  745. >>> u, X, T = map(Function, 'uXT')
  746. >>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
  747. >>> pde_separate_add(eq, u(x, t), [X(x), T(t)])
  748. [exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
  749. """
  750. return pde_separate(eq, fun, sep, strategy='add')
  751. def pde_separate_mul(eq, fun, sep):
  752. """
  753. Helper function for searching multiplicative separable solutions.
  754. Consider an equation of two independent variables x, y and a dependent
  755. variable w, we look for the product of two functions depending on different
  756. arguments:
  757. `w(x, y, z) = X(x)*u(y, z)`
  758. Examples
  759. ========
  760. >>> from sympy import Function, Eq, pde_separate_mul, Derivative as D
  761. >>> from sympy.abc import x, y
  762. >>> u, X, Y = map(Function, 'uXY')
  763. >>> eq = Eq(D(u(x, y), x, 2), D(u(x, y), y, 2))
  764. >>> pde_separate_mul(eq, u(x, y), [X(x), Y(y)])
  765. [Derivative(X(x), (x, 2))/X(x), Derivative(Y(y), (y, 2))/Y(y)]
  766. """
  767. return pde_separate(eq, fun, sep, strategy='mul')
  768. def _separate(eq, dep, others):
  769. """Separate expression into two parts based on dependencies of variables."""
  770. # FIRST PASS
  771. # Extract derivatives depending our separable variable...
  772. terms = set()
  773. for term in eq.args:
  774. if term.is_Mul:
  775. for i in term.args:
  776. if i.is_Derivative and not i.has(*others):
  777. terms.add(term)
  778. continue
  779. elif term.is_Derivative and not term.has(*others):
  780. terms.add(term)
  781. # Find the factor that we need to divide by
  782. div = set()
  783. for term in terms:
  784. ext, sep = term.expand().as_independent(dep)
  785. # Failed?
  786. if sep.has(*others):
  787. return None
  788. div.add(ext)
  789. # FIXME: Find lcm() of all the divisors and divide with it, instead of
  790. # current hack :(
  791. # https://github.com/sympy/sympy/issues/4597
  792. if len(div) > 0:
  793. # double sum required or some tests will fail
  794. eq = Add(*[simplify(Add(*[term/i for i in div])) for term in eq.args])
  795. # SECOND PASS - separate the derivatives
  796. div = set()
  797. lhs = rhs = 0
  798. for term in eq.args:
  799. # Check, whether we have already term with independent variable...
  800. if not term.has(*others):
  801. lhs += term
  802. continue
  803. # ...otherwise, try to separate
  804. temp, sep = term.expand().as_independent(dep)
  805. # Failed?
  806. if sep.has(*others):
  807. return None
  808. # Extract the divisors
  809. div.add(sep)
  810. rhs -= term.expand()
  811. # Do the division
  812. fulldiv = reduce(operator.add, div)
  813. lhs = simplify(lhs/fulldiv).expand()
  814. rhs = simplify(rhs/fulldiv).expand()
  815. # ...and check whether we were successful :)
  816. if lhs.has(*others) or rhs.has(dep):
  817. return None
  818. return [lhs, rhs]