Navigation

Source code for sympy.solvers.pde

"""This module contains pdsolve() and different helper functions that ituses. It is heavily inspired by the ode module and hence the basicinfrastructure remains the same.**Functions in this module** These are the user functions in this module: - pdsolve() - Solves PDE's - classify_pde() - Classifies PDEs into possible hints for dsolve(). - pde_separate() - Separate variables in partial differential equation either by additive or multiplicative separation approach. These are the helper functions in this module: - pde_separate_add() - Helper function for searching additive separable solutions. - pde_separate_mul() - Helper function for searching multiplicative separable solutions.**Currently implemented solver methods**The following methods are implemented for solving partial differentialequations. See the docstrings of the various pde_hint() functions formore information on each (run help(pde)): - 1st order linear homogeneous partial differential equations with constant coefficients. - 1st order linear general partial differential equations with constant coefficients. - 1st order linear partial differential equations with variable coefficients."""from__future__importprint_function,divisionfromcopyimportdeepcopyfromsympy.simplifyimportsimplifyfromsympy.coreimportAdd,C,S,Mul,Pow,oofromsympy.core.compatibilityimport(reduce,combinations_with_replacement,is_sequence)fromsympy.core.functionimport(Function,Derivative,expand,diff,AppliedUndef,Subs)fromsympy.core.numbersimportRationalfromsympy.core.relationalimportEquality,Eqfromsympy.core.symbolimportSymbol,Wild,Dummy,symbolsfromsympy.functionsimportexpfromsympy.utilities.iterablesimporthas_dupsfromsympy.solvers.deutilsimport_preprocess,ode_order,_desolvefromsympy.solvers.solversimportsolvefromsympy.simplify.simplifyimportcollectimportoperatorallhints=("1st_linear_constant_coeff_homogeneous","1st_linear_constant_coeff","1st_linear_constant_coeff_Integral","1st_linear_variable_coeff")

[docs]defpdsolve(eq,func=None,hint='default',dict=False,solvefun=None,**kwargs):""" Solves any (supported) kind of partial differential equation. **Usage** pdsolve(eq, f(x,y), hint) -> Solve partial differential equation eq for function f(x,y), using method hint. **Details** ``eq`` can be any supported partial differential equation (see the pde docstring for supported methods). This can either be an Equality, or an expression, which is assumed to be equal to 0. ``f(x,y)`` is a function of two variables whose derivatives in that variable make up the partial differential equation. In many cases it is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). ``hint`` is the solving method that you want pdsolve to use. Use classify_pde(eq, f(x,y)) to get all of the possible hints for a PDE. The default hint, 'default', will use whatever hint is returned first by classify_pde(). See Hints below for more options that you can use for hint. ``solvefun`` is the convention used for arbitrary functions returned by the PDE solver. If not set by the user, it is set by default to be F. **Hints** Aside from the various solving methods, there are also some meta-hints that you can pass to pdsolve(): "default": This uses whatever hint is returned first by classify_pde(). This is the default argument to pdsolve(). "all": To make pdsolve apply all relevant classification hints, use pdsolve(PDE, func, hint="all"). This will return a dictionary of hint:solution terms. If a hint causes pdsolve to raise the NotImplementedError, value of that hint's key will be the exception object raised. The dictionary will also include some special keys: - order: The order of the PDE. See also ode_order() in deutils.py - default: The solution that would be returned by default. This is the one produced by the hint that appears first in the tuple returned by classify_pde(). "all_Integral": This is the same as "all", except if a hint also has a corresponding "_Integral" hint, it only returns the "_Integral" hint. This is useful if "all" causes pdsolve() to hang because of a difficult or impossible integral. This meta-hint will also be much faster than "all", because integrate() is an expensive routine. See also the classify_pde() docstring for more info on hints, and the pde docstring for a list of all supported hints. **Tips** - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative >>> from sympy.abc import x, y # x and y are the independent variables >>> f = Function("f")(x, y) # f is a function of x and y >>> # fx will be the partial derivative of f with respect to x >>> fx = Derivative(f, x) >>> # fy will be the partial derivative of f with respect to y >>> fy = Derivative(f, y) - See test_pde.py for many tests, which serves also as a set of examples for how to use pdsolve(). - pdsolve always returns an Equality class (except for the case when the hint is "all" or "all_Integral"). Note that it is not possible to get an explicit solution for f(x, y) as in the case of ODE's - Do help(pde.pde_hintname) to get help more information on a specific hint Examples ======== >>> from sympy.solvers.pde import pdsolve >>> from sympy import Function, diff, Eq >>> from sympy.abc import x, y >>> f = Function('f') >>> u = f(x, y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u))) >>> pdsolve(eq) f(x, y) == F(3*x - 2*y)*exp(-2*x/13 - 3*y/13) """given_hint=hint# hint given by the user.ifnotsolvefun:solvefun=Function('F')# See the docstring of _desolve for more details.hints=_desolve(eq,func=func,hint=hint,simplify=True,type='pde',**kwargs)eq=hints.pop('eq',False)all_=hints.pop('all',False)ifall_:# TODO : 'best' hint should be implemented when adequate# number of hints are added.pdedict={}failed_hints={}gethints=classify_pde(eq,dict=True)pdedict.update({'order':gethints['order'],'default':gethints['default']})forhintinhints:try:rv=_helper_simplify(eq,hint,hints[hint]['func'],hints[hint]['order'],hints[hint][hint],solvefun)exceptNotImplementedErrorasdetail:failed_hints[hint]=detailelse:pdedict[hint]=rvpdedict.update(failed_hints)returnpdedictelse:return_helper_simplify(eq,hints['hint'],hints['func'],hints['order'],hints[hints['hint']],solvefun)

