ode.py 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566
  1. r"""
  2. This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper
  3. functions that it uses.
  4. :py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations.
  5. See the docstring on the various functions for their uses. Note that partial
  6. differential equations support is in ``pde.py``. Note that hint functions
  7. have docstrings describing their various methods, but they are intended for
  8. internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a
  9. specific hint. See also the docstring on
  10. :py:meth:`~sympy.solvers.ode.dsolve`.
  11. **Functions in this module**
  12. These are the user functions in this module:
  13. - :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs.
  14. - :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into
  15. possible hints for :py:meth:`~sympy.solvers.ode.dsolve`.
  16. - :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the
  17. solution to an ODE.
  18. - :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the
  19. homogeneous order of an expression.
  20. - :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals
  21. of the Lie group of point transformations of an ODE, such that it is
  22. invariant.
  23. - :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals
  24. are the actual infinitesimals of a first order ODE.
  25. These are the non-solver helper functions that are for internal use. The
  26. user should use the various options to
  27. :py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided
  28. by these functions:
  29. - :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE
  30. simplification.
  31. - :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for
  32. comparing solutions by simplicity.
  33. - :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary
  34. constants.
  35. - :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary
  36. constants.
  37. - :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated
  38. Integrals.
  39. See also the docstrings of these functions.
  40. **Currently implemented solver methods**
  41. The following methods are implemented for solving ordinary differential
  42. equations. See the docstrings of the various hint functions for more
  43. information on each (run ``help(ode)``):
  44. - 1st order separable differential equations.
  45. - 1st order differential equations whose coefficients or `dx` and `dy` are
  46. functions homogeneous of the same order.
  47. - 1st order exact differential equations.
  48. - 1st order linear differential equations.
  49. - 1st order Bernoulli differential equations.
  50. - Power series solutions for first order differential equations.
  51. - Lie Group method of solving first order differential equations.
  52. - 2nd order Liouville differential equations.
  53. - Power series solutions for second order differential equations
  54. at ordinary and regular singular points.
  55. - `n`\th order differential equation that can be solved with algebraic
  56. rearrangement and integration.
  57. - `n`\th order linear homogeneous differential equation with constant
  58. coefficients.
  59. - `n`\th order linear inhomogeneous differential equation with constant
  60. coefficients using the method of undetermined coefficients.
  61. - `n`\th order linear inhomogeneous differential equation with constant
  62. coefficients using the method of variation of parameters.
  63. **Philosophy behind this module**
  64. This module is designed to make it easy to add new ODE solving methods without
  65. having to mess with the solving code for other methods. The idea is that
  66. there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in
  67. an ODE and tells you what hints, if any, will solve the ODE. It does this
  68. without attempting to solve the ODE, so it is fast. Each solving method is a
  69. hint, and it has its own function, named ``ode_<hint>``. That function takes
  70. in the ODE and any match expression gathered by
  71. :py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If
  72. this result has any integrals in it, the hint function will return an
  73. unevaluated :py:class:`~sympy.integrals.integrals.Integral` class.
  74. :py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function
  75. around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on
  76. the result, which, among other things, will attempt to solve the equation for
  77. the dependent variable (the function we are solving for), simplify the
  78. arbitrary constants in the expression, and evaluate any integrals, if the hint
  79. allows it.
  80. **How to add new solution methods**
  81. If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be
  82. able to solve, try to avoid adding special case code here. Instead, try
  83. finding a general method that will solve your ODE, as well as others. This
  84. way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and
  85. unhindered by special case hacks. WolphramAlpha and Maple's
  86. DETools[odeadvisor] function are two resources you can use to classify a
  87. specific ODE. It is also better for a method to work with an `n`\th order ODE
  88. instead of only with specific orders, if possible.
  89. To add a new method, there are a few things that you need to do. First, you
  90. need a hint name for your method. Try to name your hint so that it is
  91. unambiguous with all other methods, including ones that may not be implemented
  92. yet. If your method uses integrals, also include a ``hint_Integral`` hint.
  93. If there is more than one way to solve ODEs with your method, include a hint
  94. for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()``
  95. function should choose the best using min with ``ode_sol_simplicity`` as the
  96. key argument. See
  97. :obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest`, for example.
  98. The function that uses your method will be called ``ode_<hint>()``, so the
  99. hint must only use characters that are allowed in a Python function name
  100. (alphanumeric characters and the underscore '``_``' character). Include a
  101. function for every hint, except for ``_Integral`` hints
  102. (:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically).
  103. Hint names should be all lowercase, unless a word is commonly capitalized
  104. (such as Integral or Bernoulli). If you have a hint that you do not want to
  105. run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such
  106. as a best hint that would defeat the purpose of ``all_Integral``), you will
  107. need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code.
  108. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
  109. guidelines on writing a hint name.
  110. Determine *in general* how the solutions returned by your method compare with
  111. other methods that can potentially solve the same ODEs. Then, put your hints
  112. in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they
  113. should be called. The ordering of this tuple determines which hints are
  114. default. Note that exceptions are ok, because it is easy for the user to
  115. choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In
  116. general, ``_Integral`` variants should go at the end of the list, and
  117. ``_best`` variants should go before the various hints they apply to. For
  118. example, the ``undetermined_coefficients`` hint comes before the
  119. ``variation_of_parameters`` hint because, even though variation of parameters
  120. is more general than undetermined coefficients, undetermined coefficients
  121. generally returns cleaner results for the ODEs that it can solve than
  122. variation of parameters does, and it does not require integration, so it is
  123. much faster.
  124. Next, you need to have a match expression or a function that matches the type
  125. of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode`
  126. (if the match function is more than just a few lines. It should match the
  127. ODE without solving for it as much as possible, so that
  128. :py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by
  129. bugs in solving code. Be sure to consider corner cases. For example, if your
  130. solution method involves dividing by something, make sure you exclude the case
  131. where that division will be 0.
  132. In most cases, the matching of the ODE will also give you the various parts
  133. that you need to solve it. You should put that in a dictionary (``.match()``
  134. will do this for you), and add that as ``matching_hints['hint'] = matchdict``
  135. in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`.
  136. :py:meth:`~sympy.solvers.ode.classify_ode` will then send this to
  137. :py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as
  138. the ``match`` argument. Your function should be named ``ode_<hint>(eq, func,
  139. order, match)`. If you need to send more information, put it in the ``match``
  140. dictionary. For example, if you had to substitute in a dummy variable in
  141. :py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to
  142. pass it to your function using the `match` dict to access it. You can access
  143. the independent variable using ``func.args[0]``, and the dependent variable
  144. (the function you are trying to solve for) as ``func.func``. If, while trying
  145. to solve the ODE, you find that you cannot, raise ``NotImplementedError``.
  146. :py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all``
  147. meta-hint, rather than causing the whole routine to fail.
  148. Add a docstring to your function that describes the method employed. Like
  149. with anything else in SymPy, you will need to add a doctest to the docstring,
  150. in addition to real tests in ``test_ode.py``. Try to maintain consistency
  151. with the other hint functions' docstrings. Add your method to the list at the
  152. top of this docstring. Also, add your method to ``ode.rst`` in the
  153. ``docs/src`` directory, so that the Sphinx docs will pull its docstring into
  154. the main SymPy documentation. Be sure to make the Sphinx documentation by
  155. running ``make html`` from within the doc directory to verify that the
  156. docstring formats correctly.
  157. If your solution method involves integrating, use :py:obj:`~.Integral` instead of
  158. :py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass
  159. hard/slow integration by using the ``_Integral`` variant of your hint. In
  160. most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your
  161. solution. If this is not the case, you will need to write special code in
  162. :py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be
  163. symbols named ``C1``, ``C2``, and so on. All solution methods should return
  164. an equality instance. If you need an arbitrary number of arbitrary constants,
  165. you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``.
  166. If it is possible to solve for the dependent function in a general way, do so.
  167. Otherwise, do as best as you can, but do not call solve in your
  168. ``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt
  169. to solve the solution for you, so you do not need to do that. Lastly, if your
  170. ODE has a common simplification that can be applied to your solutions, you can
  171. add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For
  172. example, solutions returned from the ``1st_homogeneous_coeff`` hints often
  173. have many :obj:`~sympy.functions.elementary.exponential.log` terms, so
  174. :py:meth:`~sympy.solvers.ode.ode.odesimp` calls
  175. :py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write
  176. the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also
  177. consider common ways that you can rearrange your solution to have
  178. :py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is
  179. better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in
  180. your method, because it can then be turned off with the simplify flag in
  181. :py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous
  182. simplification in your function, be sure to only run it using ``if
  183. match.get('simplify', True):``, especially if it can be slow or if it can
  184. reduce the domain of the solution.
  185. Finally, as with every contribution to SymPy, your method will need to be
  186. tested. Add a test for each method in ``test_ode.py``. Follow the
  187. conventions there, i.e., test the solver using ``dsolve(eq, f(x),
  188. hint=your_hint)``, and also test the solution using
  189. :py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate
  190. tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your
  191. hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test
  192. will not be broken simply by the introduction of another matching hint. If your
  193. method works for higher order (>1) ODEs, you will need to run ``sol =
  194. constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is
  195. the order of the ODE. This is because ``constant_renumber`` renumbers the
  196. arbitrary constants by printing order, which is platform dependent. Try to
  197. test every corner case of your solver, including a range of orders if it is a
  198. `n`\th order solver, but if your solver is slow, such as if it involves hard
  199. integration, try to keep the test run time down.
  200. Feel free to refactor existing hints to avoid duplicating code or creating
  201. inconsistencies. If you can show that your method exactly duplicates an
  202. existing method, including in the simplicity and speed of obtaining the
  203. solutions, then you can remove the old, less general method. The existing
  204. code is tested extensively in ``test_ode.py``, so if anything is broken, one
  205. of those tests will surely fail.
  206. """
  207. from sympy.core import Add, S, Mul, Pow, oo
  208. from sympy.core.containers import Tuple
  209. from sympy.core.expr import AtomicExpr, Expr
  210. from sympy.core.function import (Function, Derivative, AppliedUndef, diff,
  211. expand, expand_mul, Subs)
  212. from sympy.core.multidimensional import vectorize
  213. from sympy.core.numbers import nan, zoo, Number
  214. from sympy.core.relational import Equality, Eq
  215. from sympy.core.sorting import default_sort_key, ordered
  216. from sympy.core.symbol import Symbol, Wild, Dummy, symbols
  217. from sympy.core.sympify import sympify
  218. from sympy.core.traversal import preorder_traversal
  219. from sympy.logic.boolalg import (BooleanAtom, BooleanTrue,
  220. BooleanFalse)
  221. from sympy.functions import exp, log, sqrt
  222. from sympy.functions.combinatorial.factorials import factorial
  223. from sympy.integrals.integrals import Integral
  224. from sympy.polys import (Poly, terms_gcd, PolynomialError, lcm)
  225. from sympy.polys.polytools import cancel
  226. from sympy.series import Order
  227. from sympy.series.series import series
  228. from sympy.simplify import (collect, logcombine, powsimp, # type: ignore
  229. separatevars, simplify, cse)
  230. from sympy.simplify.radsimp import collect_const
  231. from sympy.solvers import checksol, solve
  232. from sympy.utilities import numbered_symbols
  233. from sympy.utilities.iterables import uniq, sift, iterable
  234. from sympy.solvers.deutils import _preprocess, ode_order, _desolve
  235. #: This is a list of hints in the order that they should be preferred by
  236. #: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the
  237. #: list should produce simpler solutions than those later in the list (for
  238. #: ODEs that fit both). For now, the order of this list is based on empirical
  239. #: observations by the developers of SymPy.
  240. #:
  241. #: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE
  242. #: can be overridden (see the docstring).
  243. #:
  244. #: In general, ``_Integral`` hints are grouped at the end of the list, unless
  245. #: there is a method that returns an unevaluable integral most of the time
  246. #: (which go near the end of the list anyway). ``default``, ``all``,
  247. #: ``best``, and ``all_Integral`` meta-hints should not be included in this
  248. #: list, but ``_best`` and ``_Integral`` hints should be included.
  249. allhints = (
  250. "factorable",
  251. "nth_algebraic",
  252. "separable",
  253. "1st_exact",
  254. "1st_linear",
  255. "Bernoulli",
  256. "1st_rational_riccati",
  257. "Riccati_special_minus2",
  258. "1st_homogeneous_coeff_best",
  259. "1st_homogeneous_coeff_subs_indep_div_dep",
  260. "1st_homogeneous_coeff_subs_dep_div_indep",
  261. "almost_linear",
  262. "linear_coefficients",
  263. "separable_reduced",
  264. "1st_power_series",
  265. "lie_group",
  266. "nth_linear_constant_coeff_homogeneous",
  267. "nth_linear_euler_eq_homogeneous",
  268. "nth_linear_constant_coeff_undetermined_coefficients",
  269. "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
  270. "nth_linear_constant_coeff_variation_of_parameters",
  271. "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
  272. "Liouville",
  273. "2nd_linear_airy",
  274. "2nd_linear_bessel",
  275. "2nd_hypergeometric",
  276. "2nd_hypergeometric_Integral",
  277. "nth_order_reducible",
  278. "2nd_power_series_ordinary",
  279. "2nd_power_series_regular",
  280. "nth_algebraic_Integral",
  281. "separable_Integral",
  282. "1st_exact_Integral",
  283. "1st_linear_Integral",
  284. "Bernoulli_Integral",
  285. "1st_homogeneous_coeff_subs_indep_div_dep_Integral",
  286. "1st_homogeneous_coeff_subs_dep_div_indep_Integral",
  287. "almost_linear_Integral",
  288. "linear_coefficients_Integral",
  289. "separable_reduced_Integral",
  290. "nth_linear_constant_coeff_variation_of_parameters_Integral",
  291. "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral",
  292. "Liouville_Integral",
  293. "2nd_nonlinear_autonomous_conserved",
  294. "2nd_nonlinear_autonomous_conserved_Integral",
  295. )
  296. def get_numbered_constants(eq, num=1, start=1, prefix='C'):
  297. """
  298. Returns a list of constants that do not occur
  299. in eq already.
  300. """
  301. ncs = iter_numbered_constants(eq, start, prefix)
  302. Cs = [next(ncs) for i in range(num)]
  303. return (Cs[0] if num == 1 else tuple(Cs))
  304. def iter_numbered_constants(eq, start=1, prefix='C'):
  305. """
  306. Returns an iterator of constants that do not occur
  307. in eq already.
  308. """
  309. if isinstance(eq, (Expr, Eq)):
  310. eq = [eq]
  311. elif not iterable(eq):
  312. raise ValueError("Expected Expr or iterable but got %s" % eq)
  313. atom_set = set().union(*[i.free_symbols for i in eq])
  314. func_set = set().union(*[i.atoms(Function) for i in eq])
  315. if func_set:
  316. atom_set |= {Symbol(str(f.func)) for f in func_set}
  317. return numbered_symbols(start=start, prefix=prefix, exclude=atom_set)
  318. def dsolve(eq, func=None, hint="default", simplify=True,
  319. ics= None, xi=None, eta=None, x0=0, n=6, **kwargs):
  320. r"""
  321. Solves any (supported) kind of ordinary differential equation and
  322. system of ordinary differential equations.
  323. For single ordinary differential equation
  324. =========================================
  325. It is classified under this when number of equation in ``eq`` is one.
  326. **Usage**
  327. ``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation
  328. ``eq`` for function ``f(x)``, using method ``hint``.
  329. **Details**
  330. ``eq`` can be any supported ordinary differential equation (see the
  331. :py:mod:`~sympy.solvers.ode` docstring for supported methods).
  332. This can either be an :py:class:`~sympy.core.relational.Equality`,
  333. or an expression, which is assumed to be equal to ``0``.
  334. ``f(x)`` is a function of one variable whose derivatives in that
  335. variable make up the ordinary differential equation ``eq``. In
  336. many cases it is not necessary to provide this; it will be
  337. autodetected (and an error raised if it couldn't be detected).
  338. ``hint`` is the solving method that you want dsolve to use. Use
  339. ``classify_ode(eq, f(x))`` to get all of the possible hints for an
  340. ODE. The default hint, ``default``, will use whatever hint is
  341. returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See
  342. Hints below for more options that you can use for hint.
  343. ``simplify`` enables simplification by
  344. :py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more
  345. information. Turn this off, for example, to disable solving of
  346. solutions for ``func`` or simplification of arbitrary constants.
  347. It will still integrate with this hint. Note that the solution may
  348. contain more arbitrary constants than the order of the ODE with
  349. this option enabled.
  350. ``xi`` and ``eta`` are the infinitesimal functions of an ordinary
  351. differential equation. They are the infinitesimals of the Lie group
  352. of point transformations for which the differential equation is
  353. invariant. The user can specify values for the infinitesimals. If
  354. nothing is specified, ``xi`` and ``eta`` are calculated using
  355. :py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various
  356. heuristics.
  357. ``ics`` is the set of initial/boundary conditions for the differential equation.
  358. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2):
  359. x3}`` and so on. For power series solutions, if no initial
  360. conditions are specified ``f(0)`` is assumed to be ``C0`` and the power
  361. series solution is calculated about 0.
  362. ``x0`` is the point about which the power series solution of a differential
  363. equation is to be evaluated.
  364. ``n`` gives the exponent of the dependent variable up to which the power series
  365. solution of a differential equation is to be evaluated.
  366. **Hints**
  367. Aside from the various solving methods, there are also some meta-hints
  368. that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`:
  369. ``default``:
  370. This uses whatever hint is returned first by
  371. :py:meth:`~sympy.solvers.ode.classify_ode`. This is the
  372. default argument to :py:meth:`~sympy.solvers.ode.dsolve`.
  373. ``all``:
  374. To make :py:meth:`~sympy.solvers.ode.dsolve` apply all
  375. relevant classification hints, use ``dsolve(ODE, func,
  376. hint="all")``. This will return a dictionary of
  377. ``hint:solution`` terms. If a hint causes dsolve to raise the
  378. ``NotImplementedError``, value of that hint's key will be the
  379. exception object raised. The dictionary will also include
  380. some special keys:
  381. - ``order``: The order of the ODE. See also
  382. :py:meth:`~sympy.solvers.deutils.ode_order` in
  383. ``deutils.py``.
  384. - ``best``: The simplest hint; what would be returned by
  385. ``best`` below.
  386. - ``best_hint``: The hint that would produce the solution
  387. given by ``best``. If more than one hint produces the best
  388. solution, the first one in the tuple returned by
  389. :py:meth:`~sympy.solvers.ode.classify_ode` is chosen.
  390. - ``default``: The solution that would be returned by default.
  391. This is the one produced by the hint that appears first in
  392. the tuple returned by
  393. :py:meth:`~sympy.solvers.ode.classify_ode`.
  394. ``all_Integral``:
  395. This is the same as ``all``, except if a hint also has a
  396. corresponding ``_Integral`` hint, it only returns the
  397. ``_Integral`` hint. This is useful if ``all`` causes
  398. :py:meth:`~sympy.solvers.ode.dsolve` to hang because of a
  399. difficult or impossible integral. This meta-hint will also be
  400. much faster than ``all``, because
  401. :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive
  402. routine.
  403. ``best``:
  404. To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods
  405. and return the simplest one. This takes into account whether
  406. the solution is solvable in the function, whether it contains
  407. any Integral classes (i.e. unevaluatable integrals), and
  408. which one is the shortest in size.
  409. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
  410. more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for
  411. a list of all supported hints.
  412. **Tips**
  413. - You can declare the derivative of an unknown function this way:
  414. >>> from sympy import Function, Derivative
  415. >>> from sympy.abc import x # x is the independent variable
  416. >>> f = Function("f")(x) # f is a function of x
  417. >>> # f_ will be the derivative of f with respect to x
  418. >>> f_ = Derivative(f, x)
  419. - See ``test_ode.py`` for many tests, which serves also as a set of
  420. examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`.
  421. - :py:meth:`~sympy.solvers.ode.dsolve` always returns an
  422. :py:class:`~sympy.core.relational.Equality` class (except for the
  423. case when the hint is ``all`` or ``all_Integral``). If possible, it
  424. solves the solution explicitly for the function being solved for.
  425. Otherwise, it returns an implicit solution.
  426. - Arbitrary constants are symbols named ``C1``, ``C2``, and so on.
  427. - Because all solutions should be mathematically equivalent, some
  428. hints may return the exact same result for an ODE. Often, though,
  429. two different hints will return the same solution formatted
  430. differently. The two should be equivalent. Also note that sometimes
  431. the values of the arbitrary constants in two different solutions may
  432. not be the same, because one constant may have "absorbed" other
  433. constants into it.
  434. - Do ``help(ode.ode_<hintname>)`` to get help more information on a
  435. specific hint, where ``<hintname>`` is the name of a hint without
  436. ``_Integral``.
  437. For system of ordinary differential equations
  438. =============================================
  439. **Usage**
  440. ``dsolve(eq, func)`` -> Solve a system of ordinary differential
  441. equations ``eq`` for ``func`` being list of functions including
  442. `x(t)`, `y(t)`, `z(t)` where number of functions in the list depends
  443. upon the number of equations provided in ``eq``.
  444. **Details**
  445. ``eq`` can be any supported system of ordinary differential equations
  446. This can either be an :py:class:`~sympy.core.relational.Equality`,
  447. or an expression, which is assumed to be equal to ``0``.
  448. ``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which
  449. together with some of their derivatives make up the system of ordinary
  450. differential equation ``eq``. It is not necessary to provide this; it
  451. will be autodetected (and an error raised if it couldn't be detected).
  452. **Hints**
  453. The hints are formed by parameters returned by classify_sysode, combining
  454. them give hints name used later for forming method name.
  455. Examples
  456. ========
  457. >>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols
  458. >>> from sympy.abc import x
  459. >>> f = Function('f')
  460. >>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
  461. Eq(f(x), C1*sin(3*x) + C2*cos(3*x))
  462. >>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
  463. >>> dsolve(eq, hint='1st_exact')
  464. [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
  465. >>> dsolve(eq, hint='almost_linear')
  466. [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
  467. >>> t = symbols('t')
  468. >>> x, y = symbols('x, y', cls=Function)
  469. >>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t)))
  470. >>> dsolve(eq)
  471. [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)),
  472. Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) +
  473. exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))]
  474. >>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t)))
  475. >>> dsolve(eq)
  476. {Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))}
  477. """
  478. if iterable(eq):
  479. from sympy.solvers.ode.systems import dsolve_system
  480. # This may have to be changed in future
  481. # when we have weakly and strongly
  482. # connected components. This have to
  483. # changed to show the systems that haven't
  484. # been solved.
  485. try:
  486. sol = dsolve_system(eq, funcs=func, ics=ics, doit=True)
  487. return sol[0] if len(sol) == 1 else sol
  488. except NotImplementedError:
  489. pass
  490. match = classify_sysode(eq, func)
  491. eq = match['eq']
  492. order = match['order']
  493. func = match['func']
  494. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  495. # keep highest order term coefficient positive
  496. for i in range(len(eq)):
  497. for func_ in func:
  498. if isinstance(func_, list):
  499. pass
  500. else:
  501. if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative:
  502. eq[i] = -eq[i]
  503. match['eq'] = eq
  504. if len(set(order.values()))!=1:
  505. raise ValueError("It solves only those systems of equations whose orders are equal")
  506. match['order'] = list(order.values())[0]
  507. def recur_len(l):
  508. return sum(recur_len(item) if isinstance(item,list) else 1 for item in l)
  509. if recur_len(func) != len(eq):
  510. raise ValueError("dsolve() and classify_sysode() work with "
  511. "number of functions being equal to number of equations")
  512. if match['type_of_equation'] is None:
  513. raise NotImplementedError
  514. else:
  515. if match['is_linear'] == True:
  516. solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match]
  517. else:
  518. solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match]
  519. sols = solvefunc(match)
  520. if ics:
  521. constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols
  522. solved_constants = solve_ics(sols, func, constants, ics)
  523. return [sol.subs(solved_constants) for sol in sols]
  524. return sols
  525. else:
  526. given_hint = hint # hint given by the user
  527. # See the docstring of _desolve for more details.
  528. hints = _desolve(eq, func=func,
  529. hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics,
  530. x0=x0, n=n, **kwargs)
  531. eq = hints.pop('eq', eq)
  532. all_ = hints.pop('all', False)
  533. if all_:
  534. retdict = {}
  535. failed_hints = {}
  536. gethints = classify_ode(eq, dict=True, hint='all')
  537. orderedhints = gethints['ordered_hints']
  538. for hint in hints:
  539. try:
  540. rv = _helper_simplify(eq, hint, hints[hint], simplify)
  541. except NotImplementedError as detail:
  542. failed_hints[hint] = detail
  543. else:
  544. retdict[hint] = rv
  545. func = hints[hint]['func']
  546. retdict['best'] = min(list(retdict.values()), key=lambda x:
  547. ode_sol_simplicity(x, func, trysolving=not simplify))
  548. if given_hint == 'best':
  549. return retdict['best']
  550. for i in orderedhints:
  551. if retdict['best'] == retdict.get(i, None):
  552. retdict['best_hint'] = i
  553. break
  554. retdict['default'] = gethints['default']
  555. retdict['order'] = gethints['order']
  556. retdict.update(failed_hints)
  557. return retdict
  558. else:
  559. # The key 'hint' stores the hint needed to be solved for.
  560. hint = hints['hint']
  561. return _helper_simplify(eq, hint, hints, simplify, ics=ics)
  562. def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs):
  563. r"""
  564. Helper function of dsolve that calls the respective
  565. :py:mod:`~sympy.solvers.ode` functions to solve for the ordinary
  566. differential equations. This minimizes the computation in calling
  567. :py:meth:`~sympy.solvers.deutils._desolve` multiple times.
  568. """
  569. r = match
  570. func = r['func']
  571. order = r['order']
  572. match = r[hint]
  573. if isinstance(match, SingleODESolver):
  574. solvefunc = match
  575. elif hint.endswith('_Integral'):
  576. solvefunc = globals()['ode_' + hint[:-len('_Integral')]]
  577. else:
  578. solvefunc = globals()['ode_' + hint]
  579. free = eq.free_symbols
  580. cons = lambda s: s.free_symbols.difference(free)
  581. if simplify:
  582. # odesimp() will attempt to integrate, if necessary, apply constantsimp(),
  583. # attempt to solve for func, and apply any other hint specific
  584. # simplifications
  585. if isinstance(solvefunc, SingleODESolver):
  586. sols = solvefunc.get_general_solution()
  587. else:
  588. sols = solvefunc(eq, func, order, match)
  589. if iterable(sols):
  590. rv = [odesimp(eq, s, func, hint) for s in sols]
  591. else:
  592. rv = odesimp(eq, sols, func, hint)
  593. else:
  594. # We still want to integrate (you can disable it separately with the hint)
  595. if isinstance(solvefunc, SingleODESolver):
  596. exprs = solvefunc.get_general_solution(simplify=False)
  597. else:
  598. match['simplify'] = False # Some hints can take advantage of this option
  599. exprs = solvefunc(eq, func, order, match)
  600. if isinstance(exprs, list):
  601. rv = [_handle_Integral(expr, func, hint) for expr in exprs]
  602. else:
  603. rv = _handle_Integral(exprs, func, hint)
  604. if isinstance(rv, list):
  605. if simplify:
  606. rv = _remove_redundant_solutions(eq, rv, order, func.args[0])
  607. if len(rv) == 1:
  608. rv = rv[0]
  609. if ics and 'power_series' not in hint:
  610. if isinstance(rv, (Expr, Eq)):
  611. solved_constants = solve_ics([rv], [r['func']], cons(rv), ics)
  612. rv = rv.subs(solved_constants)
  613. else:
  614. rv1 = []
  615. for s in rv:
  616. try:
  617. solved_constants = solve_ics([s], [r['func']], cons(s), ics)
  618. except ValueError:
  619. continue
  620. rv1.append(s.subs(solved_constants))
  621. if len(rv1) == 1:
  622. return rv1[0]
  623. rv = rv1
  624. return rv
  625. def solve_ics(sols, funcs, constants, ics):
  626. """
  627. Solve for the constants given initial conditions
  628. ``sols`` is a list of solutions.
  629. ``funcs`` is a list of functions.
  630. ``constants`` is a list of constants.
  631. ``ics`` is the set of initial/boundary conditions for the differential
  632. equation. It should be given in the form of ``{f(x0): x1,
  633. f(x).diff(x).subs(x, x2): x3}`` and so on.
  634. Returns a dictionary mapping constants to values.
  635. ``solution.subs(constants)`` will replace the constants in ``solution``.
  636. Example
  637. =======
  638. >>> # From dsolve(f(x).diff(x) - f(x), f(x))
  639. >>> from sympy import symbols, Eq, exp, Function
  640. >>> from sympy.solvers.ode.ode import solve_ics
  641. >>> f = Function('f')
  642. >>> x, C1 = symbols('x C1')
  643. >>> sols = [Eq(f(x), C1*exp(x))]
  644. >>> funcs = [f(x)]
  645. >>> constants = [C1]
  646. >>> ics = {f(0): 2}
  647. >>> solved_constants = solve_ics(sols, funcs, constants, ics)
  648. >>> solved_constants
  649. {C1: 2}
  650. >>> sols[0].subs(solved_constants)
  651. Eq(f(x), 2*exp(x))
  652. """
  653. # Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x,
  654. # x0)): value (currently checked by classify_ode). To solve, replace x
  655. # with x0, f(x0) with value, then solve for constants. For f^(n)(x0),
  656. # differentiate the solution n times, so that f^(n)(x) appears.
  657. x = funcs[0].args[0]
  658. diff_sols = []
  659. subs_sols = []
  660. diff_variables = set()
  661. for funcarg, value in ics.items():
  662. if isinstance(funcarg, AppliedUndef):
  663. x0 = funcarg.args[0]
  664. matching_func = [f for f in funcs if f.func == funcarg.func][0]
  665. S = sols
  666. elif isinstance(funcarg, (Subs, Derivative)):
  667. if isinstance(funcarg, Subs):
  668. # Make sure it stays a subs. Otherwise subs below will produce
  669. # a different looking term.
  670. funcarg = funcarg.doit()
  671. if isinstance(funcarg, Subs):
  672. deriv = funcarg.expr
  673. x0 = funcarg.point[0]
  674. variables = funcarg.expr.variables
  675. matching_func = deriv
  676. elif isinstance(funcarg, Derivative):
  677. deriv = funcarg
  678. x0 = funcarg.variables[0]
  679. variables = (x,)*len(funcarg.variables)
  680. matching_func = deriv.subs(x0, x)
  681. for sol in sols:
  682. if sol.has(deriv.expr.func):
  683. diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables)))
  684. diff_variables.add(variables)
  685. S = diff_sols
  686. else:
  687. raise NotImplementedError("Unrecognized initial condition")
  688. for sol in S:
  689. if sol.has(matching_func):
  690. sol2 = sol
  691. sol2 = sol2.subs(x, x0)
  692. sol2 = sol2.subs(funcarg, value)
  693. # This check is necessary because of issue #15724
  694. if not isinstance(sol2, BooleanAtom) or not subs_sols:
  695. subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)]
  696. subs_sols.append(sol2)
  697. # TODO: Use solveset here
  698. try:
  699. solved_constants = solve(subs_sols, constants, dict=True)
  700. except NotImplementedError:
  701. solved_constants = []
  702. # XXX: We can't differentiate between the solution not existing because of
  703. # invalid initial conditions, and not existing because solve is not smart
  704. # enough. If we could use solveset, this might be improvable, but for now,
  705. # we use NotImplementedError in this case.
  706. if not solved_constants:
  707. raise ValueError("Couldn't solve for initial conditions")
  708. if solved_constants == True:
  709. raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.")
  710. if len(solved_constants) > 1:
  711. raise NotImplementedError("Initial conditions produced too many solutions for constants")
  712. return solved_constants[0]
  713. def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs):
  714. r"""
  715. Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve`
  716. classifications for an ODE.
  717. The tuple is ordered so that first item is the classification that
  718. :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In
  719. general, classifications at the near the beginning of the list will
  720. produce better solutions faster than those near the end, thought there are
  721. always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a
  722. different classification, use ``dsolve(ODE, func,
  723. hint=<classification>)``. See also the
  724. :py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints
  725. you can use.
  726. If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will
  727. return a dictionary of ``hint:match`` expression terms. This is intended
  728. for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that
  729. because dictionaries are ordered arbitrarily, this will most likely not be
  730. in the same order as the tuple.
  731. You can get help on different hints by executing
  732. ``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint
  733. without ``_Integral``.
  734. See :py:data:`~sympy.solvers.ode.allhints` or the
  735. :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints
  736. that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`.
  737. Notes
  738. =====
  739. These are remarks on hint names.
  740. ``_Integral``
  741. If a classification has ``_Integral`` at the end, it will return the
  742. expression with an unevaluated :py:class:`~.Integral`
  743. class in it. Note that a hint may do this anyway if
  744. :py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral,
  745. though just using an ``_Integral`` will do so much faster. Indeed, an
  746. ``_Integral`` hint will always be faster than its corresponding hint
  747. without ``_Integral`` because
  748. :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine.
  749. If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because
  750. :py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or
  751. impossible integral. Try using an ``_Integral`` hint or
  752. ``all_Integral`` to get it return something.
  753. Note that some hints do not have ``_Integral`` counterparts. This is
  754. because :py:func:`~sympy.integrals.integrals.integrate` is not used in
  755. solving the ODE for those method. For example, `n`\th order linear
  756. homogeneous ODEs with constant coefficients do not require integration
  757. to solve, so there is no
  758. ``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can
  759. easily evaluate any unevaluated
  760. :py:class:`~sympy.integrals.integrals.Integral`\s in an expression by
  761. doing ``expr.doit()``.
  762. Ordinals
  763. Some hints contain an ordinal such as ``1st_linear``. This is to help
  764. differentiate them from other hints, as well as from other methods
  765. that may not be implemented yet. If a hint has ``nth`` in it, such as
  766. the ``nth_linear`` hints, this means that the method used to applies
  767. to ODEs of any order.
  768. ``indep`` and ``dep``
  769. Some hints contain the words ``indep`` or ``dep``. These reference
  770. the independent variable and the dependent function, respectively. For
  771. example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to
  772. `x` and ``dep`` will refer to `f`.
  773. ``subs``
  774. If a hints has the word ``subs`` in it, it means that the ODE is solved
  775. by substituting the expression given after the word ``subs`` for a
  776. single dummy variable. This is usually in terms of ``indep`` and
  777. ``dep`` as above. The substituted expression will be written only in
  778. characters allowed for names of Python objects, meaning operators will
  779. be spelled out. For example, ``indep``/``dep`` will be written as
  780. ``indep_div_dep``.
  781. ``coeff``
  782. The word ``coeff`` in a hint refers to the coefficients of something
  783. in the ODE, usually of the derivative terms. See the docstring for
  784. the individual methods for more info (``help(ode)``). This is
  785. contrast to ``coefficients``, as in ``undetermined_coefficients``,
  786. which refers to the common name of a method.
  787. ``_best``
  788. Methods that have more than one fundamental way to solve will have a
  789. hint for each sub-method and a ``_best`` meta-classification. This
  790. will evaluate all hints and return the best, using the same
  791. considerations as the normal ``best`` meta-hint.
  792. Examples
  793. ========
  794. >>> from sympy import Function, classify_ode, Eq
  795. >>> from sympy.abc import x
  796. >>> f = Function('f')
  797. >>> classify_ode(Eq(f(x).diff(x), 0), f(x))
  798. ('nth_algebraic',
  799. 'separable',
  800. '1st_exact',
  801. '1st_linear',
  802. 'Bernoulli',
  803. '1st_homogeneous_coeff_best',
  804. '1st_homogeneous_coeff_subs_indep_div_dep',
  805. '1st_homogeneous_coeff_subs_dep_div_indep',
  806. '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous',
  807. 'nth_linear_euler_eq_homogeneous',
  808. 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral',
  809. '1st_linear_Integral', 'Bernoulli_Integral',
  810. '1st_homogeneous_coeff_subs_indep_div_dep_Integral',
  811. '1st_homogeneous_coeff_subs_dep_div_indep_Integral')
  812. >>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4)
  813. ('factorable', 'nth_linear_constant_coeff_undetermined_coefficients',
  814. 'nth_linear_constant_coeff_variation_of_parameters',
  815. 'nth_linear_constant_coeff_variation_of_parameters_Integral')
  816. """
  817. ics = sympify(ics)
  818. if func and len(func.args) != 1:
  819. raise ValueError("dsolve() and classify_ode() only "
  820. "work with functions of one variable, not %s" % func)
  821. if isinstance(eq, Equality):
  822. eq = eq.lhs - eq.rhs
  823. # Some methods want the unprocessed equation
  824. eq_orig = eq
  825. if prep or func is None:
  826. eq, func_ = _preprocess(eq, func)
  827. if func is None:
  828. func = func_
  829. x = func.args[0]
  830. f = func.func
  831. y = Dummy('y')
  832. terms = 5 if n is None else n
  833. order = ode_order(eq, f(x))
  834. # hint:matchdict or hint:(tuple of matchdicts)
  835. # Also will contain "default":<default hint> and "order":order items.
  836. matching_hints = {"order": order}
  837. df = f(x).diff(x)
  838. a = Wild('a', exclude=[f(x)])
  839. d = Wild('d', exclude=[df, f(x).diff(x, 2)])
  840. e = Wild('e', exclude=[df])
  841. n = Wild('n', exclude=[x, f(x), df])
  842. c1 = Wild('c1', exclude=[x])
  843. a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)])
  844. b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)])
  845. c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)])
  846. boundary = {} # Used to extract initial conditions
  847. C1 = Symbol("C1")
  848. # Preprocessing to get the initial conditions out
  849. if ics is not None:
  850. for funcarg in ics:
  851. # Separating derivatives
  852. if isinstance(funcarg, (Subs, Derivative)):
  853. # f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x,
  854. # y) is a Derivative
  855. if isinstance(funcarg, Subs):
  856. deriv = funcarg.expr
  857. old = funcarg.variables[0]
  858. new = funcarg.point[0]
  859. elif isinstance(funcarg, Derivative):
  860. deriv = funcarg
  861. # No information on this. Just assume it was x
  862. old = x
  863. new = funcarg.variables[0]
  864. if (isinstance(deriv, Derivative) and isinstance(deriv.args[0],
  865. AppliedUndef) and deriv.args[0].func == f and
  866. len(deriv.args[0].args) == 1 and old == x and not
  867. new.has(x) and all(i == deriv.variables[0] for i in
  868. deriv.variables) and not ics[funcarg].has(f)):
  869. dorder = ode_order(deriv, x)
  870. temp = 'f' + str(dorder)
  871. boundary.update({temp: new, temp + 'val': ics[funcarg]})
  872. else:
  873. raise ValueError("Enter valid boundary conditions for Derivatives")
  874. # Separating functions
  875. elif isinstance(funcarg, AppliedUndef):
  876. if (funcarg.func == f and len(funcarg.args) == 1 and
  877. not funcarg.args[0].has(x) and not ics[funcarg].has(f)):
  878. boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]})
  879. else:
  880. raise ValueError("Enter valid boundary conditions for Function")
  881. else:
  882. raise ValueError("Enter boundary conditions of the form ics={f(point): value, f(x).diff(x, order).subs(x, point): value}")
  883. ode = SingleODEProblem(eq_orig, func, x, prep=prep, xi=xi, eta=eta)
  884. user_hint = kwargs.get('hint', 'default')
  885. # Used when dsolve is called without an explicit hint.
  886. # We exit early to return the first valid match
  887. early_exit = (user_hint=='default')
  888. if user_hint.endswith('_Integral'):
  889. user_hint = user_hint[:-len('_Integral')]
  890. user_map = solver_map
  891. # An explicit hint has been given to dsolve
  892. # Skip matching code for other hints
  893. if user_hint not in ['default', 'all', 'all_Integral', 'best'] and user_hint in solver_map:
  894. user_map = {user_hint: solver_map[user_hint]}
  895. for hint in user_map:
  896. solver = user_map[hint](ode)
  897. if solver.matches():
  898. matching_hints[hint] = solver
  899. if user_map[hint].has_integral:
  900. matching_hints[hint + "_Integral"] = solver
  901. if dict and early_exit:
  902. matching_hints["default"] = hint
  903. return matching_hints
  904. eq = expand(eq)
  905. # Precondition to try remove f(x) from highest order derivative
  906. reduced_eq = None
  907. if eq.is_Add:
  908. deriv_coef = eq.coeff(f(x).diff(x, order))
  909. if deriv_coef not in (1, 0):
  910. r = deriv_coef.match(a*f(x)**c1)
  911. if r and r[c1]:
  912. den = f(x)**r[c1]
  913. reduced_eq = Add(*[arg/den for arg in eq.args])
  914. if not reduced_eq:
  915. reduced_eq = eq
  916. if order == 1:
  917. # NON-REDUCED FORM OF EQUATION matches
  918. r = collect(eq, df, exact=True).match(d + e * df)
  919. if r:
  920. r['d'] = d
  921. r['e'] = e
  922. r['y'] = y
  923. r[d] = r[d].subs(f(x), y)
  924. r[e] = r[e].subs(f(x), y)
  925. # FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS
  926. # TODO: Hint first order series should match only if d/e is analytic.
  927. # For now, only d/e and (d/e).diff(arg) is checked for existence at
  928. # at a given point.
  929. # This is currently done internally in ode_1st_power_series.
  930. point = boundary.get('f0', 0)
  931. value = boundary.get('f0val', C1)
  932. check = cancel(r[d]/r[e])
  933. check1 = check.subs({x: point, y: value})
  934. if not check1.has(oo) and not check1.has(zoo) and \
  935. not check1.has(nan) and not check1.has(-oo):
  936. check2 = (check1.diff(x)).subs({x: point, y: value})
  937. if not check2.has(oo) and not check2.has(zoo) and \
  938. not check2.has(nan) and not check2.has(-oo):
  939. rseries = r.copy()
  940. rseries.update({'terms': terms, 'f0': point, 'f0val': value})
  941. matching_hints["1st_power_series"] = rseries
  942. elif order == 2:
  943. # Homogeneous second order differential equation of the form
  944. # a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3
  945. # It has a definite power series solution at point x0 if, b3/a3 and c3/a3
  946. # are analytic at x0.
  947. deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x)
  948. r = collect(reduced_eq,
  949. [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
  950. ordinary = False
  951. if r:
  952. if not all(r[key].is_polynomial() for key in r):
  953. n, d = reduced_eq.as_numer_denom()
  954. reduced_eq = expand(n)
  955. r = collect(reduced_eq,
  956. [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
  957. if r and r[a3] != 0:
  958. p = cancel(r[b3]/r[a3]) # Used below
  959. q = cancel(r[c3]/r[a3]) # Used below
  960. point = kwargs.get('x0', 0)
  961. check = p.subs(x, point)
  962. if not check.has(oo, nan, zoo, -oo):
  963. check = q.subs(x, point)
  964. if not check.has(oo, nan, zoo, -oo):
  965. ordinary = True
  966. r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms})
  967. matching_hints["2nd_power_series_ordinary"] = r
  968. # Checking if the differential equation has a regular singular point
  969. # at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0)
  970. # and (c3/a3)*((x - x0)**2) are analytic at x0.
  971. if not ordinary:
  972. p = cancel((x - point)*p)
  973. check = p.subs(x, point)
  974. if not check.has(oo, nan, zoo, -oo):
  975. q = cancel(((x - point)**2)*q)
  976. check = q.subs(x, point)
  977. if not check.has(oo, nan, zoo, -oo):
  978. coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms}
  979. matching_hints["2nd_power_series_regular"] = coeff_dict
  980. # Order keys based on allhints.
  981. retlist = [i for i in allhints if i in matching_hints]
  982. if dict:
  983. # Dictionaries are ordered arbitrarily, so make note of which
  984. # hint would come first for dsolve(). Use an ordered dict in Py 3.
  985. matching_hints["default"] = retlist[0] if retlist else None
  986. matching_hints["ordered_hints"] = tuple(retlist)
  987. return matching_hints
  988. else:
  989. return tuple(retlist)
  990. def classify_sysode(eq, funcs=None, **kwargs):
  991. r"""
  992. Returns a dictionary of parameter names and values that define the system
  993. of ordinary differential equations in ``eq``.
  994. The parameters are further used in
  995. :py:meth:`~sympy.solvers.ode.dsolve` for solving that system.
  996. Some parameter names and values are:
  997. 'is_linear' (boolean), which tells whether the given system is linear.
  998. Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are
  999. nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators.
  1000. 'func' (list) contains the :py:class:`~sympy.core.function.Function`s that
  1001. appear with a derivative in the ODE, i.e. those that we are trying to solve
  1002. the ODE for.
  1003. 'order' (dict) with the maximum derivative for each element of the 'func'
  1004. parameter.
  1005. 'func_coeff' (dict or Matrix) with the coefficient for each triple ``(equation number,
  1006. function, order)```. The coefficients are those subexpressions that do not
  1007. appear in 'func', and hence can be considered constant for purposes of ODE
  1008. solving. The value of this parameter can also be a Matrix if the system of ODEs are
  1009. linear first order of the form X' = AX where X is the vector of dependent variables.
  1010. Here, this function returns the coefficient matrix A.
  1011. 'eq' (list) with the equations from ``eq``, sympified and transformed into
  1012. expressions (we are solving for these expressions to be zero).
  1013. 'no_of_equations' (int) is the number of equations (same as ``len(eq)``).
  1014. 'type_of_equation' (string) is an internal classification of the type of
  1015. ODE.
  1016. 'is_constant' (boolean), which tells if the system of ODEs is constant coefficient
  1017. or not. This key is temporary addition for now and is in the match dict only when
  1018. the system of ODEs is linear first order constant coefficient homogeneous. So, this
  1019. key's value is True for now if it is available else it doesn't exist.
  1020. 'is_homogeneous' (boolean), which tells if the system of ODEs is homogeneous. Like the
  1021. key 'is_constant', this key is a temporary addition and it is True since this key value
  1022. is available only when the system is linear first order constant coefficient homogeneous.
  1023. References
  1024. ==========
  1025. -http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm
  1026. -A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists
  1027. Examples
  1028. ========
  1029. >>> from sympy import Function, Eq, symbols, diff
  1030. >>> from sympy.solvers.ode.ode import classify_sysode
  1031. >>> from sympy.abc import t
  1032. >>> f, x, y = symbols('f, x, y', cls=Function)
  1033. >>> k, l, m, n = symbols('k, l, m, n', Integer=True)
  1034. >>> x1 = diff(x(t), t) ; y1 = diff(y(t), t)
  1035. >>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t)
  1036. >>> eq = (Eq(x1, 12*x(t) - 6*y(t)), Eq(y1, 11*x(t) + 3*y(t)))
  1037. >>> classify_sysode(eq)
  1038. {'eq': [-12*x(t) + 6*y(t) + Derivative(x(t), t), -11*x(t) - 3*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)],
  1039. 'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 1, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
  1040. >>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t) + 2), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
  1041. >>> classify_sysode(eq)
  1042. {'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t) - 2, t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)],
  1043. 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0,
  1044. (1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2,
  1045. 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
  1046. """
  1047. # Sympify equations and convert iterables of equations into
  1048. # a list of equations
  1049. def _sympify(eq):
  1050. return list(map(sympify, eq if iterable(eq) else [eq]))
  1051. eq, funcs = (_sympify(w) for w in [eq, funcs])
  1052. for i, fi in enumerate(eq):
  1053. if isinstance(fi, Equality):
  1054. eq[i] = fi.lhs - fi.rhs
  1055. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  1056. matching_hints = {"no_of_equation":i+1}
  1057. matching_hints['eq'] = eq
  1058. if i==0:
  1059. raise ValueError("classify_sysode() works for systems of ODEs. "
  1060. "For scalar ODEs, classify_ode should be used")
  1061. # find all the functions if not given
  1062. order = dict()
  1063. if funcs==[None]:
  1064. funcs = _extract_funcs(eq)
  1065. funcs = list(set(funcs))
  1066. if len(funcs) != len(eq):
  1067. raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs)
  1068. # This logic of list of lists in funcs to
  1069. # be replaced later.
  1070. func_dict = dict()
  1071. for func in funcs:
  1072. if not order.get(func, False):
  1073. max_order = 0
  1074. for i, eqs_ in enumerate(eq):
  1075. order_ = ode_order(eqs_,func)
  1076. if max_order < order_:
  1077. max_order = order_
  1078. eq_no = i
  1079. if eq_no in func_dict:
  1080. func_dict[eq_no] = [func_dict[eq_no], func]
  1081. else:
  1082. func_dict[eq_no] = func
  1083. order[func] = max_order
  1084. funcs = [func_dict[i] for i in range(len(func_dict))]
  1085. matching_hints['func'] = funcs
  1086. for func in funcs:
  1087. if isinstance(func, list):
  1088. for func_elem in func:
  1089. if len(func_elem.args) != 1:
  1090. raise ValueError("dsolve() and classify_sysode() work with "
  1091. "functions of one variable only, not %s" % func)
  1092. else:
  1093. if func and len(func.args) != 1:
  1094. raise ValueError("dsolve() and classify_sysode() work with "
  1095. "functions of one variable only, not %s" % func)
  1096. # find the order of all equation in system of odes
  1097. matching_hints["order"] = order
  1098. # find coefficients of terms f(t), diff(f(t),t) and higher derivatives
  1099. # and similarly for other functions g(t), diff(g(t),t) in all equations.
  1100. # Here j denotes the equation number, funcs[l] denotes the function about
  1101. # which we are talking about and k denotes the order of function funcs[l]
  1102. # whose coefficient we are calculating.
  1103. def linearity_check(eqs, j, func, is_linear_):
  1104. for k in range(order[func] + 1):
  1105. func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k))
  1106. if is_linear_ == True:
  1107. if func_coef[j, func, k] == 0:
  1108. if k == 0:
  1109. coef = eqs.as_independent(func, as_Add=True)[1]
  1110. for xr in range(1, ode_order(eqs,func) + 1):
  1111. coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1]
  1112. if coef != 0:
  1113. is_linear_ = False
  1114. else:
  1115. if eqs.as_independent(diff(func, t, k), as_Add=True)[1]:
  1116. is_linear_ = False
  1117. else:
  1118. for func_ in funcs:
  1119. if isinstance(func_, list):
  1120. for elem_func_ in func_:
  1121. dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1]
  1122. if dep != 0:
  1123. is_linear_ = False
  1124. else:
  1125. dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1]
  1126. if dep != 0:
  1127. is_linear_ = False
  1128. return is_linear_
  1129. func_coef = {}
  1130. is_linear = True
  1131. for j, eqs in enumerate(eq):
  1132. for func in funcs:
  1133. if isinstance(func, list):
  1134. for func_elem in func:
  1135. is_linear = linearity_check(eqs, j, func_elem, is_linear)
  1136. else:
  1137. is_linear = linearity_check(eqs, j, func, is_linear)
  1138. matching_hints['func_coeff'] = func_coef
  1139. matching_hints['is_linear'] = is_linear
  1140. if len(set(order.values())) == 1:
  1141. order_eq = list(matching_hints['order'].values())[0]
  1142. if matching_hints['is_linear'] == True:
  1143. if matching_hints['no_of_equation'] == 2:
  1144. if order_eq == 1:
  1145. type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef)
  1146. else:
  1147. type_of_equation = None
  1148. # If the equation doesn't match up with any of the
  1149. # general case solvers in systems.py and the number
  1150. # of equations is greater than 2, then NotImplementedError
  1151. # should be raised.
  1152. else:
  1153. type_of_equation = None
  1154. else:
  1155. if matching_hints['no_of_equation'] == 2:
  1156. if order_eq == 1:
  1157. type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef)
  1158. else:
  1159. type_of_equation = None
  1160. elif matching_hints['no_of_equation'] == 3:
  1161. if order_eq == 1:
  1162. type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef)
  1163. else:
  1164. type_of_equation = None
  1165. else:
  1166. type_of_equation = None
  1167. else:
  1168. type_of_equation = None
  1169. matching_hints['type_of_equation'] = type_of_equation
  1170. return matching_hints
  1171. def check_linear_2eq_order1(eq, func, func_coef):
  1172. x = func[0].func
  1173. y = func[1].func
  1174. fc = func_coef
  1175. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  1176. r = dict()
  1177. # for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1)
  1178. # and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2)
  1179. r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1]
  1180. r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1]
  1181. r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1]
  1182. forcing = [S.Zero,S.Zero]
  1183. for i in range(2):
  1184. for j in Add.make_args(eq[i]):
  1185. if not j.has(x(t), y(t)):
  1186. forcing[i] += j
  1187. if not (forcing[0].has(t) or forcing[1].has(t)):
  1188. # We can handle homogeneous case and simple constant forcings
  1189. r['d1'] = forcing[0]
  1190. r['d2'] = forcing[1]
  1191. else:
  1192. # Issue #9244: nonhomogeneous linear systems are not supported
  1193. return None
  1194. # Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and
  1195. # Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t))
  1196. p = 0
  1197. q = 0
  1198. p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0]))
  1199. p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0]))
  1200. for n, i in enumerate([p1, p2]):
  1201. for j in Mul.make_args(collect_const(i)):
  1202. if not j.has(t):
  1203. q = j
  1204. if q and n==0:
  1205. if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j:
  1206. p = 1
  1207. elif q and n==1:
  1208. if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j:
  1209. p = 2
  1210. # End of condition for type 6
  1211. if r['d1']!=0 or r['d2']!=0:
  1212. return None
  1213. else:
  1214. if not any(r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()):
  1215. return None
  1216. else:
  1217. r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2']
  1218. r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2']
  1219. if p:
  1220. return "type6"
  1221. else:
  1222. # Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t))
  1223. return "type7"
  1224. def check_nonlinear_2eq_order1(eq, func, func_coef):
  1225. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  1226. f = Wild('f')
  1227. g = Wild('g')
  1228. u, v = symbols('u, v', cls=Dummy)
  1229. def check_type(x, y):
  1230. r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
  1231. r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
  1232. if not (r1 and r2):
  1233. r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
  1234. r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
  1235. if not (r1 and r2):
  1236. r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
  1237. r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
  1238. if not (r1 and r2):
  1239. r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
  1240. r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
  1241. if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \
  1242. or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)):
  1243. return 'type5'
  1244. else:
  1245. return None
  1246. for func_ in func:
  1247. if isinstance(func_, list):
  1248. x = func[0][0].func
  1249. y = func[0][1].func
  1250. eq_type = check_type(x, y)
  1251. if not eq_type:
  1252. eq_type = check_type(y, x)
  1253. return eq_type
  1254. x = func[0].func
  1255. y = func[1].func
  1256. fc = func_coef
  1257. n = Wild('n', exclude=[x(t),y(t)])
  1258. f1 = Wild('f1', exclude=[v,t])
  1259. f2 = Wild('f2', exclude=[v,t])
  1260. g1 = Wild('g1', exclude=[u,t])
  1261. g2 = Wild('g2', exclude=[u,t])
  1262. for i in range(2):
  1263. eqs = 0
  1264. for terms in Add.make_args(eq[i]):
  1265. eqs += terms/fc[i,func[i],1]
  1266. eq[i] = eqs
  1267. r = eq[0].match(diff(x(t),t) - x(t)**n*f)
  1268. if r:
  1269. g = (diff(y(t),t) - eq[1])/r[f]
  1270. if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
  1271. return 'type1'
  1272. r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
  1273. if r:
  1274. g = (diff(y(t),t) - eq[1])/r[f]
  1275. if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
  1276. return 'type2'
  1277. g = Wild('g')
  1278. r1 = eq[0].match(diff(x(t),t) - f)
  1279. r2 = eq[1].match(diff(y(t),t) - g)
  1280. if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \
  1281. r2[g].subs(x(t),u).subs(y(t),v).has(t)):
  1282. return 'type3'
  1283. r1 = eq[0].match(diff(x(t),t) - f)
  1284. r2 = eq[1].match(diff(y(t),t) - g)
  1285. num, den = (
  1286. (r1[f].subs(x(t),u).subs(y(t),v))/
  1287. (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
  1288. R1 = num.match(f1*g1)
  1289. R2 = den.match(f2*g2)
  1290. # phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
  1291. if R1 and R2:
  1292. return 'type4'
  1293. return None
  1294. def check_nonlinear_2eq_order2(eq, func, func_coef):
  1295. return None
  1296. def check_nonlinear_3eq_order1(eq, func, func_coef):
  1297. x = func[0].func
  1298. y = func[1].func
  1299. z = func[2].func
  1300. fc = func_coef
  1301. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  1302. u, v, w = symbols('u, v, w', cls=Dummy)
  1303. a = Wild('a', exclude=[x(t), y(t), z(t), t])
  1304. b = Wild('b', exclude=[x(t), y(t), z(t), t])
  1305. c = Wild('c', exclude=[x(t), y(t), z(t), t])
  1306. f = Wild('f')
  1307. F1 = Wild('F1')
  1308. F2 = Wild('F2')
  1309. F3 = Wild('F3')
  1310. for i in range(3):
  1311. eqs = 0
  1312. for terms in Add.make_args(eq[i]):
  1313. eqs += terms/fc[i,func[i],1]
  1314. eq[i] = eqs
  1315. r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t))
  1316. r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t))
  1317. r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t))
  1318. if r1 and r2 and r3:
  1319. num1, den1 = r1[a].as_numer_denom()
  1320. num2, den2 = r2[b].as_numer_denom()
  1321. num3, den3 = r3[c].as_numer_denom()
  1322. if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
  1323. return 'type1'
  1324. r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f)
  1325. if r:
  1326. r1 = collect_const(r[f]).match(a*f)
  1327. r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t))
  1328. r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t))
  1329. if r1 and r2 and r3:
  1330. num1, den1 = r1[a].as_numer_denom()
  1331. num2, den2 = r2[b].as_numer_denom()
  1332. num3, den3 = r3[c].as_numer_denom()
  1333. if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
  1334. return 'type2'
  1335. r = eq[0].match(diff(x(t),t) - (F2-F3))
  1336. if r:
  1337. r1 = collect_const(r[F2]).match(c*F2)
  1338. r1.update(collect_const(r[F3]).match(b*F3))
  1339. if r1:
  1340. if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
  1341. r1[F2], r1[F3] = r1[F3], r1[F2]
  1342. r1[c], r1[b] = -r1[b], -r1[c]
  1343. r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1)
  1344. if r2:
  1345. r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2])
  1346. if r1 and r2 and r3:
  1347. return 'type3'
  1348. r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
  1349. if r:
  1350. r1 = collect_const(r[F2]).match(c*F2)
  1351. r1.update(collect_const(r[F3]).match(b*F3))
  1352. if r1:
  1353. if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
  1354. r1[F2], r1[F3] = r1[F3], r1[F2]
  1355. r1[c], r1[b] = -r1[b], -r1[c]
  1356. r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1)
  1357. if r2:
  1358. r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2])
  1359. if r1 and r2 and r3:
  1360. return 'type4'
  1361. r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3))
  1362. if r:
  1363. r1 = collect_const(r[F2]).match(c*F2)
  1364. r1.update(collect_const(r[F3]).match(b*F3))
  1365. if r1:
  1366. if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
  1367. r1[F2], r1[F3] = r1[F3], r1[F2]
  1368. r1[c], r1[b] = -r1[b], -r1[c]
  1369. r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1))
  1370. if r2:
  1371. r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2]))
  1372. if r1 and r2 and r3:
  1373. return 'type5'
  1374. return None
  1375. def check_nonlinear_3eq_order2(eq, func, func_coef):
  1376. return None
  1377. @vectorize(0)
  1378. def odesimp(ode, eq, func, hint):
  1379. r"""
  1380. Simplifies solutions of ODEs, including trying to solve for ``func`` and
  1381. running :py:meth:`~sympy.solvers.ode.constantsimp`.
  1382. It may use knowledge of the type of solution that the hint returns to
  1383. apply additional simplifications.
  1384. It also attempts to integrate any :py:class:`~sympy.integrals.integrals.Integral`\s
  1385. in the expression, if the hint is not an ``_Integral`` hint.
  1386. This function should have no effect on expressions returned by
  1387. :py:meth:`~sympy.solvers.ode.dsolve`, as
  1388. :py:meth:`~sympy.solvers.ode.dsolve` already calls
  1389. :py:meth:`~sympy.solvers.ode.ode.odesimp`, but the individual hint functions
  1390. do not call :py:meth:`~sympy.solvers.ode.ode.odesimp` (because the
  1391. :py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this
  1392. function is designed for mainly internal use.
  1393. Examples
  1394. ========
  1395. >>> from sympy import sin, symbols, dsolve, pprint, Function
  1396. >>> from sympy.solvers.ode.ode import odesimp
  1397. >>> x, u2, C1= symbols('x,u2,C1')
  1398. >>> f = Function('f')
  1399. >>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x),
  1400. ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral',
  1401. ... simplify=False)
  1402. >>> pprint(eq, wrap_line=False)
  1403. x
  1404. ----
  1405. f(x)
  1406. /
  1407. |
  1408. | / 1 \
  1409. | -|u1 + -------|
  1410. | | /1 \|
  1411. | | sin|--||
  1412. | \ \u1//
  1413. log(f(x)) = log(C1) + | ---------------- d(u1)
  1414. | 2
  1415. | u1
  1416. |
  1417. /
  1418. >>> pprint(odesimp(eq, f(x), 1, {C1},
  1419. ... hint='1st_homogeneous_coeff_subs_indep_div_dep'
  1420. ... )) #doctest: +SKIP
  1421. x
  1422. --------- = C1
  1423. /f(x)\
  1424. tan|----|
  1425. \2*x /
  1426. """
  1427. x = func.args[0]
  1428. f = func.func
  1429. C1 = get_numbered_constants(eq, num=1)
  1430. constants = eq.free_symbols - ode.free_symbols
  1431. # First, integrate if the hint allows it.
  1432. eq = _handle_Integral(eq, func, hint)
  1433. if hint.startswith("nth_linear_euler_eq_nonhomogeneous"):
  1434. eq = simplify(eq)
  1435. if not isinstance(eq, Equality):
  1436. raise TypeError("eq should be an instance of Equality")
  1437. # Second, clean up the arbitrary constants.
  1438. # Right now, nth linear hints can put as many as 2*order constants in an
  1439. # expression. If that number grows with another hint, the third argument
  1440. # here should be raised accordingly, or constantsimp() rewritten to handle
  1441. # an arbitrary number of constants.
  1442. eq = constantsimp(eq, constants)
  1443. # Lastly, now that we have cleaned up the expression, try solving for func.
  1444. # When CRootOf is implemented in solve(), we will want to return a CRootOf
  1445. # every time instead of an Equality.
  1446. # Get the f(x) on the left if possible.
  1447. if eq.rhs == func and not eq.lhs.has(func):
  1448. eq = [Eq(eq.rhs, eq.lhs)]
  1449. # make sure we are working with lists of solutions in simplified form.
  1450. if eq.lhs == func and not eq.rhs.has(func):
  1451. # The solution is already solved
  1452. eq = [eq]
  1453. else:
  1454. # The solution is not solved, so try to solve it
  1455. try:
  1456. floats = any(i.is_Float for i in eq.atoms(Number))
  1457. eqsol = solve(eq, func, force=True, rational=False if floats else None)
  1458. if not eqsol:
  1459. raise NotImplementedError
  1460. except (NotImplementedError, PolynomialError):
  1461. eq = [eq]
  1462. else:
  1463. def _expand(expr):
  1464. numer, denom = expr.as_numer_denom()
  1465. if denom.is_Add:
  1466. return expr
  1467. else:
  1468. return powsimp(expr.expand(), combine='exp', deep=True)
  1469. # XXX: the rest of odesimp() expects each ``t`` to be in a
  1470. # specific normal form: rational expression with numerator
  1471. # expanded, but with combined exponential functions (at
  1472. # least in this setup all tests pass).
  1473. eq = [Eq(f(x), _expand(t)) for t in eqsol]
  1474. # special simplification of the lhs.
  1475. if hint.startswith("1st_homogeneous_coeff"):
  1476. for j, eqi in enumerate(eq):
  1477. newi = logcombine(eqi, force=True)
  1478. if isinstance(newi.lhs, log) and newi.rhs == 0:
  1479. newi = Eq(newi.lhs.args[0]/C1, C1)
  1480. eq[j] = newi
  1481. # We cleaned up the constants before solving to help the solve engine with
  1482. # a simpler expression, but the solved expression could have introduced
  1483. # things like -C1, so rerun constantsimp() one last time before returning.
  1484. for i, eqi in enumerate(eq):
  1485. eq[i] = constantsimp(eqi, constants)
  1486. eq[i] = constant_renumber(eq[i], ode.free_symbols)
  1487. # If there is only 1 solution, return it;
  1488. # otherwise return the list of solutions.
  1489. if len(eq) == 1:
  1490. eq = eq[0]
  1491. return eq
  1492. def ode_sol_simplicity(sol, func, trysolving=True):
  1493. r"""
  1494. Returns an extended integer representing how simple a solution to an ODE
  1495. is.
  1496. The following things are considered, in order from most simple to least:
  1497. - ``sol`` is solved for ``func``.
  1498. - ``sol`` is not solved for ``func``, but can be if passed to solve (e.g.,
  1499. a solution returned by ``dsolve(ode, func, simplify=False``).
  1500. - If ``sol`` is not solved for ``func``, then base the result on the
  1501. length of ``sol``, as computed by ``len(str(sol))``.
  1502. - If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s,
  1503. this will automatically be considered less simple than any of the above.
  1504. This function returns an integer such that if solution A is simpler than
  1505. solution B by above metric, then ``ode_sol_simplicity(sola, func) <
  1506. ode_sol_simplicity(solb, func)``.
  1507. Currently, the following are the numbers returned, but if the heuristic is
  1508. ever improved, this may change. Only the ordering is guaranteed.
  1509. +----------------------------------------------+-------------------+
  1510. | Simplicity | Return |
  1511. +==============================================+===================+
  1512. | ``sol`` solved for ``func`` | ``-2`` |
  1513. +----------------------------------------------+-------------------+
  1514. | ``sol`` not solved for ``func`` but can be | ``-1`` |
  1515. +----------------------------------------------+-------------------+
  1516. | ``sol`` is not solved nor solvable for | ``len(str(sol))`` |
  1517. | ``func`` | |
  1518. +----------------------------------------------+-------------------+
  1519. | ``sol`` contains an | ``oo`` |
  1520. | :obj:`~sympy.integrals.integrals.Integral` | |
  1521. +----------------------------------------------+-------------------+
  1522. ``oo`` here means the SymPy infinity, which should compare greater than
  1523. any integer.
  1524. If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve
  1525. ``sol``, you can use ``trysolving=False`` to skip that step, which is the
  1526. only potentially slow step. For example,
  1527. :py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag
  1528. should do this.
  1529. If ``sol`` is a list of solutions, if the worst solution in the list
  1530. returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``,
  1531. that is, the length of the string representation of the whole list.
  1532. Examples
  1533. ========
  1534. This function is designed to be passed to ``min`` as the key argument,
  1535. such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i,
  1536. f(x)))``.
  1537. >>> from sympy import symbols, Function, Eq, tan, Integral
  1538. >>> from sympy.solvers.ode.ode import ode_sol_simplicity
  1539. >>> x, C1, C2 = symbols('x, C1, C2')
  1540. >>> f = Function('f')
  1541. >>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x))
  1542. -2
  1543. >>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x))
  1544. -1
  1545. >>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x))
  1546. oo
  1547. >>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1)
  1548. >>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2)
  1549. >>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]]
  1550. [28, 35]
  1551. >>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x)))
  1552. Eq(f(x)/tan(f(x)/(2*x)), C1)
  1553. """
  1554. # TODO: if two solutions are solved for f(x), we still want to be
  1555. # able to get the simpler of the two
  1556. # See the docstring for the coercion rules. We check easier (faster)
  1557. # things here first, to save time.
  1558. if iterable(sol):
  1559. # See if there are Integrals
  1560. for i in sol:
  1561. if ode_sol_simplicity(i, func, trysolving=trysolving) == oo:
  1562. return oo
  1563. return len(str(sol))
  1564. if sol.has(Integral):
  1565. return oo
  1566. # Next, try to solve for func. This code will change slightly when CRootOf
  1567. # is implemented in solve(). Probably a CRootOf solution should fall
  1568. # somewhere between a normal solution and an unsolvable expression.
  1569. # First, see if they are already solved
  1570. if sol.lhs == func and not sol.rhs.has(func) or \
  1571. sol.rhs == func and not sol.lhs.has(func):
  1572. return -2
  1573. # We are not so lucky, try solving manually
  1574. if trysolving:
  1575. try:
  1576. sols = solve(sol, func)
  1577. if not sols:
  1578. raise NotImplementedError
  1579. except NotImplementedError:
  1580. pass
  1581. else:
  1582. return -1
  1583. # Finally, a naive computation based on the length of the string version
  1584. # of the expression. This may favor combined fractions because they
  1585. # will not have duplicate denominators, and may slightly favor expressions
  1586. # with fewer additions and subtractions, as those are separated by spaces
  1587. # by the printer.
  1588. # Additional ideas for simplicity heuristics are welcome, like maybe
  1589. # checking if a equation has a larger domain, or if constantsimp has
  1590. # introduced arbitrary constants numbered higher than the order of a
  1591. # given ODE that sol is a solution of.
  1592. return len(str(sol))
  1593. def _extract_funcs(eqs):
  1594. funcs = []
  1595. for eq in eqs:
  1596. derivs = [node for node in preorder_traversal(eq) if isinstance(node, Derivative)]
  1597. func = []
  1598. for d in derivs:
  1599. func += list(d.atoms(AppliedUndef))
  1600. for func_ in func:
  1601. funcs.append(func_)
  1602. funcs = list(uniq(funcs))
  1603. return funcs
  1604. def _get_constant_subexpressions(expr, Cs):
  1605. Cs = set(Cs)
  1606. Ces = []
  1607. def _recursive_walk(expr):
  1608. expr_syms = expr.free_symbols
  1609. if expr_syms and expr_syms.issubset(Cs):
  1610. Ces.append(expr)
  1611. else:
  1612. if expr.func == exp:
  1613. expr = expr.expand(mul=True)
  1614. if expr.func in (Add, Mul):
  1615. d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs))
  1616. if len(d[True]) > 1:
  1617. x = expr.func(*d[True])
  1618. if not x.is_number:
  1619. Ces.append(x)
  1620. elif isinstance(expr, Integral):
  1621. if expr.free_symbols.issubset(Cs) and \
  1622. all(len(x) == 3 for x in expr.limits):
  1623. Ces.append(expr)
  1624. for i in expr.args:
  1625. _recursive_walk(i)
  1626. return
  1627. _recursive_walk(expr)
  1628. return Ces
  1629. def __remove_linear_redundancies(expr, Cs):
  1630. cnts = {i: expr.count(i) for i in Cs}
  1631. Cs = [i for i in Cs if cnts[i] > 0]
  1632. def _linear(expr):
  1633. if isinstance(expr, Add):
  1634. xs = [i for i in Cs if expr.count(i)==cnts[i] \
  1635. and 0 == expr.diff(i, 2)]
  1636. d = {}
  1637. for x in xs:
  1638. y = expr.diff(x)
  1639. if y not in d:
  1640. d[y]=[]
  1641. d[y].append(x)
  1642. for y in d:
  1643. if len(d[y]) > 1:
  1644. d[y].sort(key=str)
  1645. for x in d[y][1:]:
  1646. expr = expr.subs(x, 0)
  1647. return expr
  1648. def _recursive_walk(expr):
  1649. if len(expr.args) != 0:
  1650. expr = expr.func(*[_recursive_walk(i) for i in expr.args])
  1651. expr = _linear(expr)
  1652. return expr
  1653. if isinstance(expr, Equality):
  1654. lhs, rhs = [_recursive_walk(i) for i in expr.args]
  1655. f = lambda i: isinstance(i, Number) or i in Cs
  1656. if isinstance(lhs, Symbol) and lhs in Cs:
  1657. rhs, lhs = lhs, rhs
  1658. if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol):
  1659. dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
  1660. drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f)
  1661. for i in [True, False]:
  1662. for hs in [dlhs, drhs]:
  1663. if i not in hs:
  1664. hs[i] = [0]
  1665. # this calculation can be simplified
  1666. lhs = Add(*dlhs[False]) - Add(*drhs[False])
  1667. rhs = Add(*drhs[True]) - Add(*dlhs[True])
  1668. elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol):
  1669. dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
  1670. if True in dlhs:
  1671. if False not in dlhs:
  1672. dlhs[False] = [1]
  1673. lhs = Mul(*dlhs[False])
  1674. rhs = rhs/Mul(*dlhs[True])
  1675. return Eq(lhs, rhs)
  1676. else:
  1677. return _recursive_walk(expr)
  1678. @vectorize(0)
  1679. def constantsimp(expr, constants):
  1680. r"""
  1681. Simplifies an expression with arbitrary constants in it.
  1682. This function is written specifically to work with
  1683. :py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use.
  1684. Simplification is done by "absorbing" the arbitrary constants into other
  1685. arbitrary constants, numbers, and symbols that they are not independent
  1686. of.
  1687. The symbols must all have the same name with numbers after it, for
  1688. example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be
  1689. '``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3.
  1690. If the arbitrary constants are independent of the variable ``x``, then the
  1691. independent symbol would be ``x``. There is no need to specify the
  1692. dependent function, such as ``f(x)``, because it already has the
  1693. independent symbol, ``x``, in it.
  1694. Because terms are "absorbed" into arbitrary constants and because
  1695. constants are renumbered after simplifying, the arbitrary constants in
  1696. expr are not necessarily equal to the ones of the same name in the
  1697. returned result.
  1698. If two or more arbitrary constants are added, multiplied, or raised to the
  1699. power of each other, they are first absorbed together into a single
  1700. arbitrary constant. Then the new constant is combined into other terms if
  1701. necessary.
  1702. Absorption of constants is done with limited assistance:
  1703. 1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join
  1704. constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x
  1705. C_1 \cos(x)`;
  1706. 2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are
  1707. expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`.
  1708. Use :py:meth:`~sympy.solvers.ode.ode.constant_renumber` to renumber constants
  1709. after simplification or else arbitrary numbers on constants may appear,
  1710. e.g. `C_1 + C_3 x`.
  1711. In rare cases, a single constant can be "simplified" into two constants.
  1712. Every differential equation solution should have as many arbitrary
  1713. constants as the order of the differential equation. The result here will
  1714. be technically correct, but it may, for example, have `C_1` and `C_2` in
  1715. an expression, when `C_1` is actually equal to `C_2`. Use your discretion
  1716. in such situations, and also take advantage of the ability to use hints in
  1717. :py:meth:`~sympy.solvers.ode.dsolve`.
  1718. Examples
  1719. ========
  1720. >>> from sympy import symbols
  1721. >>> from sympy.solvers.ode.ode import constantsimp
  1722. >>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y')
  1723. >>> constantsimp(2*C1*x, {C1, C2, C3})
  1724. C1*x
  1725. >>> constantsimp(C1 + 2 + x, {C1, C2, C3})
  1726. C1 + x
  1727. >>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3})
  1728. C1 + C3*x
  1729. """
  1730. # This function works recursively. The idea is that, for Mul,
  1731. # Add, Pow, and Function, if the class has a constant in it, then
  1732. # we can simplify it, which we do by recursing down and
  1733. # simplifying up. Otherwise, we can skip that part of the
  1734. # expression.
  1735. Cs = constants
  1736. orig_expr = expr
  1737. constant_subexprs = _get_constant_subexpressions(expr, Cs)
  1738. for xe in constant_subexprs:
  1739. xes = list(xe.free_symbols)
  1740. if not xes:
  1741. continue
  1742. if all(expr.count(c) == xe.count(c) for c in xes):
  1743. xes.sort(key=str)
  1744. expr = expr.subs(xe, xes[0])
  1745. # try to perform common sub-expression elimination of constant terms
  1746. try:
  1747. commons, rexpr = cse(expr)
  1748. commons.reverse()
  1749. rexpr = rexpr[0]
  1750. for s in commons:
  1751. cs = list(s[1].atoms(Symbol))
  1752. if len(cs) == 1 and cs[0] in Cs and \
  1753. cs[0] not in rexpr.atoms(Symbol) and \
  1754. not any(cs[0] in ex for ex in commons if ex != s):
  1755. rexpr = rexpr.subs(s[0], cs[0])
  1756. else:
  1757. rexpr = rexpr.subs(*s)
  1758. expr = rexpr
  1759. except IndexError:
  1760. pass
  1761. expr = __remove_linear_redundancies(expr, Cs)
  1762. def _conditional_term_factoring(expr):
  1763. new_expr = terms_gcd(expr, clear=False, deep=True, expand=False)
  1764. # we do not want to factor exponentials, so handle this separately
  1765. if new_expr.is_Mul:
  1766. infac = False
  1767. asfac = False
  1768. for m in new_expr.args:
  1769. if isinstance(m, exp):
  1770. asfac = True
  1771. elif m.is_Add:
  1772. infac = any(isinstance(fi, exp) for t in m.args
  1773. for fi in Mul.make_args(t))
  1774. if asfac and infac:
  1775. new_expr = expr
  1776. break
  1777. return new_expr
  1778. expr = _conditional_term_factoring(expr)
  1779. # call recursively if more simplification is possible
  1780. if orig_expr != expr:
  1781. return constantsimp(expr, Cs)
  1782. return expr
  1783. def constant_renumber(expr, variables=None, newconstants=None):
  1784. r"""
  1785. Renumber arbitrary constants in ``expr`` to use the symbol names as given
  1786. in ``newconstants``. In the process, this reorders expression terms in a
  1787. standard way.
  1788. If ``newconstants`` is not provided then the new constant names will be
  1789. ``C1``, ``C2`` etc. Otherwise ``newconstants`` should be an iterable
  1790. giving the new symbols to use for the constants in order.
  1791. The ``variables`` argument is a list of non-constant symbols. All other
  1792. free symbols found in ``expr`` are assumed to be constants and will be
  1793. renumbered. If ``variables`` is not given then any numbered symbol
  1794. beginning with ``C`` (e.g. ``C1``) is assumed to be a constant.
  1795. Symbols are renumbered based on ``.sort_key()``, so they should be
  1796. numbered roughly in the order that they appear in the final, printed
  1797. expression. Note that this ordering is based in part on hashes, so it can
  1798. produce different results on different machines.
  1799. The structure of this function is very similar to that of
  1800. :py:meth:`~sympy.solvers.ode.constantsimp`.
  1801. Examples
  1802. ========
  1803. >>> from sympy import symbols
  1804. >>> from sympy.solvers.ode.ode import constant_renumber
  1805. >>> x, C1, C2, C3 = symbols('x,C1:4')
  1806. >>> expr = C3 + C2*x + C1*x**2
  1807. >>> expr
  1808. C1*x**2 + C2*x + C3
  1809. >>> constant_renumber(expr)
  1810. C1 + C2*x + C3*x**2
  1811. The ``variables`` argument specifies which are constants so that the
  1812. other symbols will not be renumbered:
  1813. >>> constant_renumber(expr, [C1, x])
  1814. C1*x**2 + C2 + C3*x
  1815. The ``newconstants`` argument is used to specify what symbols to use when
  1816. replacing the constants:
  1817. >>> constant_renumber(expr, [x], newconstants=symbols('E1:4'))
  1818. E1 + E2*x + E3*x**2
  1819. """
  1820. # System of expressions
  1821. if isinstance(expr, (set, list, tuple)):
  1822. return type(expr)(constant_renumber(Tuple(*expr),
  1823. variables=variables, newconstants=newconstants))
  1824. # Symbols in solution but not ODE are constants
  1825. if variables is not None:
  1826. variables = set(variables)
  1827. free_symbols = expr.free_symbols
  1828. constantsymbols = list(free_symbols - variables)
  1829. # Any Cn is a constant...
  1830. else:
  1831. variables = set()
  1832. isconstant = lambda s: s.startswith('C') and s[1:].isdigit()
  1833. constantsymbols = [sym for sym in expr.free_symbols if isconstant(sym.name)]
  1834. # Find new constants checking that they aren't already in the ODE
  1835. if newconstants is None:
  1836. iter_constants = numbered_symbols(start=1, prefix='C', exclude=variables)
  1837. else:
  1838. iter_constants = (sym for sym in newconstants if sym not in variables)
  1839. constants_found = []
  1840. # make a mapping to send all constantsymbols to S.One and use
  1841. # that to make sure that term ordering is not dependent on
  1842. # the indexed value of C
  1843. C_1 = [(ci, S.One) for ci in constantsymbols]
  1844. sort_key=lambda arg: default_sort_key(arg.subs(C_1))
  1845. def _constant_renumber(expr):
  1846. r"""
  1847. We need to have an internal recursive function
  1848. """
  1849. # For system of expressions
  1850. if isinstance(expr, Tuple):
  1851. renumbered = [_constant_renumber(e) for e in expr]
  1852. return Tuple(*renumbered)
  1853. if isinstance(expr, Equality):
  1854. return Eq(
  1855. _constant_renumber(expr.lhs),
  1856. _constant_renumber(expr.rhs))
  1857. if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \
  1858. not expr.has(*constantsymbols):
  1859. # Base case, as above. Hope there aren't constants inside
  1860. # of some other class, because they won't be renumbered.
  1861. return expr
  1862. elif expr.is_Piecewise:
  1863. return expr
  1864. elif expr in constantsymbols:
  1865. if expr not in constants_found:
  1866. constants_found.append(expr)
  1867. return expr
  1868. elif expr.is_Function or expr.is_Pow:
  1869. return expr.func(
  1870. *[_constant_renumber(x) for x in expr.args])
  1871. else:
  1872. sortedargs = list(expr.args)
  1873. sortedargs.sort(key=sort_key)
  1874. return expr.func(*[_constant_renumber(x) for x in sortedargs])
  1875. expr = _constant_renumber(expr)
  1876. # Don't renumber symbols present in the ODE.
  1877. constants_found = [c for c in constants_found if c not in variables]
  1878. # Renumbering happens here
  1879. subs_dict = {var: cons for var, cons in zip(constants_found, iter_constants)}
  1880. expr = expr.subs(subs_dict, simultaneous=True)
  1881. return expr
  1882. def _handle_Integral(expr, func, hint):
  1883. r"""
  1884. Converts a solution with Integrals in it into an actual solution.
  1885. For most hints, this simply runs ``expr.doit()``.
  1886. """
  1887. if hint == "nth_linear_constant_coeff_homogeneous":
  1888. sol = expr
  1889. elif not hint.endswith("_Integral"):
  1890. sol = expr.doit()
  1891. else:
  1892. sol = expr
  1893. return sol
  1894. # XXX: Should this function maybe go somewhere else?
  1895. def homogeneous_order(eq, *symbols):
  1896. r"""
  1897. Returns the order `n` if `g` is homogeneous and ``None`` if it is not
  1898. homogeneous.
  1899. Determines if a function is homogeneous and if so of what order. A
  1900. function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y,
  1901. \cdots) = t^n f(x, y, \cdots)`.
  1902. If the function is of two variables, `F(x, y)`, then `f` being homogeneous
  1903. of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)`
  1904. or `H(y/x)`. This fact is used to solve 1st order ordinary differential
  1905. equations whose coefficients are homogeneous of the same order (see the
  1906. docstrings of
  1907. :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep` and
  1908. :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`).
  1909. Symbols can be functions, but every argument of the function must be a
  1910. symbol, and the arguments of the function that appear in the expression
  1911. must match those given in the list of symbols. If a declared function
  1912. appears with different arguments than given in the list of symbols,
  1913. ``None`` is returned.
  1914. Examples
  1915. ========
  1916. >>> from sympy import Function, homogeneous_order, sqrt
  1917. >>> from sympy.abc import x, y
  1918. >>> f = Function('f')
  1919. >>> homogeneous_order(f(x), f(x)) is None
  1920. True
  1921. >>> homogeneous_order(f(x,y), f(y, x), x, y) is None
  1922. True
  1923. >>> homogeneous_order(f(x), f(x), x)
  1924. 1
  1925. >>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x))
  1926. 2
  1927. >>> homogeneous_order(x**2+f(x), x, f(x)) is None
  1928. True
  1929. """
  1930. if not symbols:
  1931. raise ValueError("homogeneous_order: no symbols were given.")
  1932. symset = set(symbols)
  1933. eq = sympify(eq)
  1934. # The following are not supported
  1935. if eq.has(Order, Derivative):
  1936. return None
  1937. # These are all constants
  1938. if (eq.is_Number or
  1939. eq.is_NumberSymbol or
  1940. eq.is_number
  1941. ):
  1942. return S.Zero
  1943. # Replace all functions with dummy variables
  1944. dum = numbered_symbols(prefix='d', cls=Dummy)
  1945. newsyms = set()
  1946. for i in [j for j in symset if getattr(j, 'is_Function')]:
  1947. iargs = set(i.args)
  1948. if iargs.difference(symset):
  1949. return None
  1950. else:
  1951. dummyvar = next(dum)
  1952. eq = eq.subs(i, dummyvar)
  1953. symset.remove(i)
  1954. newsyms.add(dummyvar)
  1955. symset.update(newsyms)
  1956. if not eq.free_symbols & symset:
  1957. return None
  1958. # assuming order of a nested function can only be equal to zero
  1959. if isinstance(eq, Function):
  1960. return None if homogeneous_order(
  1961. eq.args[0], *tuple(symset)) != 0 else S.Zero
  1962. # make the replacement of x with x*t and see if t can be factored out
  1963. t = Dummy('t', positive=True) # It is sufficient that t > 0
  1964. eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t]
  1965. if eqs is S.One:
  1966. return S.Zero # there was no term with only t
  1967. i, d = eqs.as_independent(t, as_Add=False)
  1968. b, e = d.as_base_exp()
  1969. if b == t:
  1970. return e
  1971. def ode_2nd_power_series_ordinary(eq, func, order, match):
  1972. r"""
  1973. Gives a power series solution to a second order homogeneous differential
  1974. equation with polynomial coefficients at an ordinary point. A homogeneous
  1975. differential equation is of the form
  1976. .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0
  1977. For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials,
  1978. it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at
  1979. `x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`,
  1980. in the differential equation, and equating the nth term. Using this relation
  1981. various terms can be generated.
  1982. Examples
  1983. ========
  1984. >>> from sympy import dsolve, Function, pprint
  1985. >>> from sympy.abc import x
  1986. >>> f = Function("f")
  1987. >>> eq = f(x).diff(x, 2) + f(x)
  1988. >>> pprint(dsolve(eq, hint='2nd_power_series_ordinary'))
  1989. / 4 2 \ / 2\
  1990. |x x | | x | / 6\
  1991. f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x /
  1992. \24 2 / \ 6 /
  1993. References
  1994. ==========
  1995. - http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx
  1996. - George E. Simmons, "Differential Equations with Applications and
  1997. Historical Notes", p.p 176 - 184
  1998. """
  1999. x = func.args[0]
  2000. f = func.func
  2001. C0, C1 = get_numbered_constants(eq, num=2)
  2002. n = Dummy("n", integer=True)
  2003. s = Wild("s")
  2004. k = Wild("k", exclude=[x])
  2005. x0 = match['x0']
  2006. terms = match['terms']
  2007. p = match[match['a3']]
  2008. q = match[match['b3']]
  2009. r = match[match['c3']]
  2010. seriesdict = {}
  2011. recurr = Function("r")
  2012. # Generating the recurrence relation which works this way:
  2013. # for the second order term the summation begins at n = 2. The coefficients
  2014. # p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that
  2015. # the exponent of x becomes n.
  2016. # For example, if p is x, then the second degree recurrence term is
  2017. # an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to
  2018. # an+1*n*(n - 1)*x**n.
  2019. # A similar process is done with the first order and zeroth order term.
  2020. coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)]
  2021. for index, coeff in enumerate(coefflist):
  2022. if coeff[1]:
  2023. f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0)))
  2024. if f2.is_Add:
  2025. addargs = f2.args
  2026. else:
  2027. addargs = [f2]
  2028. for arg in addargs:
  2029. powm = arg.match(s*x**k)
  2030. term = coeff[0]*powm[s]
  2031. if not powm[k].is_Symbol:
  2032. term = term.subs(n, n - powm[k].as_independent(n)[0])
  2033. startind = powm[k].subs(n, index)
  2034. # Seeing if the startterm can be reduced further.
  2035. # If it vanishes for n lesser than startind, it is
  2036. # equal to summation from n.
  2037. if startind:
  2038. for i in reversed(range(startind)):
  2039. if not term.subs(n, i):
  2040. seriesdict[term] = i
  2041. else:
  2042. seriesdict[term] = i + 1
  2043. break
  2044. else:
  2045. seriesdict[term] = S.Zero
  2046. # Stripping of terms so that the sum starts with the same number.
  2047. teq = S.Zero
  2048. suminit = seriesdict.values()
  2049. rkeys = seriesdict.keys()
  2050. req = Add(*rkeys)
  2051. if any(suminit):
  2052. maxval = max(suminit)
  2053. for term in seriesdict:
  2054. val = seriesdict[term]
  2055. if val != maxval:
  2056. for i in range(val, maxval):
  2057. teq += term.subs(n, val)
  2058. finaldict = {}
  2059. if teq:
  2060. fargs = teq.atoms(AppliedUndef)
  2061. if len(fargs) == 1:
  2062. finaldict[fargs.pop()] = 0
  2063. else:
  2064. maxf = max(fargs, key = lambda x: x.args[0])
  2065. sol = solve(teq, maxf)
  2066. if isinstance(sol, list):
  2067. sol = sol[0]
  2068. finaldict[maxf] = sol
  2069. # Finding the recurrence relation in terms of the largest term.
  2070. fargs = req.atoms(AppliedUndef)
  2071. maxf = max(fargs, key = lambda x: x.args[0])
  2072. minf = min(fargs, key = lambda x: x.args[0])
  2073. if minf.args[0].is_Symbol:
  2074. startiter = 0
  2075. else:
  2076. startiter = -minf.args[0].as_independent(n)[0]
  2077. lhs = maxf
  2078. rhs = solve(req, maxf)
  2079. if isinstance(rhs, list):
  2080. rhs = rhs[0]
  2081. # Checking how many values are already present
  2082. tcounter = len([t for t in finaldict.values() if t])
  2083. for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary
  2084. check = rhs.subs(n, startiter)
  2085. nlhs = lhs.subs(n, startiter)
  2086. nrhs = check.subs(finaldict)
  2087. finaldict[nlhs] = nrhs
  2088. startiter += 1
  2089. # Post processing
  2090. series = C0 + C1*(x - x0)
  2091. for term in finaldict:
  2092. if finaldict[term]:
  2093. fact = term.args[0]
  2094. series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*(
  2095. x - x0)**fact)
  2096. series = collect(expand_mul(series), [C0, C1]) + Order(x**terms)
  2097. return Eq(f(x), series)
  2098. def ode_2nd_power_series_regular(eq, func, order, match):
  2099. r"""
  2100. Gives a power series solution to a second order homogeneous differential
  2101. equation with polynomial coefficients at a regular point. A second order
  2102. homogeneous differential equation is of the form
  2103. .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0
  2104. A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}`
  2105. and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity
  2106. `P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for
  2107. finding the power series solutions is:
  2108. 1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series
  2109. solutions about x0. Find `p0` and `q0` which are the constants of the
  2110. power series expansions.
  2111. 2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the
  2112. roots `m1` and `m2` of the indicial equation.
  2113. 3. If `m1 - m2` is a non integer there exists two series solutions. If
  2114. `m1 = m2`, there exists only one solution. If `m1 - m2` is an integer,
  2115. then the existence of one solution is confirmed. The other solution may
  2116. or may not exist.
  2117. The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The
  2118. coefficients are determined by the following recurrence relation.
  2119. `a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case
  2120. in which `m1 - m2` is an integer, it can be seen from the recurrence relation
  2121. that for the lower root `m`, when `n` equals the difference of both the
  2122. roots, the denominator becomes zero. So if the numerator is not equal to zero,
  2123. a second series solution exists.
  2124. Examples
  2125. ========
  2126. >>> from sympy import dsolve, Function, pprint
  2127. >>> from sympy.abc import x
  2128. >>> f = Function("f")
  2129. >>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x)
  2130. >>> pprint(dsolve(eq, hint='2nd_power_series_regular'))
  2131. / 6 4 2 \
  2132. | x x x |
  2133. / 4 2 \ C1*|- --- + -- - -- + 1|
  2134. | x x | \ 720 24 2 / / 6\
  2135. f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
  2136. \120 6 / x
  2137. References
  2138. ==========
  2139. - George E. Simmons, "Differential Equations with Applications and
  2140. Historical Notes", p.p 176 - 184
  2141. """
  2142. x = func.args[0]
  2143. f = func.func
  2144. C0, C1 = get_numbered_constants(eq, num=2)
  2145. m = Dummy("m") # for solving the indicial equation
  2146. x0 = match['x0']
  2147. terms = match['terms']
  2148. p = match['p']
  2149. q = match['q']
  2150. # Generating the indicial equation
  2151. indicial = []
  2152. for term in [p, q]:
  2153. if not term.has(x):
  2154. indicial.append(term)
  2155. else:
  2156. term = series(term, x=x, n=1, x0=x0)
  2157. if isinstance(term, Order):
  2158. indicial.append(S.Zero)
  2159. else:
  2160. for arg in term.args:
  2161. if not arg.has(x):
  2162. indicial.append(arg)
  2163. break
  2164. p0, q0 = indicial
  2165. sollist = solve(m*(m - 1) + m*p0 + q0, m)
  2166. if sollist and isinstance(sollist, list) and all(
  2167. sol.is_real for sol in sollist):
  2168. serdict1 = {}
  2169. serdict2 = {}
  2170. if len(sollist) == 1:
  2171. # Only one series solution exists in this case.
  2172. m1 = m2 = sollist.pop()
  2173. if terms-m1-1 <= 0:
  2174. return Eq(f(x), Order(terms))
  2175. serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
  2176. else:
  2177. m1 = sollist[0]
  2178. m2 = sollist[1]
  2179. if m1 < m2:
  2180. m1, m2 = m2, m1
  2181. # Irrespective of whether m1 - m2 is an integer or not, one
  2182. # Frobenius series solution exists.
  2183. serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
  2184. if not (m1 - m2).is_integer:
  2185. # Second frobenius series solution exists.
  2186. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1)
  2187. else:
  2188. # Check if second frobenius series solution exists.
  2189. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1)
  2190. if serdict1:
  2191. finalseries1 = C0
  2192. for key in serdict1:
  2193. power = int(key.name[1:])
  2194. finalseries1 += serdict1[key]*(x - x0)**power
  2195. finalseries1 = (x - x0)**m1*finalseries1
  2196. finalseries2 = S.Zero
  2197. if serdict2:
  2198. for key in serdict2:
  2199. power = int(key.name[1:])
  2200. finalseries2 += serdict2[key]*(x - x0)**power
  2201. finalseries2 += C1
  2202. finalseries2 = (x - x0)**m2*finalseries2
  2203. return Eq(f(x), collect(finalseries1 + finalseries2,
  2204. [C0, C1]) + Order(x**terms))
  2205. def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None):
  2206. r"""
  2207. Returns a dict with keys as coefficients and values as their values in terms of C0
  2208. """
  2209. n = int(n)
  2210. # In cases where m1 - m2 is not an integer
  2211. m2 = check
  2212. d = Dummy("d")
  2213. numsyms = numbered_symbols("C", start=0)
  2214. numsyms = [next(numsyms) for i in range(n + 1)]
  2215. serlist = []
  2216. for ser in [p, q]:
  2217. # Order term not present
  2218. if ser.is_polynomial(x) and Poly(ser, x).degree() <= n:
  2219. if x0:
  2220. ser = ser.subs(x, x + x0)
  2221. dict_ = Poly(ser, x).as_dict()
  2222. # Order term present
  2223. else:
  2224. tseries = series(ser, x=x0, n=n+1)
  2225. # Removing order
  2226. dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict()
  2227. # Fill in with zeros, if coefficients are zero.
  2228. for i in range(n + 1):
  2229. if (i,) not in dict_:
  2230. dict_[(i,)] = S.Zero
  2231. serlist.append(dict_)
  2232. pseries = serlist[0]
  2233. qseries = serlist[1]
  2234. indicial = d*(d - 1) + d*p0 + q0
  2235. frobdict = {}
  2236. for i in range(1, n + 1):
  2237. num = c*(m*pseries[(i,)] + qseries[(i,)])
  2238. for j in range(1, i):
  2239. sym = Symbol("C" + str(j))
  2240. num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)])
  2241. # Checking for cases when m1 - m2 is an integer. If num equals zero
  2242. # then a second Frobenius series solution cannot be found. If num is not zero
  2243. # then set constant as zero and proceed.
  2244. if m2 is not None and i == m2 - m:
  2245. if num:
  2246. return False
  2247. else:
  2248. frobdict[numsyms[i]] = S.Zero
  2249. else:
  2250. frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i))
  2251. return frobdict
  2252. def _remove_redundant_solutions(eq, solns, order, var):
  2253. r"""
  2254. Remove redundant solutions from the set of solutions.
  2255. This function is needed because otherwise dsolve can return
  2256. redundant solutions. As an example consider:
  2257. eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0)
  2258. There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0
  2259. leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0
  2260. leading to the solution f(x) = C1. In this particular case we then see
  2261. that the second solution is a special case of the first and we do not
  2262. want to return it.
  2263. This does not always happen. If we have
  2264. eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0)
  2265. then we get the algebraic solution f(x) = [-2, 2] and the integral solution
  2266. f(x) = x + C1 and in this case the two solutions are not equivalent wrt
  2267. initial conditions so both should be returned.
  2268. """
  2269. def is_special_case_of(soln1, soln2):
  2270. return _is_special_case_of(soln1, soln2, eq, order, var)
  2271. unique_solns = []
  2272. for soln1 in solns:
  2273. for soln2 in unique_solns[:]:
  2274. if is_special_case_of(soln1, soln2):
  2275. break
  2276. elif is_special_case_of(soln2, soln1):
  2277. unique_solns.remove(soln2)
  2278. else:
  2279. unique_solns.append(soln1)
  2280. return unique_solns
  2281. def _is_special_case_of(soln1, soln2, eq, order, var):
  2282. r"""
  2283. True if soln1 is found to be a special case of soln2 wrt some value of the
  2284. constants that appear in soln2. False otherwise.
  2285. """
  2286. # The solutions returned by dsolve may be given explicitly or implicitly.
  2287. # We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs)
  2288. # of the two solutions.
  2289. #
  2290. # Since this is supposed to hold for all x it also holds for derivatives.
  2291. # For an order n ode we should be able to differentiate
  2292. # each solution n times to get n+1 equations.
  2293. #
  2294. # We then try to solve those n+1 equations for the integrations constants
  2295. # in sol2. If we can find a solution that doesn't depend on x then it
  2296. # means that some value of the constants in sol1 is a special case of
  2297. # sol2 corresponding to a particular choice of the integration constants.
  2298. # In case the solution is in implicit form we subtract the sides
  2299. soln1 = soln1.rhs - soln1.lhs
  2300. soln2 = soln2.rhs - soln2.lhs
  2301. # Work for the series solution
  2302. if soln1.has(Order) and soln2.has(Order):
  2303. if soln1.getO() == soln2.getO():
  2304. soln1 = soln1.removeO()
  2305. soln2 = soln2.removeO()
  2306. else:
  2307. return False
  2308. elif soln1.has(Order) or soln2.has(Order):
  2309. return False
  2310. constants1 = soln1.free_symbols.difference(eq.free_symbols)
  2311. constants2 = soln2.free_symbols.difference(eq.free_symbols)
  2312. constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1))
  2313. if len(constants1) == 1:
  2314. constants1_new = {constants1_new}
  2315. for c_old, c_new in zip(constants1, constants1_new):
  2316. soln1 = soln1.subs(c_old, c_new)
  2317. # n equations for sol1 = sol2, sol1'=sol2', ...
  2318. lhs = soln1
  2319. rhs = soln2
  2320. eqns = [Eq(lhs, rhs)]
  2321. for n in range(1, order):
  2322. lhs = lhs.diff(var)
  2323. rhs = rhs.diff(var)
  2324. eq = Eq(lhs, rhs)
  2325. eqns.append(eq)
  2326. # BooleanTrue/False awkwardly show up for trivial equations
  2327. if any(isinstance(eq, BooleanFalse) for eq in eqns):
  2328. return False
  2329. eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)]
  2330. try:
  2331. constant_solns = solve(eqns, constants2)
  2332. except NotImplementedError:
  2333. return False
  2334. # Sometimes returns a dict and sometimes a list of dicts
  2335. if isinstance(constant_solns, dict):
  2336. constant_solns = [constant_solns]
  2337. # after solving the issue 17418, maybe we don't need the following checksol code.
  2338. for constant_soln in constant_solns:
  2339. for eq in eqns:
  2340. eq=eq.rhs-eq.lhs
  2341. if checksol(eq, constant_soln) is not True:
  2342. return False
  2343. # If any solution gives all constants as expressions that don't depend on
  2344. # x then there exists constants for soln2 that give soln1
  2345. for constant_soln in constant_solns:
  2346. if not any(c.has(var) for c in constant_soln.values()):
  2347. return True
  2348. return False
  2349. def ode_1st_power_series(eq, func, order, match):
  2350. r"""
  2351. The power series solution is a method which gives the Taylor series expansion
  2352. to the solution of a differential equation.
  2353. For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power
  2354. series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`.
  2355. The solution is given by
  2356. .. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!},
  2357. where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`.
  2358. To compute the values of the `F_{n}(x_{0},b)` the following algorithm is
  2359. followed, until the required number of terms are generated.
  2360. 1. `F_1 = h(x_{0}, b)`
  2361. 2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}`
  2362. Examples
  2363. ========
  2364. >>> from sympy import Function, pprint, exp, dsolve
  2365. >>> from sympy.abc import x
  2366. >>> f = Function('f')
  2367. >>> eq = exp(x)*(f(x).diff(x)) - f(x)
  2368. >>> pprint(dsolve(eq, hint='1st_power_series'))
  2369. 3 4 5
  2370. C1*x C1*x C1*x / 6\
  2371. f(x) = C1 + C1*x - ----- + ----- + ----- + O\x /
  2372. 6 24 60
  2373. References
  2374. ==========
  2375. - Travis W. Walker, Analytic power series technique for solving first-order
  2376. differential equations, p.p 17, 18
  2377. """
  2378. x = func.args[0]
  2379. y = match['y']
  2380. f = func.func
  2381. h = -match[match['d']]/match[match['e']]
  2382. point = match['f0']
  2383. value = match['f0val']
  2384. terms = match['terms']
  2385. # First term
  2386. F = h
  2387. if not h:
  2388. return Eq(f(x), value)
  2389. # Initialization
  2390. series = value
  2391. if terms > 1:
  2392. hc = h.subs({x: point, y: value})
  2393. if hc.has(oo) or hc.has(nan) or hc.has(zoo):
  2394. # Derivative does not exist, not analytic
  2395. return Eq(f(x), oo)
  2396. elif hc:
  2397. series += hc*(x - point)
  2398. for factcount in range(2, terms):
  2399. Fnew = F.diff(x) + F.diff(y)*h
  2400. Fnewc = Fnew.subs({x: point, y: value})
  2401. # Same logic as above
  2402. if Fnewc.has(oo) or Fnewc.has(nan) or Fnewc.has(-oo) or Fnewc.has(zoo):
  2403. return Eq(f(x), oo)
  2404. series += Fnewc*((x - point)**factcount)/factorial(factcount)
  2405. F = Fnew
  2406. series += Order(x**terms)
  2407. return Eq(f(x), series)
  2408. def checkinfsol(eq, infinitesimals, func=None, order=None):
  2409. r"""
  2410. This function is used to check if the given infinitesimals are the
  2411. actual infinitesimals of the given first order differential equation.
  2412. This method is specific to the Lie Group Solver of ODEs.
  2413. As of now, it simply checks, by substituting the infinitesimals in the
  2414. partial differential equation.
  2415. .. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y}
  2416. - \frac{\partial \xi}{\partial x}\right)*h
  2417. - \frac{\partial \xi}{\partial y}*h^{2}
  2418. - \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0
  2419. where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}`
  2420. The infinitesimals should be given in the form of a list of dicts
  2421. ``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the
  2422. output of the function infinitesimals. It returns a list
  2423. of values of the form ``[(True/False, sol)]`` where ``sol`` is the value
  2424. obtained after substituting the infinitesimals in the PDE. If it
  2425. is ``True``, then ``sol`` would be 0.
  2426. """
  2427. if isinstance(eq, Equality):
  2428. eq = eq.lhs - eq.rhs
  2429. if not func:
  2430. eq, func = _preprocess(eq)
  2431. variables = func.args
  2432. if len(variables) != 1:
  2433. raise ValueError("ODE's have only one independent variable")
  2434. else:
  2435. x = variables[0]
  2436. if not order:
  2437. order = ode_order(eq, func)
  2438. if order != 1:
  2439. raise NotImplementedError("Lie groups solver has been implemented "
  2440. "only for first order differential equations")
  2441. else:
  2442. df = func.diff(x)
  2443. a = Wild('a', exclude = [df])
  2444. b = Wild('b', exclude = [df])
  2445. match = collect(expand(eq), df).match(a*df + b)
  2446. if match:
  2447. h = -simplify(match[b]/match[a])
  2448. else:
  2449. try:
  2450. sol = solve(eq, df)
  2451. except NotImplementedError:
  2452. raise NotImplementedError("Infinitesimals for the "
  2453. "first order ODE could not be found")
  2454. else:
  2455. h = sol[0] # Find infinitesimals for one solution
  2456. y = Dummy('y')
  2457. h = h.subs(func, y)
  2458. xi = Function('xi')(x, y)
  2459. eta = Function('eta')(x, y)
  2460. dxi = Function('xi')(x, func)
  2461. deta = Function('eta')(x, func)
  2462. pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
  2463. (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)))
  2464. soltup = []
  2465. for sol in infinitesimals:
  2466. tsol = {xi: S(sol[dxi]).subs(func, y),
  2467. eta: S(sol[deta]).subs(func, y)}
  2468. sol = simplify(pde.subs(tsol).doit())
  2469. if sol:
  2470. soltup.append((False, sol.subs(y, func)))
  2471. else:
  2472. soltup.append((True, 0))
  2473. return soltup
  2474. def sysode_linear_2eq_order1(match_):
  2475. x = match_['func'][0].func
  2476. y = match_['func'][1].func
  2477. func = match_['func']
  2478. fc = match_['func_coeff']
  2479. eq = match_['eq']
  2480. r = dict()
  2481. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  2482. for i in range(2):
  2483. eqs = 0
  2484. for terms in Add.make_args(eq[i]):
  2485. eqs += terms/fc[i,func[i],1]
  2486. eq[i] = eqs
  2487. # for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1)
  2488. # and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2)
  2489. r['a'] = -fc[0,x(t),0]/fc[0,x(t),1]
  2490. r['c'] = -fc[1,x(t),0]/fc[1,y(t),1]
  2491. r['b'] = -fc[0,y(t),0]/fc[0,x(t),1]
  2492. r['d'] = -fc[1,y(t),0]/fc[1,y(t),1]
  2493. forcing = [S.Zero,S.Zero]
  2494. for i in range(2):
  2495. for j in Add.make_args(eq[i]):
  2496. if not j.has(x(t), y(t)):
  2497. forcing[i] += j
  2498. if not (forcing[0].has(t) or forcing[1].has(t)):
  2499. r['k1'] = forcing[0]
  2500. r['k2'] = forcing[1]
  2501. else:
  2502. raise NotImplementedError("Only homogeneous problems are supported" +
  2503. " (and constant inhomogeneity)")
  2504. if match_['type_of_equation'] == 'type6':
  2505. sol = _linear_2eq_order1_type6(x, y, t, r, eq)
  2506. if match_['type_of_equation'] == 'type7':
  2507. sol = _linear_2eq_order1_type7(x, y, t, r, eq)
  2508. return sol
  2509. def _linear_2eq_order1_type6(x, y, t, r, eq):
  2510. r"""
  2511. The equations of this type of ode are .
  2512. .. math:: x' = f(t) x + g(t) y
  2513. .. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y
  2514. This is solved by first multiplying the first equation by `-a` and adding
  2515. it to the second equation to obtain
  2516. .. math:: y' - a x' = -a h(t) (y - a x)
  2517. Setting `U = y - ax` and integrating the equation we arrive at
  2518. .. math:: y - ax = C_1 e^{-a \int h(t) \,dt}
  2519. and on substituting the value of y in first equation give rise to first order ODEs. After solving for
  2520. `x`, we can obtain `y` by substituting the value of `x` in second equation.
  2521. """
  2522. C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
  2523. p = 0
  2524. q = 0
  2525. p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0])
  2526. p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0])
  2527. for n, i in enumerate([p1, p2]):
  2528. for j in Mul.make_args(collect_const(i)):
  2529. if not j.has(t):
  2530. q = j
  2531. if q!=0 and n==0:
  2532. if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j:
  2533. p = 1
  2534. s = j
  2535. break
  2536. if q!=0 and n==1:
  2537. if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j:
  2538. p = 2
  2539. s = j
  2540. break
  2541. if p == 1:
  2542. equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t)))
  2543. hint1 = classify_ode(equ)[1]
  2544. sol1 = dsolve(equ, hint=hint1+'_Integral').rhs
  2545. sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t))
  2546. elif p ==2:
  2547. equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
  2548. hint1 = classify_ode(equ)[1]
  2549. sol2 = dsolve(equ, hint=hint1+'_Integral').rhs
  2550. sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
  2551. return [Eq(x(t), sol1), Eq(y(t), sol2)]
  2552. def _linear_2eq_order1_type7(x, y, t, r, eq):
  2553. r"""
  2554. The equations of this type of ode are .
  2555. .. math:: x' = f(t) x + g(t) y
  2556. .. math:: y' = h(t) x + p(t) y
  2557. Differentiating the first equation and substituting the value of `y`
  2558. from second equation will give a second-order linear equation
  2559. .. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0
  2560. This above equation can be easily integrated if following conditions are satisfied.
  2561. 1. `fgp - g^{2} h + f g' - f' g = 0`
  2562. 2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg`
  2563. If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes
  2564. a constant coefficient differential equation which is also solved by current solver.
  2565. Otherwise if the above condition fails then,
  2566. a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)`
  2567. Then the general solution is expressed as
  2568. .. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt
  2569. .. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt]
  2570. where C1 and C2 are arbitrary constants and
  2571. .. math:: F(t) = e^{\int f(t) \,dt}, P(t) = e^{\int p(t) \,dt}
  2572. """
  2573. C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
  2574. e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b']
  2575. e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t)
  2576. m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t)
  2577. m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t)
  2578. if e1 == 0:
  2579. sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs
  2580. sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
  2581. elif e2 == 0:
  2582. sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs
  2583. sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
  2584. elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t):
  2585. sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs
  2586. sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
  2587. elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t):
  2588. sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs
  2589. sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
  2590. else:
  2591. x0 = Function('x0')(t) # x0 and y0 being particular solutions
  2592. y0 = Function('y0')(t)
  2593. F = exp(Integral(r['a'],t))
  2594. P = exp(Integral(r['d'],t))
  2595. sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t)
  2596. sol2 = C1*y0 + C2*(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t))
  2597. return [Eq(x(t), sol1), Eq(y(t), sol2)]
  2598. def sysode_nonlinear_2eq_order1(match_):
  2599. func = match_['func']
  2600. eq = match_['eq']
  2601. fc = match_['func_coeff']
  2602. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  2603. if match_['type_of_equation'] == 'type5':
  2604. sol = _nonlinear_2eq_order1_type5(func, t, eq)
  2605. return sol
  2606. x = func[0].func
  2607. y = func[1].func
  2608. for i in range(2):
  2609. eqs = 0
  2610. for terms in Add.make_args(eq[i]):
  2611. eqs += terms/fc[i,func[i],1]
  2612. eq[i] = eqs
  2613. if match_['type_of_equation'] == 'type1':
  2614. sol = _nonlinear_2eq_order1_type1(x, y, t, eq)
  2615. elif match_['type_of_equation'] == 'type2':
  2616. sol = _nonlinear_2eq_order1_type2(x, y, t, eq)
  2617. elif match_['type_of_equation'] == 'type3':
  2618. sol = _nonlinear_2eq_order1_type3(x, y, t, eq)
  2619. elif match_['type_of_equation'] == 'type4':
  2620. sol = _nonlinear_2eq_order1_type4(x, y, t, eq)
  2621. return sol
  2622. def _nonlinear_2eq_order1_type1(x, y, t, eq):
  2623. r"""
  2624. Equations:
  2625. .. math:: x' = x^n F(x,y)
  2626. .. math:: y' = g(y) F(x,y)
  2627. Solution:
  2628. .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
  2629. where
  2630. if `n \neq 1`
  2631. .. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}}
  2632. if `n = 1`
  2633. .. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy}
  2634. where `C_1` and `C_2` are arbitrary constants.
  2635. """
  2636. C1, C2 = get_numbered_constants(eq, num=2)
  2637. n = Wild('n', exclude=[x(t),y(t)])
  2638. f = Wild('f')
  2639. u, v = symbols('u, v')
  2640. r = eq[0].match(diff(x(t),t) - x(t)**n*f)
  2641. g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
  2642. F = r[f].subs(x(t),u).subs(y(t),v)
  2643. n = r[n]
  2644. if n!=1:
  2645. phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n))
  2646. else:
  2647. phi = C1*exp(Integral(1/g, v))
  2648. phi = phi.doit()
  2649. sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
  2650. sol = []
  2651. for sols in sol2:
  2652. sol.append(Eq(x(t),phi.subs(v, sols)))
  2653. sol.append(Eq(y(t), sols))
  2654. return sol
  2655. def _nonlinear_2eq_order1_type2(x, y, t, eq):
  2656. r"""
  2657. Equations:
  2658. .. math:: x' = e^{\lambda x} F(x,y)
  2659. .. math:: y' = g(y) F(x,y)
  2660. Solution:
  2661. .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
  2662. where
  2663. if `\lambda \neq 0`
  2664. .. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy)
  2665. if `\lambda = 0`
  2666. .. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy
  2667. where `C_1` and `C_2` are arbitrary constants.
  2668. """
  2669. C1, C2 = get_numbered_constants(eq, num=2)
  2670. n = Wild('n', exclude=[x(t),y(t)])
  2671. f = Wild('f')
  2672. u, v = symbols('u, v')
  2673. r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
  2674. g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
  2675. F = r[f].subs(x(t),u).subs(y(t),v)
  2676. n = r[n]
  2677. if n:
  2678. phi = -1/n*log(C1 - n*Integral(1/g, v))
  2679. else:
  2680. phi = C1 + Integral(1/g, v)
  2681. phi = phi.doit()
  2682. sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
  2683. sol = []
  2684. for sols in sol2:
  2685. sol.append(Eq(x(t),phi.subs(v, sols)))
  2686. sol.append(Eq(y(t), sols))
  2687. return sol
  2688. def _nonlinear_2eq_order1_type3(x, y, t, eq):
  2689. r"""
  2690. Autonomous system of general form
  2691. .. math:: x' = F(x,y)
  2692. .. math:: y' = G(x,y)
  2693. Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general
  2694. solution of the first-order equation
  2695. .. math:: F(x,y) y'_x = G(x,y)
  2696. Then the general solution of the original system of equations has the form
  2697. .. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1
  2698. """
  2699. C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
  2700. v = Function('v')
  2701. u = Symbol('u')
  2702. f = Wild('f')
  2703. g = Wild('g')
  2704. r1 = eq[0].match(diff(x(t),t) - f)
  2705. r2 = eq[1].match(diff(y(t),t) - g)
  2706. F = r1[f].subs(x(t), u).subs(y(t), v(u))
  2707. G = r2[g].subs(x(t), u).subs(y(t), v(u))
  2708. sol2r = dsolve(Eq(diff(v(u), u), G/F))
  2709. if isinstance(sol2r, Equality):
  2710. sol2r = [sol2r]
  2711. for sol2s in sol2r:
  2712. sol1 = solve(Integral(1/F.subs(v(u), sol2s.rhs), u).doit() - t - C2, u)
  2713. sol = []
  2714. for sols in sol1:
  2715. sol.append(Eq(x(t), sols))
  2716. sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols)))
  2717. return sol
  2718. def _nonlinear_2eq_order1_type4(x, y, t, eq):
  2719. r"""
  2720. Equation:
  2721. .. math:: x' = f_1(x) g_1(y) \phi(x,y,t)
  2722. .. math:: y' = f_2(x) g_2(y) \phi(x,y,t)
  2723. First integral:
  2724. .. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C
  2725. where `C` is an arbitrary constant.
  2726. On solving the first integral for `x` (resp., `y` ) and on substituting the
  2727. resulting expression into either equation of the original solution, one
  2728. arrives at a first-order equation for determining `y` (resp., `x` ).
  2729. """
  2730. C1, C2 = get_numbered_constants(eq, num=2)
  2731. u, v = symbols('u, v')
  2732. U, V = symbols('U, V', cls=Function)
  2733. f = Wild('f')
  2734. g = Wild('g')
  2735. f1 = Wild('f1', exclude=[v,t])
  2736. f2 = Wild('f2', exclude=[v,t])
  2737. g1 = Wild('g1', exclude=[u,t])
  2738. g2 = Wild('g2', exclude=[u,t])
  2739. r1 = eq[0].match(diff(x(t),t) - f)
  2740. r2 = eq[1].match(diff(y(t),t) - g)
  2741. num, den = (
  2742. (r1[f].subs(x(t),u).subs(y(t),v))/
  2743. (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
  2744. R1 = num.match(f1*g1)
  2745. R2 = den.match(f2*g2)
  2746. phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
  2747. F1 = R1[f1]; F2 = R2[f2]
  2748. G1 = R1[g1]; G2 = R2[g2]
  2749. sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u)
  2750. sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v)
  2751. sol = []
  2752. for sols in sol1r:
  2753. sol.append(Eq(y(t), dsolve(diff(V(t),t) - F2.subs(u,sols).subs(v,V(t))*G2.subs(v,V(t))*phi.subs(u,sols).subs(v,V(t))).rhs))
  2754. for sols in sol2r:
  2755. sol.append(Eq(x(t), dsolve(diff(U(t),t) - F1.subs(u,U(t))*G1.subs(v,sols).subs(u,U(t))*phi.subs(v,sols).subs(u,U(t))).rhs))
  2756. return set(sol)
  2757. def _nonlinear_2eq_order1_type5(func, t, eq):
  2758. r"""
  2759. Clairaut system of ODEs
  2760. .. math:: x = t x' + F(x',y')
  2761. .. math:: y = t y' + G(x',y')
  2762. The following are solutions of the system
  2763. `(i)` straight lines:
  2764. .. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2)
  2765. where `C_1` and `C_2` are arbitrary constants;
  2766. `(ii)` envelopes of the above lines;
  2767. `(iii)` continuously differentiable lines made up from segments of the lines
  2768. `(i)` and `(ii)`.
  2769. """
  2770. C1, C2 = get_numbered_constants(eq, num=2)
  2771. f = Wild('f')
  2772. g = Wild('g')
  2773. def check_type(x, y):
  2774. r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
  2775. r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
  2776. if not (r1 and r2):
  2777. r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
  2778. r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
  2779. if not (r1 and r2):
  2780. r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
  2781. r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
  2782. if not (r1 and r2):
  2783. r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
  2784. r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
  2785. return [r1, r2]
  2786. for func_ in func:
  2787. if isinstance(func_, list):
  2788. x = func[0][0].func
  2789. y = func[0][1].func
  2790. [r1, r2] = check_type(x, y)
  2791. if not (r1 and r2):
  2792. [r1, r2] = check_type(y, x)
  2793. x, y = y, x
  2794. x1 = diff(x(t),t); y1 = diff(y(t),t)
  2795. return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))}
  2796. def sysode_nonlinear_3eq_order1(match_):
  2797. x = match_['func'][0].func
  2798. y = match_['func'][1].func
  2799. z = match_['func'][2].func
  2800. eq = match_['eq']
  2801. t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
  2802. if match_['type_of_equation'] == 'type1':
  2803. sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq)
  2804. if match_['type_of_equation'] == 'type2':
  2805. sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq)
  2806. if match_['type_of_equation'] == 'type3':
  2807. sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq)
  2808. if match_['type_of_equation'] == 'type4':
  2809. sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq)
  2810. if match_['type_of_equation'] == 'type5':
  2811. sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq)
  2812. return sol
  2813. def _nonlinear_3eq_order1_type1(x, y, z, t, eq):
  2814. r"""
  2815. Equations:
  2816. .. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y
  2817. First Integrals:
  2818. .. math:: a x^{2} + b y^{2} + c z^{2} = C_1
  2819. .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
  2820. where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
  2821. `z` and on substituting the resulting expressions into the first equation of the
  2822. system, we arrives at a separable first-order equation on `x`. Similarly doing that
  2823. for other two equations, we will arrive at first order equation on `y` and `z` too.
  2824. References
  2825. ==========
  2826. -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf
  2827. """
  2828. C1, C2 = get_numbered_constants(eq, num=2)
  2829. u, v, w = symbols('u, v, w')
  2830. p = Wild('p', exclude=[x(t), y(t), z(t), t])
  2831. q = Wild('q', exclude=[x(t), y(t), z(t), t])
  2832. s = Wild('s', exclude=[x(t), y(t), z(t), t])
  2833. r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t))
  2834. r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t)))
  2835. r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t)))
  2836. n1, d1 = r[p].as_numer_denom()
  2837. n2, d2 = r[q].as_numer_denom()
  2838. n3, d3 = r[s].as_numer_denom()
  2839. val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v])
  2840. vals = [val[v], val[u]]
  2841. c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
  2842. b = vals[0].subs(w, c)
  2843. a = vals[1].subs(w, c)
  2844. y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
  2845. z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
  2846. z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
  2847. x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
  2848. x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
  2849. y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
  2850. sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x)
  2851. sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y)
  2852. sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z)
  2853. return [sol1, sol2, sol3]
  2854. def _nonlinear_3eq_order1_type2(x, y, z, t, eq):
  2855. r"""
  2856. Equations:
  2857. .. math:: a x' = (b - c) y z f(x, y, z, t)
  2858. .. math:: b y' = (c - a) z x f(x, y, z, t)
  2859. .. math:: c z' = (a - b) x y f(x, y, z, t)
  2860. First Integrals:
  2861. .. math:: a x^{2} + b y^{2} + c z^{2} = C_1
  2862. .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
  2863. where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
  2864. `z` and on substituting the resulting expressions into the first equation of the
  2865. system, we arrives at a first-order differential equations on `x`. Similarly doing
  2866. that for other two equations we will arrive at first order equation on `y` and `z`.
  2867. References
  2868. ==========
  2869. -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf
  2870. """
  2871. C1, C2 = get_numbered_constants(eq, num=2)
  2872. u, v, w = symbols('u, v, w')
  2873. p = Wild('p', exclude=[x(t), y(t), z(t), t])
  2874. q = Wild('q', exclude=[x(t), y(t), z(t), t])
  2875. s = Wild('s', exclude=[x(t), y(t), z(t), t])
  2876. f = Wild('f')
  2877. r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f)
  2878. r = collect_const(r1[f]).match(p*f)
  2879. r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t)))
  2880. r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t)))
  2881. n1, d1 = r[p].as_numer_denom()
  2882. n2, d2 = r[q].as_numer_denom()
  2883. n3, d3 = r[s].as_numer_denom()
  2884. val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v])
  2885. vals = [val[v], val[u]]
  2886. c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
  2887. a = vals[0].subs(w, c)
  2888. b = vals[1].subs(w, c)
  2889. y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
  2890. z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
  2891. z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
  2892. x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
  2893. x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
  2894. y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
  2895. sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f])
  2896. sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f])
  2897. sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f])
  2898. return [sol1, sol2, sol3]
  2899. def _nonlinear_3eq_order1_type3(x, y, z, t, eq):
  2900. r"""
  2901. Equations:
  2902. .. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2
  2903. where `F_n = F_n(x, y, z, t)`.
  2904. 1. First Integral:
  2905. .. math:: a x + b y + c z = C_1,
  2906. where C is an arbitrary constant.
  2907. 2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)`
  2908. Then, on eliminating `t` and `z` from the first two equation of the system, one
  2909. arrives at the first-order equation
  2910. .. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) -
  2911. b F_3 (x, y, z)}
  2912. where `z = \frac{1}{c} (C_1 - a x - b y)`
  2913. References
  2914. ==========
  2915. -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf
  2916. """
  2917. C1 = get_numbered_constants(eq, num=1)
  2918. u, v, w = symbols('u, v, w')
  2919. fu, fv, fw = symbols('u, v, w', cls=Function)
  2920. p = Wild('p', exclude=[x(t), y(t), z(t), t])
  2921. q = Wild('q', exclude=[x(t), y(t), z(t), t])
  2922. s = Wild('s', exclude=[x(t), y(t), z(t), t])
  2923. F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
  2924. r1 = (diff(x(t), t) - eq[0]).match(F2-F3)
  2925. r = collect_const(r1[F2]).match(s*F2)
  2926. r.update(collect_const(r1[F3]).match(q*F3))
  2927. if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
  2928. r[F2], r[F3] = r[F3], r[F2]
  2929. r[s], r[q] = -r[q], -r[s]
  2930. r.update((diff(y(t), t) - eq[1]).match(p*r[F3] - r[s]*F1))
  2931. a = r[p]; b = r[q]; c = r[s]
  2932. F1 = r[F1].subs(x(t), u).subs(y(t),v).subs(z(t), w)
  2933. F2 = r[F2].subs(x(t), u).subs(y(t),v).subs(z(t), w)
  2934. F3 = r[F3].subs(x(t), u).subs(y(t),v).subs(z(t), w)
  2935. z_xy = (C1-a*u-b*v)/c
  2936. y_zx = (C1-a*u-c*w)/b
  2937. x_yz = (C1-b*v-c*w)/a
  2938. y_x = dsolve(diff(fv(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,fv(u))).rhs
  2939. z_x = dsolve(diff(fw(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,fw(u))).rhs
  2940. z_y = dsolve(diff(fw(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,fw(v))).rhs
  2941. x_y = dsolve(diff(fu(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,fu(v))).rhs
  2942. y_z = dsolve(diff(fv(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,fv(w))).rhs
  2943. x_z = dsolve(diff(fu(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,fu(w))).rhs
  2944. sol1 = dsolve(diff(fu(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,fu(t))).rhs
  2945. sol2 = dsolve(diff(fv(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,fv(t))).rhs
  2946. sol3 = dsolve(diff(fw(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,fw(t))).rhs
  2947. return [sol1, sol2, sol3]
  2948. def _nonlinear_3eq_order1_type4(x, y, z, t, eq):
  2949. r"""
  2950. Equations:
  2951. .. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2
  2952. where `F_n = F_n (x, y, z, t)`
  2953. 1. First integral:
  2954. .. math:: a x^{2} + b y^{2} + c z^{2} = C_1
  2955. where `C` is an arbitrary constant.
  2956. 2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on
  2957. eliminating `t` and `z` from the first two equations of the system, one arrives at
  2958. the first-order equation
  2959. .. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)}
  2960. {c z F_2 (x, y, z) - b y F_3 (x, y, z)}
  2961. where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}`
  2962. References
  2963. ==========
  2964. -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf
  2965. """
  2966. C1 = get_numbered_constants(eq, num=1)
  2967. u, v, w = symbols('u, v, w')
  2968. p = Wild('p', exclude=[x(t), y(t), z(t), t])
  2969. q = Wild('q', exclude=[x(t), y(t), z(t), t])
  2970. s = Wild('s', exclude=[x(t), y(t), z(t), t])
  2971. F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
  2972. r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
  2973. r = collect_const(r1[F2]).match(s*F2)
  2974. r.update(collect_const(r1[F3]).match(q*F3))
  2975. if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
  2976. r[F2], r[F3] = r[F3], r[F2]
  2977. r[s], r[q] = -r[q], -r[s]
  2978. r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1))
  2979. a = r[p]; b = r[q]; c = r[s]
  2980. F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
  2981. F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
  2982. F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
  2983. x_yz = sqrt((C1 - b*v**2 - c*w**2)/a)
  2984. y_zx = sqrt((C1 - c*w**2 - a*u**2)/b)
  2985. z_xy = sqrt((C1 - a*u**2 - b*v**2)/c)
  2986. y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs
  2987. z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs
  2988. z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs
  2989. x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs
  2990. y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs
  2991. x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs
  2992. sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
  2993. sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
  2994. sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
  2995. return [sol1, sol2, sol3]
  2996. def _nonlinear_3eq_order1_type5(x, y, z, t, eq):
  2997. r"""
  2998. .. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2)
  2999. where `F_n = F_n (x, y, z, t)` and are arbitrary functions.
  3000. First Integral:
  3001. .. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1
  3002. where `C` is an arbitrary constant. If the function `F_n` is independent of `t`,
  3003. then, by eliminating `t` and `z` from the first two equations of the system, one
  3004. arrives at a first-order equation.
  3005. References
  3006. ==========
  3007. -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf
  3008. """
  3009. C1 = get_numbered_constants(eq, num=1)
  3010. u, v, w = symbols('u, v, w')
  3011. fu, fv, fw = symbols('u, v, w', cls=Function)
  3012. p = Wild('p', exclude=[x(t), y(t), z(t), t])
  3013. q = Wild('q', exclude=[x(t), y(t), z(t), t])
  3014. s = Wild('s', exclude=[x(t), y(t), z(t), t])
  3015. F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
  3016. r1 = eq[0].match(diff(x(t), t) - x(t)*F2 + x(t)*F3)
  3017. r = collect_const(r1[F2]).match(s*F2)
  3018. r.update(collect_const(r1[F3]).match(q*F3))
  3019. if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
  3020. r[F2], r[F3] = r[F3], r[F2]
  3021. r[s], r[q] = -r[q], -r[s]
  3022. r.update((diff(y(t), t) - eq[1]).match(y(t)*(p*r[F3] - r[s]*F1)))
  3023. a = r[p]; b = r[q]; c = r[s]
  3024. F1 = r[F1].subs(x(t), u).subs(y(t), v).subs(z(t), w)
  3025. F2 = r[F2].subs(x(t), u).subs(y(t), v).subs(z(t), w)
  3026. F3 = r[F3].subs(x(t), u).subs(y(t), v).subs(z(t), w)
  3027. x_yz = (C1*v**-b*w**-c)**-a
  3028. y_zx = (C1*w**-c*u**-a)**-b
  3029. z_xy = (C1*u**-a*v**-b)**-c
  3030. y_x = dsolve(diff(fv(u), u) - ((v*(a*F3 - c*F1))/(u*(c*F2 - b*F3))).subs(w, z_xy).subs(v, fv(u))).rhs
  3031. z_x = dsolve(diff(fw(u), u) - ((w*(b*F1 - a*F2))/(u*(c*F2 - b*F3))).subs(v, y_zx).subs(w, fw(u))).rhs
  3032. z_y = dsolve(diff(fw(v), v) - ((w*(b*F1 - a*F2))/(v*(a*F3 - c*F1))).subs(u, x_yz).subs(w, fw(v))).rhs
  3033. x_y = dsolve(diff(fu(v), v) - ((u*(c*F2 - b*F3))/(v*(a*F3 - c*F1))).subs(w, z_xy).subs(u, fu(v))).rhs
  3034. y_z = dsolve(diff(fv(w), w) - ((v*(a*F3 - c*F1))/(w*(b*F1 - a*F2))).subs(u, x_yz).subs(v, fv(w))).rhs
  3035. x_z = dsolve(diff(fu(w), w) - ((u*(c*F2 - b*F3))/(w*(b*F1 - a*F2))).subs(v, y_zx).subs(u, fu(w))).rhs
  3036. sol1 = dsolve(diff(fu(t), t) - (u*(c*F2 - b*F3)).subs(v, y_x).subs(w, z_x).subs(u, fu(t))).rhs
  3037. sol2 = dsolve(diff(fv(t), t) - (v*(a*F3 - c*F1)).subs(u, x_y).subs(w, z_y).subs(v, fv(t))).rhs
  3038. sol3 = dsolve(diff(fw(t), t) - (w*(b*F1 - a*F2)).subs(u, x_z).subs(v, y_z).subs(w, fw(t))).rhs
  3039. return [sol1, sol2, sol3]
  3040. #This import is written at the bottom to avoid circular imports.
  3041. from .single import SingleODEProblem, SingleODESolver, solver_map