nonhomogeneous.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. r"""
  2. This File contains helper functions for nth_linear_constant_coeff_undetermined_coefficients,
  3. nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients,
  4. nth_linear_constant_coeff_variation_of_parameters,
  5. and nth_linear_euler_eq_nonhomogeneous_variation_of_parameters.
  6. All the functions in this file are used by more than one solvers so, instead of creating
  7. instances in other classes for using them it is better to keep it here as separate helpers.
  8. """
  9. from collections import Counter
  10. from sympy.core import Add, S
  11. from sympy.core.function import diff, expand, _mexpand, expand_mul
  12. from sympy.core.relational import Eq
  13. from sympy.core.sorting import default_sort_key
  14. from sympy.core.symbol import Dummy, Wild
  15. from sympy.functions import exp, cos, cosh, im, log, re, sin, sinh, \
  16. atan2, conjugate
  17. from sympy.integrals import Integral
  18. from sympy.polys import (Poly, RootOf, rootof, roots)
  19. from sympy.simplify import collect, simplify, separatevars, powsimp, trigsimp # type: ignore
  20. from sympy.utilities import numbered_symbols
  21. from sympy.solvers.solvers import solve
  22. from sympy.matrices import wronskian
  23. from .subscheck import sub_func_doit
  24. from sympy.solvers.ode.ode import get_numbered_constants
  25. def _test_term(coeff, func, order):
  26. r"""
  27. Linear Euler ODEs have the form K*x**order*diff(y(x), x, order) = F(x),
  28. where K is independent of x and y(x), order>= 0.
  29. So we need to check that for each term, coeff == K*x**order from
  30. some K. We have a few cases, since coeff may have several
  31. different types.
  32. """
  33. x = func.args[0]
  34. f = func.func
  35. if order < 0:
  36. raise ValueError("order should be greater than 0")
  37. if coeff == 0:
  38. return True
  39. if order == 0:
  40. if x in coeff.free_symbols:
  41. return False
  42. return True
  43. if coeff.is_Mul:
  44. if coeff.has(f(x)):
  45. return False
  46. return x**order in coeff.args
  47. elif coeff.is_Pow:
  48. return coeff.as_base_exp() == (x, order)
  49. elif order == 1:
  50. return x == coeff
  51. return False
  52. def _get_euler_characteristic_eq_sols(eq, func, match_obj):
  53. r"""
  54. Returns the solution of homogeneous part of the linear euler ODE and
  55. the list of roots of characteristic equation.
  56. The parameter ``match_obj`` is a dict of order:coeff terms, where order is the order
  57. of the derivative on each term, and coeff is the coefficient of that derivative.
  58. """
  59. x = func.args[0]
  60. f = func.func
  61. # First, set up characteristic equation.
  62. chareq, symbol = S.Zero, Dummy('x')
  63. for i in match_obj:
  64. if i >= 0:
  65. chareq += (match_obj[i]*diff(x**symbol, x, i)*x**-symbol).expand()
  66. chareq = Poly(chareq, symbol)
  67. chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
  68. collectterms = []
  69. # A generator of constants
  70. constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
  71. constants.reverse()
  72. # Create a dict root: multiplicity or charroots
  73. charroots = Counter(chareqroots)
  74. gsol = S.Zero
  75. ln = log
  76. for root, multiplicity in charroots.items():
  77. for i in range(multiplicity):
  78. if isinstance(root, RootOf):
  79. gsol += (x**root) * constants.pop()
  80. if multiplicity != 1:
  81. raise ValueError("Value should be 1")
  82. collectterms = [(0, root, 0)] + collectterms
  83. elif root.is_real:
  84. gsol += ln(x)**i*(x**root) * constants.pop()
  85. collectterms = [(i, root, 0)] + collectterms
  86. else:
  87. reroot = re(root)
  88. imroot = im(root)
  89. gsol += ln(x)**i * (x**reroot) * (
  90. constants.pop() * sin(abs(imroot)*ln(x))
  91. + constants.pop() * cos(imroot*ln(x)))
  92. collectterms = [(i, reroot, imroot)] + collectterms
  93. gsol = Eq(f(x), gsol)
  94. gensols = []
  95. # Keep track of when to use sin or cos for nonzero imroot
  96. for i, reroot, imroot in collectterms:
  97. if imroot == 0:
  98. gensols.append(ln(x)**i*x**reroot)
  99. else:
  100. sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
  101. if sin_form in gensols:
  102. cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
  103. gensols.append(cos_form)
  104. else:
  105. gensols.append(sin_form)
  106. return gsol, gensols
  107. def _solve_variation_of_parameters(eq, func, roots, homogen_sol, order, match_obj, simplify_flag=True):
  108. r"""
  109. Helper function for the method of variation of parameters and nonhomogeneous euler eq.
  110. See the
  111. :py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffVariationOfParameters`
  112. docstring for more information on this method.
  113. The parameter are ``match_obj`` should be a dictionary that has the following
  114. keys:
  115. ``list``
  116. A list of solutions to the homogeneous equation.
  117. ``sol``
  118. The general solution.
  119. """
  120. f = func.func
  121. x = func.args[0]
  122. r = match_obj
  123. psol = 0
  124. wr = wronskian(roots, x)
  125. if simplify_flag:
  126. wr = simplify(wr) # We need much better simplification for
  127. # some ODEs. See issue 4662, for example.
  128. # To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1
  129. wr = trigsimp(wr, deep=True, recursive=True)
  130. if not wr:
  131. # The wronskian will be 0 iff the solutions are not linearly
  132. # independent.
  133. raise NotImplementedError("Cannot find " + str(order) +
  134. " solutions to the homogeneous equation necessary to apply " +
  135. "variation of parameters to " + str(eq) + " (Wronskian == 0)")
  136. if len(roots) != order:
  137. raise NotImplementedError("Cannot find " + str(order) +
  138. " solutions to the homogeneous equation necessary to apply " +
  139. "variation of parameters to " +
  140. str(eq) + " (number of terms != order)")
  141. negoneterm = S.NegativeOne**(order)
  142. for i in roots:
  143. psol += negoneterm*Integral(wronskian([sol for sol in roots if sol != i], x)*r[-1]/wr, x)*i/r[order]
  144. negoneterm *= -1
  145. if simplify_flag:
  146. psol = simplify(psol)
  147. psol = trigsimp(psol, deep=True)
  148. return Eq(f(x), homogen_sol.rhs + psol)
  149. def _get_const_characteristic_eq_sols(r, func, order):
  150. r"""
  151. Returns the roots of characteristic equation of constant coefficient
  152. linear ODE and list of collectterms which is later on used by simplification
  153. to use collect on solution.
  154. The parameter `r` is a dict of order:coeff terms, where order is the order of the
  155. derivative on each term, and coeff is the coefficient of that derivative.
  156. """
  157. x = func.args[0]
  158. # First, set up characteristic equation.
  159. chareq, symbol = S.Zero, Dummy('x')
  160. for i in r.keys():
  161. if isinstance(i, str) or i < 0:
  162. pass
  163. else:
  164. chareq += r[i]*symbol**i
  165. chareq = Poly(chareq, symbol)
  166. # Can't just call roots because it doesn't return rootof for unsolveable
  167. # polynomials.
  168. chareqroots = roots(chareq, multiple=True)
  169. if len(chareqroots) != order:
  170. chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
  171. chareq_is_complex = not all(i.is_real for i in chareq.all_coeffs())
  172. # Create a dict root: multiplicity or charroots
  173. charroots = Counter(chareqroots)
  174. # We need to keep track of terms so we can run collect() at the end.
  175. # This is necessary for constantsimp to work properly.
  176. collectterms = []
  177. gensols = []
  178. conjugate_roots = [] # used to prevent double-use of conjugate roots
  179. # Loop over roots in theorder provided by roots/rootof...
  180. for root in chareqroots:
  181. # but don't repoeat multiple roots.
  182. if root not in charroots:
  183. continue
  184. multiplicity = charroots.pop(root)
  185. for i in range(multiplicity):
  186. if chareq_is_complex:
  187. gensols.append(x**i*exp(root*x))
  188. collectterms = [(i, root, 0)] + collectterms
  189. continue
  190. reroot = re(root)
  191. imroot = im(root)
  192. if imroot.has(atan2) and reroot.has(atan2):
  193. # Remove this condition when re and im stop returning
  194. # circular atan2 usages.
  195. gensols.append(x**i*exp(root*x))
  196. collectterms = [(i, root, 0)] + collectterms
  197. else:
  198. if root in conjugate_roots:
  199. collectterms = [(i, reroot, imroot)] + collectterms
  200. continue
  201. if imroot == 0:
  202. gensols.append(x**i*exp(reroot*x))
  203. collectterms = [(i, reroot, 0)] + collectterms
  204. continue
  205. conjugate_roots.append(conjugate(root))
  206. gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
  207. gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
  208. # This ordering is important
  209. collectterms = [(i, reroot, imroot)] + collectterms
  210. return gensols, collectterms
  211. # Ideally these kind of simplification functions shouldn't be part of solvers.
  212. # odesimp should be improved to handle these kind of specific simplifications.
  213. def _get_simplified_sol(sol, func, collectterms):
  214. r"""
  215. Helper function which collects the solution on
  216. collectterms. Ideally this should be handled by odesimp.It is used
  217. only when the simplify is set to True in dsolve.
  218. The parameter ``collectterms`` is a list of tuple (i, reroot, imroot) where `i` is
  219. the multiplicity of the root, reroot is real part and imroot being the imaginary part.
  220. """
  221. f = func.func
  222. x = func.args[0]
  223. collectterms.sort(key=default_sort_key)
  224. collectterms.reverse()
  225. assert len(sol) == 1 and sol[0].lhs == f(x)
  226. sol = sol[0].rhs
  227. sol = expand_mul(sol)
  228. for i, reroot, imroot in collectterms:
  229. sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
  230. sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
  231. for i, reroot, imroot in collectterms:
  232. sol = collect(sol, x**i*exp(reroot*x))
  233. sol = powsimp(sol)
  234. return Eq(f(x), sol)
  235. def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
  236. r"""
  237. Returns a trial function match if undetermined coefficients can be applied
  238. to ``expr``, and ``None`` otherwise.
  239. A trial expression can be found for an expression for use with the method
  240. of undetermined coefficients if the expression is an
  241. additive/multiplicative combination of constants, polynomials in `x` (the
  242. independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
  243. `e^{a x}` terms (in other words, it has a finite number of linearly
  244. independent derivatives).
  245. Note that you may still need to multiply each term returned here by
  246. sufficient `x` to make it linearly independent with the solutions to the
  247. homogeneous equation.
  248. This is intended for internal use by ``undetermined_coefficients`` hints.
  249. SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
  250. only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
  251. for example, you will need to manually convert `\sin^2(x)` into `[1 +
  252. \cos(2 x)]/2` to properly apply the method of undetermined coefficients on
  253. it.
  254. Examples
  255. ========
  256. >>> from sympy import log, exp
  257. >>> from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match
  258. >>> from sympy.abc import x
  259. >>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
  260. {'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}}
  261. >>> _undetermined_coefficients_match(log(x), x)
  262. {'test': False}
  263. """
  264. a = Wild('a', exclude=[x])
  265. b = Wild('b', exclude=[x])
  266. expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
  267. retdict = {}
  268. def _test_term(expr, x) -> bool:
  269. r"""
  270. Test if ``expr`` fits the proper form for undetermined coefficients.
  271. """
  272. if not expr.has(x):
  273. return True
  274. if expr.is_Add:
  275. return all(_test_term(i, x) for i in expr.args)
  276. if expr.is_Mul:
  277. if expr.has(sin, cos):
  278. foundtrig = False
  279. # Make sure that there is only one trig function in the args.
  280. # See the docstring.
  281. for i in expr.args:
  282. if i.has(sin, cos):
  283. if foundtrig:
  284. return False
  285. else:
  286. foundtrig = True
  287. return all(_test_term(i, x) for i in expr.args)
  288. if expr.is_Function:
  289. return expr.func in (sin, cos, exp, sinh, cosh) and \
  290. bool(expr.args[0].match(a*x + b))
  291. if expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
  292. expr.exp >= 0:
  293. return True
  294. if expr.is_Pow and expr.base.is_number:
  295. return bool(expr.exp.match(a*x + b))
  296. return expr.is_Symbol or bool(expr.is_number)
  297. def _get_trial_set(expr, x, exprs=set()):
  298. r"""
  299. Returns a set of trial terms for undetermined coefficients.
  300. The idea behind undetermined coefficients is that the terms expression
  301. repeat themselves after a finite number of derivatives, except for the
  302. coefficients (they are linearly dependent). So if we collect these,
  303. we should have the terms of our trial function.
  304. """
  305. def _remove_coefficient(expr, x):
  306. r"""
  307. Returns the expression without a coefficient.
  308. Similar to expr.as_independent(x)[1], except it only works
  309. multiplicatively.
  310. """
  311. term = S.One
  312. if expr.is_Mul:
  313. for i in expr.args:
  314. if i.has(x):
  315. term *= i
  316. elif expr.has(x):
  317. term = expr
  318. return term
  319. expr = expand_mul(expr)
  320. if expr.is_Add:
  321. for term in expr.args:
  322. if _remove_coefficient(term, x) in exprs:
  323. pass
  324. else:
  325. exprs.add(_remove_coefficient(term, x))
  326. exprs = exprs.union(_get_trial_set(term, x, exprs))
  327. else:
  328. term = _remove_coefficient(expr, x)
  329. tmpset = exprs.union({term})
  330. oldset = set()
  331. while tmpset != oldset:
  332. # If you get stuck in this loop, then _test_term is probably
  333. # broken
  334. oldset = tmpset.copy()
  335. expr = expr.diff(x)
  336. term = _remove_coefficient(expr, x)
  337. if term.is_Add:
  338. tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
  339. else:
  340. tmpset.add(term)
  341. exprs = tmpset
  342. return exprs
  343. def is_homogeneous_solution(term):
  344. r""" This function checks whether the given trialset contains any root
  345. of homogeneous equation"""
  346. return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero
  347. retdict['test'] = _test_term(expr, x)
  348. if retdict['test']:
  349. # Try to generate a list of trial solutions that will have the
  350. # undetermined coefficients. Note that if any of these are not linearly
  351. # independent with any of the solutions to the homogeneous equation,
  352. # then they will need to be multiplied by sufficient x to make them so.
  353. # This function DOES NOT do that (it doesn't even look at the
  354. # homogeneous equation).
  355. temp_set = set()
  356. for i in Add.make_args(expr):
  357. act = _get_trial_set(i, x)
  358. if eq_homogeneous is not S.Zero:
  359. while any(is_homogeneous_solution(ts) for ts in act):
  360. act = {x*ts for ts in act}
  361. temp_set = temp_set.union(act)
  362. retdict['trialset'] = temp_set
  363. return retdict
  364. def _solve_undetermined_coefficients(eq, func, order, match, trialset):
  365. r"""
  366. Helper function for the method of undetermined coefficients.
  367. See the
  368. :py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffUndeterminedCoefficients`
  369. docstring for more information on this method.
  370. The parameter ``trialset`` is the set of trial functions as returned by
  371. ``_undetermined_coefficients_match()['trialset']``.
  372. The parameter ``match`` should be a dictionary that has the following
  373. keys:
  374. ``list``
  375. A list of solutions to the homogeneous equation.
  376. ``sol``
  377. The general solution.
  378. """
  379. r = match
  380. coeffs = numbered_symbols('a', cls=Dummy)
  381. coefflist = []
  382. gensols = r['list']
  383. gsol = r['sol']
  384. f = func.func
  385. x = func.args[0]
  386. if len(gensols) != order:
  387. raise NotImplementedError("Cannot find " + str(order) +
  388. " solutions to the homogeneous equation necessary to apply" +
  389. " undetermined coefficients to " + str(eq) +
  390. " (number of terms != order)")
  391. trialfunc = 0
  392. for i in trialset:
  393. c = next(coeffs)
  394. coefflist.append(c)
  395. trialfunc += c*i
  396. eqs = sub_func_doit(eq, f(x), trialfunc)
  397. coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
  398. eqs = _mexpand(eqs)
  399. for i in Add.make_args(eqs):
  400. s = separatevars(i, dict=True, symbols=[x])
  401. if coeffsdict.get(s[x]):
  402. coeffsdict[s[x]] += s['coeff']
  403. else:
  404. coeffsdict[s[x]] = s['coeff']
  405. coeffvals = solve(list(coeffsdict.values()), coefflist)
  406. if not coeffvals:
  407. raise NotImplementedError(
  408. "Could not solve `%s` using the "
  409. "method of undetermined coefficients "
  410. "(unable to solve for coefficients)." % eq)
  411. psol = trialfunc.subs(coeffvals)
  412. return Eq(f(x), gsol.rhs + psol)