def_helper_simplify(eq,hint,func,order,match,solvefun):"""Helper function of pdsolve that calls the respective pde functions to solve for the partial differential equations. This minimises the computation in calling _desolve multiple times. """ifhint.endswith("_Integral"):solvefunc=globals()["pde_"+hint[:-len("_Integral")]]else:solvefunc=globals()["pde_"+hint]return_handle_Integral(solvefunc(eq,func,order,match,solvefun),func,order,hint)def_handle_Integral(expr,func,order,hint):r""" Converts a solution with integrals in it into an actual solution. Simplifies the integral mainly using doit() """ifhint.endswith("_Integral"):returnexprelifhint=="1st_linear_constant_coeff":returnsimplify(expr.doit())else:returnexpr

[docs]defclassify_pde(eq,func=None,dict=False,**kwargs):""" Returns a tuple of possible pdsolve() classifications for a PDE. The tuple is ordered so that first item is the classification that pdsolve() uses to solve the PDE by default. In general, classifications at the near the beginning of the list will produce better solutions faster than those near the end, thought there are always exceptions. To make pdsolve use a different classification, use pdsolve(PDE, func, hint=<classification>). See also the pdsolve() docstring for different meta-hints you can use. If ``dict`` is true, classify_pde() will return a dictionary of hint:match expression terms. This is intended for internal use by pdsolve(). Note that because dictionaries are ordered arbitrarily, this will most likely not be in the same order as the tuple. You can get help on different hints by doing help(pde.pde_hintname), where hintname is the name of the hint without "_Integral". See sympy.pde.allhints or the sympy.pde docstring for a list of all supported hints that can be returned from classify_pde. Examples ======== >>> from sympy.solvers.pde import classify_pde >>> from sympy import Function, diff, Eq >>> from sympy.abc import x, y >>> f = Function('f') >>> u = f(x, y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u))) >>> classify_pde(eq) ('1st_linear_constant_coeff_homogeneous',) """prep=kwargs.pop('prep',True)iffuncandlen(func.args)!=2:raiseNotImplementedError("Right now only partial ""differential equations of two variables are supported")ifpreporfuncisNone:prep,func_=_preprocess(eq,func)iffuncisNone:func=func_ifisinstance(eq,Equality):ifeq.rhs!=0:returnclassify_pde(eq.lhs-eq.rhs,func)eq=eq.lhsf=func.funcx=func.args[0]y=func.args[1]fx=f(x,y).diff(x)fy=f(x,y).diff(y)# TODO : For now pde.py uses support offered by the ode_order function# to find the order with respect to a multi-variable function. An# improvement could be to classify the order of the PDE on the basis of# individual variables.order=ode_order(eq,f(x,y))# hint:matchdict or hint:(tuple of matchdicts)# Also will contain "default":<default hint> and "order":order items.matching_hints={'order':order}ifnotorder:ifdict:matching_hints["default"]=Nonereturnmatching_hintselse:return()eq=expand(eq)a=Wild('a',exclude=[f(x,y)])b=Wild('b',exclude=[f(x,y),fx,fy,x,y])c=Wild('c',exclude=[f(x,y),fx,fy,x,y])d=Wild('d',exclude=[f(x,y),fx,fy,x,y])e=Wild('e',exclude=[f(x,y),fx,fy])n=Wild('n',exclude=[x,y])# Try removing the smallest power of f(x,y)# from the highest partial derivatives of f(x,y)reduced_eq=Noneifeq.is_Add:var=set(combinations_with_replacement((x,y),order))dummyvar=deepcopy(var)power=Noneforiinvar:coeff=eq.coeff(f(x,y).diff(*i))ifcoeff!=1:match=coeff.match(a*f(x,y)**n)ifmatchandmatch[a]:power=match[n]dummyvar.remove(i)breakdummyvar.remove(i)foriindummyvar:coeff=eq.coeff(f(x,y).diff(*i))ifcoeff!=1:match=coeff.match(a*f(x,y)**n)ifmatchandmatch[a]andmatch[n]<power:power=match[n]ifpower:den=f(x,y)**powerreduced_eq=Add(*[arg/denforargineq.args])ifnotreduced_eq:reduced_eq=eqiforder==1:reduced_eq=collect(reduced_eq,f(x,y))r=reduced_eq.match(b*fx+c*fy+d*f(x,y)+e)ifr:ifnotr[e]:## Linear first-order homogeneous partial-differential## equation with constant coefficientsr.update({'b':b,'c':c,'d':d})matching_hints["1st_linear_constant_coeff_homogeneous"]=relse:ifr[b]**2+r[c]**2!=0:## Linear first-order general partial-differential## equation with constant coefficientsr.update({'b':b,'c':c,'d':d,'e':e})matching_hints["1st_linear_constant_coeff"]=rmatching_hints["1st_linear_constant_coeff_Integral"]=relse:b=Wild('b',exclude=[f(x,y),fx,fy])c=Wild('c',exclude=[f(x,y),fx,fy])d=Wild('d',exclude=[f(x,y),fx,fy])r=reduced_eq.match(b*fx+c*fy+d*f(x,y)+e)ifr:r.update({'b':b,'c':c,'d':d,'e':e})matching_hints["1st_linear_variable_coeff"]=r# Order keys based on allhints.retlist=[]foriinallhints:ifiinmatching_hints:retlist.append(i)ifdict:# Dictionaries are ordered arbitrarily, so make note of which# hint would come first for pdsolve(). Use an ordered dict in Py 3.matching_hints["default"]=Nonematching_hints["ordered_hints"]=tuple(retlist)foriinallhints:ifiinmatching_hints:matching_hints["default"]=ibreakreturnmatching_hintselse:returntuple(retlist)

