prde.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. """
  2. Algorithms for solving Parametric Risch Differential Equations.
  3. The methods used for solving Parametric Risch Differential Equations parallel
  4. those for solving Risch Differential Equations. See the outline in the
  5. docstring of rde.py for more information.
  6. The Parametric Risch Differential Equation problem is, given f, g1, ..., gm in
  7. K(t), to determine if there exist y in K(t) and c1, ..., cm in Const(K) such
  8. that Dy + f*y == Sum(ci*gi, (i, 1, m)), and to find such y and ci if they exist.
  9. For the algorithms here G is a list of tuples of factions of the terms on the
  10. right hand side of the equation (i.e., gi in k(t)), and Q is a list of terms on
  11. the right hand side of the equation (i.e., qi in k[t]). See the docstring of
  12. each function for more information.
  13. """
  14. import itertools
  15. from functools import reduce
  16. from sympy.core.intfunc import ilcm
  17. from sympy.core import Dummy, Add, Mul, Pow, S
  18. from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer,
  19. bound_degree)
  20. from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation,
  21. residue_reduce, splitfactor, residue_reduce_derivation, DecrementLevel,
  22. recognize_log_derivative)
  23. from sympy.polys import Poly, lcm, cancel, sqf_list
  24. from sympy.polys.polymatrix import PolyMatrix as Matrix
  25. from sympy.solvers import solve
  26. zeros = Matrix.zeros
  27. eye = Matrix.eye
  28. def prde_normal_denom(fa, fd, G, DE):
  29. """
  30. Parametric Risch Differential Equation - Normal part of the denominator.
  31. Explanation
  32. ===========
  33. Given a derivation D on k[t] and f, g1, ..., gm in k(t) with f weakly
  34. normalized with respect to t, return the tuple (a, b, G, h) such that
  35. a, h in k[t], b in k<t>, G = [g1, ..., gm] in k(t)^m, and for any solution
  36. c1, ..., cm in Const(k) and y in k(t) of Dy + f*y == Sum(ci*gi, (i, 1, m)),
  37. q == y*h in k<t> satisfies a*Dq + b*q == Sum(ci*Gi, (i, 1, m)).
  38. """
  39. dn, ds = splitfactor(fd, DE)
  40. Gas, Gds = list(zip(*G))
  41. gd = reduce(lambda i, j: i.lcm(j), Gds, Poly(1, DE.t))
  42. en, es = splitfactor(gd, DE)
  43. p = dn.gcd(en)
  44. h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t)))
  45. a = dn*h
  46. c = a*h
  47. ba = a*fa - dn*derivation(h, DE)*fd
  48. ba, bd = ba.cancel(fd, include=True)
  49. G = [(c*A).cancel(D, include=True) for A, D in G]
  50. return (a, (ba, bd), G, h)
  51. def real_imag(ba, bd, gen):
  52. """
  53. Helper function, to get the real and imaginary part of a rational function
  54. evaluated at sqrt(-1) without actually evaluating it at sqrt(-1).
  55. Explanation
  56. ===========
  57. Separates the even and odd power terms by checking the degree of terms wrt
  58. mod 4. Returns a tuple (ba[0], ba[1], bd) where ba[0] is real part
  59. of the numerator ba[1] is the imaginary part and bd is the denominator
  60. of the rational function.
  61. """
  62. bd = bd.as_poly(gen).as_dict()
  63. ba = ba.as_poly(gen).as_dict()
  64. denom_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in bd.items()]
  65. denom_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in bd.items()]
  66. bd_real = sum(r for r in denom_real)
  67. bd_imag = sum(r for r in denom_imag)
  68. num_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in ba.items()]
  69. num_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in ba.items()]
  70. ba_real = sum(r for r in num_real)
  71. ba_imag = sum(r for r in num_imag)
  72. ba = ((ba_real*bd_real + ba_imag*bd_imag).as_poly(gen), (ba_imag*bd_real - ba_real*bd_imag).as_poly(gen))
  73. bd = (bd_real*bd_real + bd_imag*bd_imag).as_poly(gen)
  74. return (ba[0], ba[1], bd)
  75. def prde_special_denom(a, ba, bd, G, DE, case='auto'):
  76. """
  77. Parametric Risch Differential Equation - Special part of the denominator.
  78. Explanation
  79. ===========
  80. Case is one of {'exp', 'tan', 'primitive'} for the hyperexponential,
  81. hypertangent, and primitive cases, respectively. For the hyperexponential
  82. (resp. hypertangent) case, given a derivation D on k[t] and a in k[t],
  83. b in k<t>, and g1, ..., gm in k(t) with Dt/t in k (resp. Dt/(t**2 + 1) in
  84. k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp.
  85. gcd(a, t**2 + 1) == 1), return the tuple (A, B, GG, h) such that A, B, h in
  86. k[t], GG = [gg1, ..., ggm] in k(t)^m, and for any solution c1, ..., cm in
  87. Const(k) and q in k<t> of a*Dq + b*q == Sum(ci*gi, (i, 1, m)), r == q*h in
  88. k[t] satisfies A*Dr + B*r == Sum(ci*ggi, (i, 1, m)).
  89. For case == 'primitive', k<t> == k[t], so it returns (a, b, G, 1) in this
  90. case.
  91. """
  92. # TODO: Merge this with the very similar special_denom() in rde.py
  93. if case == 'auto':
  94. case = DE.case
  95. if case == 'exp':
  96. p = Poly(DE.t, DE.t)
  97. elif case == 'tan':
  98. p = Poly(DE.t**2 + 1, DE.t)
  99. elif case in ('primitive', 'base'):
  100. B = ba.quo(bd)
  101. return (a, B, G, Poly(1, DE.t))
  102. else:
  103. raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
  104. "'base'}, not %s." % case)
  105. nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t)
  106. nc = min(order_at(Ga, p, DE.t) - order_at(Gd, p, DE.t) for Ga, Gd in G)
  107. n = min(0, nc - min(0, nb))
  108. if not nb:
  109. # Possible cancellation.
  110. if case == 'exp':
  111. dcoeff = DE.d.quo(Poly(DE.t, DE.t))
  112. with DecrementLevel(DE): # We are guaranteed to not have problems,
  113. # because case != 'base'.
  114. alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t)
  115. etaa, etad = frac_in(dcoeff, DE.t)
  116. A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
  117. if A is not None:
  118. Q, m, z = A
  119. if Q == 1:
  120. n = min(n, m)
  121. elif case == 'tan':
  122. dcoeff = DE.d.quo(Poly(DE.t**2 + 1, DE.t))
  123. with DecrementLevel(DE): # We are guaranteed to not have problems,
  124. # because case != 'base'.
  125. betaa, alphaa, alphad = real_imag(ba, bd*a, DE.t)
  126. betad = alphad
  127. etaa, etad = frac_in(dcoeff, DE.t)
  128. if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE):
  129. A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
  130. B = parametric_log_deriv(betaa, betad, etaa, etad, DE)
  131. if A is not None and B is not None:
  132. Q, s, z = A
  133. # TODO: Add test
  134. if Q == 1:
  135. n = min(n, s/2)
  136. N = max(0, -nb)
  137. pN = p**N
  138. pn = p**-n # This is 1/h
  139. A = a*pN
  140. B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN
  141. G = [(Ga*pN*pn).cancel(Gd, include=True) for Ga, Gd in G]
  142. h = pn
  143. # (a*p**N, (b + n*a*Dp/p)*p**N, g1*p**(N - n), ..., gm*p**(N - n), p**-n)
  144. return (A, B, G, h)
  145. def prde_linear_constraints(a, b, G, DE):
  146. """
  147. Parametric Risch Differential Equation - Generate linear constraints on the constants.
  148. Explanation
  149. ===========
  150. Given a derivation D on k[t], a, b, in k[t] with gcd(a, b) == 1, and
  151. G = [g1, ..., gm] in k(t)^m, return Q = [q1, ..., qm] in k[t]^m and a
  152. matrix M with entries in k(t) such that for any solution c1, ..., cm in
  153. Const(k) and p in k[t] of a*Dp + b*p == Sum(ci*gi, (i, 1, m)),
  154. (c1, ..., cm) is a solution of Mx == 0, and p and the ci satisfy
  155. a*Dp + b*p == Sum(ci*qi, (i, 1, m)).
  156. Because M has entries in k(t), and because Matrix does not play well with
  157. Poly, M will be a Matrix of Basic expressions.
  158. """
  159. m = len(G)
  160. Gns, Gds = list(zip(*G))
  161. d = reduce(lambda i, j: i.lcm(j), Gds)
  162. d = Poly(d, field=True)
  163. Q = [(ga*(d).quo(gd)).div(d) for ga, gd in G]
  164. if not all(ri.is_zero for _, ri in Q):
  165. N = max(ri.degree(DE.t) for _, ri in Q)
  166. M = Matrix(N + 1, m, lambda i, j: Q[j][1].nth(i), DE.t)
  167. else:
  168. M = Matrix(0, m, [], DE.t) # No constraints, return the empty matrix.
  169. qs, _ = list(zip(*Q))
  170. return (qs, M)
  171. def poly_linear_constraints(p, d):
  172. """
  173. Given p = [p1, ..., pm] in k[t]^m and d in k[t], return
  174. q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such
  175. that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible
  176. by d if and only if (c1, ..., cm) is a solution of Mx = 0, in
  177. which case the quotient is Sum(ci*qi, (i, 1, m)).
  178. """
  179. m = len(p)
  180. q, r = zip(*[pi.div(d) for pi in p])
  181. if not all(ri.is_zero for ri in r):
  182. n = max(ri.degree() for ri in r)
  183. M = Matrix(n + 1, m, lambda i, j: r[j].nth(i), d.gens)
  184. else:
  185. M = Matrix(0, m, [], d.gens) # No constraints.
  186. return q, M
  187. def constant_system(A, u, DE):
  188. """
  189. Generate a system for the constant solutions.
  190. Explanation
  191. ===========
  192. Given a differential field (K, D) with constant field C = Const(K), a Matrix
  193. A, and a vector (Matrix) u with coefficients in K, returns the tuple
  194. (B, v, s), where B is a Matrix with coefficients in C and v is a vector
  195. (Matrix) such that either v has coefficients in C, in which case s is True
  196. and the solutions in C of Ax == u are exactly all the solutions of Bx == v,
  197. or v has a non-constant coefficient, in which case s is False Ax == u has no
  198. constant solution.
  199. This algorithm is used both in solving parametric problems and in
  200. determining if an element a of K is a derivative of an element of K or the
  201. logarithmic derivative of a K-radical using the structure theorem approach.
  202. Because Poly does not play well with Matrix yet, this algorithm assumes that
  203. all matrix entries are Basic expressions.
  204. """
  205. if not A:
  206. return A, u
  207. Au = A.row_join(u)
  208. Au, _ = Au.rref()
  209. # Warning: This will NOT return correct results if cancel() cannot reduce
  210. # an identically zero expression to 0. The danger is that we might
  211. # incorrectly prove that an integral is nonelementary (such as
  212. # risch_integrate(exp((sin(x)**2 + cos(x)**2 - 1)*x**2), x).
  213. # But this is a limitation in computer algebra in general, and implicit
  214. # in the correctness of the Risch Algorithm is the computability of the
  215. # constant field (actually, this same correctness problem exists in any
  216. # algorithm that uses rref()).
  217. #
  218. # We therefore limit ourselves to constant fields that are computable
  219. # via the cancel() function, in order to prevent a speed bottleneck from
  220. # calling some more complex simplification function (rational function
  221. # coefficients will fall into this class). Furthermore, (I believe) this
  222. # problem will only crop up if the integral explicitly contains an
  223. # expression in the constant field that is identically zero, but cannot
  224. # be reduced to such by cancel(). Therefore, a careful user can avoid this
  225. # problem entirely by being careful with the sorts of expressions that
  226. # appear in his integrand in the variables other than the integration
  227. # variable (the structure theorems should be able to completely decide these
  228. # problems in the integration variable).
  229. A, u = Au[:, :-1], Au[:, -1]
  230. D = lambda x: derivation(x, DE, basic=True)
  231. for j, i in itertools.product(range(A.cols), range(A.rows)):
  232. if A[i, j].expr.has(*DE.T):
  233. # This assumes that const(F(t0, ..., tn) == const(K) == F
  234. Ri = A[i, :]
  235. # Rm+1; m = A.rows
  236. DAij = D(A[i, j])
  237. Rm1 = Ri.applyfunc(lambda x: D(x) / DAij)
  238. um1 = D(u[i]) / DAij
  239. Aj = A[:, j]
  240. A = A - Aj * Rm1
  241. u = u - Aj * um1
  242. A = A.col_join(Rm1)
  243. u = u.col_join(Matrix([um1], u.gens))
  244. return (A, u)
  245. def prde_spde(a, b, Q, n, DE):
  246. """
  247. Special Polynomial Differential Equation algorithm: Parametric Version.
  248. Explanation
  249. ===========
  250. Given a derivation D on k[t], an integer n, and a, b, q1, ..., qm in k[t]
  251. with deg(a) > 0 and gcd(a, b) == 1, return (A, B, Q, R, n1), with
  252. Qq = [q1, ..., qm] and R = [r1, ..., rm], such that for any solution
  253. c1, ..., cm in Const(k) and q in k[t] of degree at most n of
  254. a*Dq + b*q == Sum(ci*gi, (i, 1, m)), p = (q - Sum(ci*ri, (i, 1, m)))/a has
  255. degree at most n1 and satisfies A*Dp + B*p == Sum(ci*qi, (i, 1, m))
  256. """
  257. R, Z = list(zip(*[gcdex_diophantine(b, a, qi) for qi in Q]))
  258. A = a
  259. B = b + derivation(a, DE)
  260. Qq = [zi - derivation(ri, DE) for ri, zi in zip(R, Z)]
  261. R = list(R)
  262. n1 = n - a.degree(DE.t)
  263. return (A, B, Qq, R, n1)
  264. def prde_no_cancel_b_large(b, Q, n, DE):
  265. """
  266. Parametric Poly Risch Differential Equation - No cancellation: deg(b) large enough.
  267. Explanation
  268. ===========
  269. Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
  270. b != 0 and either D == d/dt or deg(b) > max(0, deg(D) - 1), returns
  271. h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
  272. if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
  273. Dq + b*q == Sum(ci*qi, (i, 1, m)), then q = Sum(dj*hj, (j, 1, r)), where
  274. d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
  275. """
  276. db = b.degree(DE.t)
  277. m = len(Q)
  278. H = [Poly(0, DE.t)]*m
  279. for N, i in itertools.product(range(n, -1, -1), range(m)): # [n, ..., 0]
  280. si = Q[i].nth(N + db)/b.LC()
  281. sitn = Poly(si*DE.t**N, DE.t)
  282. H[i] = H[i] + sitn
  283. Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
  284. if all(qi.is_zero for qi in Q):
  285. dc = -1
  286. else:
  287. dc = max(qi.degree(DE.t) for qi in Q)
  288. M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
  289. A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
  290. c = eye(m, DE.t)
  291. A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
  292. return (H, A)
  293. def prde_no_cancel_b_small(b, Q, n, DE):
  294. """
  295. Parametric Poly Risch Differential Equation - No cancellation: deg(b) small enough.
  296. Explanation
  297. ===========
  298. Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
  299. deg(b) < deg(D) - 1 and either D == d/dt or deg(D) >= 2, returns
  300. h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
  301. if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
  302. Dq + b*q == Sum(ci*qi, (i, 1, m)) then q = Sum(dj*hj, (j, 1, r)) where
  303. d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
  304. """
  305. m = len(Q)
  306. H = [Poly(0, DE.t)]*m
  307. for N, i in itertools.product(range(n, 0, -1), range(m)): # [n, ..., 1]
  308. si = Q[i].nth(N + DE.d.degree(DE.t) - 1)/(N*DE.d.LC())
  309. sitn = Poly(si*DE.t**N, DE.t)
  310. H[i] = H[i] + sitn
  311. Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
  312. if b.degree(DE.t) > 0:
  313. for i in range(m):
  314. si = Poly(Q[i].nth(b.degree(DE.t))/b.LC(), DE.t)
  315. H[i] = H[i] + si
  316. Q[i] = Q[i] - derivation(si, DE) - b*si
  317. if all(qi.is_zero for qi in Q):
  318. dc = -1
  319. else:
  320. dc = max(qi.degree(DE.t) for qi in Q)
  321. M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
  322. A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
  323. c = eye(m, DE.t)
  324. A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
  325. return (H, A)
  326. # else: b is in k, deg(qi) < deg(Dt)
  327. t = DE.t
  328. if DE.case != 'base':
  329. with DecrementLevel(DE):
  330. t0 = DE.t # k = k0(t0)
  331. ba, bd = frac_in(b, t0, field=True)
  332. Q0 = [frac_in(qi.TC(), t0, field=True) for qi in Q]
  333. f, B = param_rischDE(ba, bd, Q0, DE)
  334. # f = [f1, ..., fr] in k^r and B is a matrix with
  335. # m + r columns and entries in Const(k) = Const(k0)
  336. # such that Dy0 + b*y0 = Sum(ci*qi, (i, 1, m)) has
  337. # a solution y0 in k with c1, ..., cm in Const(k)
  338. # if and only y0 = Sum(dj*fj, (j, 1, r)) where
  339. # d1, ..., dr ar in Const(k) and
  340. # B*Matrix([c1, ..., cm, d1, ..., dr]) == 0.
  341. # Transform fractions (fa, fd) in f into constant
  342. # polynomials fa/fd in k[t].
  343. # (Is there a better way?)
  344. f = [Poly(fa.as_expr()/fd.as_expr(), t, field=True)
  345. for fa, fd in f]
  346. B = Matrix.from_Matrix(B.to_Matrix(), t)
  347. else:
  348. # Base case. Dy == 0 for all y in k and b == 0.
  349. # Dy + b*y = Sum(ci*qi) is solvable if and only if
  350. # Sum(ci*qi) == 0 in which case the solutions are
  351. # y = d1*f1 for f1 = 1 and any d1 in Const(k) = k.
  352. f = [Poly(1, t, field=True)] # r = 1
  353. B = Matrix([[qi.TC() for qi in Q] + [S.Zero]], DE.t)
  354. # The condition for solvability is
  355. # B*Matrix([c1, ..., cm, d1]) == 0
  356. # There are no constraints on d1.
  357. # Coefficients of t^j (j > 0) in Sum(ci*qi) must be zero.
  358. d = max(qi.degree(DE.t) for qi in Q)
  359. if d > 0:
  360. M = Matrix(d, m, lambda i, j: Q[j].nth(i + 1), DE.t)
  361. A, _ = constant_system(M, zeros(d, 1, DE.t), DE)
  362. else:
  363. # No constraints on the hj.
  364. A = Matrix(0, m, [], DE.t)
  365. # Solutions of the original equation are
  366. # y = Sum(dj*fj, (j, 1, r) + Sum(ei*hi, (i, 1, m)),
  367. # where ei == ci (i = 1, ..., m), when
  368. # A*Matrix([c1, ..., cm]) == 0 and
  369. # B*Matrix([c1, ..., cm, d1, ..., dr]) == 0
  370. # Build combined constraint matrix with m + r + m columns.
  371. r = len(f)
  372. I = eye(m, DE.t)
  373. A = A.row_join(zeros(A.rows, r + m, DE.t))
  374. B = B.row_join(zeros(B.rows, m, DE.t))
  375. C = I.row_join(zeros(m, r, DE.t)).row_join(-I)
  376. return f + H, A.col_join(B).col_join(C)
  377. def prde_cancel_liouvillian(b, Q, n, DE):
  378. """
  379. Pg, 237.
  380. """
  381. H = []
  382. # Why use DecrementLevel? Below line answers that:
  383. # Assuming that we can solve such problems over 'k' (not k[t])
  384. if DE.case == 'primitive':
  385. with DecrementLevel(DE):
  386. ba, bd = frac_in(b, DE.t, field=True)
  387. for i in range(n, -1, -1):
  388. if DE.case == 'exp': # this re-checking can be avoided
  389. with DecrementLevel(DE):
  390. ba, bd = frac_in(b + (i*(derivation(DE.t, DE)/DE.t)).as_poly(b.gens),
  391. DE.t, field=True)
  392. with DecrementLevel(DE):
  393. Qy = [frac_in(q.nth(i), DE.t, field=True) for q in Q]
  394. fi, Ai = param_rischDE(ba, bd, Qy, DE)
  395. fi = [Poly(fa.as_expr()/fd.as_expr(), DE.t, field=True)
  396. for fa, fd in fi]
  397. Ai = Ai.set_gens(DE.t)
  398. ri = len(fi)
  399. if i == n:
  400. M = Ai
  401. else:
  402. M = Ai.col_join(M.row_join(zeros(M.rows, ri, DE.t)))
  403. Fi, hi = [None]*ri, [None]*ri
  404. # from eq. on top of p.238 (unnumbered)
  405. for j in range(ri):
  406. hji = fi[j] * (DE.t**i).as_poly(fi[j].gens)
  407. hi[j] = hji
  408. # building up Sum(djn*(D(fjn*t^n) - b*fjnt^n))
  409. Fi[j] = -(derivation(hji, DE) - b*hji)
  410. H += hi
  411. # in the next loop instead of Q it has
  412. # to be Q + Fi taking its place
  413. Q = Q + Fi
  414. return (H, M)
  415. def param_poly_rischDE(a, b, q, n, DE):
  416. """Polynomial solutions of a parametric Risch differential equation.
  417. Explanation
  418. ===========
  419. Given a derivation D in k[t], a, b in k[t] relatively prime, and q
  420. = [q1, ..., qm] in k[t]^m, return h = [h1, ..., hr] in k[t]^r and
  421. a matrix A with m + r columns and entries in Const(k) such that
  422. a*Dp + b*p = Sum(ci*qi, (i, 1, m)) has a solution p of degree <= n
  423. in k[t] with c1, ..., cm in Const(k) if and only if p = Sum(dj*hj,
  424. (j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
  425. d1, ..., dr) is a solution of Ax == 0.
  426. """
  427. m = len(q)
  428. if n < 0:
  429. # Only the trivial zero solution is possible.
  430. # Find relations between the qi.
  431. if all(qi.is_zero for qi in q):
  432. return [], zeros(1, m, DE.t) # No constraints.
  433. N = max(qi.degree(DE.t) for qi in q)
  434. M = Matrix(N + 1, m, lambda i, j: q[j].nth(i), DE.t)
  435. A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
  436. return [], A
  437. if a.is_ground:
  438. # Normalization: a = 1.
  439. a = a.LC()
  440. b, q = b.to_field().exquo_ground(a), [qi.to_field().exquo_ground(a) for qi in q]
  441. if not b.is_zero and (DE.case == 'base' or
  442. b.degree() > max(0, DE.d.degree() - 1)):
  443. return prde_no_cancel_b_large(b, q, n, DE)
  444. elif ((b.is_zero or b.degree() < DE.d.degree() - 1)
  445. and (DE.case == 'base' or DE.d.degree() >= 2)):
  446. return prde_no_cancel_b_small(b, q, n, DE)
  447. elif (DE.d.degree() >= 2 and
  448. b.degree() == DE.d.degree() - 1 and
  449. n > -b.as_poly().LC()/DE.d.as_poly().LC()):
  450. raise NotImplementedError("prde_no_cancel_b_equal() is "
  451. "not yet implemented.")
  452. else:
  453. # Liouvillian cases
  454. if DE.case in ('primitive', 'exp'):
  455. return prde_cancel_liouvillian(b, q, n, DE)
  456. else:
  457. raise NotImplementedError("non-linear and hypertangent "
  458. "cases have not yet been implemented")
  459. # else: deg(a) > 0
  460. # Iterate SPDE as long as possible cumulating coefficient
  461. # and terms for the recovery of original solutions.
  462. alpha, beta = a.one, [a.zero]*m
  463. while n >= 0: # and a, b relatively prime
  464. a, b, q, r, n = prde_spde(a, b, q, n, DE)
  465. beta = [betai + alpha*ri for betai, ri in zip(beta, r)]
  466. alpha *= a
  467. # Solutions p of a*Dp + b*p = Sum(ci*qi) correspond to
  468. # solutions alpha*p + Sum(ci*betai) of the initial equation.
  469. d = a.gcd(b)
  470. if not d.is_ground:
  471. break
  472. # a*Dp + b*p = Sum(ci*qi) may have a polynomial solution
  473. # only if the sum is divisible by d.
  474. qq, M = poly_linear_constraints(q, d)
  475. # qq = [qq1, ..., qqm] where qqi = qi.quo(d).
  476. # M is a matrix with m columns an entries in k.
  477. # Sum(fi*qi, (i, 1, m)), where f1, ..., fm are elements of k, is
  478. # divisible by d if and only if M*Matrix([f1, ..., fm]) == 0,
  479. # in which case the quotient is Sum(fi*qqi).
  480. A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
  481. # A is a matrix with m columns and entries in Const(k).
  482. # Sum(ci*qqi) is Sum(ci*qi).quo(d), and the remainder is zero
  483. # for c1, ..., cm in Const(k) if and only if
  484. # A*Matrix([c1, ...,cm]) == 0.
  485. V = A.nullspace()
  486. # V = [v1, ..., vu] where each vj is a column matrix with
  487. # entries aj1, ..., ajm in Const(k).
  488. # Sum(aji*qi) is divisible by d with exact quotient Sum(aji*qqi).
  489. # Sum(ci*qi) is divisible by d if and only if ci = Sum(dj*aji)
  490. # (i = 1, ..., m) for some d1, ..., du in Const(k).
  491. # In that case, solutions of
  492. # a*Dp + b*p = Sum(ci*qi) = Sum(dj*Sum(aji*qi))
  493. # are the same as those of
  494. # (a/d)*Dp + (b/d)*p = Sum(dj*rj)
  495. # where rj = Sum(aji*qqi).
  496. if not V: # No non-trivial solution.
  497. return [], eye(m, DE.t) # Could return A, but this has
  498. # the minimum number of rows.
  499. Mqq = Matrix([qq]) # A single row.
  500. r = [(Mqq*vj)[0] for vj in V] # [r1, ..., ru]
  501. # Solutions of (a/d)*Dp + (b/d)*p = Sum(dj*rj) correspond to
  502. # solutions alpha*p + Sum(Sum(dj*aji)*betai) of the initial
  503. # equation. These are equal to alpha*p + Sum(dj*fj) where
  504. # fj = Sum(aji*betai).
  505. Mbeta = Matrix([beta])
  506. f = [(Mbeta*vj)[0] for vj in V] # [f1, ..., fu]
  507. #
  508. # Solve the reduced equation recursively.
  509. #
  510. g, B = param_poly_rischDE(a.quo(d), b.quo(d), r, n, DE)
  511. # g = [g1, ..., gv] in k[t]^v and and B is a matrix with u + v
  512. # columns and entries in Const(k) such that
  513. # (a/d)*Dp + (b/d)*p = Sum(dj*rj) has a solution p of degree <= n
  514. # in k[t] if and only if p = Sum(ek*gk) where e1, ..., ev are in
  515. # Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
  516. # The solutions of the original equation are then
  517. # Sum(dj*fj, (j, 1, u)) + alpha*Sum(ek*gk, (k, 1, v)).
  518. # Collect solution components.
  519. h = f + [alpha*gk for gk in g]
  520. # Build combined relation matrix.
  521. A = -eye(m, DE.t)
  522. for vj in V:
  523. A = A.row_join(vj)
  524. A = A.row_join(zeros(m, len(g), DE.t))
  525. A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
  526. return h, A
  527. def param_rischDE(fa, fd, G, DE):
  528. """
  529. Solve a Parametric Risch Differential Equation: Dy + f*y == Sum(ci*Gi, (i, 1, m)).
  530. Explanation
  531. ===========
  532. Given a derivation D in k(t), f in k(t), and G
  533. = [G1, ..., Gm] in k(t)^m, return h = [h1, ..., hr] in k(t)^r and
  534. a matrix A with m + r columns and entries in Const(k) such that
  535. Dy + f*y = Sum(ci*Gi, (i, 1, m)) has a solution y
  536. in k(t) with c1, ..., cm in Const(k) if and only if y = Sum(dj*hj,
  537. (j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
  538. d1, ..., dr) is a solution of Ax == 0.
  539. Elements of k(t) are tuples (a, d) with a and d in k[t].
  540. """
  541. m = len(G)
  542. q, (fa, fd) = weak_normalizer(fa, fd, DE)
  543. # Solutions of the weakly normalized equation Dz + f*z = q*Sum(ci*Gi)
  544. # correspond to solutions y = z/q of the original equation.
  545. gamma = q
  546. G = [(q*ga).cancel(gd, include=True) for ga, gd in G]
  547. a, (ba, bd), G, hn = prde_normal_denom(fa, fd, G, DE)
  548. # Solutions q in k<t> of a*Dq + b*q = Sum(ci*Gi) correspond
  549. # to solutions z = q/hn of the weakly normalized equation.
  550. gamma *= hn
  551. A, B, G, hs = prde_special_denom(a, ba, bd, G, DE)
  552. # Solutions p in k[t] of A*Dp + B*p = Sum(ci*Gi) correspond
  553. # to solutions q = p/hs of the previous equation.
  554. gamma *= hs
  555. g = A.gcd(B)
  556. a, b, g = A.quo(g), B.quo(g), [gia.cancel(gid*g, include=True) for
  557. gia, gid in G]
  558. # a*Dp + b*p = Sum(ci*gi) may have a polynomial solution
  559. # only if the sum is in k[t].
  560. q, M = prde_linear_constraints(a, b, g, DE)
  561. # q = [q1, ..., qm] where qi in k[t] is the polynomial component
  562. # of the partial fraction expansion of gi.
  563. # M is a matrix with m columns and entries in k.
  564. # Sum(fi*gi, (i, 1, m)), where f1, ..., fm are elements of k,
  565. # is a polynomial if and only if M*Matrix([f1, ..., fm]) == 0,
  566. # in which case the sum is equal to Sum(fi*qi).
  567. M, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
  568. # M is a matrix with m columns and entries in Const(k).
  569. # Sum(ci*gi) is in k[t] for c1, ..., cm in Const(k)
  570. # if and only if M*Matrix([c1, ..., cm]) == 0,
  571. # in which case the sum is Sum(ci*qi).
  572. ## Reduce number of constants at this point
  573. V = M.nullspace()
  574. # V = [v1, ..., vu] where each vj is a column matrix with
  575. # entries aj1, ..., ajm in Const(k).
  576. # Sum(aji*gi) is in k[t] and equal to Sum(aji*qi) (j = 1, ..., u).
  577. # Sum(ci*gi) is in k[t] if and only is ci = Sum(dj*aji)
  578. # (i = 1, ..., m) for some d1, ..., du in Const(k).
  579. # In that case,
  580. # Sum(ci*gi) = Sum(ci*qi) = Sum(dj*Sum(aji*qi)) = Sum(dj*rj)
  581. # where rj = Sum(aji*qi) (j = 1, ..., u) in k[t].
  582. if not V: # No non-trivial solution
  583. return [], eye(m, DE.t)
  584. Mq = Matrix([q]) # A single row.
  585. r = [(Mq*vj)[0] for vj in V] # [r1, ..., ru]
  586. # Solutions of a*Dp + b*p = Sum(dj*rj) correspond to solutions
  587. # y = p/gamma of the initial equation with ci = Sum(dj*aji).
  588. try:
  589. # We try n=5. At least for prde_spde, it will always
  590. # terminate no matter what n is.
  591. n = bound_degree(a, b, r, DE, parametric=True)
  592. except NotImplementedError:
  593. # A temporary bound is set. Eventually, it will be removed.
  594. # the currently added test case takes large time
  595. # even with n=5, and much longer with large n's.
  596. n = 5
  597. h, B = param_poly_rischDE(a, b, r, n, DE)
  598. # h = [h1, ..., hv] in k[t]^v and and B is a matrix with u + v
  599. # columns and entries in Const(k) such that
  600. # a*Dp + b*p = Sum(dj*rj) has a solution p of degree <= n
  601. # in k[t] if and only if p = Sum(ek*hk) where e1, ..., ev are in
  602. # Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
  603. # The solutions of the original equation for ci = Sum(dj*aji)
  604. # (i = 1, ..., m) are then y = Sum(ek*hk, (k, 1, v))/gamma.
  605. ## Build combined relation matrix with m + u + v columns.
  606. A = -eye(m, DE.t)
  607. for vj in V:
  608. A = A.row_join(vj)
  609. A = A.row_join(zeros(m, len(h), DE.t))
  610. A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
  611. ## Eliminate d1, ..., du.
  612. W = A.nullspace()
  613. # W = [w1, ..., wt] where each wl is a column matrix with
  614. # entries blk (k = 1, ..., m + u + v) in Const(k).
  615. # The vectors (bl1, ..., blm) generate the space of those
  616. # constant families (c1, ..., cm) for which a solution of
  617. # the equation Dy + f*y == Sum(ci*Gi) exists. They generate
  618. # the space and form a basis except possibly when Dy + f*y == 0
  619. # is solvable in k(t}. The corresponding solutions are
  620. # y = Sum(blk'*hk, (k, 1, v))/gamma, where k' = k + m + u.
  621. v = len(h)
  622. shape = (len(W), m+v)
  623. elements = [wl[:m] + wl[-v:] for wl in W] # excise dj's.
  624. items = [e for row in elements for e in row]
  625. # Need to set the shape in case W is empty
  626. M = Matrix(*shape, items, DE.t)
  627. N = M.nullspace()
  628. # N = [n1, ..., ns] where the ni in Const(k)^(m + v) are column
  629. # vectors generating the space of linear relations between
  630. # c1, ..., cm, e1, ..., ev.
  631. C = Matrix([ni[:] for ni in N], DE.t) # rows n1, ..., ns.
  632. return [hk.cancel(gamma, include=True) for hk in h], C
  633. def limited_integrate_reduce(fa, fd, G, DE):
  634. """
  635. Simpler version of step 1 & 2 for the limited integration problem.
  636. Explanation
  637. ===========
  638. Given a derivation D on k(t) and f, g1, ..., gn in k(t), return
  639. (a, b, h, N, g, V) such that a, b, h in k[t], N is a non-negative integer,
  640. g in k(t), V == [v1, ..., vm] in k(t)^m, and for any solution v in k(t),
  641. c1, ..., cm in C of f == Dv + Sum(ci*wi, (i, 1, m)), p = v*h is in k<t>, and
  642. p and the ci satisfy a*Dp + b*p == g + Sum(ci*vi, (i, 1, m)). Furthermore,
  643. if S1irr == Sirr, then p is in k[t], and if t is nonlinear or Liouvillian
  644. over k, then deg(p) <= N.
  645. So that the special part is always computed, this function calls the more
  646. general prde_special_denom() automatically if it cannot determine that
  647. S1irr == Sirr. Furthermore, it will automatically call bound_degree() when
  648. t is linear and non-Liouvillian, which for the transcendental case, implies
  649. that Dt == a*t + b with for some a, b in k*.
  650. """
  651. dn, ds = splitfactor(fd, DE)
  652. E = [splitfactor(gd, DE) for _, gd in G]
  653. En, Es = list(zip(*E))
  654. c = reduce(lambda i, j: i.lcm(j), (dn,) + En) # lcm(dn, en1, ..., enm)
  655. hn = c.gcd(c.diff(DE.t))
  656. a = hn
  657. b = -derivation(hn, DE)
  658. N = 0
  659. # These are the cases where we know that S1irr = Sirr, but there could be
  660. # others, and this algorithm will need to be extended to handle them.
  661. if DE.case in ('base', 'primitive', 'exp', 'tan'):
  662. hs = reduce(lambda i, j: i.lcm(j), (ds,) + Es) # lcm(ds, es1, ..., esm)
  663. a = hn*hs
  664. b -= (hn*derivation(hs, DE)).quo(hs)
  665. mu = min(order_at_oo(fa, fd, DE.t), min(order_at_oo(ga, gd, DE.t) for
  666. ga, gd in G))
  667. # So far, all the above are also nonlinear or Liouvillian, but if this
  668. # changes, then this will need to be updated to call bound_degree()
  669. # as per the docstring of this function (DE.case == 'other_linear').
  670. N = hn.degree(DE.t) + hs.degree(DE.t) + max(0, 1 - DE.d.degree(DE.t) - mu)
  671. else:
  672. # TODO: implement this
  673. raise NotImplementedError
  674. V = [(-a*hn*ga).cancel(gd, include=True) for ga, gd in G]
  675. return (a, b, a, N, (a*hn*fa).cancel(fd, include=True), V)
  676. def limited_integrate(fa, fd, G, DE):
  677. """
  678. Solves the limited integration problem: f = Dv + Sum(ci*wi, (i, 1, n))
  679. """
  680. fa, fd = fa*Poly(1/fd.LC(), DE.t), fd.monic()
  681. # interpreting limited integration problem as a
  682. # parametric Risch DE problem
  683. Fa = Poly(0, DE.t)
  684. Fd = Poly(1, DE.t)
  685. G = [(fa, fd)] + G
  686. h, A = param_rischDE(Fa, Fd, G, DE)
  687. V = A.nullspace()
  688. V = [v for v in V if v[0] != 0]
  689. if not V:
  690. return None
  691. else:
  692. # we can take any vector from V, we take V[0]
  693. c0 = V[0][0]
  694. # v = [-1, c1, ..., cm, d1, ..., dr]
  695. v = V[0]/(-c0)
  696. r = len(h)
  697. m = len(v) - r - 1
  698. C = list(v[1: m + 1])
  699. y = -sum(v[m + 1 + i]*h[i][0].as_expr()/h[i][1].as_expr() \
  700. for i in range(r))
  701. y_num, y_den = y.as_numer_denom()
  702. Ya, Yd = Poly(y_num, DE.t), Poly(y_den, DE.t)
  703. Y = Ya*Poly(1/Yd.LC(), DE.t), Yd.monic()
  704. return Y, C
  705. def parametric_log_deriv_heu(fa, fd, wa, wd, DE, c1=None):
  706. """
  707. Parametric logarithmic derivative heuristic.
  708. Explanation
  709. ===========
  710. Given a derivation D on k[t], f in k(t), and a hyperexponential monomial
  711. theta over k(t), raises either NotImplementedError, in which case the
  712. heuristic failed, or returns None, in which case it has proven that no
  713. solution exists, or returns a solution (n, m, v) of the equation
  714. n*f == Dv/v + m*Dtheta/theta, with v in k(t)* and n, m in ZZ with n != 0.
  715. If this heuristic fails, the structure theorem approach will need to be
  716. used.
  717. The argument w == Dtheta/theta
  718. """
  719. # TODO: finish writing this and write tests
  720. c1 = c1 or Dummy('c1')
  721. p, a = fa.div(fd)
  722. q, b = wa.div(wd)
  723. B = max(0, derivation(DE.t, DE).degree(DE.t) - 1)
  724. C = max(p.degree(DE.t), q.degree(DE.t))
  725. if q.degree(DE.t) > B:
  726. eqs = [p.nth(i) - c1*q.nth(i) for i in range(B + 1, C + 1)]
  727. s = solve(eqs, c1)
  728. if not s or not s[c1].is_Rational:
  729. # deg(q) > B, no solution for c.
  730. return None
  731. M, N = s[c1].as_numer_denom()
  732. M_poly = M.as_poly(q.gens)
  733. N_poly = N.as_poly(q.gens)
  734. nfmwa = N_poly*fa*wd - M_poly*wa*fd
  735. nfmwd = fd*wd
  736. Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE, 'auto')
  737. if Qv is None:
  738. # (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
  739. return None
  740. Q, v = Qv
  741. if Q.is_zero or v.is_zero:
  742. return None
  743. return (Q*N, Q*M, v)
  744. if p.degree(DE.t) > B:
  745. return None
  746. c = lcm(fd.as_poly(DE.t).LC(), wd.as_poly(DE.t).LC())
  747. l = fd.monic().lcm(wd.monic())*Poly(c, DE.t)
  748. ln, ls = splitfactor(l, DE)
  749. z = ls*ln.gcd(ln.diff(DE.t))
  750. if not z.has(DE.t):
  751. # TODO: We treat this as 'no solution', until the structure
  752. # theorem version of parametric_log_deriv is implemented.
  753. return None
  754. u1, r1 = (fa*l.quo(fd)).div(z) # (l*f).div(z)
  755. u2, r2 = (wa*l.quo(wd)).div(z) # (l*w).div(z)
  756. eqs = [r1.nth(i) - c1*r2.nth(i) for i in range(z.degree(DE.t))]
  757. s = solve(eqs, c1)
  758. if not s or not s[c1].is_Rational:
  759. # deg(q) <= B, no solution for c.
  760. return None
  761. M, N = s[c1].as_numer_denom()
  762. nfmwa = N.as_poly(DE.t)*fa*wd - M.as_poly(DE.t)*wa*fd
  763. nfmwd = fd*wd
  764. Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE)
  765. if Qv is None:
  766. # (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
  767. return None
  768. Q, v = Qv
  769. if Q.is_zero or v.is_zero:
  770. return None
  771. return (Q*N, Q*M, v)
  772. def parametric_log_deriv(fa, fd, wa, wd, DE):
  773. # TODO: Write the full algorithm using the structure theorems.
  774. # try:
  775. A = parametric_log_deriv_heu(fa, fd, wa, wd, DE)
  776. # except NotImplementedError:
  777. # Heuristic failed, we have to use the full method.
  778. # TODO: This could be implemented more efficiently.
  779. # It isn't too worrisome, because the heuristic handles most difficult
  780. # cases.
  781. return A
  782. def is_deriv_k(fa, fd, DE):
  783. r"""
  784. Checks if Df/f is the derivative of an element of k(t).
  785. Explanation
  786. ===========
  787. a in k(t) is the derivative of an element of k(t) if there exists b in k(t)
  788. such that a = Db. Either returns (ans, u), such that Df/f == Du, or None,
  789. which means that Df/f is not the derivative of an element of k(t). ans is
  790. a list of tuples such that Add(*[i*j for i, j in ans]) == u. This is useful
  791. for seeing exactly which elements of k(t) produce u.
  792. This function uses the structure theorem approach, which says that for any
  793. f in K, Df/f is the derivative of a element of K if and only if there are ri
  794. in QQ such that::
  795. --- --- Dt
  796. \ r * Dt + \ r * i Df
  797. / i i / i --- = --.
  798. --- --- t f
  799. i in L i in E i
  800. K/C(x) K/C(x)
  801. Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
  802. transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
  803. in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
  804. monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
  805. is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
  806. a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
  807. hyperexponential monomials of K over C(x)). If K is an elementary extension
  808. over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
  809. transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
  810. Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
  811. deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
  812. and L_K/C(x) are disjoint.
  813. The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
  814. recursively using this same function. Therefore, it is required to pass
  815. them as indices to D (or T). E_args are the arguments of the
  816. hyperexponentials indexed by E_K (i.e., if i is in E_K, then T[i] ==
  817. exp(E_args[i])). This is needed to compute the final answer u such that
  818. Df/f == Du.
  819. log(f) will be the same as u up to a additive constant. This is because
  820. they will both behave the same as monomials. For example, both log(x) and
  821. log(2*x) == log(x) + log(2) satisfy Dt == 1/x, because log(2) is constant.
  822. Therefore, the term const is returned. const is such that
  823. log(const) + f == u. This is calculated by dividing the arguments of one
  824. logarithm from the other. Therefore, it is necessary to pass the arguments
  825. of the logarithmic terms in L_args.
  826. To handle the case where we are given Df/f, not f, use is_deriv_k_in_field().
  827. See also
  828. ========
  829. is_log_deriv_k_t_radical_in_field, is_log_deriv_k_t_radical
  830. """
  831. # Compute Df/f
  832. dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)), fd*fa
  833. dfa, dfd = dfa.cancel(dfd, include=True)
  834. # Our assumption here is that each monomial is recursively transcendental
  835. if len(DE.exts) != len(DE.D):
  836. if [i for i in DE.cases if i == 'tan'] or \
  837. ({i for i in DE.cases if i == 'primitive'} -
  838. set(DE.indices('log'))):
  839. raise NotImplementedError("Real version of the structure "
  840. "theorems with hypertangent support is not yet implemented.")
  841. # TODO: What should really be done in this case?
  842. raise NotImplementedError("Nonelementary extensions not supported "
  843. "in the structure theorems.")
  844. E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
  845. L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
  846. # The expression dfa/dfd might not be polynomial in any of its symbols so we
  847. # use a Dummy as the generator for PolyMatrix.
  848. dum = Dummy()
  849. lhs = Matrix([E_part + L_part], dum)
  850. rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
  851. A, u = constant_system(lhs, rhs, DE)
  852. u = u.to_Matrix() # Poly to Expr
  853. if not A or not all(derivation(i, DE, basic=True).is_zero for i in u):
  854. # If the elements of u are not all constant
  855. # Note: See comment in constant_system
  856. # Also note: derivation(basic=True) calls cancel()
  857. return None
  858. else:
  859. if not all(i.is_Rational for i in u):
  860. raise NotImplementedError("Cannot work with non-rational "
  861. "coefficients in this case.")
  862. else:
  863. terms = ([DE.extargs[i] for i in DE.indices('exp')] +
  864. [DE.T[i] for i in DE.indices('log')])
  865. ans = list(zip(terms, u))
  866. result = Add(*[Mul(i, j) for i, j in ans])
  867. argterms = ([DE.T[i] for i in DE.indices('exp')] +
  868. [DE.extargs[i] for i in DE.indices('log')])
  869. l = []
  870. ld = []
  871. for i, j in zip(argterms, u):
  872. # We need to get around things like sqrt(x**2) != x
  873. # and also sqrt(x**2 + 2*x + 1) != x + 1
  874. # Issue 10798: i need not be a polynomial
  875. i, d = i.as_numer_denom()
  876. icoeff, iterms = sqf_list(i)
  877. l.append(Mul(*([Pow(icoeff, j)] + [Pow(b, e*j) for b, e in iterms])))
  878. dcoeff, dterms = sqf_list(d)
  879. ld.append(Mul(*([Pow(dcoeff, j)] + [Pow(b, e*j) for b, e in dterms])))
  880. const = cancel(fa.as_expr()/fd.as_expr()/Mul(*l)*Mul(*ld))
  881. return (ans, result, const)
  882. def is_log_deriv_k_t_radical(fa, fd, DE, Df=True):
  883. r"""
  884. Checks if Df is the logarithmic derivative of a k(t)-radical.
  885. Explanation
  886. ===========
  887. b in k(t) can be written as the logarithmic derivative of a k(t) radical if
  888. there exist n in ZZ and u in k(t) with n, u != 0 such that n*b == Du/u.
  889. Either returns (ans, u, n, const) or None, which means that Df cannot be
  890. written as the logarithmic derivative of a k(t)-radical. ans is a list of
  891. tuples such that Mul(*[i**j for i, j in ans]) == u. This is useful for
  892. seeing exactly what elements of k(t) produce u.
  893. This function uses the structure theorem approach, which says that for any
  894. f in K, Df is the logarithmic derivative of a K-radical if and only if there
  895. are ri in QQ such that::
  896. --- --- Dt
  897. \ r * Dt + \ r * i
  898. / i i / i --- = Df.
  899. --- --- t
  900. i in L i in E i
  901. K/C(x) K/C(x)
  902. Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
  903. transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
  904. in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
  905. monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
  906. is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
  907. a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
  908. hyperexponential monomials of K over C(x)). If K is an elementary extension
  909. over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
  910. transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
  911. Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
  912. deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
  913. and L_K/C(x) are disjoint.
  914. The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
  915. recursively using this same function. Therefore, it is required to pass
  916. them as indices to D (or T). L_args are the arguments of the logarithms
  917. indexed by L_K (i.e., if i is in L_K, then T[i] == log(L_args[i])). This is
  918. needed to compute the final answer u such that n*f == Du/u.
  919. exp(f) will be the same as u up to a multiplicative constant. This is
  920. because they will both behave the same as monomials. For example, both
  921. exp(x) and exp(x + 1) == E*exp(x) satisfy Dt == t. Therefore, the term const
  922. is returned. const is such that exp(const)*f == u. This is calculated by
  923. subtracting the arguments of one exponential from the other. Therefore, it
  924. is necessary to pass the arguments of the exponential terms in E_args.
  925. To handle the case where we are given Df, not f, use
  926. is_log_deriv_k_t_radical_in_field().
  927. See also
  928. ========
  929. is_log_deriv_k_t_radical_in_field, is_deriv_k
  930. """
  931. if Df:
  932. dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)).cancel(fd**2,
  933. include=True)
  934. else:
  935. dfa, dfd = fa, fd
  936. # Our assumption here is that each monomial is recursively transcendental
  937. if len(DE.exts) != len(DE.D):
  938. if [i for i in DE.cases if i == 'tan'] or \
  939. ({i for i in DE.cases if i == 'primitive'} -
  940. set(DE.indices('log'))):
  941. raise NotImplementedError("Real version of the structure "
  942. "theorems with hypertangent support is not yet implemented.")
  943. # TODO: What should really be done in this case?
  944. raise NotImplementedError("Nonelementary extensions not supported "
  945. "in the structure theorems.")
  946. E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
  947. L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
  948. # The expression dfa/dfd might not be polynomial in any of its symbols so we
  949. # use a Dummy as the generator for PolyMatrix.
  950. dum = Dummy()
  951. lhs = Matrix([E_part + L_part], dum)
  952. rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
  953. A, u = constant_system(lhs, rhs, DE)
  954. u = u.to_Matrix() # Poly to Expr
  955. if not A or not all(derivation(i, DE, basic=True).is_zero for i in u):
  956. # If the elements of u are not all constant
  957. # Note: See comment in constant_system
  958. # Also note: derivation(basic=True) calls cancel()
  959. return None
  960. else:
  961. if not all(i.is_Rational for i in u):
  962. # TODO: But maybe we can tell if they're not rational, like
  963. # log(2)/log(3). Also, there should be an option to continue
  964. # anyway, even if the result might potentially be wrong.
  965. raise NotImplementedError("Cannot work with non-rational "
  966. "coefficients in this case.")
  967. else:
  968. n = S.One*reduce(ilcm, [i.as_numer_denom()[1] for i in u])
  969. u *= n
  970. terms = ([DE.T[i] for i in DE.indices('exp')] +
  971. [DE.extargs[i] for i in DE.indices('log')])
  972. ans = list(zip(terms, u))
  973. result = Mul(*[Pow(i, j) for i, j in ans])
  974. # exp(f) will be the same as result up to a multiplicative
  975. # constant. We now find the log of that constant.
  976. argterms = ([DE.extargs[i] for i in DE.indices('exp')] +
  977. [DE.T[i] for i in DE.indices('log')])
  978. const = cancel(fa.as_expr()/fd.as_expr() -
  979. Add(*[Mul(i, j/n) for i, j in zip(argterms, u)]))
  980. return (ans, result, n, const)
  981. def is_log_deriv_k_t_radical_in_field(fa, fd, DE, case='auto', z=None):
  982. """
  983. Checks if f can be written as the logarithmic derivative of a k(t)-radical.
  984. Explanation
  985. ===========
  986. It differs from is_log_deriv_k_t_radical(fa, fd, DE, Df=False)
  987. for any given fa, fd, DE in that it finds the solution in the
  988. given field not in some (possibly unspecified extension) and
  989. "in_field" with the function name is used to indicate that.
  990. f in k(t) can be written as the logarithmic derivative of a k(t) radical if
  991. there exist n in ZZ and u in k(t) with n, u != 0 such that n*f == Du/u.
  992. Either returns (n, u) or None, which means that f cannot be written as the
  993. logarithmic derivative of a k(t)-radical.
  994. case is one of {'primitive', 'exp', 'tan', 'auto'} for the primitive,
  995. hyperexponential, and hypertangent cases, respectively. If case is 'auto',
  996. it will attempt to determine the type of the derivation automatically.
  997. See also
  998. ========
  999. is_log_deriv_k_t_radical, is_deriv_k
  1000. """
  1001. fa, fd = fa.cancel(fd, include=True)
  1002. # f must be simple
  1003. n, s = splitfactor(fd, DE)
  1004. if not s.is_one:
  1005. pass
  1006. z = z or Dummy('z')
  1007. H, b = residue_reduce(fa, fd, DE, z=z)
  1008. if not b:
  1009. # I will have to verify, but I believe that the answer should be
  1010. # None in this case. This should never happen for the
  1011. # functions given when solving the parametric logarithmic
  1012. # derivative problem when integration elementary functions (see
  1013. # Bronstein's book, page 255), so most likely this indicates a bug.
  1014. return None
  1015. roots = [(i, i.real_roots()) for i, _ in H]
  1016. if not all(len(j) == i.degree() and all(k.is_Rational for k in j) for
  1017. i, j in roots):
  1018. # If f is the logarithmic derivative of a k(t)-radical, then all the
  1019. # roots of the resultant must be rational numbers.
  1020. return None
  1021. # [(a, i), ...], where i*log(a) is a term in the log-part of the integral
  1022. # of f
  1023. respolys, residues = list(zip(*roots)) or [[], []]
  1024. # Note: this might be empty, but everything below should work find in that
  1025. # case (it should be the same as if it were [[1, 1]])
  1026. residueterms = [(H[j][1].subs(z, i), i) for j in range(len(H)) for
  1027. i in residues[j]]
  1028. # TODO: finish writing this and write tests
  1029. p = cancel(fa.as_expr()/fd.as_expr() - residue_reduce_derivation(H, DE, z))
  1030. p = p.as_poly(DE.t)
  1031. if p is None:
  1032. # f - Dg will be in k[t] if f is the logarithmic derivative of a k(t)-radical
  1033. return None
  1034. if p.degree(DE.t) >= max(1, DE.d.degree(DE.t)):
  1035. return None
  1036. if case == 'auto':
  1037. case = DE.case
  1038. if case == 'exp':
  1039. wa, wd = derivation(DE.t, DE).cancel(Poly(DE.t, DE.t), include=True)
  1040. with DecrementLevel(DE):
  1041. pa, pd = frac_in(p, DE.t, cancel=True)
  1042. wa, wd = frac_in((wa, wd), DE.t)
  1043. A = parametric_log_deriv(pa, pd, wa, wd, DE)
  1044. if A is None:
  1045. return None
  1046. n, e, u = A
  1047. u *= DE.t**e
  1048. elif case == 'primitive':
  1049. with DecrementLevel(DE):
  1050. pa, pd = frac_in(p, DE.t)
  1051. A = is_log_deriv_k_t_radical_in_field(pa, pd, DE, case='auto')
  1052. if A is None:
  1053. return None
  1054. n, u = A
  1055. elif case == 'base':
  1056. # TODO: we can use more efficient residue reduction from ratint()
  1057. if not fd.is_sqf or fa.degree() >= fd.degree():
  1058. # f is the logarithmic derivative in the base case if and only if
  1059. # f = fa/fd, fd is square-free, deg(fa) < deg(fd), and
  1060. # gcd(fa, fd) == 1. The last condition is handled by cancel() above.
  1061. return None
  1062. # Note: if residueterms = [], returns (1, 1)
  1063. # f had better be 0 in that case.
  1064. n = S.One*reduce(ilcm, [i.as_numer_denom()[1] for _, i in residueterms], 1)
  1065. u = Mul(*[Pow(i, j*n) for i, j in residueterms])
  1066. return (n, u)
  1067. elif case == 'tan':
  1068. raise NotImplementedError("The hypertangent case is "
  1069. "not yet implemented for is_log_deriv_k_t_radical_in_field()")
  1070. elif case in ('other_linear', 'other_nonlinear'):
  1071. # XXX: If these are supported by the structure theorems, change to NotImplementedError.
  1072. raise ValueError("The %s case is not supported in this function." % case)
  1073. else:
  1074. raise ValueError("case must be one of {'primitive', 'exp', 'tan', "
  1075. "'base', 'auto'}, not %s" % case)
  1076. common_denom = S.One*reduce(ilcm, [i.as_numer_denom()[1] for i in [j for _, j in
  1077. residueterms]] + [n], 1)
  1078. residueterms = [(i, j*common_denom) for i, j in residueterms]
  1079. m = common_denom//n
  1080. if common_denom != n*m: # Verify exact division
  1081. raise ValueError("Inexact division")
  1082. u = cancel(u**m*Mul(*[Pow(i, j) for i, j in residueterms]))
  1083. return (common_denom, u)