riccati.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. r"""
  2. This module contains :py:meth:`~sympy.solvers.ode.riccati.solve_riccati`,
  3. a function which gives all rational particular solutions to first order
  4. Riccati ODEs. A general first order Riccati ODE is given by -
  5. .. math:: y' = b_0(x) + b_1(x)w + b_2(x)w^2
  6. where `b_0, b_1` and `b_2` can be arbitrary rational functions of `x`
  7. with `b_2 \ne 0`. When `b_2 = 0`, the equation is not a Riccati ODE
  8. anymore and becomes a Linear ODE. Similarly, when `b_0 = 0`, the equation
  9. is a Bernoulli ODE. The algorithm presented below can find rational
  10. solution(s) to all ODEs with `b_2 \ne 0` that have a rational solution,
  11. or prove that no rational solution exists for the equation.
  12. Background
  13. ==========
  14. A Riccati equation can be transformed to its normal form
  15. .. math:: y' + y^2 = a(x)
  16. using the transformation
  17. .. math:: y = -b_2(x) - \frac{b'_2(x)}{2 b_2(x)} - \frac{b_1(x)}{2}
  18. where `a(x)` is given by
  19. .. math:: a(x) = \frac{1}{4}\left(\frac{b_2'}{b_2} + b_1\right)^2 - \frac{1}{2}\left(\frac{b_2'}{b_2} + b_1\right)' - b_0 b_2
  20. Thus, we can develop an algorithm to solve for the Riccati equation
  21. in its normal form, which would in turn give us the solution for
  22. the original Riccati equation.
  23. Algorithm
  24. =========
  25. The algorithm implemented here is presented in the Ph.D thesis
  26. "Rational and Algebraic Solutions of First-Order Algebraic ODEs"
  27. by N. Thieu Vo. The entire thesis can be found here -
  28. https://www3.risc.jku.at/publications/download/risc_5387/PhDThesisThieu.pdf
  29. We have only implemented the Rational Riccati solver (Algorithm 11,
  30. Pg 78-82 in Thesis). Before we proceed towards the implementation
  31. of the algorithm, a few definitions to understand are -
  32. 1. Valuation of a Rational Function at `\infty`:
  33. The valuation of a rational function `p(x)` at `\infty` is equal
  34. to the difference between the degree of the denominator and the
  35. numerator of `p(x)`.
  36. NOTE: A general definition of valuation of a rational function
  37. at any value of `x` can be found in Pg 63 of the thesis, but
  38. is not of any interest for this algorithm.
  39. 2. Zeros and Poles of a Rational Function:
  40. Let `a(x) = \frac{S(x)}{T(x)}, T \ne 0` be a rational function
  41. of `x`. Then -
  42. a. The Zeros of `a(x)` are the roots of `S(x)`.
  43. b. The Poles of `a(x)` are the roots of `T(x)`. However, `\infty`
  44. can also be a pole of a(x). We say that `a(x)` has a pole at
  45. `\infty` if `a(\frac{1}{x})` has a pole at 0.
  46. Every pole is associated with an order that is equal to the multiplicity
  47. of its appearence as a root of `T(x)`. A pole is called a simple pole if
  48. it has an order 1. Similarly, a pole is called a multiple pole if it has
  49. an order `\ge` 2.
  50. Necessary Conditions
  51. ====================
  52. For a Riccati equation in its normal form,
  53. .. math:: y' + y^2 = a(x)
  54. we can define
  55. a. A pole is called a movable pole if it is a pole of `y(x)` and is not
  56. a pole of `a(x)`.
  57. b. Similarly, a pole is called a non-movable pole if it is a pole of both
  58. `y(x)` and `a(x)`.
  59. Then, the algorithm states that a rational solution exists only if -
  60. a. Every pole of `a(x)` must be either a simple pole or a multiple pole
  61. of even order.
  62. b. The valuation of `a(x)` at `\infty` must be even or be `\ge` 2.
  63. This algorithm finds all possible rational solutions for the Riccati ODE.
  64. If no rational solutions are found, it means that no rational solutions
  65. exist.
  66. The algorithm works for Riccati ODEs where the coefficients are rational
  67. functions in the independent variable `x` with rational number coefficients
  68. i.e. in `Q(x)`. The coefficients in the rational function cannot be floats,
  69. irrational numbers, symbols or any other kind of expression. The reasons
  70. for this are -
  71. 1. When using symbols, different symbols could take the same value and this
  72. would affect the multiplicity of poles if symbols are present here.
  73. 2. An integer degree bound is required to calculate a polynomial solution
  74. to an auxiliary differential equation, which in turn gives the particular
  75. solution for the original ODE. If symbols/floats/irrational numbers are
  76. present, we cannot determine if the expression for the degree bound is an
  77. integer or not.
  78. Solution
  79. ========
  80. With these definitions, we can state a general form for the solution of
  81. the equation. `y(x)` must have the form -
  82. .. math:: y(x) = \sum_{i=1}^{n} \sum_{j=1}^{r_i} \frac{c_{ij}}{(x - x_i)^j} + \sum_{i=1}^{m} \frac{1}{x - \chi_i} + \sum_{i=0}^{N} d_i x^i
  83. where `x_1, x_2, \dots, x_n` are non-movable poles of `a(x)`,
  84. `\chi_1, \chi_2, \dots, \chi_m` are movable poles of `a(x)`, and the values
  85. of `N, n, r_1, r_2, \dots, r_n` can be determined from `a(x)`. The
  86. coefficient vectors `(d_0, d_1, \dots, d_N)` and `(c_{i1}, c_{i2}, \dots, c_{i r_i})`
  87. can be determined from `a(x)`. We will have 2 choices each of these vectors
  88. and part of the procedure is figuring out which of the 2 should be used
  89. to get the solution correctly.
  90. Implementation
  91. ==============
  92. In this implementatin, we use ``Poly`` to represent a rational function
  93. rather than using ``Expr`` since ``Poly`` is much faster. Since we cannot
  94. represent rational functions directly using ``Poly``, we instead represent
  95. a rational function with 2 ``Poly`` objects - one for its numerator and
  96. the other for its denominator.
  97. The code is written to match the steps given in the thesis (Pg 82)
  98. Step 0 : Match the equation -
  99. Find `b_0, b_1` and `b_2`. If `b_2 = 0` or no such functions exist, raise
  100. an error
  101. Step 1 : Transform the equation to its normal form as explained in the
  102. theory section.
  103. Step 2 : Initialize an empty set of solutions, ``sol``.
  104. Step 3 : If `a(x) = 0`, append `\frac{1}/{(x - C1)}` to ``sol``.
  105. Step 4 : If `a(x)` is a rational non-zero number, append `\pm \sqrt{a}`
  106. to ``sol``.
  107. Step 5 : Find the poles and their multiplicities of `a(x)`. Let
  108. the number of poles be `n`. Also find the valuation of `a(x)` at
  109. `\infty` using ``val_at_inf``.
  110. NOTE: Although the algorithm considers `\infty` as a pole, it is
  111. not mentioned if it a part of the set of finite poles. `\infty`
  112. is NOT a part of the set of finite poles. If a pole exists at
  113. `\infty`, we use its multiplicty to find the laurent series of
  114. `a(x)` about `\infty`.
  115. Step 6 : Find `n` c-vectors (one for each pole) and 1 d-vector using
  116. ``construct_c`` and ``construct_d``. Now, determine all the ``2**(n + 1)``
  117. combinations of choosing between 2 choices for each of the `n` c-vectors
  118. and 1 d-vector.
  119. NOTE: The equation for `d_{-1}` in Case 4 (Pg 80) has a printinig
  120. mistake. The term `- d_N` must be replaced with `-N d_N`. The same
  121. has been explained in the code as well.
  122. For each of these above combinations, do
  123. Step 8 : Compute `m` in ``compute_m_ybar``. `m` is the degree bound of
  124. the polynomial solution we must find for the auxiliary equation.
  125. Step 9 : In ``compute_m_ybar``, compute ybar as well where ``ybar`` is
  126. one part of y(x) -
  127. .. math:: \overline{y}(x) = \sum_{i=1}^{n} \sum_{j=1}^{r_i} \frac{c_{ij}}{(x - x_i)^j} + \sum_{i=0}^{N} d_i x^i
  128. Step 10 : If `m` is a non-negative integer -
  129. Step 11: Find a polynomial solution of degree `m` for the auxiliary equation.
  130. There are 2 cases possible -
  131. a. `m` is a non-negative integer: We can solve for the coefficients
  132. in `p(x)` using Undetermined Coefficients.
  133. b. `m` is not a non-negative integer: In this case, we cannot find
  134. a polynomial solution to the auxiliary equation, and hence, we ignore
  135. this value of `m`.
  136. Step 12 : For each `p(x)` that exists, append `ybar + \frac{p'(x)}{p(x)}`
  137. to ``sol``.
  138. Step 13 : For each solution in ``sol``, apply an inverse transformation,
  139. so that the solutions of the original equation are found using the
  140. solutions of the equation in its normal form.
  141. """
  142. from itertools import product
  143. from sympy.core import S
  144. from sympy.core.add import Add
  145. from sympy.core.numbers import oo, Float
  146. from sympy.core.function import count_ops
  147. from sympy.core.relational import Eq
  148. from sympy.core.symbol import symbols, Symbol, Dummy
  149. from sympy.functions import sqrt, exp
  150. from sympy.functions.elementary.complexes import sign
  151. from sympy.integrals.integrals import Integral
  152. from sympy.polys.domains import ZZ
  153. from sympy.polys.polytools import Poly
  154. from sympy.polys.polyroots import roots
  155. from sympy.solvers.solveset import linsolve
  156. def riccati_normal(w, x, b1, b2):
  157. """
  158. Given a solution `w(x)` to the equation
  159. .. math:: w'(x) = b_0(x) + b_1(x)*w(x) + b_2(x)*w(x)^2
  160. and rational function coefficients `b_1(x)` and
  161. `b_2(x)`, this function transforms the solution to
  162. give a solution `y(x)` for its corresponding normal
  163. Riccati ODE
  164. .. math:: y'(x) + y(x)^2 = a(x)
  165. using the transformation
  166. .. math:: y(x) = -b_2(x)*w(x) - b'_2(x)/(2*b_2(x)) - b_1(x)/2
  167. """
  168. return -b2*w - b2.diff(x)/(2*b2) - b1/2
  169. def riccati_inverse_normal(y, x, b1, b2, bp=None):
  170. """
  171. Inverse transforming the solution to the normal
  172. Riccati ODE to get the solution to the Riccati ODE.
  173. """
  174. # bp is the expression which is independent of the solution
  175. # and hence, it need not be computed again
  176. if bp is None:
  177. bp = -b2.diff(x)/(2*b2**2) - b1/(2*b2)
  178. # w(x) = -y(x)/b2(x) - b2'(x)/(2*b2(x)^2) - b1(x)/(2*b2(x))
  179. return -y/b2 + bp
  180. def riccati_reduced(eq, f, x):
  181. """
  182. Convert a Riccati ODE into its corresponding
  183. normal Riccati ODE.
  184. """
  185. match, funcs = match_riccati(eq, f, x)
  186. # If equation is not a Riccati ODE, exit
  187. if not match:
  188. return False
  189. # Using the rational functions, find the expression for a(x)
  190. b0, b1, b2 = funcs
  191. a = -b0*b2 + b1**2/4 - b1.diff(x)/2 + 3*b2.diff(x)**2/(4*b2**2) + b1*b2.diff(x)/(2*b2) - \
  192. b2.diff(x, 2)/(2*b2)
  193. # Normal form of Riccati ODE is f'(x) + f(x)^2 = a(x)
  194. return f(x).diff(x) + f(x)**2 - a
  195. def linsolve_dict(eq, syms):
  196. """
  197. Get the output of linsolve as a dict
  198. """
  199. # Convert tuple type return value of linsolve
  200. # to a dictionary for ease of use
  201. sol = linsolve(eq, syms)
  202. if not sol:
  203. return {}
  204. return {k:v for k, v in zip(syms, list(sol)[0])}
  205. def match_riccati(eq, f, x):
  206. """
  207. A function that matches and returns the coefficients
  208. if an equation is a Riccati ODE
  209. Parameters
  210. ==========
  211. eq: Equation to be matched
  212. f: Dependent variable
  213. x: Independent variable
  214. Returns
  215. =======
  216. match: True if equation is a Riccati ODE, False otherwise
  217. funcs: [b0, b1, b2] if match is True, [] otherwise. Here,
  218. b0, b1 and b2 are rational functions which match the equation.
  219. """
  220. # Group terms based on f(x)
  221. if isinstance(eq, Eq):
  222. eq = eq.lhs - eq.rhs
  223. eq = eq.expand().collect(f(x))
  224. cf = eq.coeff(f(x).diff(x))
  225. # There must be an f(x).diff(x) term.
  226. # eq must be an Add object since we are using the expanded
  227. # equation and it must have atleast 2 terms (b2 != 0)
  228. if cf != 0 and isinstance(eq, Add):
  229. # Divide all coefficients by the coefficient of f(x).diff(x)
  230. # and add the terms again to get the same equation
  231. eq = Add(*((x/cf).cancel() for x in eq.args)).collect(f(x))
  232. # Match the equation with the pattern
  233. b1 = -eq.coeff(f(x))
  234. b2 = -eq.coeff(f(x)**2)
  235. b0 = (f(x).diff(x) - b1*f(x) - b2*f(x)**2 - eq).expand()
  236. funcs = [b0, b1, b2]
  237. # Check if coefficients are not symbols and floats
  238. if any(len(x.atoms(Symbol)) > 1 or len(x.atoms(Float)) for x in funcs):
  239. return False, []
  240. # If b_0(x) contains f(x), it is not a Riccati ODE
  241. if len(b0.atoms(f)) or not all((b2 != 0, b0.is_rational_function(x),
  242. b1.is_rational_function(x), b2.is_rational_function(x))):
  243. return False, []
  244. return True, funcs
  245. return False, []
  246. def val_at_inf(num, den, x):
  247. # Valuation of a rational function at oo = deg(denom) - deg(numer)
  248. return den.degree(x) - num.degree(x)
  249. def check_necessary_conds(val_inf, muls):
  250. """
  251. The necessary conditions for a rational solution
  252. to exist are as follows -
  253. i) Every pole of a(x) must be either a simple pole
  254. or a multiple pole of even order.
  255. ii) The valuation of a(x) at infinity must be even
  256. or be greater than or equal to 2.
  257. Here, a simple pole is a pole with multiplicity 1
  258. and a multiple pole is a pole with multiplicity
  259. greater than 1.
  260. """
  261. return (val_inf >= 2 or (val_inf <= 0 and val_inf%2 == 0)) and \
  262. all(mul == 1 or (mul%2 == 0 and mul >= 2) for mul in muls)
  263. def inverse_transform_poly(num, den, x):
  264. """
  265. A function to make the substitution
  266. x -> 1/x in a rational function that
  267. is represented using Poly objects for
  268. numerator and denominator.
  269. """
  270. # Declare for reuse
  271. one = Poly(1, x)
  272. xpoly = Poly(x, x)
  273. # Check if degree of numerator is same as denominator
  274. pwr = val_at_inf(num, den, x)
  275. if pwr >= 0:
  276. # Denominator has greater degree. Substituting x with
  277. # 1/x would make the extra power go to the numerator
  278. if num.expr != 0:
  279. num = num.transform(one, xpoly) * x**pwr
  280. den = den.transform(one, xpoly)
  281. else:
  282. # Numerator has greater degree. Substituting x with
  283. # 1/x would make the extra power go to the denominator
  284. num = num.transform(one, xpoly)
  285. den = den.transform(one, xpoly) * x**(-pwr)
  286. return num.cancel(den, include=True)
  287. def limit_at_inf(num, den, x):
  288. """
  289. Find the limit of a rational function
  290. at oo
  291. """
  292. # pwr = degree(num) - degree(den)
  293. pwr = -val_at_inf(num, den, x)
  294. # Numerator has a greater degree than denominator
  295. # Limit at infinity would depend on the sign of the
  296. # leading coefficients of numerator and denominator
  297. if pwr > 0:
  298. return oo*sign(num.LC()/den.LC())
  299. # Degree of numerator is equal to that of denominator
  300. # Limit at infinity is just the ratio of leading coeffs
  301. elif pwr == 0:
  302. return num.LC()/den.LC()
  303. # Degree of numerator is less than that of denominator
  304. # Limit at infinity is just 0
  305. else:
  306. return 0
  307. def construct_c_case_1(num, den, x, pole):
  308. # Find the coefficient of 1/(x - pole)**2 in the
  309. # Laurent series expansion of a(x) about pole.
  310. num1, den1 = (num*Poly((x - pole)**2, x, extension=True)).cancel(den, include=True)
  311. r = (num1.subs(x, pole))/(den1.subs(x, pole))
  312. # If multiplicity is 2, the coefficient to be added
  313. # in the c-vector is c = (1 +- sqrt(1 + 4*r))/2
  314. if r != -S(1)/4:
  315. return [[(1 + sqrt(1 + 4*r))/2], [(1 - sqrt(1 + 4*r))/2]]
  316. return [[S.Half]]
  317. def construct_c_case_2(num, den, x, pole, mul):
  318. # Generate the coefficients using the recurrence
  319. # relation mentioned in (5.14) in the thesis (Pg 80)
  320. # r_i = mul/2
  321. ri = mul//2
  322. # Find the Laurent series coefficients about the pole
  323. ser = rational_laurent_series(num, den, x, pole, mul, 6)
  324. # Start with an empty memo to store the coefficients
  325. # This is for the plus case
  326. cplus = [0 for i in range(ri)]
  327. # Base Case
  328. cplus[ri-1] = sqrt(ser[2*ri])
  329. # Iterate backwards to find all coefficients
  330. s = ri - 1
  331. sm = 0
  332. for s in range(ri-1, 0, -1):
  333. sm = 0
  334. for j in range(s+1, ri):
  335. sm += cplus[j-1]*cplus[ri+s-j-1]
  336. if s!= 1:
  337. cplus[s-1] = (ser[ri+s] - sm)/(2*cplus[ri-1])
  338. # Memo for the minus case
  339. cminus = [-x for x in cplus]
  340. # Find the 0th coefficient in the recurrence
  341. cplus[0] = (ser[ri+s] - sm - ri*cplus[ri-1])/(2*cplus[ri-1])
  342. cminus[0] = (ser[ri+s] - sm - ri*cminus[ri-1])/(2*cminus[ri-1])
  343. # Add both the plus and minus cases' coefficients
  344. if cplus != cminus:
  345. return [cplus, cminus]
  346. return cplus
  347. def construct_c_case_3():
  348. # If multiplicity is 1, the coefficient to be added
  349. # in the c-vector is 1 (no choice)
  350. return [[1]]
  351. def construct_c(num, den, x, poles, muls):
  352. """
  353. Helper function to calculate the coefficients
  354. in the c-vector for each pole.
  355. """
  356. c = []
  357. for pole, mul in zip(poles, muls):
  358. c.append([])
  359. # Case 3
  360. if mul == 1:
  361. # Add the coefficients from Case 3
  362. c[-1].extend(construct_c_case_3())
  363. # Case 1
  364. elif mul == 2:
  365. # Add the coefficients from Case 1
  366. c[-1].extend(construct_c_case_1(num, den, x, pole))
  367. # Case 2
  368. else:
  369. # Add the coefficients from Case 2
  370. c[-1].extend(construct_c_case_2(num, den, x, pole, mul))
  371. return c
  372. def construct_d_case_4(ser, N):
  373. # Initialize an empty vector
  374. dplus = [0 for i in range(N+2)]
  375. # d_N = sqrt(a_{2*N})
  376. dplus[N] = sqrt(ser[2*N])
  377. # Use the recurrence relations to find
  378. # the value of d_s
  379. for s in range(N-1, -2, -1):
  380. sm = 0
  381. for j in range(s+1, N):
  382. sm += dplus[j]*dplus[N+s-j]
  383. if s != -1:
  384. dplus[s] = (ser[N+s] - sm)/(2*dplus[N])
  385. # Coefficients for the case of d_N = -sqrt(a_{2*N})
  386. dminus = [-x for x in dplus]
  387. # The third equation in Eq 5.15 of the thesis is WRONG!
  388. # d_N must be replaced with N*d_N in that equation.
  389. dplus[-1] = (ser[N+s] - N*dplus[N] - sm)/(2*dplus[N])
  390. dminus[-1] = (ser[N+s] - N*dminus[N] - sm)/(2*dminus[N])
  391. if dplus != dminus:
  392. return [dplus, dminus]
  393. return dplus
  394. def construct_d_case_5(ser):
  395. # List to store coefficients for plus case
  396. dplus = [0, 0]
  397. # d_0 = sqrt(a_0)
  398. dplus[0] = sqrt(ser[0])
  399. # d_(-1) = a_(-1)/(2*d_0)
  400. dplus[-1] = ser[-1]/(2*dplus[0])
  401. # Coefficients for the minus case are just the negative
  402. # of the coefficients for the positive case.
  403. dminus = [-x for x in dplus]
  404. if dplus != dminus:
  405. return [dplus, dminus]
  406. return dplus
  407. def construct_d_case_6(num, den, x):
  408. # s_oo = lim x->0 1/x**2 * a(1/x) which is equivalent to
  409. # s_oo = lim x->oo x**2 * a(x)
  410. s_inf = limit_at_inf(Poly(x**2, x)*num, den, x)
  411. # d_(-1) = (1 +- sqrt(1 + 4*s_oo))/2
  412. if s_inf != -S(1)/4:
  413. return [[(1 + sqrt(1 + 4*s_inf))/2], [(1 - sqrt(1 + 4*s_inf))/2]]
  414. return [[S.Half]]
  415. def construct_d(num, den, x, val_inf):
  416. """
  417. Helper function to calculate the coefficients
  418. in the d-vector based on the valuation of the
  419. function at oo.
  420. """
  421. N = -val_inf//2
  422. # Multiplicity of oo as a pole
  423. mul = -val_inf if val_inf < 0 else 0
  424. ser = rational_laurent_series(num, den, x, oo, mul, 1)
  425. # Case 4
  426. if val_inf < 0:
  427. d = construct_d_case_4(ser, N)
  428. # Case 5
  429. elif val_inf == 0:
  430. d = construct_d_case_5(ser)
  431. # Case 6
  432. else:
  433. d = construct_d_case_6(num, den, x)
  434. return d
  435. def rational_laurent_series(num, den, x, r, m, n):
  436. r"""
  437. The function computes the Laurent series coefficients
  438. of a rational function.
  439. Parameters
  440. ==========
  441. num: A Poly object that is the numerator of `f(x)`.
  442. den: A Poly object that is the denominator of `f(x)`.
  443. x: The variable of expansion of the series.
  444. r: The point of expansion of the series.
  445. m: Multiplicity of r if r is a pole of `f(x)`. Should
  446. be zero otherwise.
  447. n: Order of the term upto which the series is expanded.
  448. Returns
  449. =======
  450. series: A dictionary that has power of the term as key
  451. and coefficient of that term as value.
  452. Below is a basic outline of how the Laurent series of a
  453. rational function `f(x)` about `x_0` is being calculated -
  454. 1. Substitute `x + x_0` in place of `x`. If `x_0`
  455. is a pole of `f(x)`, multiply the expression by `x^m`
  456. where `m` is the multiplicity of `x_0`. Denote the
  457. the resulting expression as g(x). We do this substitution
  458. so that we can now find the Laurent series of g(x) about
  459. `x = 0`.
  460. 2. We can then assume that the Laurent series of `g(x)`
  461. takes the following form -
  462. .. math:: g(x) = \frac{num(x)}{den(x)} = \sum_{m = 0}^{\infty} a_m x^m
  463. where `a_m` denotes the Laurent series coefficients.
  464. 3. Multiply the denominator to the RHS of the equation
  465. and form a recurrence relation for the coefficients `a_m`.
  466. """
  467. one = Poly(1, x, extension=True)
  468. if r == oo:
  469. # Series at x = oo is equal to first transforming
  470. # the function from x -> 1/x and finding the
  471. # series at x = 0
  472. num, den = inverse_transform_poly(num, den, x)
  473. r = S(0)
  474. if r:
  475. # For an expansion about a non-zero point, a
  476. # transformation from x -> x + r must be made
  477. num = num.transform(Poly(x + r, x, extension=True), one)
  478. den = den.transform(Poly(x + r, x, extension=True), one)
  479. # Remove the pole from the denominator if the series
  480. # expansion is about one of the poles
  481. num, den = (num*x**m).cancel(den, include=True)
  482. # Equate coefficients for the first terms (base case)
  483. maxdegree = 1 + max(num.degree(), den.degree())
  484. syms = symbols(f'a:{maxdegree}', cls=Dummy)
  485. diff = num - den * Poly(syms[::-1], x)
  486. coeff_diffs = diff.all_coeffs()[::-1][:maxdegree]
  487. (coeffs, ) = linsolve(coeff_diffs, syms)
  488. # Use the recursion relation for the rest
  489. recursion = den.all_coeffs()[::-1]
  490. div, rec_rhs = recursion[0], recursion[1:]
  491. series = list(coeffs)
  492. while len(series) < n:
  493. next_coeff = Add(*(c*series[-1-n] for n, c in enumerate(rec_rhs))) / div
  494. series.append(-next_coeff)
  495. series = {m - i: val for i, val in enumerate(series)}
  496. return series
  497. def compute_m_ybar(x, poles, choice, N):
  498. """
  499. Helper function to calculate -
  500. 1. m - The degree bound for the polynomial
  501. solution that must be found for the auxiliary
  502. differential equation.
  503. 2. ybar - Part of the solution which can be
  504. computed using the poles, c and d vectors.
  505. """
  506. ybar = 0
  507. m = Poly(choice[-1][-1], x, extension=True)
  508. # Calculate the first (nested) summation for ybar
  509. # as given in Step 9 of the Thesis (Pg 82)
  510. for i in range(len(poles)):
  511. for j in range(len(choice[i])):
  512. ybar += choice[i][j]/(x - poles[i])**(j+1)
  513. m -= Poly(choice[i][0], x, extension=True)
  514. # Calculate the second summation for ybar
  515. for i in range(N+1):
  516. ybar += choice[-1][i]*x**i
  517. return (m.expr, ybar)
  518. def solve_aux_eq(numa, dena, numy, deny, x, m):
  519. """
  520. Helper function to find a polynomial solution
  521. of degree m for the auxiliary differential
  522. equation.
  523. """
  524. # Assume that the solution is of the type
  525. # p(x) = C_0 + C_1*x + ... + C_{m-1}*x**(m-1) + x**m
  526. psyms = symbols(f'C0:{m}', cls=Dummy)
  527. K = ZZ[psyms]
  528. psol = Poly(K.gens, x, domain=K) + Poly(x**m, x, domain=K)
  529. # Eq (5.16) in Thesis - Pg 81
  530. auxeq = (dena*(numy.diff(x)*deny - numy*deny.diff(x) + numy**2) - numa*deny**2)*psol
  531. if m >= 1:
  532. px = psol.diff(x)
  533. auxeq += px*(2*numy*deny*dena)
  534. if m >= 2:
  535. auxeq += px.diff(x)*(deny**2*dena)
  536. if m != 0:
  537. # m is a non-zero integer. Find the constant terms using undetermined coefficients
  538. return psol, linsolve_dict(auxeq.all_coeffs(), psyms), True
  539. else:
  540. # m == 0 . Check if 1 (x**0) is a solution to the auxiliary equation
  541. return S.One, auxeq, auxeq == 0
  542. def remove_redundant_sols(sol1, sol2, x):
  543. """
  544. Helper function to remove redundant
  545. solutions to the differential equation.
  546. """
  547. # If y1 and y2 are redundant solutions, there is
  548. # some value of the arbitrary constant for which
  549. # they will be equal
  550. syms1 = sol1.atoms(Symbol, Dummy)
  551. syms2 = sol2.atoms(Symbol, Dummy)
  552. num1, den1 = [Poly(e, x, extension=True) for e in sol1.together().as_numer_denom()]
  553. num2, den2 = [Poly(e, x, extension=True) for e in sol2.together().as_numer_denom()]
  554. # Cross multiply
  555. e = num1*den2 - den1*num2
  556. # Check if there are any constants
  557. syms = list(e.atoms(Symbol, Dummy))
  558. if len(syms):
  559. # Find values of constants for which solutions are equal
  560. redn = linsolve(e.all_coeffs(), syms)
  561. if len(redn):
  562. # Return the general solution over a particular solution
  563. if len(syms1) > len(syms2):
  564. return sol2
  565. # If both have constants, return the lesser complex solution
  566. elif len(syms1) == len(syms2):
  567. return sol1 if count_ops(syms1) >= count_ops(syms2) else sol2
  568. else:
  569. return sol1
  570. def get_gen_sol_from_part_sol(part_sols, a, x):
  571. """"
  572. Helper function which computes the general
  573. solution for a Riccati ODE from its particular
  574. solutions.
  575. There are 3 cases to find the general solution
  576. from the particular solutions for a Riccati ODE
  577. depending on the number of particular solution(s)
  578. we have - 1, 2 or 3.
  579. For more information, see Section 6 of
  580. "Methods of Solution of the Riccati Differential Equation"
  581. by D. R. Haaheim and F. M. Stein
  582. """
  583. # If no particular solutions are found, a general
  584. # solution cannot be found
  585. if len(part_sols) == 0:
  586. return []
  587. # In case of a single particular solution, the general
  588. # solution can be found by using the substitution
  589. # y = y1 + 1/z and solving a Bernoulli ODE to find z.
  590. elif len(part_sols) == 1:
  591. y1 = part_sols[0]
  592. i = exp(Integral(2*y1, x))
  593. z = i * Integral(a/i, x)
  594. z = z.doit()
  595. if a == 0 or z == 0:
  596. return y1
  597. return y1 + 1/z
  598. # In case of 2 particular solutions, the general solution
  599. # can be found by solving a separable equation. This is
  600. # the most common case, i.e. most Riccati ODEs have 2
  601. # rational particular solutions.
  602. elif len(part_sols) == 2:
  603. y1, y2 = part_sols
  604. # One of them already has a constant
  605. if len(y1.atoms(Dummy)) + len(y2.atoms(Dummy)) > 0:
  606. u = exp(Integral(y2 - y1, x)).doit()
  607. # Introduce a constant
  608. else:
  609. C1 = Dummy('C1')
  610. u = C1*exp(Integral(y2 - y1, x)).doit()
  611. if u == 1:
  612. return y2
  613. return (y2*u - y1)/(u - 1)
  614. # In case of 3 particular solutions, a closed form
  615. # of the general solution can be obtained directly
  616. else:
  617. y1, y2, y3 = part_sols[:3]
  618. C1 = Dummy('C1')
  619. return (C1 + 1)*y2*(y1 - y3)/(C1*y1 + y2 - (C1 + 1)*y3)
  620. def solve_riccati(fx, x, b0, b1, b2, gensol=False):
  621. """
  622. The main function that gives particular/general
  623. solutions to Riccati ODEs that have atleast 1
  624. rational particular solution.
  625. """
  626. # Step 1 : Convert to Normal Form
  627. a = -b0*b2 + b1**2/4 - b1.diff(x)/2 + 3*b2.diff(x)**2/(4*b2**2) + b1*b2.diff(x)/(2*b2) - \
  628. b2.diff(x, 2)/(2*b2)
  629. a_t = a.together()
  630. num, den = [Poly(e, x, extension=True) for e in a_t.as_numer_denom()]
  631. num, den = num.cancel(den, include=True)
  632. # Step 2
  633. presol = []
  634. # Step 3 : a(x) is 0
  635. if num == 0:
  636. presol.append(1/(x + Dummy('C1')))
  637. # Step 4 : a(x) is a non-zero constant
  638. elif x not in num.free_symbols.union(den.free_symbols):
  639. presol.extend([sqrt(a), -sqrt(a)])
  640. # Step 5 : Find poles and valuation at infinity
  641. poles = roots(den, x)
  642. poles, muls = list(poles.keys()), list(poles.values())
  643. val_inf = val_at_inf(num, den, x)
  644. if len(poles):
  645. # Check necessary conditions (outlined in the module docstring)
  646. if not check_necessary_conds(val_inf, muls):
  647. raise ValueError("Rational Solution doesn't exist")
  648. # Step 6
  649. # Construct c-vectors for each singular point
  650. c = construct_c(num, den, x, poles, muls)
  651. # Construct d vectors for each singular point
  652. d = construct_d(num, den, x, val_inf)
  653. # Step 7 : Iterate over all possible combinations and return solutions
  654. # For each possible combination, generate an array of 0's and 1's
  655. # where 0 means pick 1st choice and 1 means pick the second choice.
  656. # NOTE: We could exit from the loop if we find 3 particular solutions,
  657. # but it is not implemented here as -
  658. # a. Finding 3 particular solutions is very rare. Most of the time,
  659. # only 2 particular solutions are found.
  660. # b. In case we exit after finding 3 particular solutions, it might
  661. # happen that 1 or 2 of them are redundant solutions. So, instead of
  662. # spending some more time in computing the particular solutions,
  663. # we will end up computing the general solution from a single
  664. # particular solution which is usually slower than computing the
  665. # general solution from 2 or 3 particular solutions.
  666. c.append(d)
  667. choices = product(*c)
  668. for choice in choices:
  669. m, ybar = compute_m_ybar(x, poles, choice, -val_inf//2)
  670. numy, deny = [Poly(e, x, extension=True) for e in ybar.together().as_numer_denom()]
  671. # Step 10 : Check if a valid solution exists. If yes, also check
  672. # if m is a non-negative integer
  673. if m.is_nonnegative == True and m.is_integer == True:
  674. # Step 11 : Find polynomial solutions of degree m for the auxiliary equation
  675. psol, coeffs, exists = solve_aux_eq(num, den, numy, deny, x, m)
  676. # Step 12 : If valid polynomial solution exists, append solution.
  677. if exists:
  678. # m == 0 case
  679. if psol == 1 and coeffs == 0:
  680. # p(x) = 1, so p'(x)/p(x) term need not be added
  681. presol.append(ybar)
  682. # m is a positive integer and there are valid coefficients
  683. elif len(coeffs):
  684. # Substitute the valid coefficients to get p(x)
  685. psol = psol.xreplace(coeffs)
  686. # y(x) = ybar(x) + p'(x)/p(x)
  687. presol.append(ybar + psol.diff(x)/psol)
  688. # Remove redundant solutions from the list of existing solutions
  689. remove = set()
  690. for i in range(len(presol)):
  691. for j in range(i+1, len(presol)):
  692. rem = remove_redundant_sols(presol[i], presol[j], x)
  693. if rem is not None:
  694. remove.add(rem)
  695. sols = [x for x in presol if x not in remove]
  696. # Step 15 : Inverse transform the solutions of the equation in normal form
  697. bp = -b2.diff(x)/(2*b2**2) - b1/(2*b2)
  698. # If general solution is required, compute it from the particular solutions
  699. if gensol:
  700. sols = [get_gen_sol_from_part_sol(sols, a, x)]
  701. # Inverse transform the particular solutions
  702. presol = [Eq(fx, riccati_inverse_normal(y, x, b1, b2, bp).cancel(extension=True)) for y in sols]
  703. return presol