[docs]defcheckpdesol(pde,sol,func=None,solve_for_func=True):""" Checks if the given solution satisfies the partial differential equation. pde is the partial differential equation which can be given in the form of an equation or an expression. sol is the solution for which the pde is to be checked. This can also be given in an equation or an expression form. If the function is not provided, the helper function _preprocess from deutils is used to identify the function. If a sequence of solutions is passed, the same sort of container will be used to return the result for each solution. The following methods are currently being implemented to check if the solution satisfies the PDE: 1. Directly substitute the solution in the PDE and check. If the solution hasn't been solved for f, then it will solve for f provided solve_for_func hasn't been set to False. If the solution satisfies the PDE, then a tuple (True, 0) is returned. Otherwise a tuple (False, expr) where expr is the value obtained after substituting the solution in the PDE. However if a known solution returns False, it may be due to the inability of doit() to simplify it to zero. Examples ======== >>> from sympy import Function, symbols, diff >>> from sympy.solvers.pde import checkpdesol, pdsolve >>> x, y = symbols('x y') >>> f = Function('f') >>> eq = 2*f(x,y) + 3*f(x,y).diff(x) + 4*f(x,y).diff(y) >>> sol = pdsolve(eq) >>> assert checkpdesol(eq, sol)[0] >>> eq = x*f(x,y) + f(x,y).diff(x) >>> checkpdesol(eq, sol) (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)) """# Converting the pde into an equationifnotisinstance(pde,Equality):pde=Eq(pde,0)# If no function is given, try finding the function present.iffuncisNone:try:_,func=_preprocess(pde.lhs)exceptValueError:funcs=[s.atoms(AppliedUndef)forsin(solifis_sequence(sol,set)else[sol])]funcs=reduce(set.union,funcs,set())iflen(funcs)!=1:raiseValueError('must pass func arg to checkpdesol for this case.')func=funcs.pop()# If the given solution is in the form of a list or a set# then return a list or set of tuples.ifis_sequence(sol,set):returntype(sol)(map(lambdai:checkpdesol(pde,i,solve_for_func=solve_for_func),sol))# Convert solution into an equationifnotisinstance(sol,Equality):sol=Eq(func,sol)# Try solving for the functionifsolve_for_funcandnot(sol.lhs==funcandnotsol.rhs.has(func))andnot \
(sol.rhs==funcandnotsol.lhs.has(func)):try:solved=solve(sol,func)ifnotsolved:raiseNotImplementedErrorexceptNotImplementedError:passelse:iflen(solved)==1:result=checkpdesol(pde,Eq(func,solved[0]),order=order,solve_for_func=False)else:result=checkpdesol(pde,[Eq(func,t)fortinsolved],order=order,solve_for_func=False)# The first method includes direct substitution of the solution in# the PDE and simplifying.pde=pde.lhs-pde.rhsifsol.lhs==func:s=pde.subs(func,sol.rhs).doit()elifsol.rhs==func:s=pde.subs(func,sol.lhs).doit()ifs:ss=simplify(s)ifss:returnFalse,sselse:returnTrue,0else:returnTrue,0

