systems.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135
  1. from sympy.core import Add, Mul, S
  2. from sympy.core.containers import Tuple
  3. from sympy.core.exprtools import factor_terms
  4. from sympy.core.numbers import I
  5. from sympy.core.relational import Eq, Equality
  6. from sympy.core.sorting import default_sort_key, ordered
  7. from sympy.core.symbol import Dummy, Symbol
  8. from sympy.core.function import (expand_mul, expand, Derivative,
  9. AppliedUndef, Function, Subs)
  10. from sympy.functions import (exp, im, cos, sin, re, Piecewise,
  11. piecewise_fold, sqrt, log)
  12. from sympy.functions.combinatorial.factorials import factorial
  13. from sympy.matrices import zeros, Matrix, NonSquareMatrixError, MatrixBase, eye
  14. from sympy.polys import Poly, together
  15. from sympy.simplify import collect, radsimp, signsimp # type: ignore
  16. from sympy.simplify.powsimp import powdenest, powsimp
  17. from sympy.simplify.ratsimp import ratsimp
  18. from sympy.simplify.simplify import simplify
  19. from sympy.sets.sets import FiniteSet
  20. from sympy.solvers.deutils import ode_order
  21. from sympy.solvers.solveset import NonlinearError, solveset
  22. from sympy.utilities.iterables import (connected_components, iterable,
  23. strongly_connected_components)
  24. from sympy.utilities.misc import filldedent
  25. from sympy.integrals.integrals import Integral, integrate
  26. def _get_func_order(eqs, funcs):
  27. return {func: max(ode_order(eq, func) for eq in eqs) for func in funcs}
  28. class ODEOrderError(ValueError):
  29. """Raised by linear_ode_to_matrix if the system has the wrong order"""
  30. pass
  31. class ODENonlinearError(NonlinearError):
  32. """Raised by linear_ode_to_matrix if the system is nonlinear"""
  33. pass
  34. def _simpsol(soleq):
  35. lhs = soleq.lhs
  36. sol = soleq.rhs
  37. sol = powsimp(sol)
  38. gens = list(sol.atoms(exp))
  39. p = Poly(sol, *gens, expand=False)
  40. gens = [factor_terms(g) for g in gens]
  41. if not gens:
  42. gens = p.gens
  43. syms = [Symbol('C1'), Symbol('C2')]
  44. terms = []
  45. for coeff, monom in zip(p.coeffs(), p.monoms()):
  46. coeff = piecewise_fold(coeff)
  47. if isinstance(coeff, Piecewise):
  48. coeff = Piecewise(*((ratsimp(coef).collect(syms), cond) for coef, cond in coeff.args))
  49. else:
  50. coeff = ratsimp(coeff).collect(syms)
  51. monom = Mul(*(g ** i for g, i in zip(gens, monom)))
  52. terms.append(coeff * monom)
  53. return Eq(lhs, Add(*terms))
  54. def _solsimp(e, t):
  55. no_t, has_t = powsimp(expand_mul(e)).as_independent(t)
  56. no_t = ratsimp(no_t)
  57. has_t = has_t.replace(exp, lambda a: exp(factor_terms(a)))
  58. return no_t + has_t
  59. def simpsol(sol, wrt1, wrt2, doit=True):
  60. """Simplify solutions from dsolve_system."""
  61. # The parameter sol is the solution as returned by dsolve (list of Eq).
  62. #
  63. # The parameters wrt1 and wrt2 are lists of symbols to be collected for
  64. # with those in wrt1 being collected for first. This allows for collecting
  65. # on any factors involving the independent variable before collecting on
  66. # the integration constants or vice versa using e.g.:
  67. #
  68. # sol = simpsol(sol, [t], [C1, C2]) # t first, constants after
  69. # sol = simpsol(sol, [C1, C2], [t]) # constants first, t after
  70. #
  71. # If doit=True (default) then simpsol will begin by evaluating any
  72. # unevaluated integrals. Since many integrals will appear multiple times
  73. # in the solutions this is done intelligently by computing each integral
  74. # only once.
  75. #
  76. # The strategy is to first perform simple cancellation with factor_terms
  77. # and then multiply out all brackets with expand_mul. This gives an Add
  78. # with many terms.
  79. #
  80. # We split each term into two multiplicative factors dep and coeff where
  81. # all factors that involve wrt1 are in dep and any constant factors are in
  82. # coeff e.g.
  83. # sqrt(2)*C1*exp(t) -> ( exp(t), sqrt(2)*C1 )
  84. #
  85. # The dep factors are simplified using powsimp to combine expanded
  86. # exponential factors e.g.
  87. # exp(a*t)*exp(b*t) -> exp(t*(a+b))
  88. #
  89. # We then collect coefficients for all terms having the same (simplified)
  90. # dep. The coefficients are then simplified using together and ratsimp and
  91. # lastly by recursively applying the same transformation to the
  92. # coefficients to collect on wrt2.
  93. #
  94. # Finally the result is recombined into an Add and signsimp is used to
  95. # normalise any minus signs.
  96. def simprhs(rhs, rep, wrt1, wrt2):
  97. """Simplify the rhs of an ODE solution"""
  98. if rep:
  99. rhs = rhs.subs(rep)
  100. rhs = factor_terms(rhs)
  101. rhs = simp_coeff_dep(rhs, wrt1, wrt2)
  102. rhs = signsimp(rhs)
  103. return rhs
  104. def simp_coeff_dep(expr, wrt1, wrt2=None):
  105. """Split rhs into terms, split terms into dep and coeff and collect on dep"""
  106. add_dep_terms = lambda e: e.is_Add and e.has(*wrt1)
  107. expandable = lambda e: e.is_Mul and any(map(add_dep_terms, e.args))
  108. expand_func = lambda e: expand_mul(e, deep=False)
  109. expand_mul_mod = lambda e: e.replace(expandable, expand_func)
  110. terms = Add.make_args(expand_mul_mod(expr))
  111. dc = {}
  112. for term in terms:
  113. coeff, dep = term.as_independent(*wrt1, as_Add=False)
  114. # Collect together the coefficients for terms that have the same
  115. # dependence on wrt1 (after dep is normalised using simpdep).
  116. dep = simpdep(dep, wrt1)
  117. # See if the dependence on t cancels out...
  118. if dep is not S.One:
  119. dep2 = factor_terms(dep)
  120. if not dep2.has(*wrt1):
  121. coeff *= dep2
  122. dep = S.One
  123. if dep not in dc:
  124. dc[dep] = coeff
  125. else:
  126. dc[dep] += coeff
  127. # Apply the method recursively to the coefficients but this time
  128. # collecting on wrt2 rather than wrt2.
  129. termpairs = ((simpcoeff(c, wrt2), d) for d, c in dc.items())
  130. if wrt2 is not None:
  131. termpairs = ((simp_coeff_dep(c, wrt2), d) for c, d in termpairs)
  132. return Add(*(c * d for c, d in termpairs))
  133. def simpdep(term, wrt1):
  134. """Normalise factors involving t with powsimp and recombine exp"""
  135. def canonicalise(a):
  136. # Using factor_terms here isn't quite right because it leads to things
  137. # like exp(t*(1+t)) that we don't want. We do want to cancel factors
  138. # and pull out a common denominator but ideally the numerator would be
  139. # expressed as a standard form polynomial in t so we expand_mul
  140. # and collect afterwards.
  141. a = factor_terms(a)
  142. num, den = a.as_numer_denom()
  143. num = expand_mul(num)
  144. num = collect(num, wrt1)
  145. return num / den
  146. term = powsimp(term)
  147. rep = {e: exp(canonicalise(e.args[0])) for e in term.atoms(exp)}
  148. term = term.subs(rep)
  149. return term
  150. def simpcoeff(coeff, wrt2):
  151. """Bring to a common fraction and cancel with ratsimp"""
  152. coeff = together(coeff)
  153. if coeff.is_polynomial():
  154. # Calling ratsimp can be expensive. The main reason is to simplify
  155. # sums of terms with irrational denominators so we limit ourselves
  156. # to the case where the expression is polynomial in any symbols.
  157. # Maybe there's a better approach...
  158. coeff = ratsimp(radsimp(coeff))
  159. # collect on secondary variables first and any remaining symbols after
  160. if wrt2 is not None:
  161. syms = list(wrt2) + list(ordered(coeff.free_symbols - set(wrt2)))
  162. else:
  163. syms = list(ordered(coeff.free_symbols))
  164. coeff = collect(coeff, syms)
  165. coeff = together(coeff)
  166. return coeff
  167. # There are often repeated integrals. Collect unique integrals and
  168. # evaluate each once and then substitute into the final result to replace
  169. # all occurrences in each of the solution equations.
  170. if doit:
  171. integrals = set().union(*(s.atoms(Integral) for s in sol))
  172. rep = {i: factor_terms(i).doit() for i in integrals}
  173. else:
  174. rep = {}
  175. sol = [Eq(s.lhs, simprhs(s.rhs, rep, wrt1, wrt2)) for s in sol]
  176. return sol
  177. def linodesolve_type(A, t, b=None):
  178. r"""
  179. Helper function that determines the type of the system of ODEs for solving with :obj:`sympy.solvers.ode.systems.linodesolve()`
  180. Explanation
  181. ===========
  182. This function takes in the coefficient matrix and/or the non-homogeneous term
  183. and returns the type of the equation that can be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`.
  184. If the system is constant coefficient homogeneous, then "type1" is returned
  185. If the system is constant coefficient non-homogeneous, then "type2" is returned
  186. If the system is non-constant coefficient homogeneous, then "type3" is returned
  187. If the system is non-constant coefficient non-homogeneous, then "type4" is returned
  188. If the system has a non-constant coefficient matrix which can be factorized into constant
  189. coefficient matrix, then "type5" or "type6" is returned for when the system is homogeneous or
  190. non-homogeneous respectively.
  191. Note that, if the system of ODEs is of "type3" or "type4", then along with the type,
  192. the commutative antiderivative of the coefficient matrix is also returned.
  193. If the system cannot be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`, then
  194. NotImplementedError is raised.
  195. Parameters
  196. ==========
  197. A : Matrix
  198. Coefficient matrix of the system of ODEs
  199. b : Matrix or None
  200. Non-homogeneous term of the system. The default value is None.
  201. If this argument is None, then the system is assumed to be homogeneous.
  202. Examples
  203. ========
  204. >>> from sympy import symbols, Matrix
  205. >>> from sympy.solvers.ode.systems import linodesolve_type
  206. >>> t = symbols("t")
  207. >>> A = Matrix([[1, 1], [2, 3]])
  208. >>> b = Matrix([t, 1])
  209. >>> linodesolve_type(A, t)
  210. {'antiderivative': None, 'type_of_equation': 'type1'}
  211. >>> linodesolve_type(A, t, b=b)
  212. {'antiderivative': None, 'type_of_equation': 'type2'}
  213. >>> A_t = Matrix([[1, t], [-t, 1]])
  214. >>> linodesolve_type(A_t, t)
  215. {'antiderivative': Matrix([
  216. [ t, t**2/2],
  217. [-t**2/2, t]]), 'type_of_equation': 'type3'}
  218. >>> linodesolve_type(A_t, t, b=b)
  219. {'antiderivative': Matrix([
  220. [ t, t**2/2],
  221. [-t**2/2, t]]), 'type_of_equation': 'type4'}
  222. >>> A_non_commutative = Matrix([[1, t], [t, -1]])
  223. >>> linodesolve_type(A_non_commutative, t)
  224. Traceback (most recent call last):
  225. ...
  226. NotImplementedError:
  227. The system does not have a commutative antiderivative, it cannot be
  228. solved by linodesolve.
  229. Returns
  230. =======
  231. Dict
  232. Raises
  233. ======
  234. NotImplementedError
  235. When the coefficient matrix does not have a commutative antiderivative
  236. See Also
  237. ========
  238. linodesolve: Function for which linodesolve_type gets the information
  239. """
  240. match = {}
  241. is_non_constant = not _matrix_is_constant(A, t)
  242. is_non_homogeneous = not (b is None or b.is_zero_matrix)
  243. type = "type{}".format(int("{}{}".format(int(is_non_constant), int(is_non_homogeneous)), 2) + 1)
  244. B = None
  245. match.update({"type_of_equation": type, "antiderivative": B})
  246. if is_non_constant:
  247. B, is_commuting = _is_commutative_anti_derivative(A, t)
  248. if not is_commuting:
  249. raise NotImplementedError(filldedent('''
  250. The system does not have a commutative antiderivative, it cannot be solved
  251. by linodesolve.
  252. '''))
  253. match['antiderivative'] = B
  254. match.update(_first_order_type5_6_subs(A, t, b=b))
  255. return match
  256. def _first_order_type5_6_subs(A, t, b=None):
  257. match = {}
  258. factor_terms = _factor_matrix(A, t)
  259. is_homogeneous = b is None or b.is_zero_matrix
  260. if factor_terms is not None:
  261. t_ = Symbol("{}_".format(t))
  262. F_t = integrate(factor_terms[0], t)
  263. inverse = solveset(Eq(t_, F_t), t)
  264. # Note: A simple way to check if a function is invertible
  265. # or not.
  266. if isinstance(inverse, FiniteSet) and not inverse.has(Piecewise)\
  267. and len(inverse) == 1:
  268. A = factor_terms[1]
  269. if not is_homogeneous:
  270. b = b / factor_terms[0]
  271. b = b.subs(t, list(inverse)[0])
  272. type = "type{}".format(5 + (not is_homogeneous))
  273. match.update({'func_coeff': A, 'tau': F_t,
  274. 't_': t_, 'type_of_equation': type, 'rhs': b})
  275. return match
  276. def linear_ode_to_matrix(eqs, funcs, t, order):
  277. r"""
  278. Convert a linear system of ODEs to matrix form
  279. Explanation
  280. ===========
  281. Express a system of linear ordinary differential equations as a single
  282. matrix differential equation [1]. For example the system $x' = x + y + 1$
  283. and $y' = x - y$ can be represented as
  284. .. math:: A_1 X' = A_0 X + b
  285. where $A_1$ and $A_0$ are $2 \times 2$ matrices and $b$, $X$ and $X'$ are
  286. $2 \times 1$ matrices with $X = [x, y]^T$.
  287. Higher-order systems are represented with additional matrices e.g. a
  288. second-order system would look like
  289. .. math:: A_2 X'' = A_1 X' + A_0 X + b
  290. Examples
  291. ========
  292. >>> from sympy import Function, Symbol, Matrix, Eq
  293. >>> from sympy.solvers.ode.systems import linear_ode_to_matrix
  294. >>> t = Symbol('t')
  295. >>> x = Function('x')
  296. >>> y = Function('y')
  297. We can create a system of linear ODEs like
  298. >>> eqs = [
  299. ... Eq(x(t).diff(t), x(t) + y(t) + 1),
  300. ... Eq(y(t).diff(t), x(t) - y(t)),
  301. ... ]
  302. >>> funcs = [x(t), y(t)]
  303. >>> order = 1 # 1st order system
  304. Now ``linear_ode_to_matrix`` can represent this as a matrix
  305. differential equation.
  306. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, order)
  307. >>> A1
  308. Matrix([
  309. [1, 0],
  310. [0, 1]])
  311. >>> A0
  312. Matrix([
  313. [1, 1],
  314. [1, -1]])
  315. >>> b
  316. Matrix([
  317. [1],
  318. [0]])
  319. The original equations can be recovered from these matrices:
  320. >>> eqs_mat = Matrix([eq.lhs - eq.rhs for eq in eqs])
  321. >>> X = Matrix(funcs)
  322. >>> A1 * X.diff(t) - A0 * X - b == eqs_mat
  323. True
  324. If the system of equations has a maximum order greater than the
  325. order of the system specified, a ODEOrderError exception is raised.
  326. >>> eqs = [Eq(x(t).diff(t, 2), x(t).diff(t) + x(t)), Eq(y(t).diff(t), y(t) + x(t))]
  327. >>> linear_ode_to_matrix(eqs, funcs, t, 1)
  328. Traceback (most recent call last):
  329. ...
  330. ODEOrderError: Cannot represent system in 1-order form
  331. If the system of equations is nonlinear, then ODENonlinearError is
  332. raised.
  333. >>> eqs = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), y(t)**2 + x(t))]
  334. >>> linear_ode_to_matrix(eqs, funcs, t, 1)
  335. Traceback (most recent call last):
  336. ...
  337. ODENonlinearError: The system of ODEs is nonlinear.
  338. Parameters
  339. ==========
  340. eqs : list of SymPy expressions or equalities
  341. The equations as expressions (assumed equal to zero).
  342. funcs : list of applied functions
  343. The dependent variables of the system of ODEs.
  344. t : symbol
  345. The independent variable.
  346. order : int
  347. The order of the system of ODEs.
  348. Returns
  349. =======
  350. The tuple ``(As, b)`` where ``As`` is a tuple of matrices and ``b`` is the
  351. the matrix representing the rhs of the matrix equation.
  352. Raises
  353. ======
  354. ODEOrderError
  355. When the system of ODEs have an order greater than what was specified
  356. ODENonlinearError
  357. When the system of ODEs is nonlinear
  358. See Also
  359. ========
  360. linear_eq_to_matrix: for systems of linear algebraic equations.
  361. References
  362. ==========
  363. .. [1] https://en.wikipedia.org/wiki/Matrix_differential_equation
  364. """
  365. from sympy.solvers.solveset import linear_eq_to_matrix
  366. if any(ode_order(eq, func) > order for eq in eqs for func in funcs):
  367. msg = "Cannot represent system in {}-order form"
  368. raise ODEOrderError(msg.format(order))
  369. As = []
  370. for o in range(order, -1, -1):
  371. # Work from the highest derivative down
  372. syms = [func.diff(t, o) for func in funcs]
  373. # Ai is the matrix for X(t).diff(t, o)
  374. # eqs is minus the remainder of the equations.
  375. try:
  376. Ai, b = linear_eq_to_matrix(eqs, syms)
  377. except NonlinearError:
  378. raise ODENonlinearError("The system of ODEs is nonlinear.")
  379. Ai = Ai.applyfunc(expand_mul)
  380. As.append(Ai if o == order else -Ai)
  381. if o:
  382. eqs = [-eq for eq in b]
  383. else:
  384. rhs = b
  385. return As, rhs
  386. def matrix_exp(A, t):
  387. r"""
  388. Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``.
  389. Explanation
  390. ===========
  391. This functions returns the $\exp(A*t)$ by doing a simple
  392. matrix multiplication:
  393. .. math:: \exp(A*t) = P * expJ * P^{-1}
  394. where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal
  395. form of $A$ and $P$ is matrix such that:
  396. .. math:: A = P * J * P^{-1}
  397. The matrix exponential $\exp(A*t)$ appears in the solution of linear
  398. differential equations. For example if $x$ is a vector and $A$ is a matrix
  399. then the initial value problem
  400. .. math:: \frac{dx(t)}{dt} = A \times x(t), x(0) = x0
  401. has the unique solution
  402. .. math:: x(t) = \exp(A t) x0
  403. Examples
  404. ========
  405. >>> from sympy import Symbol, Matrix, pprint
  406. >>> from sympy.solvers.ode.systems import matrix_exp
  407. >>> t = Symbol('t')
  408. We will consider a 2x2 matrix for comupting the exponential
  409. >>> A = Matrix([[2, -5], [2, -4]])
  410. >>> pprint(A)
  411. [2 -5]
  412. [ ]
  413. [2 -4]
  414. Now, exp(A*t) is given as follows:
  415. >>> pprint(matrix_exp(A, t))
  416. [ -t -t -t ]
  417. [3*e *sin(t) + e *cos(t) -5*e *sin(t) ]
  418. [ ]
  419. [ -t -t -t ]
  420. [ 2*e *sin(t) - 3*e *sin(t) + e *cos(t)]
  421. Parameters
  422. ==========
  423. A : Matrix
  424. The matrix $A$ in the expression $\exp(A*t)$
  425. t : Symbol
  426. The independent variable
  427. See Also
  428. ========
  429. matrix_exp_jordan_form: For exponential of Jordan normal form
  430. References
  431. ==========
  432. .. [1] https://en.wikipedia.org/wiki/Jordan_normal_form
  433. .. [2] https://en.wikipedia.org/wiki/Matrix_exponential
  434. """
  435. P, expJ = matrix_exp_jordan_form(A, t)
  436. return P * expJ * P.inv()
  437. def matrix_exp_jordan_form(A, t):
  438. r"""
  439. Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*.
  440. Explanation
  441. ===========
  442. Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that:
  443. .. math::
  444. \exp(A*t) = P * expJ * P^{-1}
  445. Examples
  446. ========
  447. >>> from sympy import Matrix, Symbol
  448. >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form
  449. >>> t = Symbol('t')
  450. We will consider a 2x2 defective matrix. This shows that our method
  451. works even for defective matrices.
  452. >>> A = Matrix([[1, 1], [0, 1]])
  453. It can be observed that this function gives us the Jordan normal form
  454. and the required invertible matrix P.
  455. >>> P, expJ = matrix_exp_jordan_form(A, t)
  456. Here, it is shown that P and expJ returned by this function is correct
  457. as they satisfy the formula: P * expJ * P_inverse = exp(A*t).
  458. >>> P * expJ * P.inv() == matrix_exp(A, t)
  459. True
  460. Parameters
  461. ==========
  462. A : Matrix
  463. The matrix $A$ in the expression $\exp(A*t)$
  464. t : Symbol
  465. The independent variable
  466. References
  467. ==========
  468. .. [1] https://en.wikipedia.org/wiki/Defective_matrix
  469. .. [2] https://en.wikipedia.org/wiki/Jordan_matrix
  470. .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form
  471. """
  472. N, M = A.shape
  473. if N != M:
  474. raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M))
  475. elif A.has(t):
  476. raise ValueError('Matrix A should not depend on t')
  477. def jordan_chains(A):
  478. '''Chains from Jordan normal form analogous to M.eigenvects().
  479. Returns a dict with eignevalues as keys like:
  480. {e1: [[v111,v112,...], [v121, v122,...]], e2:...}
  481. where vijk is the kth vector in the jth chain for eigenvalue i.
  482. '''
  483. P, blocks = A.jordan_cells()
  484. basis = [P[:,i] for i in range(P.shape[1])]
  485. n = 0
  486. chains = {}
  487. for b in blocks:
  488. eigval = b[0, 0]
  489. size = b.shape[0]
  490. if eigval not in chains:
  491. chains[eigval] = []
  492. chains[eigval].append(basis[n:n+size])
  493. n += size
  494. return chains
  495. eigenchains = jordan_chains(A)
  496. # Needed for consistency across Python versions
  497. eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key)
  498. isreal = not A.has(I)
  499. blocks = []
  500. vectors = []
  501. seen_conjugate = set()
  502. for e, chains in eigenchains_iter:
  503. for chain in chains:
  504. n = len(chain)
  505. if isreal and e != e.conjugate() and e.conjugate() in eigenchains:
  506. if e in seen_conjugate:
  507. continue
  508. seen_conjugate.add(e.conjugate())
  509. exprt = exp(re(e) * t)
  510. imrt = im(e) * t
  511. imblock = Matrix([[cos(imrt), sin(imrt)],
  512. [-sin(imrt), cos(imrt)]])
  513. expJblock2 = Matrix(n, n, lambda i,j:
  514. imblock * t**(j-i) / factorial(j-i) if j >= i
  515. else zeros(2, 2))
  516. expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2])
  517. blocks.append(exprt * expJblock)
  518. for i in range(n):
  519. vectors.append(re(chain[i]))
  520. vectors.append(im(chain[i]))
  521. else:
  522. vectors.extend(chain)
  523. fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0
  524. expJblock = Matrix(n, n, fun)
  525. blocks.append(exp(e * t) * expJblock)
  526. expJ = Matrix.diag(*blocks)
  527. P = Matrix(N, N, lambda i,j: vectors[j][i])
  528. return P, expJ
  529. # Note: To add a docstring example with tau
  530. def linodesolve(A, t, b=None, B=None, type="auto", doit=False,
  531. tau=None):
  532. r"""
  533. System of n equations linear first-order differential equations
  534. Explanation
  535. ===========
  536. This solver solves the system of ODEs of the following form:
  537. .. math::
  538. X'(t) = A(t) X(t) + b(t)
  539. Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables,
  540. $b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$
  541. Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution
  542. differently.
  543. When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous,
  544. the system is "type1". The solution is:
  545. .. math::
  546. X(t) = \exp(A t) C
  547. Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix.
  548. When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous,
  549. the system is "type2". The solution is:
  550. .. math::
  551. X(t) = e^{A t} ( \int e^{- A t} b \,dt + C)
  552. When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and
  553. $b(t)$ is a zero vector i.e. system is homogeneous, the system is "type3". The solution is:
  554. .. math::
  555. X(t) = \exp(B(t)) C
  556. When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is
  557. non-homogeneous, the system is "type4". The solution is:
  558. .. math::
  559. X(t) = e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C)
  560. When $A(t)$ is a coefficient matrix such that it can be factorized into a scalar and a constant
  561. coefficient matrix:
  562. .. math::
  563. A(t) = f(t) * A
  564. Where $f(t)$ is a scalar expression in the independent variable $t$ and $A$ is a constant matrix,
  565. then we can do the following substitutions:
  566. .. math::
  567. tau = \int f(t) dt, X(t) = Y(tau), b(t) = b(f^{-1}(tau))
  568. Here, the substitution for the non-homogeneous term is done only when its non-zero.
  569. Using these substitutions, our original system becomes:
  570. .. math::
  571. Y'(tau) = A * Y(tau) + b(tau)/f(tau)
  572. The above system can be easily solved using the solution for "type1" or "type2" depending
  573. on the homogeneity of the system. After we get the solution for $Y(tau)$, we substitute the
  574. solution for $tau$ as $t$ to get back $X(t)$
  575. .. math::
  576. X(t) = Y(tau)
  577. Systems of "type5" and "type6" have a commutative antiderivative but we use this solution
  578. because its faster to compute.
  579. The final solution is the general solution for all the four equations since a constant coefficient
  580. matrix is always commutative with its antidervative.
  581. An additional feature of this function is, if someone wants to substitute for value of the independent
  582. variable, they can pass the substitution `tau` and the solution will have the independent variable
  583. substituted with the passed expression(`tau`).
  584. Parameters
  585. ==========
  586. A : Matrix
  587. Coefficient matrix of the system of linear first order ODEs.
  588. t : Symbol
  589. Independent variable in the system of ODEs.
  590. b : Matrix or None
  591. Non-homogeneous term in the system of ODEs. If None is passed,
  592. a homogeneous system of ODEs is assumed.
  593. B : Matrix or None
  594. Antiderivative of the coefficient matrix. If the antiderivative
  595. is not passed and the solution requires the term, then the solver
  596. would compute it internally.
  597. type : String
  598. Type of the system of ODEs passed. Depending on the type, the
  599. solution is evaluated. The type values allowed and the corresponding
  600. system it solves are: "type1" for constant coefficient homogeneous
  601. "type2" for constant coefficient non-homogeneous, "type3" for non-constant
  602. coefficient homogeneous, "type4" for non-constant coefficient non-homogeneous,
  603. "type5" and "type6" for non-constant coefficient homogeneous and non-homogeneous
  604. systems respectively where the coefficient matrix can be factorized to a constant
  605. coefficient matrix.
  606. The default value is "auto" which will let the solver decide the correct type of
  607. the system passed.
  608. doit : Boolean
  609. Evaluate the solution if True, default value is False
  610. tau: Expression
  611. Used to substitute for the value of `t` after we get the solution of the system.
  612. Examples
  613. ========
  614. To solve the system of ODEs using this function directly, several things must be
  615. done in the right order. Wrong inputs to the function will lead to incorrect results.
  616. >>> from sympy import symbols, Function, Eq
  617. >>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type
  618. >>> from sympy.solvers.ode.subscheck import checkodesol
  619. >>> f, g = symbols("f, g", cls=Function)
  620. >>> x, a = symbols("x, a")
  621. >>> funcs = [f(x), g(x)]
  622. >>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))]
  623. Here, it is important to note that before we derive the coefficient matrix, it is
  624. important to get the system of ODEs into the desired form. For that we will use
  625. :obj:`sympy.solvers.ode.systems.canonical_odes()`.
  626. >>> eqs = canonical_odes(eqs, funcs, x)
  627. >>> eqs
  628. [[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]]
  629. Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the
  630. non-homogeneous term if it is there.
  631. >>> eqs = eqs[0]
  632. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
  633. >>> A = A0
  634. We have the coefficient matrices and the non-homogeneous term ready. Now, we can use
  635. :obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs
  636. to finally pass it to the solver.
  637. >>> system_info = linodesolve_type(A, x, b=b)
  638. >>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type_of_equation'])
  639. Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()`
  640. >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  641. >>> checkodesol(eqs, sol)
  642. (True, [0, 0])
  643. We can also use the doit method to evaluate the solutions passed by the function.
  644. >>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True)
  645. Now, we will look at a system of ODEs which is non-constant.
  646. >>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))]
  647. The system defined above is already in the desired form, so we do not have to convert it.
  648. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
  649. >>> A = A0
  650. A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs.
  651. Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative
  652. with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError.
  653. If it does have a commutative antiderivative, then the function just returns the information about the system.
  654. >>> system_info = linodesolve_type(A, x, b=b)
  655. Now, we can pass the antiderivative as an argument to get the solution. If the system information is not
  656. passed, then the solver will compute the required arguments internally.
  657. >>> sol_vector = linodesolve(A, x, b=b)
  658. Once again, we can verify the solution obtained.
  659. >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  660. >>> checkodesol(eqs, sol)
  661. (True, [0, 0])
  662. Returns
  663. =======
  664. List
  665. Raises
  666. ======
  667. ValueError
  668. This error is raised when the coefficient matrix, non-homogeneous term
  669. or the antiderivative, if passed, are not a matrix or
  670. do not have correct dimensions
  671. NonSquareMatrixError
  672. When the coefficient matrix or its antiderivative, if passed is not a
  673. square matrix
  674. NotImplementedError
  675. If the coefficient matrix does not have a commutative antiderivative
  676. See Also
  677. ========
  678. linear_ode_to_matrix: Coefficient matrix computation function
  679. canonical_odes: System of ODEs representation change
  680. linodesolve_type: Getting information about systems of ODEs to pass in this solver
  681. """
  682. if not isinstance(A, MatrixBase):
  683. raise ValueError(filldedent('''\
  684. The coefficients of the system of ODEs should be of type Matrix
  685. '''))
  686. if not A.is_square:
  687. raise NonSquareMatrixError(filldedent('''\
  688. The coefficient matrix must be a square
  689. '''))
  690. if b is not None:
  691. if not isinstance(b, MatrixBase):
  692. raise ValueError(filldedent('''\
  693. The non-homogeneous terms of the system of ODEs should be of type Matrix
  694. '''))
  695. if A.rows != b.rows:
  696. raise ValueError(filldedent('''\
  697. The system of ODEs should have the same number of non-homogeneous terms and the number of
  698. equations
  699. '''))
  700. if B is not None:
  701. if not isinstance(B, MatrixBase):
  702. raise ValueError(filldedent('''\
  703. The antiderivative of coefficients of the system of ODEs should be of type Matrix
  704. '''))
  705. if not B.is_square:
  706. raise NonSquareMatrixError(filldedent('''\
  707. The antiderivative of the coefficient matrix must be a square
  708. '''))
  709. if A.rows != B.rows:
  710. raise ValueError(filldedent('''\
  711. The coefficient matrix and its antiderivative should have same dimensions
  712. '''))
  713. if not any(type == "type{}".format(i) for i in range(1, 7)) and not type == "auto":
  714. raise ValueError(filldedent('''\
  715. The input type should be a valid one
  716. '''))
  717. n = A.rows
  718. # constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1)
  719. Cvect = Matrix([Dummy() for _ in range(n)])
  720. if b is None and any(type == typ for typ in ["type2", "type4", "type6"]):
  721. b = zeros(n, 1)
  722. is_transformed = tau is not None
  723. passed_type = type
  724. if type == "auto":
  725. system_info = linodesolve_type(A, t, b=b)
  726. type = system_info["type_of_equation"]
  727. B = system_info["antiderivative"]
  728. if type in ("type5", "type6"):
  729. is_transformed = True
  730. if passed_type != "auto":
  731. if tau is None:
  732. system_info = _first_order_type5_6_subs(A, t, b=b)
  733. if not system_info:
  734. raise ValueError(filldedent('''
  735. The system passed isn't {}.
  736. '''.format(type)))
  737. tau = system_info['tau']
  738. t = system_info['t_']
  739. A = system_info['A']
  740. b = system_info['b']
  741. intx_wrtt = lambda x: Integral(x, t) if x else 0
  742. if type in ("type1", "type2", "type5", "type6"):
  743. P, J = matrix_exp_jordan_form(A, t)
  744. P = simplify(P)
  745. if type in ("type1", "type5"):
  746. sol_vector = P * (J * Cvect)
  747. else:
  748. Jinv = J.subs(t, -t)
  749. sol_vector = P * J * ((Jinv * P.inv() * b).applyfunc(intx_wrtt) + Cvect)
  750. else:
  751. if B is None:
  752. B, _ = _is_commutative_anti_derivative(A, t)
  753. if type == "type3":
  754. sol_vector = B.exp() * Cvect
  755. else:
  756. sol_vector = B.exp() * (((-B).exp() * b).applyfunc(intx_wrtt) + Cvect)
  757. if is_transformed:
  758. sol_vector = sol_vector.subs(t, tau)
  759. gens = sol_vector.atoms(exp)
  760. if type != "type1":
  761. sol_vector = [expand_mul(s) for s in sol_vector]
  762. sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector]
  763. if doit:
  764. sol_vector = [s.doit() for s in sol_vector]
  765. return sol_vector
  766. def _matrix_is_constant(M, t):
  767. """Checks if the matrix M is independent of t or not."""
  768. return all(coef.as_independent(t, as_Add=True)[1] == 0 for coef in M)
  769. def canonical_odes(eqs, funcs, t):
  770. r"""
  771. Function that solves for highest order derivatives in a system
  772. Explanation
  773. ===========
  774. This function inputs a system of ODEs and based on the system,
  775. the dependent variables and their highest order, returns the system
  776. in the following form:
  777. .. math::
  778. X'(t) = A(t) X(t) + b(t)
  779. Here, $X(t)$ is the vector of dependent variables of lower order, $A(t)$ is
  780. the coefficient matrix, $b(t)$ is the non-homogeneous term and $X'(t)$ is the
  781. vector of dependent variables in their respective highest order. We use the term
  782. canonical form to imply the system of ODEs which is of the above form.
  783. If the system passed has a non-linear term with multiple solutions, then a list of
  784. systems is returned in its canonical form.
  785. Parameters
  786. ==========
  787. eqs : List
  788. List of the ODEs
  789. funcs : List
  790. List of dependent variables
  791. t : Symbol
  792. Independent variable
  793. Examples
  794. ========
  795. >>> from sympy import symbols, Function, Eq, Derivative
  796. >>> from sympy.solvers.ode.systems import canonical_odes
  797. >>> f, g = symbols("f g", cls=Function)
  798. >>> x, y = symbols("x y")
  799. >>> funcs = [f(x), g(x)]
  800. >>> eqs = [Eq(f(x).diff(x) - 7*f(x), 12*g(x)), Eq(g(x).diff(x) + g(x), 20*f(x))]
  801. >>> canonical_eqs = canonical_odes(eqs, funcs, x)
  802. >>> canonical_eqs
  803. [[Eq(Derivative(f(x), x), 7*f(x) + 12*g(x)), Eq(Derivative(g(x), x), 20*f(x) - g(x))]]
  804. >>> system = [Eq(Derivative(f(x), x)**2 - 2*Derivative(f(x), x) + 1, 4), Eq(-y*f(x) + Derivative(g(x), x), 0)]
  805. >>> canonical_system = canonical_odes(system, funcs, x)
  806. >>> canonical_system
  807. [[Eq(Derivative(f(x), x), -1), Eq(Derivative(g(x), x), y*f(x))], [Eq(Derivative(f(x), x), 3), Eq(Derivative(g(x), x), y*f(x))]]
  808. Returns
  809. =======
  810. List
  811. """
  812. from sympy.solvers.solvers import solve
  813. order = _get_func_order(eqs, funcs)
  814. canon_eqs = solve(eqs, *[func.diff(t, order[func]) for func in funcs], dict=True)
  815. systems = []
  816. for eq in canon_eqs:
  817. system = [Eq(func.diff(t, order[func]), eq[func.diff(t, order[func])]) for func in funcs]
  818. systems.append(system)
  819. return systems
  820. def _is_commutative_anti_derivative(A, t):
  821. r"""
  822. Helper function for determining if the Matrix passed is commutative with its antiderivative
  823. Explanation
  824. ===========
  825. This function checks if the Matrix $A$ passed is commutative with its antiderivative with respect
  826. to the independent variable $t$.
  827. .. math::
  828. B(t) = \int A(t) dt
  829. The function outputs two values, first one being the antiderivative $B(t)$, second one being a
  830. boolean value, if True, then the matrix $A(t)$ passed is commutative with $B(t)$, else the matrix
  831. passed isn't commutative with $B(t)$.
  832. Parameters
  833. ==========
  834. A : Matrix
  835. The matrix which has to be checked
  836. t : Symbol
  837. Independent variable
  838. Examples
  839. ========
  840. >>> from sympy import symbols, Matrix
  841. >>> from sympy.solvers.ode.systems import _is_commutative_anti_derivative
  842. >>> t = symbols("t")
  843. >>> A = Matrix([[1, t], [-t, 1]])
  844. >>> B, is_commuting = _is_commutative_anti_derivative(A, t)
  845. >>> is_commuting
  846. True
  847. Returns
  848. =======
  849. Matrix, Boolean
  850. """
  851. B = integrate(A, t)
  852. is_commuting = (B*A - A*B).applyfunc(expand).applyfunc(factor_terms).is_zero_matrix
  853. is_commuting = False if is_commuting is None else is_commuting
  854. return B, is_commuting
  855. def _factor_matrix(A, t):
  856. term = None
  857. for element in A:
  858. temp_term = element.as_independent(t)[1]
  859. if temp_term.has(t):
  860. term = temp_term
  861. break
  862. if term is not None:
  863. A_factored = (A/term).applyfunc(ratsimp)
  864. can_factor = _matrix_is_constant(A_factored, t)
  865. term = (term, A_factored) if can_factor else None
  866. return term
  867. def _is_second_order_type2(A, t):
  868. term = _factor_matrix(A, t)
  869. is_type2 = False
  870. if term is not None:
  871. term = 1/term[0]
  872. is_type2 = term.is_polynomial()
  873. if is_type2:
  874. poly = Poly(term.expand(), t)
  875. monoms = poly.monoms()
  876. if monoms[0][0] in (2, 4):
  877. cs = _get_poly_coeffs(poly, 4)
  878. a, b, c, d, e = cs
  879. a1 = powdenest(sqrt(a), force=True)
  880. c1 = powdenest(sqrt(e), force=True)
  881. b1 = powdenest(sqrt(c - 2*a1*c1), force=True)
  882. is_type2 = (b == 2*a1*b1) and (d == 2*b1*c1)
  883. term = a1*t**2 + b1*t + c1
  884. else:
  885. is_type2 = False
  886. return is_type2, term
  887. def _get_poly_coeffs(poly, order):
  888. cs = [0 for _ in range(order+1)]
  889. for c, m in zip(poly.coeffs(), poly.monoms()):
  890. cs[-1-m[0]] = c
  891. return cs
  892. def _match_second_order_type(A1, A0, t, b=None):
  893. r"""
  894. Works only for second order system in its canonical form.
  895. Type 0: Constant coefficient matrix, can be simply solved by
  896. introducing dummy variables.
  897. Type 1: When the substitution: $U = t*X' - X$ works for reducing
  898. the second order system to first order system.
  899. Type 2: When the system is of the form: $poly * X'' = A*X$ where
  900. $poly$ is square of a quadratic polynomial with respect to
  901. *t* and $A$ is a constant coefficient matrix.
  902. """
  903. match = {"type_of_equation": "type0"}
  904. n = A1.shape[0]
  905. if _matrix_is_constant(A1, t) and _matrix_is_constant(A0, t):
  906. return match
  907. if (A1 + A0*t).applyfunc(expand_mul).is_zero_matrix:
  908. match.update({"type_of_equation": "type1", "A1": A1})
  909. elif A1.is_zero_matrix and (b is None or b.is_zero_matrix):
  910. is_type2, term = _is_second_order_type2(A0, t)
  911. if is_type2:
  912. a, b, c = _get_poly_coeffs(Poly(term, t), 2)
  913. A = (A0*(term**2).expand()).applyfunc(ratsimp) + (b**2/4 - a*c)*eye(n, n)
  914. tau = integrate(1/term, t)
  915. t_ = Symbol("{}_".format(t))
  916. match.update({"type_of_equation": "type2", "A0": A,
  917. "g(t)": sqrt(term), "tau": tau, "is_transformed": True,
  918. "t_": t_})
  919. return match
  920. def _second_order_subs_type1(A, b, funcs, t):
  921. r"""
  922. For a linear, second order system of ODEs, a particular substitution.
  923. A system of the below form can be reduced to a linear first order system of
  924. ODEs:
  925. .. math::
  926. X'' = A(t) * (t*X' - X) + b(t)
  927. By substituting:
  928. .. math:: U = t*X' - X
  929. To get the system:
  930. .. math:: U' = t*(A(t)*U + b(t))
  931. Where $U$ is the vector of dependent variables, $X$ is the vector of dependent
  932. variables in `funcs` and $X'$ is the first order derivative of $X$ with respect to
  933. $t$. It may or may not reduce the system into linear first order system of ODEs.
  934. Then a check is made to determine if the system passed can be reduced or not, if
  935. this substitution works, then the system is reduced and its solved for the new
  936. substitution. After we get the solution for $U$:
  937. .. math:: U = a(t)
  938. We substitute and return the reduced system:
  939. .. math::
  940. a(t) = t*X' - X
  941. Parameters
  942. ==========
  943. A: Matrix
  944. Coefficient matrix($A(t)*t$) of the second order system of this form.
  945. b: Matrix
  946. Non-homogeneous term($b(t)$) of the system of ODEs.
  947. funcs: List
  948. List of dependent variables
  949. t: Symbol
  950. Independent variable of the system of ODEs.
  951. Returns
  952. =======
  953. List
  954. """
  955. U = Matrix([t*func.diff(t) - func for func in funcs])
  956. sol = linodesolve(A, t, t*b)
  957. reduced_eqs = [Eq(u, s) for s, u in zip(sol, U)]
  958. reduced_eqs = canonical_odes(reduced_eqs, funcs, t)[0]
  959. return reduced_eqs
  960. def _second_order_subs_type2(A, funcs, t_):
  961. r"""
  962. Returns a second order system based on the coefficient matrix passed.
  963. Explanation
  964. ===========
  965. This function returns a system of second order ODE of the following form:
  966. .. math::
  967. X'' = A * X
  968. Here, $X$ is the vector of dependent variables, but a bit modified, $A$ is the
  969. coefficient matrix passed.
  970. Along with returning the second order system, this function also returns the new
  971. dependent variables with the new independent variable `t_` passed.
  972. Parameters
  973. ==========
  974. A: Matrix
  975. Coefficient matrix of the system
  976. funcs: List
  977. List of old dependent variables
  978. t_: Symbol
  979. New independent variable
  980. Returns
  981. =======
  982. List, List
  983. """
  984. func_names = [func.func.__name__ for func in funcs]
  985. new_funcs = [Function(Dummy("{}_".format(name)))(t_) for name in func_names]
  986. rhss = A * Matrix(new_funcs)
  987. new_eqs = [Eq(func.diff(t_, 2), rhs) for func, rhs in zip(new_funcs, rhss)]
  988. return new_eqs, new_funcs
  989. def _is_euler_system(As, t):
  990. return all(_matrix_is_constant((A*t**i).applyfunc(ratsimp), t) for i, A in enumerate(As))
  991. def _classify_linear_system(eqs, funcs, t, is_canon=False):
  992. r"""
  993. Returns a dictionary with details of the eqs if the system passed is linear
  994. and can be classified by this function else returns None
  995. Explanation
  996. ===========
  997. This function takes the eqs, converts it into a form Ax = b where x is a vector of terms
  998. containing dependent variables and their derivatives till their maximum order. If it is
  999. possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise
  1000. they are non-linear.
  1001. To check if the equations are constant coefficient, we need to check if all the terms in
  1002. A obtained above are constant or not.
  1003. To check if the equations are homogeneous or not, we need to check if b is a zero matrix
  1004. or not.
  1005. Parameters
  1006. ==========
  1007. eqs: List
  1008. List of ODEs
  1009. funcs: List
  1010. List of dependent variables
  1011. t: Symbol
  1012. Independent variable of the equations in eqs
  1013. is_canon: Boolean
  1014. If True, then this function will not try to get the
  1015. system in canonical form. Default value is False
  1016. Returns
  1017. =======
  1018. match = {
  1019. 'no_of_equation': len(eqs),
  1020. 'eq': eqs,
  1021. 'func': funcs,
  1022. 'order': order,
  1023. 'is_linear': is_linear,
  1024. 'is_constant': is_constant,
  1025. 'is_homogeneous': is_homogeneous,
  1026. }
  1027. Dict or list of Dicts or None
  1028. Dict with values for keys:
  1029. 1. no_of_equation: Number of equations
  1030. 2. eq: The set of equations
  1031. 3. func: List of dependent variables
  1032. 4. order: A dictionary that gives the order of the
  1033. dependent variable in eqs
  1034. 5. is_linear: Boolean value indicating if the set of
  1035. equations are linear or not.
  1036. 6. is_constant: Boolean value indicating if the set of
  1037. equations have constant coefficients or not.
  1038. 7. is_homogeneous: Boolean value indicating if the set of
  1039. equations are homogeneous or not.
  1040. 8. commutative_antiderivative: Antiderivative of the coefficient
  1041. matrix if the coefficient matrix is non-constant
  1042. and commutative with its antiderivative. This key
  1043. may or may not exist.
  1044. 9. is_general: Boolean value indicating if the system of ODEs is
  1045. solvable using one of the general case solvers or not.
  1046. 10. rhs: rhs of the non-homogeneous system of ODEs in Matrix form. This
  1047. key may or may not exist.
  1048. 11. is_higher_order: True if the system passed has an order greater than 1.
  1049. This key may or may not exist.
  1050. 12. is_second_order: True if the system passed is a second order ODE. This
  1051. key may or may not exist.
  1052. This Dict is the answer returned if the eqs are linear and constant
  1053. coefficient. Otherwise, None is returned.
  1054. """
  1055. # Error for i == 0 can be added but isn't for now
  1056. # Check for len(funcs) == len(eqs)
  1057. if len(funcs) != len(eqs):
  1058. raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs)
  1059. # ValueError when functions have more than one arguments
  1060. for func in funcs:
  1061. if len(func.args) != 1:
  1062. raise ValueError("dsolve() and classify_sysode() work with "
  1063. "functions of one variable only, not %s" % func)
  1064. # Getting the func_dict and order using the helper
  1065. # function
  1066. order = _get_func_order(eqs, funcs)
  1067. system_order = max(order[func] for func in funcs)
  1068. is_higher_order = system_order > 1
  1069. is_second_order = system_order == 2 and all(order[func] == 2 for func in funcs)
  1070. # Not adding the check if the len(func.args) for
  1071. # every func in funcs is 1
  1072. # Linearity check
  1073. try:
  1074. canon_eqs = canonical_odes(eqs, funcs, t) if not is_canon else [eqs]
  1075. if len(canon_eqs) == 1:
  1076. As, b = linear_ode_to_matrix(canon_eqs[0], funcs, t, system_order)
  1077. else:
  1078. match = {
  1079. 'is_implicit': True,
  1080. 'canon_eqs': canon_eqs
  1081. }
  1082. return match
  1083. # When the system of ODEs is non-linear, an ODENonlinearError is raised.
  1084. # This function catches the error and None is returned.
  1085. except ODENonlinearError:
  1086. return None
  1087. is_linear = True
  1088. # Homogeneous check
  1089. is_homogeneous = True if b.is_zero_matrix else False
  1090. # Is general key is used to identify if the system of ODEs can be solved by
  1091. # one of the general case solvers or not.
  1092. match = {
  1093. 'no_of_equation': len(eqs),
  1094. 'eq': eqs,
  1095. 'func': funcs,
  1096. 'order': order,
  1097. 'is_linear': is_linear,
  1098. 'is_homogeneous': is_homogeneous,
  1099. 'is_general': True
  1100. }
  1101. if not is_homogeneous:
  1102. match['rhs'] = b
  1103. is_constant = all(_matrix_is_constant(A_, t) for A_ in As)
  1104. # The match['is_linear'] check will be added in the future when this
  1105. # function becomes ready to deal with non-linear systems of ODEs
  1106. if not is_higher_order:
  1107. A = As[1]
  1108. match['func_coeff'] = A
  1109. # Constant coefficient check
  1110. is_constant = _matrix_is_constant(A, t)
  1111. match['is_constant'] = is_constant
  1112. try:
  1113. system_info = linodesolve_type(A, t, b=b)
  1114. except NotImplementedError:
  1115. return None
  1116. match.update(system_info)
  1117. antiderivative = match.pop("antiderivative")
  1118. if not is_constant:
  1119. match['commutative_antiderivative'] = antiderivative
  1120. return match
  1121. else:
  1122. match['type_of_equation'] = "type0"
  1123. if is_second_order:
  1124. A1, A0 = As[1:]
  1125. match_second_order = _match_second_order_type(A1, A0, t)
  1126. match.update(match_second_order)
  1127. match['is_second_order'] = True
  1128. # If system is constant, then no need to check if its in euler
  1129. # form or not. It will be easier and faster to directly proceed
  1130. # to solve it.
  1131. if match['type_of_equation'] == "type0" and not is_constant:
  1132. is_euler = _is_euler_system(As, t)
  1133. if is_euler:
  1134. t_ = Symbol('{}_'.format(t))
  1135. match.update({'is_transformed': True, 'type_of_equation': 'type1',
  1136. 't_': t_})
  1137. else:
  1138. is_jordan = lambda M: M == Matrix.jordan_block(M.shape[0], M[0, 0])
  1139. terms = _factor_matrix(As[-1], t)
  1140. if all(A.is_zero_matrix for A in As[1:-1]) and terms is not None and not is_jordan(terms[1]):
  1141. P, J = terms[1].jordan_form()
  1142. match.update({'type_of_equation': 'type2', 'J': J,
  1143. 'f(t)': terms[0], 'P': P, 'is_transformed': True})
  1144. if match['type_of_equation'] != 'type0' and is_second_order:
  1145. match.pop('is_second_order', None)
  1146. match['is_higher_order'] = is_higher_order
  1147. return match
  1148. def _preprocess_eqs(eqs):
  1149. processed_eqs = []
  1150. for eq in eqs:
  1151. processed_eqs.append(eq if isinstance(eq, Equality) else Eq(eq, 0))
  1152. return processed_eqs
  1153. def _eqs2dict(eqs, funcs):
  1154. eqsorig = {}
  1155. eqsmap = {}
  1156. funcset = set(funcs)
  1157. for eq in eqs:
  1158. f1, = eq.lhs.atoms(AppliedUndef)
  1159. f2s = (eq.rhs.atoms(AppliedUndef) - {f1}) & funcset
  1160. eqsmap[f1] = f2s
  1161. eqsorig[f1] = eq
  1162. return eqsmap, eqsorig
  1163. def _dict2graph(d):
  1164. nodes = list(d)
  1165. edges = [(f1, f2) for f1, f2s in d.items() for f2 in f2s]
  1166. G = (nodes, edges)
  1167. return G
  1168. def _is_type1(scc, t):
  1169. eqs, funcs = scc
  1170. try:
  1171. (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 1)
  1172. except (ODENonlinearError, ODEOrderError):
  1173. return False
  1174. if _matrix_is_constant(A0, t) and b.is_zero_matrix:
  1175. return True
  1176. return False
  1177. def _combine_type1_subsystems(subsystem, funcs, t):
  1178. indices = [i for i, sys in enumerate(zip(subsystem, funcs)) if _is_type1(sys, t)]
  1179. remove = set()
  1180. for ip, i in enumerate(indices):
  1181. for j in indices[ip+1:]:
  1182. if any(eq2.has(funcs[i]) for eq2 in subsystem[j]):
  1183. subsystem[j] = subsystem[i] + subsystem[j]
  1184. remove.add(i)
  1185. subsystem = [sys for i, sys in enumerate(subsystem) if i not in remove]
  1186. return subsystem
  1187. def _component_division(eqs, funcs, t):
  1188. # Assuming that each eq in eqs is in canonical form,
  1189. # that is, [f(x).diff(x) = .., g(x).diff(x) = .., etc]
  1190. # and that the system passed is in its first order
  1191. eqsmap, eqsorig = _eqs2dict(eqs, funcs)
  1192. subsystems = []
  1193. for cc in connected_components(_dict2graph(eqsmap)):
  1194. eqsmap_c = {f: eqsmap[f] for f in cc}
  1195. sccs = strongly_connected_components(_dict2graph(eqsmap_c))
  1196. subsystem = [[eqsorig[f] for f in scc] for scc in sccs]
  1197. subsystem = _combine_type1_subsystems(subsystem, sccs, t)
  1198. subsystems.append(subsystem)
  1199. return subsystems
  1200. # Returns: List of equations
  1201. def _linear_ode_solver(match):
  1202. t = match['t']
  1203. funcs = match['func']
  1204. rhs = match.get('rhs', None)
  1205. tau = match.get('tau', None)
  1206. t = match['t_'] if 't_' in match else t
  1207. A = match['func_coeff']
  1208. # Note: To make B None when the matrix has constant
  1209. # coefficient
  1210. B = match.get('commutative_antiderivative', None)
  1211. type = match['type_of_equation']
  1212. sol_vector = linodesolve(A, t, b=rhs, B=B,
  1213. type=type, tau=tau)
  1214. sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  1215. return sol
  1216. def _select_equations(eqs, funcs, key=lambda x: x):
  1217. eq_dict = {e.lhs: e.rhs for e in eqs}
  1218. return [Eq(f, eq_dict[key(f)]) for f in funcs]
  1219. def _higher_order_ode_solver(match):
  1220. eqs = match["eq"]
  1221. funcs = match["func"]
  1222. t = match["t"]
  1223. sysorder = match['order']
  1224. type = match.get('type_of_equation', "type0")
  1225. is_second_order = match.get('is_second_order', False)
  1226. is_transformed = match.get('is_transformed', False)
  1227. is_euler = is_transformed and type == "type1"
  1228. is_higher_order_type2 = is_transformed and type == "type2" and 'P' in match
  1229. if is_second_order:
  1230. new_eqs, new_funcs = _second_order_to_first_order(eqs, funcs, t,
  1231. A1=match.get("A1", None), A0=match.get("A0", None),
  1232. b=match.get("rhs", None), type=type,
  1233. t_=match.get("t_", None))
  1234. else:
  1235. new_eqs, new_funcs = _higher_order_to_first_order(eqs, sysorder, t, funcs=funcs,
  1236. type=type, J=match.get('J', None),
  1237. f_t=match.get('f(t)', None),
  1238. P=match.get('P', None), b=match.get('rhs', None))
  1239. if is_transformed:
  1240. t = match.get('t_', t)
  1241. if not is_higher_order_type2:
  1242. new_eqs = _select_equations(new_eqs, [f.diff(t) for f in new_funcs])
  1243. sol = None
  1244. # NotImplementedError may be raised when the system may be actually
  1245. # solvable if it can be just divided into sub-systems
  1246. try:
  1247. if not is_higher_order_type2:
  1248. sol = _strong_component_solver(new_eqs, new_funcs, t)
  1249. except NotImplementedError:
  1250. sol = None
  1251. # Dividing the system only when it becomes essential
  1252. if sol is None:
  1253. try:
  1254. sol = _component_solver(new_eqs, new_funcs, t)
  1255. except NotImplementedError:
  1256. sol = None
  1257. if sol is None:
  1258. return sol
  1259. is_second_order_type2 = is_second_order and type == "type2"
  1260. underscores = '__' if is_transformed else '_'
  1261. sol = _select_equations(sol, funcs,
  1262. key=lambda x: Function(Dummy('{}{}0'.format(x.func.__name__, underscores)))(t))
  1263. if match.get("is_transformed", False):
  1264. if is_second_order_type2:
  1265. g_t = match["g(t)"]
  1266. tau = match["tau"]
  1267. sol = [Eq(s.lhs, s.rhs.subs(t, tau) * g_t) for s in sol]
  1268. elif is_euler:
  1269. t = match['t']
  1270. tau = match['t_']
  1271. sol = [s.subs(tau, log(t)) for s in sol]
  1272. elif is_higher_order_type2:
  1273. P = match['P']
  1274. sol_vector = P * Matrix([s.rhs for s in sol])
  1275. sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  1276. return sol
  1277. # Returns: List of equations or None
  1278. # If None is returned by this solver, then the system
  1279. # of ODEs cannot be solved directly by dsolve_system.
  1280. def _strong_component_solver(eqs, funcs, t):
  1281. from sympy.solvers.ode.ode import dsolve, constant_renumber
  1282. match = _classify_linear_system(eqs, funcs, t, is_canon=True)
  1283. sol = None
  1284. # Assuming that we can't get an implicit system
  1285. # since we are already canonical equations from
  1286. # dsolve_system
  1287. if match:
  1288. match['t'] = t
  1289. if match.get('is_higher_order', False):
  1290. sol = _higher_order_ode_solver(match)
  1291. elif match.get('is_linear', False):
  1292. sol = _linear_ode_solver(match)
  1293. # Note: For now, only linear systems are handled by this function
  1294. # hence, the match condition is added. This can be removed later.
  1295. if sol is None and len(eqs) == 1:
  1296. sol = dsolve(eqs[0], func=funcs[0])
  1297. variables = Tuple(eqs[0]).free_symbols
  1298. new_constants = [Dummy() for _ in range(ode_order(eqs[0], funcs[0]))]
  1299. sol = constant_renumber(sol, variables=variables, newconstants=new_constants)
  1300. sol = [sol]
  1301. # To add non-linear case here in future
  1302. return sol
  1303. def _get_funcs_from_canon(eqs):
  1304. return [eq.lhs.args[0] for eq in eqs]
  1305. # Returns: List of Equations(a solution)
  1306. def _weak_component_solver(wcc, t):
  1307. # We will divide the systems into sccs
  1308. # only when the wcc cannot be solved as
  1309. # a whole
  1310. eqs = []
  1311. for scc in wcc:
  1312. eqs += scc
  1313. funcs = _get_funcs_from_canon(eqs)
  1314. sol = _strong_component_solver(eqs, funcs, t)
  1315. if sol:
  1316. return sol
  1317. sol = []
  1318. for j, scc in enumerate(wcc):
  1319. eqs = scc
  1320. funcs = _get_funcs_from_canon(eqs)
  1321. # Substituting solutions for the dependent
  1322. # variables solved in previous SCC, if any solved.
  1323. comp_eqs = [eq.subs({s.lhs: s.rhs for s in sol}) for eq in eqs]
  1324. scc_sol = _strong_component_solver(comp_eqs, funcs, t)
  1325. if scc_sol is None:
  1326. raise NotImplementedError(filldedent('''
  1327. The system of ODEs passed cannot be solved by dsolve_system.
  1328. '''))
  1329. # scc_sol: List of equations
  1330. # scc_sol is a solution
  1331. sol += scc_sol
  1332. return sol
  1333. # Returns: List of Equations(a solution)
  1334. def _component_solver(eqs, funcs, t):
  1335. components = _component_division(eqs, funcs, t)
  1336. sol = []
  1337. for wcc in components:
  1338. # wcc_sol: List of Equations
  1339. sol += _weak_component_solver(wcc, t)
  1340. # sol: List of Equations
  1341. return sol
  1342. def _second_order_to_first_order(eqs, funcs, t, type="auto", A1=None,
  1343. A0=None, b=None, t_=None):
  1344. r"""
  1345. Expects the system to be in second order and in canonical form
  1346. Explanation
  1347. ===========
  1348. Reduces a second order system into a first order one depending on the type of second
  1349. order system.
  1350. 1. "type0": If this is passed, then the system will be reduced to first order by
  1351. introducing dummy variables.
  1352. 2. "type1": If this is passed, then a particular substitution will be used to reduce the
  1353. the system into first order.
  1354. 3. "type2": If this is passed, then the system will be transformed with new dependent
  1355. variables and independent variables. This transformation is a part of solving
  1356. the corresponding system of ODEs.
  1357. `A1` and `A0` are the coefficient matrices from the system and it is assumed that the
  1358. second order system has the form given below:
  1359. .. math::
  1360. A2 * X'' = A1 * X' + A0 * X + b
  1361. Here, $A2$ is the coefficient matrix for the vector $X''$ and $b$ is the non-homogeneous
  1362. term.
  1363. Default value for `b` is None but if `A1` and `A0` are passed and `b` is not passed, then the
  1364. system will be assumed homogeneous.
  1365. """
  1366. is_a1 = A1 is None
  1367. is_a0 = A0 is None
  1368. if (type == "type1" and is_a1) or (type == "type2" and is_a0)\
  1369. or (type == "auto" and (is_a1 or is_a0)):
  1370. (A2, A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 2)
  1371. if not A2.is_Identity:
  1372. raise ValueError(filldedent('''
  1373. The system must be in its canonical form.
  1374. '''))
  1375. if type == "auto":
  1376. match = _match_second_order_type(A1, A0, t)
  1377. type = match["type_of_equation"]
  1378. A1 = match.get("A1", None)
  1379. A0 = match.get("A0", None)
  1380. sys_order = {func: 2 for func in funcs}
  1381. if type == "type1":
  1382. if b is None:
  1383. b = zeros(len(eqs))
  1384. eqs = _second_order_subs_type1(A1, b, funcs, t)
  1385. sys_order = {func: 1 for func in funcs}
  1386. if type == "type2":
  1387. if t_ is None:
  1388. t_ = Symbol("{}_".format(t))
  1389. t = t_
  1390. eqs, funcs = _second_order_subs_type2(A0, funcs, t_)
  1391. sys_order = {func: 2 for func in funcs}
  1392. return _higher_order_to_first_order(eqs, sys_order, t, funcs=funcs)
  1393. def _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, b=None, P=None):
  1394. # Note: To add a test for this ValueError
  1395. if J is None or f_t is None or not _matrix_is_constant(J, t):
  1396. raise ValueError(filldedent('''
  1397. Correctly input for args 'A' and 'f_t' for Linear, Higher Order,
  1398. Type 2
  1399. '''))
  1400. if P is None and b is not None and not b.is_zero_matrix:
  1401. raise ValueError(filldedent('''
  1402. Provide the keyword 'P' for matrix P in A = P * J * P-1.
  1403. '''))
  1404. new_funcs = Matrix([Function(Dummy('{}__0'.format(f.func.__name__)))(t) for f in funcs])
  1405. new_eqs = new_funcs.diff(t, max_order) - f_t * J * new_funcs
  1406. if b is not None and not b.is_zero_matrix:
  1407. new_eqs -= P.inv() * b
  1408. new_eqs = canonical_odes(new_eqs, new_funcs, t)[0]
  1409. return new_eqs, new_funcs
  1410. def _higher_order_to_first_order(eqs, sys_order, t, funcs=None, type="type0", **kwargs):
  1411. if funcs is None:
  1412. funcs = sys_order.keys()
  1413. # Standard Cauchy Euler system
  1414. if type == "type1":
  1415. t_ = Symbol('{}_'.format(t))
  1416. new_funcs = [Function(Dummy('{}_'.format(f.func.__name__)))(t_) for f in funcs]
  1417. max_order = max(sys_order[func] for func in funcs)
  1418. subs_dict = {func: new_func for func, new_func in zip(funcs, new_funcs)}
  1419. subs_dict[t] = exp(t_)
  1420. free_function = Function(Dummy())
  1421. def _get_coeffs_from_subs_expression(expr):
  1422. if isinstance(expr, Subs):
  1423. free_symbol = expr.args[1][0]
  1424. term = expr.args[0]
  1425. return {ode_order(term, free_symbol): 1}
  1426. if isinstance(expr, Mul):
  1427. coeff = expr.args[0]
  1428. order = list(_get_coeffs_from_subs_expression(expr.args[1]).keys())[0]
  1429. return {order: coeff}
  1430. if isinstance(expr, Add):
  1431. coeffs = {}
  1432. for arg in expr.args:
  1433. if isinstance(arg, Mul):
  1434. coeffs.update(_get_coeffs_from_subs_expression(arg))
  1435. else:
  1436. order = list(_get_coeffs_from_subs_expression(arg).keys())[0]
  1437. coeffs[order] = 1
  1438. return coeffs
  1439. for o in range(1, max_order + 1):
  1440. expr = free_function(log(t_)).diff(t_, o)*t_**o
  1441. coeff_dict = _get_coeffs_from_subs_expression(expr)
  1442. coeffs = [coeff_dict[order] if order in coeff_dict else 0 for order in range(o + 1)]
  1443. expr_to_subs = sum(free_function(t_).diff(t_, i) * c for i, c in
  1444. enumerate(coeffs)) / t**o
  1445. subs_dict.update({f.diff(t, o): expr_to_subs.subs(free_function(t_), nf)
  1446. for f, nf in zip(funcs, new_funcs)})
  1447. new_eqs = [eq.subs(subs_dict) for eq in eqs]
  1448. new_sys_order = {nf: sys_order[f] for f, nf in zip(funcs, new_funcs)}
  1449. new_eqs = canonical_odes(new_eqs, new_funcs, t_)[0]
  1450. return _higher_order_to_first_order(new_eqs, new_sys_order, t_, funcs=new_funcs)
  1451. # Systems of the form: X(n)(t) = f(t)*A*X + b
  1452. # where X(n)(t) is the nth derivative of the vector of dependent variables
  1453. # with respect to the independent variable and A is a constant matrix.
  1454. if type == "type2":
  1455. J = kwargs.get('J', None)
  1456. f_t = kwargs.get('f_t', None)
  1457. b = kwargs.get('b', None)
  1458. P = kwargs.get('P', None)
  1459. max_order = max(sys_order[func] for func in funcs)
  1460. return _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, P=P, b=b)
  1461. # Note: To be changed to this after doit option is disabled for default cases
  1462. # new_sysorder = _get_func_order(new_eqs, new_funcs)
  1463. #
  1464. # return _higher_order_to_first_order(new_eqs, new_sysorder, t, funcs=new_funcs)
  1465. new_funcs = []
  1466. for prev_func in funcs:
  1467. func_name = prev_func.func.__name__
  1468. func = Function(Dummy('{}_0'.format(func_name)))(t)
  1469. new_funcs.append(func)
  1470. subs_dict = {prev_func: func}
  1471. new_eqs = []
  1472. for i in range(1, sys_order[prev_func]):
  1473. new_func = Function(Dummy('{}_{}'.format(func_name, i)))(t)
  1474. subs_dict[prev_func.diff(t, i)] = new_func
  1475. new_funcs.append(new_func)
  1476. prev_f = subs_dict[prev_func.diff(t, i-1)]
  1477. new_eq = Eq(prev_f.diff(t), new_func)
  1478. new_eqs.append(new_eq)
  1479. eqs = [eq.subs(subs_dict) for eq in eqs] + new_eqs
  1480. return eqs, new_funcs
  1481. def dsolve_system(eqs, funcs=None, t=None, ics=None, doit=False, simplify=True):
  1482. r"""
  1483. Solves any(supported) system of Ordinary Differential Equations
  1484. Explanation
  1485. ===========
  1486. This function takes a system of ODEs as an input, determines if the
  1487. it is solvable by this function, and returns the solution if found any.
  1488. This function can handle:
  1489. 1. Linear, First Order, Constant coefficient homogeneous system of ODEs
  1490. 2. Linear, First Order, Constant coefficient non-homogeneous system of ODEs
  1491. 3. Linear, First Order, non-constant coefficient homogeneous system of ODEs
  1492. 4. Linear, First Order, non-constant coefficient non-homogeneous system of ODEs
  1493. 5. Any implicit system which can be divided into system of ODEs which is of the above 4 forms
  1494. 6. Any higher order linear system of ODEs that can be reduced to one of the 5 forms of systems described above.
  1495. The types of systems described above are not limited by the number of equations, i.e. this
  1496. function can solve the above types irrespective of the number of equations in the system passed.
  1497. But, the bigger the system, the more time it will take to solve the system.
  1498. This function returns a list of solutions. Each solution is a list of equations where LHS is
  1499. the dependent variable and RHS is an expression in terms of the independent variable.
  1500. Among the non constant coefficient types, not all the systems are solvable by this function. Only
  1501. those which have either a coefficient matrix with a commutative antiderivative or those systems which
  1502. may be divided further so that the divided systems may have coefficient matrix with commutative antiderivative.
  1503. Parameters
  1504. ==========
  1505. eqs : List
  1506. system of ODEs to be solved
  1507. funcs : List or None
  1508. List of dependent variables that make up the system of ODEs
  1509. t : Symbol or None
  1510. Independent variable in the system of ODEs
  1511. ics : Dict or None
  1512. Set of initial boundary/conditions for the system of ODEs
  1513. doit : Boolean
  1514. Evaluate the solutions if True. Default value is True. Can be
  1515. set to false if the integral evaluation takes too much time and/or
  1516. is not required.
  1517. simplify: Boolean
  1518. Simplify the solutions for the systems. Default value is True.
  1519. Can be set to false if simplification takes too much time and/or
  1520. is not required.
  1521. Examples
  1522. ========
  1523. >>> from sympy import symbols, Eq, Function
  1524. >>> from sympy.solvers.ode.systems import dsolve_system
  1525. >>> f, g = symbols("f g", cls=Function)
  1526. >>> x = symbols("x")
  1527. >>> eqs = [Eq(f(x).diff(x), g(x)), Eq(g(x).diff(x), f(x))]
  1528. >>> dsolve_system(eqs)
  1529. [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
  1530. You can also pass the initial conditions for the system of ODEs:
  1531. >>> dsolve_system(eqs, ics={f(0): 1, g(0): 0})
  1532. [[Eq(f(x), exp(x)/2 + exp(-x)/2), Eq(g(x), exp(x)/2 - exp(-x)/2)]]
  1533. Optionally, you can pass the dependent variables and the independent
  1534. variable for which the system is to be solved:
  1535. >>> funcs = [f(x), g(x)]
  1536. >>> dsolve_system(eqs, funcs=funcs, t=x)
  1537. [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
  1538. Lets look at an implicit system of ODEs:
  1539. >>> eqs = [Eq(f(x).diff(x)**2, g(x)**2), Eq(g(x).diff(x), g(x))]
  1540. >>> dsolve_system(eqs)
  1541. [[Eq(f(x), C1 - C2*exp(x)), Eq(g(x), C2*exp(x))], [Eq(f(x), C1 + C2*exp(x)), Eq(g(x), C2*exp(x))]]
  1542. Returns
  1543. =======
  1544. List of List of Equations
  1545. Raises
  1546. ======
  1547. NotImplementedError
  1548. When the system of ODEs is not solvable by this function.
  1549. ValueError
  1550. When the parameters passed are not in the required form.
  1551. """
  1552. from sympy.solvers.ode.ode import solve_ics, _extract_funcs, constant_renumber
  1553. if not iterable(eqs):
  1554. raise ValueError(filldedent('''
  1555. List of equations should be passed. The input is not valid.
  1556. '''))
  1557. eqs = _preprocess_eqs(eqs)
  1558. if funcs is not None and not isinstance(funcs, list):
  1559. raise ValueError(filldedent('''
  1560. Input to the funcs should be a list of functions.
  1561. '''))
  1562. if funcs is None:
  1563. funcs = _extract_funcs(eqs)
  1564. if any(len(func.args) != 1 for func in funcs):
  1565. raise ValueError(filldedent('''
  1566. dsolve_system can solve a system of ODEs with only one independent
  1567. variable.
  1568. '''))
  1569. if len(eqs) != len(funcs):
  1570. raise ValueError(filldedent('''
  1571. Number of equations and number of functions do not match
  1572. '''))
  1573. if t is not None and not isinstance(t, Symbol):
  1574. raise ValueError(filldedent('''
  1575. The independent variable must be of type Symbol
  1576. '''))
  1577. if t is None:
  1578. t = list(list(eqs[0].atoms(Derivative))[0].atoms(Symbol))[0]
  1579. sols = []
  1580. canon_eqs = canonical_odes(eqs, funcs, t)
  1581. for canon_eq in canon_eqs:
  1582. try:
  1583. sol = _strong_component_solver(canon_eq, funcs, t)
  1584. except NotImplementedError:
  1585. sol = None
  1586. if sol is None:
  1587. sol = _component_solver(canon_eq, funcs, t)
  1588. sols.append(sol)
  1589. if sols:
  1590. final_sols = []
  1591. variables = Tuple(*eqs).free_symbols
  1592. for sol in sols:
  1593. sol = _select_equations(sol, funcs)
  1594. sol = constant_renumber(sol, variables=variables)
  1595. if ics:
  1596. constants = Tuple(*sol).free_symbols - variables
  1597. solved_constants = solve_ics(sol, funcs, constants, ics)
  1598. sol = [s.subs(solved_constants) for s in sol]
  1599. if simplify:
  1600. constants = Tuple(*sol).free_symbols - variables
  1601. sol = simpsol(sol, [t], constants, doit=doit)
  1602. final_sols.append(sol)
  1603. sols = final_sols
  1604. return sols