systems.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  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 doesn't 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. funcs_deriv = [func.diff(t, o) for func in funcs]
  373. # linear_eq_to_matrix expects a proper symbol so substitute e.g.
  374. # Derivative(x(t), t) for a Dummy.
  375. rep = {func_deriv: Dummy() for func_deriv in funcs_deriv}
  376. eqs = [eq.subs(rep) for eq in eqs]
  377. syms = [rep[func_deriv] for func_deriv in funcs_deriv]
  378. # Ai is the matrix for X(t).diff(t, o)
  379. # eqs is minus the remainder of the equations.
  380. try:
  381. Ai, b = linear_eq_to_matrix(eqs, syms)
  382. except NonlinearError:
  383. raise ODENonlinearError("The system of ODEs is nonlinear.")
  384. Ai = Ai.applyfunc(expand_mul)
  385. As.append(Ai if o == order else -Ai)
  386. if o:
  387. eqs = [-eq for eq in b]
  388. else:
  389. rhs = b
  390. return As, rhs
  391. def matrix_exp(A, t):
  392. r"""
  393. Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``.
  394. Explanation
  395. ===========
  396. This functions returns the $\exp(A*t)$ by doing a simple
  397. matrix multiplication:
  398. .. math:: \exp(A*t) = P * expJ * P^{-1}
  399. where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal
  400. form of $A$ and $P$ is matrix such that:
  401. .. math:: A = P * J * P^{-1}
  402. The matrix exponential $\exp(A*t)$ appears in the solution of linear
  403. differential equations. For example if $x$ is a vector and $A$ is a matrix
  404. then the initial value problem
  405. .. math:: \frac{dx(t)}{dt} = A \times x(t), x(0) = x0
  406. has the unique solution
  407. .. math:: x(t) = \exp(A t) x0
  408. Examples
  409. ========
  410. >>> from sympy import Symbol, Matrix, pprint
  411. >>> from sympy.solvers.ode.systems import matrix_exp
  412. >>> t = Symbol('t')
  413. We will consider a 2x2 matrix for comupting the exponential
  414. >>> A = Matrix([[2, -5], [2, -4]])
  415. >>> pprint(A)
  416. [2 -5]
  417. [ ]
  418. [2 -4]
  419. Now, exp(A*t) is given as follows:
  420. >>> pprint(matrix_exp(A, t))
  421. [ -t -t -t ]
  422. [3*e *sin(t) + e *cos(t) -5*e *sin(t) ]
  423. [ ]
  424. [ -t -t -t ]
  425. [ 2*e *sin(t) - 3*e *sin(t) + e *cos(t)]
  426. Parameters
  427. ==========
  428. A : Matrix
  429. The matrix $A$ in the expression $\exp(A*t)$
  430. t : Symbol
  431. The independent variable
  432. See Also
  433. ========
  434. matrix_exp_jordan_form: For exponential of Jordan normal form
  435. References
  436. ==========
  437. .. [1] https://en.wikipedia.org/wiki/Jordan_normal_form
  438. .. [2] https://en.wikipedia.org/wiki/Matrix_exponential
  439. """
  440. P, expJ = matrix_exp_jordan_form(A, t)
  441. return P * expJ * P.inv()
  442. def matrix_exp_jordan_form(A, t):
  443. r"""
  444. Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*.
  445. Explanation
  446. ===========
  447. Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that:
  448. .. math::
  449. \exp(A*t) = P * expJ * P^{-1}
  450. Examples
  451. ========
  452. >>> from sympy import Matrix, Symbol
  453. >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form
  454. >>> t = Symbol('t')
  455. We will consider a 2x2 defective matrix. This shows that our method
  456. works even for defective matrices.
  457. >>> A = Matrix([[1, 1], [0, 1]])
  458. It can be observed that this function gives us the Jordan normal form
  459. and the required invertible matrix P.
  460. >>> P, expJ = matrix_exp_jordan_form(A, t)
  461. Here, it is shown that P and expJ returned by this function is correct
  462. as they satisfy the formula: P * expJ * P_inverse = exp(A*t).
  463. >>> P * expJ * P.inv() == matrix_exp(A, t)
  464. True
  465. Parameters
  466. ==========
  467. A : Matrix
  468. The matrix $A$ in the expression $\exp(A*t)$
  469. t : Symbol
  470. The independent variable
  471. References
  472. ==========
  473. .. [1] https://en.wikipedia.org/wiki/Defective_matrix
  474. .. [2] https://en.wikipedia.org/wiki/Jordan_matrix
  475. .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form
  476. """
  477. N, M = A.shape
  478. if N != M:
  479. raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M))
  480. elif A.has(t):
  481. raise ValueError('Matrix A should not depend on t')
  482. def jordan_chains(A):
  483. '''Chains from Jordan normal form analogous to M.eigenvects().
  484. Returns a dict with eignevalues as keys like:
  485. {e1: [[v111,v112,...], [v121, v122,...]], e2:...}
  486. where vijk is the kth vector in the jth chain for eigenvalue i.
  487. '''
  488. P, blocks = A.jordan_cells()
  489. basis = [P[:,i] for i in range(P.shape[1])]
  490. n = 0
  491. chains = {}
  492. for b in blocks:
  493. eigval = b[0, 0]
  494. size = b.shape[0]
  495. if eigval not in chains:
  496. chains[eigval] = []
  497. chains[eigval].append(basis[n:n+size])
  498. n += size
  499. return chains
  500. eigenchains = jordan_chains(A)
  501. # Needed for consistency across Python versions
  502. eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key)
  503. isreal = not A.has(I)
  504. blocks = []
  505. vectors = []
  506. seen_conjugate = set()
  507. for e, chains in eigenchains_iter:
  508. for chain in chains:
  509. n = len(chain)
  510. if isreal and e != e.conjugate() and e.conjugate() in eigenchains:
  511. if e in seen_conjugate:
  512. continue
  513. seen_conjugate.add(e.conjugate())
  514. exprt = exp(re(e) * t)
  515. imrt = im(e) * t
  516. imblock = Matrix([[cos(imrt), sin(imrt)],
  517. [-sin(imrt), cos(imrt)]])
  518. expJblock2 = Matrix(n, n, lambda i,j:
  519. imblock * t**(j-i) / factorial(j-i) if j >= i
  520. else zeros(2, 2))
  521. expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2])
  522. blocks.append(exprt * expJblock)
  523. for i in range(n):
  524. vectors.append(re(chain[i]))
  525. vectors.append(im(chain[i]))
  526. else:
  527. vectors.extend(chain)
  528. fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0
  529. expJblock = Matrix(n, n, fun)
  530. blocks.append(exp(e * t) * expJblock)
  531. expJ = Matrix.diag(*blocks)
  532. P = Matrix(N, N, lambda i,j: vectors[j][i])
  533. return P, expJ
  534. # Note: To add a docstring example with tau
  535. def linodesolve(A, t, b=None, B=None, type="auto", doit=False,
  536. tau=None):
  537. r"""
  538. System of n equations linear first-order differential equations
  539. Explanation
  540. ===========
  541. This solver solves the system of ODEs of the follwing form:
  542. .. math::
  543. X'(t) = A(t) X(t) + b(t)
  544. Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables,
  545. $b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$
  546. Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution
  547. differently.
  548. When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous,
  549. the system is "type1". The solution is:
  550. .. math::
  551. X(t) = \exp(A t) C
  552. Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix.
  553. When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous,
  554. the system is "type2". The solution is:
  555. .. math::
  556. X(t) = e^{A t} ( \int e^{- A t} b \,dt + C)
  557. When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and
  558. $b(t)$ is a zero vector i.e. system is homogeneous, the system is "type3". The solution is:
  559. .. math::
  560. X(t) = \exp(B(t)) C
  561. When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is
  562. non-homogeneous, the system is "type4". The solution is:
  563. .. math::
  564. X(t) = e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C)
  565. When $A(t)$ is a coefficient matrix such that it can be factorized into a scalar and a constant
  566. coefficient matrix:
  567. .. math::
  568. A(t) = f(t) * A
  569. Where $f(t)$ is a scalar expression in the independent variable $t$ and $A$ is a constant matrix,
  570. then we can do the following substitutions:
  571. .. math::
  572. tau = \int f(t) dt, X(t) = Y(tau), b(t) = b(f^{-1}(tau))
  573. Here, the substitution for the non-homogeneous term is done only when its non-zero.
  574. Using these substitutions, our original system becomes:
  575. .. math::
  576. Y'(tau) = A * Y(tau) + b(tau)/f(tau)
  577. The above system can be easily solved using the solution for "type1" or "type2" depending
  578. on the homogeneity of the system. After we get the solution for $Y(tau)$, we substitute the
  579. solution for $tau$ as $t$ to get back $X(t)$
  580. .. math::
  581. X(t) = Y(tau)
  582. Systems of "type5" and "type6" have a commutative antiderivative but we use this solution
  583. because its faster to compute.
  584. The final solution is the general solution for all the four equations since a constant coefficient
  585. matrix is always commutative with its antidervative.
  586. An additional feature of this function is, if someone wants to substitute for value of the independent
  587. variable, they can pass the substitution `tau` and the solution will have the independent variable
  588. substituted with the passed expression(`tau`).
  589. Parameters
  590. ==========
  591. A : Matrix
  592. Coefficient matrix of the system of linear first order ODEs.
  593. t : Symbol
  594. Independent variable in the system of ODEs.
  595. b : Matrix or None
  596. Non-homogeneous term in the system of ODEs. If None is passed,
  597. a homogeneous system of ODEs is assumed.
  598. B : Matrix or None
  599. Antiderivative of the coefficient matrix. If the antiderivative
  600. is not passed and the solution requires the term, then the solver
  601. would compute it internally.
  602. type : String
  603. Type of the system of ODEs passed. Depending on the type, the
  604. solution is evaluated. The type values allowed and the corresponding
  605. system it solves are: "type1" for constant coefficient homogeneous
  606. "type2" for constant coefficient non-homogeneous, "type3" for non-constant
  607. coefficient homogeneous, "type4" for non-constant coefficient non-homogeneous,
  608. "type5" and "type6" for non-constant coefficient homogeneous and non-homogeneous
  609. systems respectively where the coefficient matrix can be factorized to a constant
  610. coefficient matrix.
  611. The default value is "auto" which will let the solver decide the correct type of
  612. the system passed.
  613. doit : Boolean
  614. Evaluate the solution if True, default value is False
  615. tau: Expression
  616. Used to substitute for the value of `t` after we get the solution of the system.
  617. Examples
  618. ========
  619. To solve the system of ODEs using this function directly, several things must be
  620. done in the right order. Wrong inputs to the function will lead to incorrect results.
  621. >>> from sympy import symbols, Function, Eq
  622. >>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type
  623. >>> from sympy.solvers.ode.subscheck import checkodesol
  624. >>> f, g = symbols("f, g", cls=Function)
  625. >>> x, a = symbols("x, a")
  626. >>> funcs = [f(x), g(x)]
  627. >>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))]
  628. Here, it is important to note that before we derive the coefficient matrix, it is
  629. important to get the system of ODEs into the desired form. For that we will use
  630. :obj:`sympy.solvers.ode.systems.canonical_odes()`.
  631. >>> eqs = canonical_odes(eqs, funcs, x)
  632. >>> eqs
  633. [[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]]
  634. Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the
  635. non-homogeneous term if it is there.
  636. >>> eqs = eqs[0]
  637. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
  638. >>> A = A0
  639. We have the coefficient matrices and the non-homogeneous term ready. Now, we can use
  640. :obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs
  641. to finally pass it to the solver.
  642. >>> system_info = linodesolve_type(A, x, b=b)
  643. >>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type_of_equation'])
  644. Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()`
  645. >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  646. >>> checkodesol(eqs, sol)
  647. (True, [0, 0])
  648. We can also use the doit method to evaluate the solutions passed by the function.
  649. >>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True)
  650. Now, we will look at a system of ODEs which is non-constant.
  651. >>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))]
  652. The system defined above is already in the desired form, so we do not have to convert it.
  653. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
  654. >>> A = A0
  655. A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs.
  656. Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative
  657. with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError.
  658. If it does have a commutative antiderivative, then the function just returns the information about the system.
  659. >>> system_info = linodesolve_type(A, x, b=b)
  660. Now, we can pass the antiderivative as an argument to get the solution. If the system information is not
  661. passed, then the solver will compute the required arguments internally.
  662. >>> sol_vector = linodesolve(A, x, b=b)
  663. Once again, we can verify the solution obtained.
  664. >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  665. >>> checkodesol(eqs, sol)
  666. (True, [0, 0])
  667. Returns
  668. =======
  669. List
  670. Raises
  671. ======
  672. ValueError
  673. This error is raised when the coefficient matrix, non-homogeneous term
  674. or the antiderivative, if passed, aren't a matrix or
  675. do not have correct dimensions
  676. NonSquareMatrixError
  677. When the coefficient matrix or its antiderivative, if passed isn't a square
  678. matrix
  679. NotImplementedError
  680. If the coefficient matrix doesn't have a commutative antiderivative
  681. See Also
  682. ========
  683. linear_ode_to_matrix: Coefficient matrix computation function
  684. canonical_odes: System of ODEs representation change
  685. linodesolve_type: Getting information about systems of ODEs to pass in this solver
  686. """
  687. if not isinstance(A, MatrixBase):
  688. raise ValueError(filldedent('''\
  689. The coefficients of the system of ODEs should be of type Matrix
  690. '''))
  691. if not A.is_square:
  692. raise NonSquareMatrixError(filldedent('''\
  693. The coefficient matrix must be a square
  694. '''))
  695. if b is not None:
  696. if not isinstance(b, MatrixBase):
  697. raise ValueError(filldedent('''\
  698. The non-homogeneous terms of the system of ODEs should be of type Matrix
  699. '''))
  700. if A.rows != b.rows:
  701. raise ValueError(filldedent('''\
  702. The system of ODEs should have the same number of non-homogeneous terms and the number of
  703. equations
  704. '''))
  705. if B is not None:
  706. if not isinstance(B, MatrixBase):
  707. raise ValueError(filldedent('''\
  708. The antiderivative of coefficients of the system of ODEs should be of type Matrix
  709. '''))
  710. if not B.is_square:
  711. raise NonSquareMatrixError(filldedent('''\
  712. The antiderivative of the coefficient matrix must be a square
  713. '''))
  714. if A.rows != B.rows:
  715. raise ValueError(filldedent('''\
  716. The coefficient matrix and its antiderivative should have same dimensions
  717. '''))
  718. if not any(type == "type{}".format(i) for i in range(1, 7)) and not type == "auto":
  719. raise ValueError(filldedent('''\
  720. The input type should be a valid one
  721. '''))
  722. n = A.rows
  723. # constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1)
  724. Cvect = Matrix(list(Dummy() for _ in range(n)))
  725. if any(type == typ for typ in ["type2", "type4", "type6"]) and b is None:
  726. b = zeros(n, 1)
  727. is_transformed = tau is not None
  728. passed_type = type
  729. if type == "auto":
  730. system_info = linodesolve_type(A, t, b=b)
  731. type = system_info["type_of_equation"]
  732. B = system_info["antiderivative"]
  733. if type in ("type5", "type6"):
  734. is_transformed = True
  735. if passed_type != "auto":
  736. if tau is None:
  737. system_info = _first_order_type5_6_subs(A, t, b=b)
  738. if not system_info:
  739. raise ValueError(filldedent('''
  740. The system passed isn't {}.
  741. '''.format(type)))
  742. tau = system_info['tau']
  743. t = system_info['t_']
  744. A = system_info['A']
  745. b = system_info['b']
  746. if type in ("type1", "type2", "type5", "type6"):
  747. P, J = matrix_exp_jordan_form(A, t)
  748. P = simplify(P)
  749. if type in ("type1", "type5"):
  750. sol_vector = P * (J * Cvect)
  751. else:
  752. Jinv = J.subs(t, -t)
  753. sol_vector = P * J * ((Jinv * P.inv() * b).applyfunc(lambda x: Integral(x, t)) + Cvect)
  754. else:
  755. if B is None:
  756. B, _ = _is_commutative_anti_derivative(A, t)
  757. if type == "type3":
  758. sol_vector = B.exp() * Cvect
  759. else:
  760. sol_vector = B.exp() * (((-B).exp() * b).applyfunc(lambda x: Integral(x, t)) + Cvect)
  761. if is_transformed:
  762. sol_vector = sol_vector.subs(t, tau)
  763. gens = sol_vector.atoms(exp)
  764. if type != "type1":
  765. sol_vector = [expand_mul(s) for s in sol_vector]
  766. sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector]
  767. if doit:
  768. sol_vector = [s.doit() for s in sol_vector]
  769. return sol_vector
  770. def _matrix_is_constant(M, t):
  771. """Checks if the matrix M is independent of t or not."""
  772. return all(coef.as_independent(t, as_Add=True)[1] == 0 for coef in M)
  773. def canonical_odes(eqs, funcs, t):
  774. r"""
  775. Function that solves for highest order derivatives in a system
  776. Explanation
  777. ===========
  778. This function inputs a system of ODEs and based on the system,
  779. the dependent variables and their highest order, returns the system
  780. in the following form:
  781. .. math::
  782. X'(t) = A(t) X(t) + b(t)
  783. Here, $X(t)$ is the vector of dependent variables of lower order, $A(t)$ is
  784. the coefficient matrix, $b(t)$ is the non-homogeneous term and $X'(t)$ is the
  785. vector of dependent variables in their respective highest order. We use the term
  786. canonical form to imply the system of ODEs which is of the above form.
  787. If the system passed has a non-linear term with multiple solutions, then a list of
  788. systems is returned in its canonical form.
  789. Parameters
  790. ==========
  791. eqs : List
  792. List of the ODEs
  793. funcs : List
  794. List of dependent variables
  795. t : Symbol
  796. Independent variable
  797. Examples
  798. ========
  799. >>> from sympy import symbols, Function, Eq, Derivative
  800. >>> from sympy.solvers.ode.systems import canonical_odes
  801. >>> f, g = symbols("f g", cls=Function)
  802. >>> x, y = symbols("x y")
  803. >>> funcs = [f(x), g(x)]
  804. >>> eqs = [Eq(f(x).diff(x) - 7*f(x), 12*g(x)), Eq(g(x).diff(x) + g(x), 20*f(x))]
  805. >>> canonical_eqs = canonical_odes(eqs, funcs, x)
  806. >>> canonical_eqs
  807. [[Eq(Derivative(f(x), x), 7*f(x) + 12*g(x)), Eq(Derivative(g(x), x), 20*f(x) - g(x))]]
  808. >>> system = [Eq(Derivative(f(x), x)**2 - 2*Derivative(f(x), x) + 1, 4), Eq(-y*f(x) + Derivative(g(x), x), 0)]
  809. >>> canonical_system = canonical_odes(system, funcs, x)
  810. >>> canonical_system
  811. [[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))]]
  812. Returns
  813. =======
  814. List
  815. """
  816. from sympy.solvers.solvers import solve
  817. order = _get_func_order(eqs, funcs)
  818. canon_eqs = solve(eqs, *[func.diff(t, order[func]) for func in funcs], dict=True)
  819. systems = []
  820. for eq in canon_eqs:
  821. system = [Eq(func.diff(t, order[func]), eq[func.diff(t, order[func])]) for func in funcs]
  822. systems.append(system)
  823. return systems
  824. def _is_commutative_anti_derivative(A, t):
  825. r"""
  826. Helper function for determining if the Matrix passed is commutative with its antiderivative
  827. Explanation
  828. ===========
  829. This function checks if the Matrix $A$ passed is commutative with its antiderivative with respect
  830. to the independent variable $t$.
  831. .. math::
  832. B(t) = \int A(t) dt
  833. The function outputs two values, first one being the antiderivative $B(t)$, second one being a
  834. boolean value, if True, then the matrix $A(t)$ passed is commutative with $B(t)$, else the matrix
  835. passed isn't commutative with $B(t)$.
  836. Parameters
  837. ==========
  838. A : Matrix
  839. The matrix which has to be checked
  840. t : Symbol
  841. Independent variable
  842. Examples
  843. ========
  844. >>> from sympy import symbols, Matrix
  845. >>> from sympy.solvers.ode.systems import _is_commutative_anti_derivative
  846. >>> t = symbols("t")
  847. >>> A = Matrix([[1, t], [-t, 1]])
  848. >>> B, is_commuting = _is_commutative_anti_derivative(A, t)
  849. >>> is_commuting
  850. True
  851. Returns
  852. =======
  853. Matrix, Boolean
  854. """
  855. B = integrate(A, t)
  856. is_commuting = (B*A - A*B).applyfunc(expand).applyfunc(factor_terms).is_zero_matrix
  857. is_commuting = False if is_commuting is None else is_commuting
  858. return B, is_commuting
  859. def _factor_matrix(A, t):
  860. term = None
  861. for element in A:
  862. temp_term = element.as_independent(t)[1]
  863. if temp_term.has(t):
  864. term = temp_term
  865. break
  866. if term is not None:
  867. A_factored = (A/term).applyfunc(ratsimp)
  868. can_factor = _matrix_is_constant(A_factored, t)
  869. term = (term, A_factored) if can_factor else None
  870. return term
  871. def _is_second_order_type2(A, t):
  872. term = _factor_matrix(A, t)
  873. is_type2 = False
  874. if term is not None:
  875. term = 1/term[0]
  876. is_type2 = term.is_polynomial()
  877. if is_type2:
  878. poly = Poly(term.expand(), t)
  879. monoms = poly.monoms()
  880. if monoms[0][0] in (2, 4):
  881. cs = _get_poly_coeffs(poly, 4)
  882. a, b, c, d, e = cs
  883. a1 = powdenest(sqrt(a), force=True)
  884. c1 = powdenest(sqrt(e), force=True)
  885. b1 = powdenest(sqrt(c - 2*a1*c1), force=True)
  886. is_type2 = (b == 2*a1*b1) and (d == 2*b1*c1)
  887. term = a1*t**2 + b1*t + c1
  888. else:
  889. is_type2 = False
  890. return is_type2, term
  891. def _get_poly_coeffs(poly, order):
  892. cs = [0 for _ in range(order+1)]
  893. for c, m in zip(poly.coeffs(), poly.monoms()):
  894. cs[-1-m[0]] = c
  895. return cs
  896. def _match_second_order_type(A1, A0, t, b=None):
  897. r"""
  898. Works only for second order system in its canonical form.
  899. Type 0: Constant coefficient matrix, can be simply solved by
  900. introducing dummy variables.
  901. Type 1: When the substitution: $U = t*X' - X$ works for reducing
  902. the second order system to first order system.
  903. Type 2: When the system is of the form: $poly * X'' = A*X$ where
  904. $poly$ is square of a quadratic polynomial with respect to
  905. *t* and $A$ is a constant coefficient matrix.
  906. """
  907. match = {"type_of_equation": "type0"}
  908. n = A1.shape[0]
  909. if _matrix_is_constant(A1, t) and _matrix_is_constant(A0, t):
  910. return match
  911. if (A1 + A0*t).applyfunc(expand_mul).is_zero_matrix:
  912. match.update({"type_of_equation": "type1", "A1": A1})
  913. elif A1.is_zero_matrix and (b is None or b.is_zero_matrix):
  914. is_type2, term = _is_second_order_type2(A0, t)
  915. if is_type2:
  916. a, b, c = _get_poly_coeffs(Poly(term, t), 2)
  917. A = (A0*(term**2).expand()).applyfunc(ratsimp) + (b**2/4 - a*c)*eye(n, n)
  918. tau = integrate(1/term, t)
  919. t_ = Symbol("{}_".format(t))
  920. match.update({"type_of_equation": "type2", "A0": A,
  921. "g(t)": sqrt(term), "tau": tau, "is_transformed": True,
  922. "t_": t_})
  923. return match
  924. def _second_order_subs_type1(A, b, funcs, t):
  925. r"""
  926. For a linear, second order system of ODEs, a particular substitution.
  927. A system of the below form can be reduced to a linear first order system of
  928. ODEs:
  929. .. math::
  930. X'' = A(t) * (t*X' - X) + b(t)
  931. By substituting:
  932. .. math:: U = t*X' - X
  933. To get the system:
  934. .. math:: U' = t*(A(t)*U + b(t))
  935. Where $U$ is the vector of dependent variables, $X$ is the vector of dependent
  936. variables in `funcs` and $X'$ is the first order derivative of $X$ with respect to
  937. $t$. It may or may not reduce the system into linear first order system of ODEs.
  938. Then a check is made to determine if the system passed can be reduced or not, if
  939. this substitution works, then the system is reduced and its solved for the new
  940. substitution. After we get the solution for $U$:
  941. .. math:: U = a(t)
  942. We substitute and return the reduced system:
  943. .. math::
  944. a(t) = t*X' - X
  945. Parameters
  946. ==========
  947. A: Matrix
  948. Coefficient matrix($A(t)*t$) of the second order system of this form.
  949. b: Matrix
  950. Non-homogeneous term($b(t)$) of the system of ODEs.
  951. funcs: List
  952. List of dependent variables
  953. t: Symbol
  954. Independent variable of the system of ODEs.
  955. Returns
  956. =======
  957. List
  958. """
  959. U = Matrix([t*func.diff(t) - func for func in funcs])
  960. sol = linodesolve(A, t, t*b)
  961. reduced_eqs = [Eq(u, s) for s, u in zip(sol, U)]
  962. reduced_eqs = canonical_odes(reduced_eqs, funcs, t)[0]
  963. return reduced_eqs
  964. def _second_order_subs_type2(A, funcs, t_):
  965. r"""
  966. Returns a second order system based on the coefficient matrix passed.
  967. Explanation
  968. ===========
  969. This function returns a system of second order ODE of the following form:
  970. .. math::
  971. X'' = A * X
  972. Here, $X$ is the vector of dependent variables, but a bit modified, $A$ is the
  973. coefficient matrix passed.
  974. Along with returning the second order system, this function also returns the new
  975. dependent variables with the new independent variable `t_` passed.
  976. Parameters
  977. ==========
  978. A: Matrix
  979. Coefficient matrix of the system
  980. funcs: List
  981. List of old dependent variables
  982. t_: Symbol
  983. New independent variable
  984. Returns
  985. =======
  986. List, List
  987. """
  988. func_names = [func.func.__name__ for func in funcs]
  989. new_funcs = [Function(Dummy("{}_".format(name)))(t_) for name in func_names]
  990. rhss = A * Matrix(new_funcs)
  991. new_eqs = [Eq(func.diff(t_, 2), rhs) for func, rhs in zip(new_funcs, rhss)]
  992. return new_eqs, new_funcs
  993. def _is_euler_system(As, t):
  994. return all(_matrix_is_constant((A*t**i).applyfunc(ratsimp), t) for i, A in enumerate(As))
  995. def _classify_linear_system(eqs, funcs, t, is_canon=False):
  996. r"""
  997. Returns a dictionary with details of the eqs if the system passed is linear
  998. and can be classified by this function else returns None
  999. Explanation
  1000. ===========
  1001. This function takes the eqs, converts it into a form Ax = b where x is a vector of terms
  1002. containing dependent variables and their derivatives till their maximum order. If it is
  1003. possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise
  1004. they are non-linear.
  1005. To check if the equations are constant coefficient, we need to check if all the terms in
  1006. A obtained above are constant or not.
  1007. To check if the equations are homogeneous or not, we need to check if b is a zero matrix
  1008. or not.
  1009. Parameters
  1010. ==========
  1011. eqs: List
  1012. List of ODEs
  1013. funcs: List
  1014. List of dependent variables
  1015. t: Symbol
  1016. Independent variable of the equations in eqs
  1017. is_canon: Boolean
  1018. If True, then this function will not try to get the
  1019. system in canonical form. Default value is False
  1020. Returns
  1021. =======
  1022. match = {
  1023. 'no_of_equation': len(eqs),
  1024. 'eq': eqs,
  1025. 'func': funcs,
  1026. 'order': order,
  1027. 'is_linear': is_linear,
  1028. 'is_constant': is_constant,
  1029. 'is_homogeneous': is_homogeneous,
  1030. }
  1031. Dict or list of Dicts or None
  1032. Dict with values for keys:
  1033. 1. no_of_equation: Number of equations
  1034. 2. eq: The set of equations
  1035. 3. func: List of dependent variables
  1036. 4. order: A dictionary that gives the order of the
  1037. dependent variable in eqs
  1038. 5. is_linear: Boolean value indicating if the set of
  1039. equations are linear or not.
  1040. 6. is_constant: Boolean value indicating if the set of
  1041. equations have constant coefficients or not.
  1042. 7. is_homogeneous: Boolean value indicating if the set of
  1043. equations are homogeneous or not.
  1044. 8. commutative_antiderivative: Antiderivative of the coefficient
  1045. matrix if the coefficient matrix is non-constant
  1046. and commutative with its antiderivative. This key
  1047. may or may not exist.
  1048. 9. is_general: Boolean value indicating if the system of ODEs is
  1049. solvable using one of the general case solvers or not.
  1050. 10. rhs: rhs of the non-homogeneous system of ODEs in Matrix form. This
  1051. key may or may not exist.
  1052. 11. is_higher_order: True if the system passed has an order greater than 1.
  1053. This key may or may not exist.
  1054. 12. is_second_order: True if the system passed is a second order ODE. This
  1055. key may or may not exist.
  1056. This Dict is the answer returned if the eqs are linear and constant
  1057. coefficient. Otherwise, None is returned.
  1058. """
  1059. # Error for i == 0 can be added but isn't for now
  1060. # Check for len(funcs) == len(eqs)
  1061. if len(funcs) != len(eqs):
  1062. raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs)
  1063. # ValueError when functions have more than one arguments
  1064. for func in funcs:
  1065. if len(func.args) != 1:
  1066. raise ValueError("dsolve() and classify_sysode() work with "
  1067. "functions of one variable only, not %s" % func)
  1068. # Getting the func_dict and order using the helper
  1069. # function
  1070. order = _get_func_order(eqs, funcs)
  1071. system_order = max(order[func] for func in funcs)
  1072. is_higher_order = system_order > 1
  1073. is_second_order = system_order == 2 and all(order[func] == 2 for func in funcs)
  1074. # Not adding the check if the len(func.args) for
  1075. # every func in funcs is 1
  1076. # Linearity check
  1077. try:
  1078. canon_eqs = canonical_odes(eqs, funcs, t) if not is_canon else [eqs]
  1079. if len(canon_eqs) == 1:
  1080. As, b = linear_ode_to_matrix(canon_eqs[0], funcs, t, system_order)
  1081. else:
  1082. match = {
  1083. 'is_implicit': True,
  1084. 'canon_eqs': canon_eqs
  1085. }
  1086. return match
  1087. # When the system of ODEs is non-linear, an ODENonlinearError is raised.
  1088. # This function catches the error and None is returned.
  1089. except ODENonlinearError:
  1090. return None
  1091. is_linear = True
  1092. # Homogeneous check
  1093. is_homogeneous = True if b.is_zero_matrix else False
  1094. # Is general key is used to identify if the system of ODEs can be solved by
  1095. # one of the general case solvers or not.
  1096. match = {
  1097. 'no_of_equation': len(eqs),
  1098. 'eq': eqs,
  1099. 'func': funcs,
  1100. 'order': order,
  1101. 'is_linear': is_linear,
  1102. 'is_homogeneous': is_homogeneous,
  1103. 'is_general': True
  1104. }
  1105. if not is_homogeneous:
  1106. match['rhs'] = b
  1107. is_constant = all(_matrix_is_constant(A_, t) for A_ in As)
  1108. # The match['is_linear'] check will be added in the future when this
  1109. # function becomes ready to deal with non-linear systems of ODEs
  1110. if not is_higher_order:
  1111. A = As[1]
  1112. match['func_coeff'] = A
  1113. # Constant coefficient check
  1114. is_constant = _matrix_is_constant(A, t)
  1115. match['is_constant'] = is_constant
  1116. try:
  1117. system_info = linodesolve_type(A, t, b=b)
  1118. except NotImplementedError:
  1119. return None
  1120. match.update(system_info)
  1121. antiderivative = match.pop("antiderivative")
  1122. if not is_constant:
  1123. match['commutative_antiderivative'] = antiderivative
  1124. return match
  1125. else:
  1126. match['type_of_equation'] = "type0"
  1127. if is_second_order:
  1128. A1, A0 = As[1:]
  1129. match_second_order = _match_second_order_type(A1, A0, t)
  1130. match.update(match_second_order)
  1131. match['is_second_order'] = True
  1132. # If system is constant, then no need to check if its in euler
  1133. # form or not. It will be easier and faster to directly proceed
  1134. # to solve it.
  1135. if match['type_of_equation'] == "type0" and not is_constant:
  1136. is_euler = _is_euler_system(As, t)
  1137. if is_euler:
  1138. t_ = Symbol('{}_'.format(t))
  1139. match.update({'is_transformed': True, 'type_of_equation': 'type1',
  1140. 't_': t_})
  1141. else:
  1142. is_jordan = lambda M: M == Matrix.jordan_block(M.shape[0], M[0, 0])
  1143. terms = _factor_matrix(As[-1], t)
  1144. if all(A.is_zero_matrix for A in As[1:-1]) and terms is not None and not is_jordan(terms[1]):
  1145. P, J = terms[1].jordan_form()
  1146. match.update({'type_of_equation': 'type2', 'J': J,
  1147. 'f(t)': terms[0], 'P': P, 'is_transformed': True})
  1148. if match['type_of_equation'] != 'type0' and is_second_order:
  1149. match.pop('is_second_order', None)
  1150. match['is_higher_order'] = is_higher_order
  1151. return match
  1152. def _preprocess_eqs(eqs):
  1153. processed_eqs = []
  1154. for eq in eqs:
  1155. processed_eqs.append(eq if isinstance(eq, Equality) else Eq(eq, 0))
  1156. return processed_eqs
  1157. def _eqs2dict(eqs, funcs):
  1158. eqsorig = {}
  1159. eqsmap = {}
  1160. funcset = set(funcs)
  1161. for eq in eqs:
  1162. f1, = eq.lhs.atoms(AppliedUndef)
  1163. f2s = (eq.rhs.atoms(AppliedUndef) - {f1}) & funcset
  1164. eqsmap[f1] = f2s
  1165. eqsorig[f1] = eq
  1166. return eqsmap, eqsorig
  1167. def _dict2graph(d):
  1168. nodes = list(d)
  1169. edges = [(f1, f2) for f1, f2s in d.items() for f2 in f2s]
  1170. G = (nodes, edges)
  1171. return G
  1172. def _is_type1(scc, t):
  1173. eqs, funcs = scc
  1174. try:
  1175. (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 1)
  1176. except (ODENonlinearError, ODEOrderError):
  1177. return False
  1178. if _matrix_is_constant(A0, t) and b.is_zero_matrix:
  1179. return True
  1180. return False
  1181. def _combine_type1_subsystems(subsystem, funcs, t):
  1182. indices = [i for i, sys in enumerate(zip(subsystem, funcs)) if _is_type1(sys, t)]
  1183. remove = set()
  1184. for ip, i in enumerate(indices):
  1185. for j in indices[ip+1:]:
  1186. if any(eq2.has(funcs[i]) for eq2 in subsystem[j]):
  1187. subsystem[j] = subsystem[i] + subsystem[j]
  1188. remove.add(i)
  1189. subsystem = [sys for i, sys in enumerate(subsystem) if i not in remove]
  1190. return subsystem
  1191. def _component_division(eqs, funcs, t):
  1192. # Assuming that each eq in eqs is in canonical form,
  1193. # that is, [f(x).diff(x) = .., g(x).diff(x) = .., etc]
  1194. # and that the system passed is in its first order
  1195. eqsmap, eqsorig = _eqs2dict(eqs, funcs)
  1196. subsystems = []
  1197. for cc in connected_components(_dict2graph(eqsmap)):
  1198. eqsmap_c = {f: eqsmap[f] for f in cc}
  1199. sccs = strongly_connected_components(_dict2graph(eqsmap_c))
  1200. subsystem = [[eqsorig[f] for f in scc] for scc in sccs]
  1201. subsystem = _combine_type1_subsystems(subsystem, sccs, t)
  1202. subsystems.append(subsystem)
  1203. return subsystems
  1204. # Returns: List of equations
  1205. def _linear_ode_solver(match):
  1206. t = match['t']
  1207. funcs = match['func']
  1208. rhs = match.get('rhs', None)
  1209. tau = match.get('tau', None)
  1210. t = match['t_'] if 't_' in match else t
  1211. A = match['func_coeff']
  1212. # Note: To make B None when the matrix has constant
  1213. # coefficient
  1214. B = match.get('commutative_antiderivative', None)
  1215. type = match['type_of_equation']
  1216. sol_vector = linodesolve(A, t, b=rhs, B=B,
  1217. type=type, tau=tau)
  1218. sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  1219. return sol
  1220. def _select_equations(eqs, funcs, key=lambda x: x):
  1221. eq_dict = {e.lhs: e.rhs for e in eqs}
  1222. return [Eq(f, eq_dict[key(f)]) for f in funcs]
  1223. def _higher_order_ode_solver(match):
  1224. eqs = match["eq"]
  1225. funcs = match["func"]
  1226. t = match["t"]
  1227. sysorder = match['order']
  1228. type = match.get('type_of_equation', "type0")
  1229. is_second_order = match.get('is_second_order', False)
  1230. is_transformed = match.get('is_transformed', False)
  1231. is_euler = is_transformed and type == "type1"
  1232. is_higher_order_type2 = is_transformed and type == "type2" and 'P' in match
  1233. if is_second_order:
  1234. new_eqs, new_funcs = _second_order_to_first_order(eqs, funcs, t,
  1235. A1=match.get("A1", None), A0=match.get("A0", None),
  1236. b=match.get("rhs", None), type=type,
  1237. t_=match.get("t_", None))
  1238. else:
  1239. new_eqs, new_funcs = _higher_order_to_first_order(eqs, sysorder, t, funcs=funcs,
  1240. type=type, J=match.get('J', None),
  1241. f_t=match.get('f(t)', None),
  1242. P=match.get('P', None), b=match.get('rhs', None))
  1243. if is_transformed:
  1244. t = match.get('t_', t)
  1245. if not is_higher_order_type2:
  1246. new_eqs = _select_equations(new_eqs, [f.diff(t) for f in new_funcs])
  1247. sol = None
  1248. # NotImplementedError may be raised when the system may be actually
  1249. # solvable if it can be just divided into sub-systems
  1250. try:
  1251. if not is_higher_order_type2:
  1252. sol = _strong_component_solver(new_eqs, new_funcs, t)
  1253. except NotImplementedError:
  1254. sol = None
  1255. # Dividing the system only when it becomes essential
  1256. if sol is None:
  1257. try:
  1258. sol = _component_solver(new_eqs, new_funcs, t)
  1259. except NotImplementedError:
  1260. sol = None
  1261. if sol is None:
  1262. return sol
  1263. is_second_order_type2 = is_second_order and type == "type2"
  1264. underscores = '__' if is_transformed else '_'
  1265. sol = _select_equations(sol, funcs,
  1266. key=lambda x: Function(Dummy('{}{}0'.format(x.func.__name__, underscores)))(t))
  1267. if match.get("is_transformed", False):
  1268. if is_second_order_type2:
  1269. g_t = match["g(t)"]
  1270. tau = match["tau"]
  1271. sol = [Eq(s.lhs, s.rhs.subs(t, tau) * g_t) for s in sol]
  1272. elif is_euler:
  1273. t = match['t']
  1274. tau = match['t_']
  1275. sol = [s.subs(tau, log(t)) for s in sol]
  1276. elif is_higher_order_type2:
  1277. P = match['P']
  1278. sol_vector = P * Matrix([s.rhs for s in sol])
  1279. sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
  1280. return sol
  1281. # Returns: List of equations or None
  1282. # If None is returned by this solver, then the system
  1283. # of ODEs cannot be solved directly by dsolve_system.
  1284. def _strong_component_solver(eqs, funcs, t):
  1285. from sympy.solvers.ode.ode import dsolve, constant_renumber
  1286. match = _classify_linear_system(eqs, funcs, t, is_canon=True)
  1287. sol = None
  1288. # Assuming that we can't get an implicit system
  1289. # since we are already canonical equations from
  1290. # dsolve_system
  1291. if match:
  1292. match['t'] = t
  1293. if match.get('is_higher_order', False):
  1294. sol = _higher_order_ode_solver(match)
  1295. elif match.get('is_linear', False):
  1296. sol = _linear_ode_solver(match)
  1297. # Note: For now, only linear systems are handled by this function
  1298. # hence, the match condition is added. This can be removed later.
  1299. if sol is None and len(eqs) == 1:
  1300. sol = dsolve(eqs[0], func=funcs[0])
  1301. variables = Tuple(eqs[0]).free_symbols
  1302. new_constants = [Dummy() for _ in range(ode_order(eqs[0], funcs[0]))]
  1303. sol = constant_renumber(sol, variables=variables, newconstants=new_constants)
  1304. sol = [sol]
  1305. # To add non-linear case here in future
  1306. return sol
  1307. def _get_funcs_from_canon(eqs):
  1308. return [eq.lhs.args[0] for eq in eqs]
  1309. # Returns: List of Equations(a solution)
  1310. def _weak_component_solver(wcc, t):
  1311. # We will divide the systems into sccs
  1312. # only when the wcc cannot be solved as
  1313. # a whole
  1314. eqs = []
  1315. for scc in wcc:
  1316. eqs += scc
  1317. funcs = _get_funcs_from_canon(eqs)
  1318. sol = _strong_component_solver(eqs, funcs, t)
  1319. if sol:
  1320. return sol
  1321. sol = []
  1322. for j, scc in enumerate(wcc):
  1323. eqs = scc
  1324. funcs = _get_funcs_from_canon(eqs)
  1325. # Substituting solutions for the dependent
  1326. # variables solved in previous SCC, if any solved.
  1327. comp_eqs = [eq.subs({s.lhs: s.rhs for s in sol}) for eq in eqs]
  1328. scc_sol = _strong_component_solver(comp_eqs, funcs, t)
  1329. if scc_sol is None:
  1330. raise NotImplementedError(filldedent('''
  1331. The system of ODEs passed cannot be solved by dsolve_system.
  1332. '''))
  1333. # scc_sol: List of equations
  1334. # scc_sol is a solution
  1335. sol += scc_sol
  1336. return sol
  1337. # Returns: List of Equations(a solution)
  1338. def _component_solver(eqs, funcs, t):
  1339. components = _component_division(eqs, funcs, t)
  1340. sol = []
  1341. for wcc in components:
  1342. # wcc_sol: List of Equations
  1343. sol += _weak_component_solver(wcc, t)
  1344. # sol: List of Equations
  1345. return sol
  1346. def _second_order_to_first_order(eqs, funcs, t, type="auto", A1=None,
  1347. A0=None, b=None, t_=None):
  1348. r"""
  1349. Expects the system to be in second order and in canonical form
  1350. Explanation
  1351. ===========
  1352. Reduces a second order system into a first order one depending on the type of second
  1353. order system.
  1354. 1. "type0": If this is passed, then the system will be reduced to first order by
  1355. introducing dummy variables.
  1356. 2. "type1": If this is passed, then a particular substitution will be used to reduce the
  1357. the system into first order.
  1358. 3. "type2": If this is passed, then the system will be transformed with new dependent
  1359. variables and independent variables. This transformation is a part of solving
  1360. the corresponding system of ODEs.
  1361. `A1` and `A0` are the coefficient matrices from the system and it is assumed that the
  1362. second order system has the form given below:
  1363. .. math::
  1364. A2 * X'' = A1 * X' + A0 * X + b
  1365. Here, $A2$ is the coefficient matrix for the vector $X''$ and $b$ is the non-homogeneous
  1366. term.
  1367. Default value for `b` is None but if `A1` and `A0` are passed and `b` isn't passed, then the
  1368. system will be assumed homogeneous.
  1369. """
  1370. is_a1 = A1 is None
  1371. is_a0 = A0 is None
  1372. if (type == "type1" and is_a1) or (type == "type2" and is_a0)\
  1373. or (type == "auto" and (is_a1 or is_a0)):
  1374. (A2, A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 2)
  1375. if not A2.is_Identity:
  1376. raise ValueError(filldedent('''
  1377. The system must be in its canonical form.
  1378. '''))
  1379. if type == "auto":
  1380. match = _match_second_order_type(A1, A0, t)
  1381. type = match["type_of_equation"]
  1382. A1 = match.get("A1", None)
  1383. A0 = match.get("A0", None)
  1384. sys_order = {func: 2 for func in funcs}
  1385. if type == "type1":
  1386. if b is None:
  1387. b = zeros(len(eqs))
  1388. eqs = _second_order_subs_type1(A1, b, funcs, t)
  1389. sys_order = {func: 1 for func in funcs}
  1390. if type == "type2":
  1391. if t_ is None:
  1392. t_ = Symbol("{}_".format(t))
  1393. t = t_
  1394. eqs, funcs = _second_order_subs_type2(A0, funcs, t_)
  1395. sys_order = {func: 2 for func in funcs}
  1396. return _higher_order_to_first_order(eqs, sys_order, t, funcs=funcs)
  1397. def _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, b=None, P=None):
  1398. # Note: To add a test for this ValueError
  1399. if J is None or f_t is None or not _matrix_is_constant(J, t):
  1400. raise ValueError(filldedent('''
  1401. Correctly input for args 'A' and 'f_t' for Linear, Higher Order,
  1402. Type 2
  1403. '''))
  1404. if P is None and b is not None and not b.is_zero_matrix:
  1405. raise ValueError(filldedent('''
  1406. Provide the keyword 'P' for matrix P in A = P * J * P-1.
  1407. '''))
  1408. new_funcs = Matrix([Function(Dummy('{}__0'.format(f.func.__name__)))(t) for f in funcs])
  1409. new_eqs = new_funcs.diff(t, max_order) - f_t * J * new_funcs
  1410. if b is not None and not b.is_zero_matrix:
  1411. new_eqs -= P.inv() * b
  1412. new_eqs = canonical_odes(new_eqs, new_funcs, t)[0]
  1413. return new_eqs, new_funcs
  1414. def _higher_order_to_first_order(eqs, sys_order, t, funcs=None, type="type0", **kwargs):
  1415. if funcs is None:
  1416. funcs = sys_order.keys()
  1417. # Standard Cauchy Euler system
  1418. if type == "type1":
  1419. t_ = Symbol('{}_'.format(t))
  1420. new_funcs = [Function(Dummy('{}_'.format(f.func.__name__)))(t_) for f in funcs]
  1421. max_order = max(sys_order[func] for func in funcs)
  1422. subs_dict = {func: new_func for func, new_func in zip(funcs, new_funcs)}
  1423. subs_dict[t] = exp(t_)
  1424. free_function = Function(Dummy())
  1425. def _get_coeffs_from_subs_expression(expr):
  1426. if isinstance(expr, Subs):
  1427. free_symbol = expr.args[1][0]
  1428. term = expr.args[0]
  1429. return {ode_order(term, free_symbol): 1}
  1430. if isinstance(expr, Mul):
  1431. coeff = expr.args[0]
  1432. order = list(_get_coeffs_from_subs_expression(expr.args[1]).keys())[0]
  1433. return {order: coeff}
  1434. if isinstance(expr, Add):
  1435. coeffs = {}
  1436. for arg in expr.args:
  1437. if isinstance(arg, Mul):
  1438. coeffs.update(_get_coeffs_from_subs_expression(arg))
  1439. else:
  1440. order = list(_get_coeffs_from_subs_expression(arg).keys())[0]
  1441. coeffs[order] = 1
  1442. return coeffs
  1443. for o in range(1, max_order + 1):
  1444. expr = free_function(log(t_)).diff(t_, o)*t_**o
  1445. coeff_dict = _get_coeffs_from_subs_expression(expr)
  1446. coeffs = [coeff_dict[order] if order in coeff_dict else 0 for order in range(o + 1)]
  1447. expr_to_subs = sum(free_function(t_).diff(t_, i) * c for i, c in
  1448. enumerate(coeffs)) / t**o
  1449. subs_dict.update({f.diff(t, o): expr_to_subs.subs(free_function(t_), nf)
  1450. for f, nf in zip(funcs, new_funcs)})
  1451. new_eqs = [eq.subs(subs_dict) for eq in eqs]
  1452. new_sys_order = {nf: sys_order[f] for f, nf in zip(funcs, new_funcs)}
  1453. new_eqs = canonical_odes(new_eqs, new_funcs, t_)[0]
  1454. return _higher_order_to_first_order(new_eqs, new_sys_order, t_, funcs=new_funcs)
  1455. # Systems of the form: X(n)(t) = f(t)*A*X + b
  1456. # where X(n)(t) is the nth derivative of the vector of dependent variables
  1457. # with respect to the independent variable and A is a constant matrix.
  1458. if type == "type2":
  1459. J = kwargs.get('J', None)
  1460. f_t = kwargs.get('f_t', None)
  1461. b = kwargs.get('b', None)
  1462. P = kwargs.get('P', None)
  1463. max_order = max(sys_order[func] for func in funcs)
  1464. return _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, P=P, b=b)
  1465. # Note: To be changed to this after doit option is disabled for default cases
  1466. # new_sysorder = _get_func_order(new_eqs, new_funcs)
  1467. #
  1468. # return _higher_order_to_first_order(new_eqs, new_sysorder, t, funcs=new_funcs)
  1469. new_funcs = []
  1470. for prev_func in funcs:
  1471. func_name = prev_func.func.__name__
  1472. func = Function(Dummy('{}_0'.format(func_name)))(t)
  1473. new_funcs.append(func)
  1474. subs_dict = {prev_func: func}
  1475. new_eqs = []
  1476. for i in range(1, sys_order[prev_func]):
  1477. new_func = Function(Dummy('{}_{}'.format(func_name, i)))(t)
  1478. subs_dict[prev_func.diff(t, i)] = new_func
  1479. new_funcs.append(new_func)
  1480. prev_f = subs_dict[prev_func.diff(t, i-1)]
  1481. new_eq = Eq(prev_f.diff(t), new_func)
  1482. new_eqs.append(new_eq)
  1483. eqs = [eq.subs(subs_dict) for eq in eqs] + new_eqs
  1484. return eqs, new_funcs
  1485. def dsolve_system(eqs, funcs=None, t=None, ics=None, doit=False, simplify=True):
  1486. r"""
  1487. Solves any(supported) system of Ordinary Differential Equations
  1488. Explanation
  1489. ===========
  1490. This function takes a system of ODEs as an input, determines if the
  1491. it is solvable by this function, and returns the solution if found any.
  1492. This function can handle:
  1493. 1. Linear, First Order, Constant coefficient homogeneous system of ODEs
  1494. 2. Linear, First Order, Constant coefficient non-homogeneous system of ODEs
  1495. 3. Linear, First Order, non-constant coefficient homogeneous system of ODEs
  1496. 4. Linear, First Order, non-constant coefficient non-homogeneous system of ODEs
  1497. 5. Any implicit system which can be divided into system of ODEs which is of the above 4 forms
  1498. 6. Any higher order linear system of ODEs that can be reduced to one of the 5 forms of systems described above.
  1499. The types of systems described above aren't limited by the number of equations, i.e. this
  1500. function can solve the above types irrespective of the number of equations in the system passed.
  1501. But, the bigger the system, the more time it will take to solve the system.
  1502. This function returns a list of solutions. Each solution is a list of equations where LHS is
  1503. the dependent variable and RHS is an expression in terms of the independent variable.
  1504. Among the non constant coefficient types, not all the systems are solvable by this function. Only
  1505. those which have either a coefficient matrix with a commutative antiderivative or those systems which
  1506. may be divided further so that the divided systems may have coefficient matrix with commutative antiderivative.
  1507. Parameters
  1508. ==========
  1509. eqs : List
  1510. system of ODEs to be solved
  1511. funcs : List or None
  1512. List of dependent variables that make up the system of ODEs
  1513. t : Symbol or None
  1514. Independent variable in the system of ODEs
  1515. ics : Dict or None
  1516. Set of initial boundary/conditions for the system of ODEs
  1517. doit : Boolean
  1518. Evaluate the solutions if True. Default value is True. Can be
  1519. set to false if the integral evaluation takes too much time and/or
  1520. isn't required.
  1521. simplify: Boolean
  1522. Simplify the solutions for the systems. Default value is True.
  1523. Can be set to false if simplification takes too much time and/or
  1524. isn't required.
  1525. Examples
  1526. ========
  1527. >>> from sympy import symbols, Eq, Function
  1528. >>> from sympy.solvers.ode.systems import dsolve_system
  1529. >>> f, g = symbols("f g", cls=Function)
  1530. >>> x = symbols("x")
  1531. >>> eqs = [Eq(f(x).diff(x), g(x)), Eq(g(x).diff(x), f(x))]
  1532. >>> dsolve_system(eqs)
  1533. [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
  1534. You can also pass the initial conditions for the system of ODEs:
  1535. >>> dsolve_system(eqs, ics={f(0): 1, g(0): 0})
  1536. [[Eq(f(x), exp(x)/2 + exp(-x)/2), Eq(g(x), exp(x)/2 - exp(-x)/2)]]
  1537. Optionally, you can pass the dependent variables and the independent
  1538. variable for which the system is to be solved:
  1539. >>> funcs = [f(x), g(x)]
  1540. >>> dsolve_system(eqs, funcs=funcs, t=x)
  1541. [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
  1542. Lets look at an implicit system of ODEs:
  1543. >>> eqs = [Eq(f(x).diff(x)**2, g(x)**2), Eq(g(x).diff(x), g(x))]
  1544. >>> dsolve_system(eqs)
  1545. [[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))]]
  1546. Returns
  1547. =======
  1548. List of List of Equations
  1549. Raises
  1550. ======
  1551. NotImplementedError
  1552. When the system of ODEs is not solvable by this function.
  1553. ValueError
  1554. When the parameters passed aren't in the required form.
  1555. """
  1556. from sympy.solvers.ode.ode import solve_ics, _extract_funcs, constant_renumber
  1557. if not iterable(eqs):
  1558. raise ValueError(filldedent('''
  1559. List of equations should be passed. The input is not valid.
  1560. '''))
  1561. eqs = _preprocess_eqs(eqs)
  1562. if funcs is not None and not isinstance(funcs, list):
  1563. raise ValueError(filldedent('''
  1564. Input to the funcs should be a list of functions.
  1565. '''))
  1566. if funcs is None:
  1567. funcs = _extract_funcs(eqs)
  1568. if any(len(func.args) != 1 for func in funcs):
  1569. raise ValueError(filldedent('''
  1570. dsolve_system can solve a system of ODEs with only one independent
  1571. variable.
  1572. '''))
  1573. if len(eqs) != len(funcs):
  1574. raise ValueError(filldedent('''
  1575. Number of equations and number of functions do not match
  1576. '''))
  1577. if t is not None and not isinstance(t, Symbol):
  1578. raise ValueError(filldedent('''
  1579. The indepedent variable must be of type Symbol
  1580. '''))
  1581. if t is None:
  1582. t = list(list(eqs[0].atoms(Derivative))[0].atoms(Symbol))[0]
  1583. sols = []
  1584. canon_eqs = canonical_odes(eqs, funcs, t)
  1585. for canon_eq in canon_eqs:
  1586. try:
  1587. sol = _strong_component_solver(canon_eq, funcs, t)
  1588. except NotImplementedError:
  1589. sol = None
  1590. if sol is None:
  1591. sol = _component_solver(canon_eq, funcs, t)
  1592. sols.append(sol)
  1593. if sols:
  1594. final_sols = []
  1595. variables = Tuple(*eqs).free_symbols
  1596. for sol in sols:
  1597. sol = _select_equations(sol, funcs)
  1598. sol = constant_renumber(sol, variables=variables)
  1599. if ics:
  1600. constants = Tuple(*sol).free_symbols - variables
  1601. solved_constants = solve_ics(sol, funcs, constants, ics)
  1602. sol = [s.subs(solved_constants) for s in sol]
  1603. if simplify:
  1604. constants = Tuple(*sol).free_symbols - variables
  1605. sol = simpsol(sol, [t], constants, doit=doit)
  1606. final_sols.append(sol)
  1607. sols = final_sols
  1608. return sols