def_separate(eq,dep,others):"""Separate expression into two parts based on dependencies of variables."""# FIRST PASS# Extract derivatives depending our separable variable...terms=set()fortermineq.args:ifterm.is_Mul:foriinterm.args:ifi.is_Derivativeandnoti.has(*others):terms.add(term)continueelifterm.is_Derivativeandnotterm.has(*others):terms.add(term)# Find the factor that we need to divide bydiv=set()forterminterms:ext,sep=term.expand().as_independent(dep)# Failed?ifsep.has(*others):returnNonediv.add(ext)# FIXME: Find lcm() of all the divisors and divide with it, instead of# current hack :(# http://code.google.com/p/sympy/issues/detail?id=1498iflen(div)>0:final=0fortermineq.args:eqn=0foriindiv:eqn+=term/ifinal+=simplify(eqn)eq=final# SECOND PASS - separate the derivativesdiv=set()lhs=rhs=0fortermineq.args:# Check, whether we have already term with independent variable...ifnotterm.has(*others):lhs+=termcontinue# ...otherwise, try to separatetemp,sep=term.expand().as_independent(dep)# Failed?ifsep.has(*others):returnNone# Extract the divisorsdiv.add(sep)rhs-=term.expand()# Do the divisionfulldiv=reduce(operator.add,div)lhs=simplify(lhs/fulldiv).expand()rhs=simplify(rhs/fulldiv).expand()# ...and check whether we were successful :)iflhs.has(*others)orrhs.has(dep):returnNonereturn[lhs,rhs]