ode.py 142 KB

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