hyperexpand.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494
  1. """
  2. Expand Hypergeometric (and Meijer G) functions into named
  3. special functions.
  4. The algorithm for doing this uses a collection of lookup tables of
  5. hypergeometric functions, and various of their properties, to expand
  6. many hypergeometric functions in terms of special functions.
  7. It is based on the following paper:
  8. Kelly B. Roach. Meijer G Function Representations.
  9. In: Proceedings of the 1997 International Symposium on Symbolic and
  10. Algebraic Computation, pages 205-211, New York, 1997. ACM.
  11. It is described in great(er) detail in the Sphinx documentation.
  12. """
  13. # SUMMARY OF EXTENSIONS FOR MEIJER G FUNCTIONS
  14. #
  15. # o z**rho G(ap, bq; z) = G(ap + rho, bq + rho; z)
  16. #
  17. # o denote z*d/dz by D
  18. #
  19. # o It is helpful to keep in mind that ap and bq play essentially symmetric
  20. # roles: G(1/z) has slightly altered parameters, with ap and bq interchanged.
  21. #
  22. # o There are four shift operators:
  23. # A_J = b_J - D, J = 1, ..., n
  24. # B_J = 1 - a_j + D, J = 1, ..., m
  25. # C_J = -b_J + D, J = m+1, ..., q
  26. # D_J = a_J - 1 - D, J = n+1, ..., p
  27. #
  28. # A_J, C_J increment b_J
  29. # B_J, D_J decrement a_J
  30. #
  31. # o The corresponding four inverse-shift operators are defined if there
  32. # is no cancellation. Thus e.g. an index a_J (upper or lower) can be
  33. # incremented if a_J != b_i for i = 1, ..., q.
  34. #
  35. # o Order reduction: if b_j - a_i is a non-negative integer, where
  36. # j <= m and i > n, the corresponding quotient of gamma functions reduces
  37. # to a polynomial. Hence the G function can be expressed using a G-function
  38. # of lower order.
  39. # Similarly if j > m and i <= n.
  40. #
  41. # Secondly, there are paired index theorems [Adamchik, The evaluation of
  42. # integrals of Bessel functions via G-function identities]. Suppose there
  43. # are three parameters a, b, c, where a is an a_i, i <= n, b is a b_j,
  44. # j <= m and c is a denominator parameter (i.e. a_i, i > n or b_j, j > m).
  45. # Suppose further all three differ by integers.
  46. # Then the order can be reduced.
  47. # TODO work this out in detail.
  48. #
  49. # o An index quadruple is called suitable if its order cannot be reduced.
  50. # If there exists a sequence of shift operators transforming one index
  51. # quadruple into another, we say one is reachable from the other.
  52. #
  53. # o Deciding if one index quadruple is reachable from another is tricky. For
  54. # this reason, we use hand-built routines to match and instantiate formulas.
  55. #
  56. from collections import defaultdict
  57. from itertools import product
  58. from functools import reduce
  59. from math import prod
  60. from sympy import SYMPY_DEBUG
  61. from sympy.core import (S, Dummy, symbols, sympify, Tuple, expand, I, pi, Mul,
  62. EulerGamma, oo, zoo, expand_func, Add, nan, Expr, Rational)
  63. from sympy.core.mod import Mod
  64. from sympy.core.sorting import default_sort_key
  65. from sympy.functions import (exp, sqrt, root, log, lowergamma, cos,
  66. besseli, gamma, uppergamma, expint, erf, sin, besselj, Ei, Ci, Si, Shi,
  67. sinh, cosh, Chi, fresnels, fresnelc, polar_lift, exp_polar, floor, ceiling,
  68. rf, factorial, lerchphi, Piecewise, re, elliptic_k, elliptic_e)
  69. from sympy.functions.elementary.complexes import polarify, unpolarify
  70. from sympy.functions.special.hyper import (hyper, HyperRep_atanh,
  71. HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
  72. HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
  73. HyperRep_cosasin, HyperRep_sinasin, meijerg)
  74. from sympy.matrices import Matrix, eye, zeros
  75. from sympy.polys import apart, poly, Poly
  76. from sympy.series import residue
  77. from sympy.simplify.powsimp import powdenest
  78. from sympy.utilities.iterables import sift
  79. # function to define "buckets"
  80. def _mod1(x):
  81. # TODO see if this can work as Mod(x, 1); this will require
  82. # different handling of the "buckets" since these need to
  83. # be sorted and that fails when there is a mixture of
  84. # integers and expressions with parameters. With the current
  85. # Mod behavior, Mod(k, 1) == Mod(1, 1) == 0 if k is an integer.
  86. # Although the sorting can be done with Basic.compare, this may
  87. # still require different handling of the sorted buckets.
  88. if x.is_Number:
  89. return Mod(x, 1)
  90. c, x = x.as_coeff_Add()
  91. return Mod(c, 1) + x
  92. # leave add formulae at the top for easy reference
  93. def add_formulae(formulae):
  94. """ Create our knowledge base. """
  95. a, b, c, z = symbols('a b c, z', cls=Dummy)
  96. def add(ap, bq, res):
  97. func = Hyper_Function(ap, bq)
  98. formulae.append(Formula(func, z, res, (a, b, c)))
  99. def addb(ap, bq, B, C, M):
  100. func = Hyper_Function(ap, bq)
  101. formulae.append(Formula(func, z, None, (a, b, c), B, C, M))
  102. # Luke, Y. L. (1969), The Special Functions and Their Approximations,
  103. # Volume 1, section 6.2
  104. # 0F0
  105. add((), (), exp(z))
  106. # 1F0
  107. add((a, ), (), HyperRep_power1(-a, z))
  108. # 2F1
  109. addb((a, a - S.Half), (2*a, ),
  110. Matrix([HyperRep_power2(a, z),
  111. HyperRep_power2(a + S.Half, z)/2]),
  112. Matrix([[1, 0]]),
  113. Matrix([[(a - S.Half)*z/(1 - z), (S.Half - a)*z/(1 - z)],
  114. [a/(1 - z), a*(z - 2)/(1 - z)]]))
  115. addb((1, 1), (2, ),
  116. Matrix([HyperRep_log1(z), 1]), Matrix([[-1/z, 0]]),
  117. Matrix([[0, z/(z - 1)], [0, 0]]))
  118. addb((S.Half, 1), (S('3/2'), ),
  119. Matrix([HyperRep_atanh(z), 1]),
  120. Matrix([[1, 0]]),
  121. Matrix([[Rational(-1, 2), 1/(1 - z)/2], [0, 0]]))
  122. addb((S.Half, S.Half), (S('3/2'), ),
  123. Matrix([HyperRep_asin1(z), HyperRep_power1(Rational(-1, 2), z)]),
  124. Matrix([[1, 0]]),
  125. Matrix([[Rational(-1, 2), S.Half], [0, z/(1 - z)/2]]))
  126. addb((a, S.Half + a), (S.Half, ),
  127. Matrix([HyperRep_sqrts1(-a, z), -HyperRep_sqrts2(-a - S.Half, z)]),
  128. Matrix([[1, 0]]),
  129. Matrix([[0, -a],
  130. [z*(-2*a - 1)/2/(1 - z), S.Half - z*(-2*a - 1)/(1 - z)]]))
  131. # A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
  132. # Integrals and Series: More Special Functions, Vol. 3,.
  133. # Gordon and Breach Science Publisher
  134. addb([a, -a], [S.Half],
  135. Matrix([HyperRep_cosasin(a, z), HyperRep_sinasin(a, z)]),
  136. Matrix([[1, 0]]),
  137. Matrix([[0, -a], [a*z/(1 - z), 1/(1 - z)/2]]))
  138. addb([1, 1], [3*S.Half],
  139. Matrix([HyperRep_asin2(z), 1]), Matrix([[1, 0]]),
  140. Matrix([[(z - S.Half)/(1 - z), 1/(1 - z)/2], [0, 0]]))
  141. # Complete elliptic integrals K(z) and E(z), both a 2F1 function
  142. addb([S.Half, S.Half], [S.One],
  143. Matrix([elliptic_k(z), elliptic_e(z)]),
  144. Matrix([[2/pi, 0]]),
  145. Matrix([[Rational(-1, 2), -1/(2*z-2)],
  146. [Rational(-1, 2), S.Half]]))
  147. addb([Rational(-1, 2), S.Half], [S.One],
  148. Matrix([elliptic_k(z), elliptic_e(z)]),
  149. Matrix([[0, 2/pi]]),
  150. Matrix([[Rational(-1, 2), -1/(2*z-2)],
  151. [Rational(-1, 2), S.Half]]))
  152. # 3F2
  153. addb([Rational(-1, 2), 1, 1], [S.Half, 2],
  154. Matrix([z*HyperRep_atanh(z), HyperRep_log1(z), 1]),
  155. Matrix([[Rational(-2, 3), -S.One/(3*z), Rational(2, 3)]]),
  156. Matrix([[S.Half, 0, z/(1 - z)/2],
  157. [0, 0, z/(z - 1)],
  158. [0, 0, 0]]))
  159. # actually the formula for 3/2 is much nicer ...
  160. addb([Rational(-1, 2), 1, 1], [2, 2],
  161. Matrix([HyperRep_power1(S.Half, z), HyperRep_log2(z), 1]),
  162. Matrix([[Rational(4, 9) - 16/(9*z), 4/(3*z), 16/(9*z)]]),
  163. Matrix([[z/2/(z - 1), 0, 0], [1/(2*(z - 1)), 0, S.Half], [0, 0, 0]]))
  164. # 1F1
  165. addb([1], [b], Matrix([z**(1 - b) * exp(z) * lowergamma(b - 1, z), 1]),
  166. Matrix([[b - 1, 0]]), Matrix([[1 - b + z, 1], [0, 0]]))
  167. addb([a], [2*a],
  168. Matrix([z**(S.Half - a)*exp(z/2)*besseli(a - S.Half, z/2)
  169. * gamma(a + S.Half)/4**(S.Half - a),
  170. z**(S.Half - a)*exp(z/2)*besseli(a + S.Half, z/2)
  171. * gamma(a + S.Half)/4**(S.Half - a)]),
  172. Matrix([[1, 0]]),
  173. Matrix([[z/2, z/2], [z/2, (z/2 - 2*a)]]))
  174. mz = polar_lift(-1)*z
  175. addb([a], [a + 1],
  176. Matrix([mz**(-a)*a*lowergamma(a, mz), a*exp(z)]),
  177. Matrix([[1, 0]]),
  178. Matrix([[-a, 1], [0, z]]))
  179. # This one is redundant.
  180. add([Rational(-1, 2)], [S.Half], exp(z) - sqrt(pi*z)*(-I)*erf(I*sqrt(z)))
  181. # Added to get nice results for Laplace transform of Fresnel functions
  182. # https://functions.wolfram.com/07.22.03.6437.01
  183. # Basic rule
  184. #add([1], [Rational(3, 4), Rational(5, 4)],
  185. # sqrt(pi) * (cos(2*sqrt(polar_lift(-1)*z))*fresnelc(2*root(polar_lift(-1)*z,4)/sqrt(pi)) +
  186. # sin(2*sqrt(polar_lift(-1)*z))*fresnels(2*root(polar_lift(-1)*z,4)/sqrt(pi)))
  187. # / (2*root(polar_lift(-1)*z,4)))
  188. # Manually tuned rule
  189. addb([1], [Rational(3, 4), Rational(5, 4)],
  190. Matrix([ sqrt(pi)*(I*sinh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
  191. + cosh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
  192. * exp(-I*pi/4)/(2*root(z, 4)),
  193. sqrt(pi)*root(z, 4)*(sinh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
  194. + I*cosh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
  195. *exp(-I*pi/4)/2,
  196. 1 ]),
  197. Matrix([[1, 0, 0]]),
  198. Matrix([[Rational(-1, 4), 1, Rational(1, 4)],
  199. [ z, Rational(1, 4), 0],
  200. [ 0, 0, 0]]))
  201. # 2F2
  202. addb([S.Half, a], [Rational(3, 2), a + 1],
  203. Matrix([a/(2*a - 1)*(-I)*sqrt(pi/z)*erf(I*sqrt(z)),
  204. a/(2*a - 1)*(polar_lift(-1)*z)**(-a)*
  205. lowergamma(a, polar_lift(-1)*z),
  206. a/(2*a - 1)*exp(z)]),
  207. Matrix([[1, -1, 0]]),
  208. Matrix([[Rational(-1, 2), 0, 1], [0, -a, 1], [0, 0, z]]))
  209. # We make a "basis" of four functions instead of three, and give EulerGamma
  210. # an extra slot (it could just be a coefficient to 1). The advantage is
  211. # that this way Polys will not see multivariate polynomials (it treats
  212. # EulerGamma as an indeterminate), which is *way* faster.
  213. addb([1, 1], [2, 2],
  214. Matrix([Ei(z) - log(z), exp(z), 1, EulerGamma]),
  215. Matrix([[1/z, 0, 0, -1/z]]),
  216. Matrix([[0, 1, -1, 0], [0, z, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]))
  217. # 0F1
  218. add((), (S.Half, ), cosh(2*sqrt(z)))
  219. addb([], [b],
  220. Matrix([gamma(b)*z**((1 - b)/2)*besseli(b - 1, 2*sqrt(z)),
  221. gamma(b)*z**(1 - b/2)*besseli(b, 2*sqrt(z))]),
  222. Matrix([[1, 0]]), Matrix([[0, 1], [z, (1 - b)]]))
  223. # 0F3
  224. x = 4*z**Rational(1, 4)
  225. def fp(a, z):
  226. return besseli(a, x) + besselj(a, x)
  227. def fm(a, z):
  228. return besseli(a, x) - besselj(a, x)
  229. # TODO branching
  230. addb([], [S.Half, a, a + S.Half],
  231. Matrix([fp(2*a - 1, z), fm(2*a, z)*z**Rational(1, 4),
  232. fm(2*a - 1, z)*sqrt(z), fp(2*a, z)*z**Rational(3, 4)])
  233. * 2**(-2*a)*gamma(2*a)*z**((1 - 2*a)/4),
  234. Matrix([[1, 0, 0, 0]]),
  235. Matrix([[0, 1, 0, 0],
  236. [0, S.Half - a, 1, 0],
  237. [0, 0, S.Half, 1],
  238. [z, 0, 0, 1 - a]]))
  239. x = 2*(4*z)**Rational(1, 4)*exp_polar(I*pi/4)
  240. addb([], [a, a + S.Half, 2*a],
  241. (2*sqrt(polar_lift(-1)*z))**(1 - 2*a)*gamma(2*a)**2 *
  242. Matrix([besselj(2*a - 1, x)*besseli(2*a - 1, x),
  243. x*(besseli(2*a, x)*besselj(2*a - 1, x)
  244. - besseli(2*a - 1, x)*besselj(2*a, x)),
  245. x**2*besseli(2*a, x)*besselj(2*a, x),
  246. x**3*(besseli(2*a, x)*besselj(2*a - 1, x)
  247. + besseli(2*a - 1, x)*besselj(2*a, x))]),
  248. Matrix([[1, 0, 0, 0]]),
  249. Matrix([[0, Rational(1, 4), 0, 0],
  250. [0, (1 - 2*a)/2, Rational(-1, 2), 0],
  251. [0, 0, 1 - 2*a, Rational(1, 4)],
  252. [-32*z, 0, 0, 1 - a]]))
  253. # 1F2
  254. addb([a], [a - S.Half, 2*a],
  255. Matrix([z**(S.Half - a)*besseli(a - S.Half, sqrt(z))**2,
  256. z**(1 - a)*besseli(a - S.Half, sqrt(z))
  257. *besseli(a - Rational(3, 2), sqrt(z)),
  258. z**(Rational(3, 2) - a)*besseli(a - Rational(3, 2), sqrt(z))**2]),
  259. Matrix([[-gamma(a + S.Half)**2/4**(S.Half - a),
  260. 2*gamma(a - S.Half)*gamma(a + S.Half)/4**(1 - a),
  261. 0]]),
  262. Matrix([[1 - 2*a, 1, 0], [z/2, S.Half - a, S.Half], [0, z, 0]]))
  263. addb([S.Half], [b, 2 - b],
  264. pi*(1 - b)/sin(pi*b)*
  265. Matrix([besseli(1 - b, sqrt(z))*besseli(b - 1, sqrt(z)),
  266. sqrt(z)*(besseli(-b, sqrt(z))*besseli(b - 1, sqrt(z))
  267. + besseli(1 - b, sqrt(z))*besseli(b, sqrt(z))),
  268. besseli(-b, sqrt(z))*besseli(b, sqrt(z))]),
  269. Matrix([[1, 0, 0]]),
  270. Matrix([[b - 1, S.Half, 0],
  271. [z, 0, z],
  272. [0, S.Half, -b]]))
  273. addb([S.Half], [Rational(3, 2), Rational(3, 2)],
  274. Matrix([Shi(2*sqrt(z))/2/sqrt(z), sinh(2*sqrt(z))/2/sqrt(z),
  275. cosh(2*sqrt(z))]),
  276. Matrix([[1, 0, 0]]),
  277. Matrix([[Rational(-1, 2), S.Half, 0], [0, Rational(-1, 2), S.Half], [0, 2*z, 0]]))
  278. # FresnelS
  279. # Basic rule
  280. #add([Rational(3, 4)], [Rational(3, 2),Rational(7, 4)], 6*fresnels( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( pi * (exp(pi*I/4)*root(z,4)*2/sqrt(pi))**3 ) )
  281. # Manually tuned rule
  282. addb([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)],
  283. Matrix(
  284. [ fresnels(
  285. exp(
  286. pi*I/4)*root(
  287. z, 4)*2/sqrt(
  288. pi) ) / (
  289. pi * (exp(pi*I/4)*root(z, 4)*2/sqrt(pi))**3 ),
  290. sinh(2*sqrt(z))/sqrt(z),
  291. cosh(2*sqrt(z)) ]),
  292. Matrix([[6, 0, 0]]),
  293. Matrix([[Rational(-3, 4), Rational(1, 16), 0],
  294. [ 0, Rational(-1, 2), 1],
  295. [ 0, z, 0]]))
  296. # FresnelC
  297. # Basic rule
  298. #add([Rational(1, 4)], [S.Half,Rational(5, 4)], fresnelc( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) )
  299. # Manually tuned rule
  300. addb([Rational(1, 4)], [S.Half, Rational(5, 4)],
  301. Matrix(
  302. [ sqrt(
  303. pi)*exp(
  304. -I*pi/4)*fresnelc(
  305. 2*root(z, 4)*exp(I*pi/4)/sqrt(pi))/(2*root(z, 4)),
  306. cosh(2*sqrt(z)),
  307. sinh(2*sqrt(z))*sqrt(z) ]),
  308. Matrix([[1, 0, 0]]),
  309. Matrix([[Rational(-1, 4), Rational(1, 4), 0 ],
  310. [ 0, 0, 1 ],
  311. [ 0, z, S.Half]]))
  312. # 2F3
  313. # XXX with this five-parameter formula is pretty slow with the current
  314. # Formula.find_instantiations (creates 2!*3!*3**(2+3) ~ 3000
  315. # instantiations ... But it's not too bad.
  316. addb([a, a + S.Half], [2*a, b, 2*a - b + 1],
  317. gamma(b)*gamma(2*a - b + 1) * (sqrt(z)/2)**(1 - 2*a) *
  318. Matrix([besseli(b - 1, sqrt(z))*besseli(2*a - b, sqrt(z)),
  319. sqrt(z)*besseli(b, sqrt(z))*besseli(2*a - b, sqrt(z)),
  320. sqrt(z)*besseli(b - 1, sqrt(z))*besseli(2*a - b + 1, sqrt(z)),
  321. besseli(b, sqrt(z))*besseli(2*a - b + 1, sqrt(z))]),
  322. Matrix([[1, 0, 0, 0]]),
  323. Matrix([[0, S.Half, S.Half, 0],
  324. [z/2, 1 - b, 0, z/2],
  325. [z/2, 0, b - 2*a, z/2],
  326. [0, S.Half, S.Half, -2*a]]))
  327. # (C/f above comment about eulergamma in the basis).
  328. addb([1, 1], [2, 2, Rational(3, 2)],
  329. Matrix([Chi(2*sqrt(z)) - log(2*sqrt(z)),
  330. cosh(2*sqrt(z)), sqrt(z)*sinh(2*sqrt(z)), 1, EulerGamma]),
  331. Matrix([[1/z, 0, 0, 0, -1/z]]),
  332. Matrix([[0, S.Half, 0, Rational(-1, 2), 0],
  333. [0, 0, 1, 0, 0],
  334. [0, z, S.Half, 0, 0],
  335. [0, 0, 0, 0, 0],
  336. [0, 0, 0, 0, 0]]))
  337. # 3F3
  338. # This is rule: https://functions.wolfram.com/07.31.03.0134.01
  339. # Initial reason to add it was a nice solution for
  340. # integrate(erf(a*z)/z**2, z) and same for erfc and erfi.
  341. # Basic rule
  342. # add([1, 1, a], [2, 2, a+1], (a/(z*(a-1)**2)) *
  343. # (1 - (-z)**(1-a) * (gamma(a) - uppergamma(a,-z))
  344. # - (a-1) * (EulerGamma + uppergamma(0,-z) + log(-z))
  345. # - exp(z)))
  346. # Manually tuned rule
  347. addb([1, 1, a], [2, 2, a+1],
  348. Matrix([a*(log(-z) + expint(1, -z) + EulerGamma)/(z*(a**2 - 2*a + 1)),
  349. a*(-z)**(-a)*(gamma(a) - uppergamma(a, -z))/(a - 1)**2,
  350. a*exp(z)/(a**2 - 2*a + 1),
  351. a/(z*(a**2 - 2*a + 1))]),
  352. Matrix([[1-a, 1, -1/z, 1]]),
  353. Matrix([[-1,0,-1/z,1],
  354. [0,-a,1,0],
  355. [0,0,z,0],
  356. [0,0,0,-1]]))
  357. def add_meijerg_formulae(formulae):
  358. a, b, c, z = list(map(Dummy, 'abcz'))
  359. rho = Dummy('rho')
  360. def add(an, ap, bm, bq, B, C, M, matcher):
  361. formulae.append(MeijerFormula(an, ap, bm, bq, z, [a, b, c, rho],
  362. B, C, M, matcher))
  363. def detect_uppergamma(func):
  364. x = func.an[0]
  365. y, z = func.bm
  366. swapped = False
  367. if not _mod1((x - y).simplify()):
  368. swapped = True
  369. (y, z) = (z, y)
  370. if _mod1((x - z).simplify()) or x - z > 0:
  371. return None
  372. l = [y, x]
  373. if swapped:
  374. l = [x, y]
  375. return {rho: y, a: x - y}, G_Function([x], [], l, [])
  376. add([a + rho], [], [rho, a + rho], [],
  377. Matrix([gamma(1 - a)*z**rho*exp(z)*uppergamma(a, z),
  378. gamma(1 - a)*z**(a + rho)]),
  379. Matrix([[1, 0]]),
  380. Matrix([[rho + z, -1], [0, a + rho]]),
  381. detect_uppergamma)
  382. def detect_3113(func):
  383. """https://functions.wolfram.com/07.34.03.0984.01"""
  384. x = func.an[0]
  385. u, v, w = func.bm
  386. if _mod1((u - v).simplify()) == 0:
  387. if _mod1((v - w).simplify()) == 0:
  388. return
  389. sig = (S.Half, S.Half, S.Zero)
  390. x1, x2, y = u, v, w
  391. else:
  392. if _mod1((x - u).simplify()) == 0:
  393. sig = (S.Half, S.Zero, S.Half)
  394. x1, y, x2 = u, v, w
  395. else:
  396. sig = (S.Zero, S.Half, S.Half)
  397. y, x1, x2 = u, v, w
  398. if (_mod1((x - x1).simplify()) != 0 or
  399. _mod1((x - x2).simplify()) != 0 or
  400. _mod1((x - y).simplify()) != S.Half or
  401. x - x1 > 0 or x - x2 > 0):
  402. return
  403. return {a: x}, G_Function([x], [], [x - S.Half + t for t in sig], [])
  404. s = sin(2*sqrt(z))
  405. c_ = cos(2*sqrt(z))
  406. S_ = Si(2*sqrt(z)) - pi/2
  407. C = Ci(2*sqrt(z))
  408. add([a], [], [a, a, a - S.Half], [],
  409. Matrix([sqrt(pi)*z**(a - S.Half)*(c_*S_ - s*C),
  410. sqrt(pi)*z**a*(s*S_ + c_*C),
  411. sqrt(pi)*z**a]),
  412. Matrix([[-2, 0, 0]]),
  413. Matrix([[a - S.Half, -1, 0], [z, a, S.Half], [0, 0, a]]),
  414. detect_3113)
  415. def make_simp(z):
  416. """ Create a function that simplifies rational functions in ``z``. """
  417. def simp(expr):
  418. """ Efficiently simplify the rational function ``expr``. """
  419. numer, denom = expr.as_numer_denom()
  420. numer = numer.expand()
  421. # denom = denom.expand() # is this needed?
  422. c, numer, denom = poly(numer, z).cancel(poly(denom, z))
  423. return c * numer.as_expr() / denom.as_expr()
  424. return simp
  425. def debug(*args):
  426. if SYMPY_DEBUG:
  427. for a in args:
  428. print(a, end="")
  429. print()
  430. class Hyper_Function(Expr):
  431. """ A generalized hypergeometric function. """
  432. def __new__(cls, ap, bq):
  433. obj = super().__new__(cls)
  434. obj.ap = Tuple(*list(map(expand, ap)))
  435. obj.bq = Tuple(*list(map(expand, bq)))
  436. return obj
  437. @property
  438. def args(self):
  439. return (self.ap, self.bq)
  440. @property
  441. def sizes(self):
  442. return (len(self.ap), len(self.bq))
  443. @property
  444. def gamma(self):
  445. """
  446. Number of upper parameters that are negative integers
  447. This is a transformation invariant.
  448. """
  449. return sum(bool(x.is_integer and x.is_negative) for x in self.ap)
  450. def _hashable_content(self):
  451. return super()._hashable_content() + (self.ap,
  452. self.bq)
  453. def __call__(self, arg):
  454. return hyper(self.ap, self.bq, arg)
  455. def build_invariants(self):
  456. """
  457. Compute the invariant vector.
  458. Explanation
  459. ===========
  460. The invariant vector is:
  461. (gamma, ((s1, n1), ..., (sk, nk)), ((t1, m1), ..., (tr, mr)))
  462. where gamma is the number of integer a < 0,
  463. s1 < ... < sk
  464. nl is the number of parameters a_i congruent to sl mod 1
  465. t1 < ... < tr
  466. ml is the number of parameters b_i congruent to tl mod 1
  467. If the index pair contains parameters, then this is not truly an
  468. invariant, since the parameters cannot be sorted uniquely mod1.
  469. Examples
  470. ========
  471. >>> from sympy.simplify.hyperexpand import Hyper_Function
  472. >>> from sympy import S
  473. >>> ap = (S.Half, S.One/3, S(-1)/2, -2)
  474. >>> bq = (1, 2)
  475. Here gamma = 1,
  476. k = 3, s1 = 0, s2 = 1/3, s3 = 1/2
  477. n1 = 1, n2 = 1, n2 = 2
  478. r = 1, t1 = 0
  479. m1 = 2:
  480. >>> Hyper_Function(ap, bq).build_invariants()
  481. (1, ((0, 1), (1/3, 1), (1/2, 2)), ((0, 2),))
  482. """
  483. abuckets, bbuckets = sift(self.ap, _mod1), sift(self.bq, _mod1)
  484. def tr(bucket):
  485. bucket = list(bucket.items())
  486. if not any(isinstance(x[0], Mod) for x in bucket):
  487. bucket.sort(key=lambda x: default_sort_key(x[0]))
  488. bucket = tuple([(mod, len(values)) for mod, values in bucket if
  489. values])
  490. return bucket
  491. return (self.gamma, tr(abuckets), tr(bbuckets))
  492. def difficulty(self, func):
  493. """ Estimate how many steps it takes to reach ``func`` from self.
  494. Return -1 if impossible. """
  495. if self.gamma != func.gamma:
  496. return -1
  497. oabuckets, obbuckets, abuckets, bbuckets = [sift(params, _mod1) for
  498. params in (self.ap, self.bq, func.ap, func.bq)]
  499. diff = 0
  500. for bucket, obucket in [(abuckets, oabuckets), (bbuckets, obbuckets)]:
  501. for mod in set(list(bucket.keys()) + list(obucket.keys())):
  502. if (mod not in bucket) or (mod not in obucket) \
  503. or len(bucket[mod]) != len(obucket[mod]):
  504. return -1
  505. l1 = list(bucket[mod])
  506. l2 = list(obucket[mod])
  507. l1.sort()
  508. l2.sort()
  509. for i, j in zip(l1, l2):
  510. diff += abs(i - j)
  511. return diff
  512. def _is_suitable_origin(self):
  513. """
  514. Decide if ``self`` is a suitable origin.
  515. Explanation
  516. ===========
  517. A function is a suitable origin iff:
  518. * none of the ai equals bj + n, with n a non-negative integer
  519. * none of the ai is zero
  520. * none of the bj is a non-positive integer
  521. Note that this gives meaningful results only when none of the indices
  522. are symbolic.
  523. """
  524. for a in self.ap:
  525. for b in self.bq:
  526. if (a - b).is_integer and (a - b).is_negative is False:
  527. return False
  528. for a in self.ap:
  529. if a == 0:
  530. return False
  531. for b in self.bq:
  532. if b.is_integer and b.is_nonpositive:
  533. return False
  534. return True
  535. class G_Function(Expr):
  536. """ A Meijer G-function. """
  537. def __new__(cls, an, ap, bm, bq):
  538. obj = super().__new__(cls)
  539. obj.an = Tuple(*list(map(expand, an)))
  540. obj.ap = Tuple(*list(map(expand, ap)))
  541. obj.bm = Tuple(*list(map(expand, bm)))
  542. obj.bq = Tuple(*list(map(expand, bq)))
  543. return obj
  544. @property
  545. def args(self):
  546. return (self.an, self.ap, self.bm, self.bq)
  547. def _hashable_content(self):
  548. return super()._hashable_content() + self.args
  549. def __call__(self, z):
  550. return meijerg(self.an, self.ap, self.bm, self.bq, z)
  551. def compute_buckets(self):
  552. """
  553. Compute buckets for the fours sets of parameters.
  554. Explanation
  555. ===========
  556. We guarantee that any two equal Mod objects returned are actually the
  557. same, and that the buckets are sorted by real part (an and bq
  558. descendending, bm and ap ascending).
  559. Examples
  560. ========
  561. >>> from sympy.simplify.hyperexpand import G_Function
  562. >>> from sympy.abc import y
  563. >>> from sympy import S
  564. >>> a, b = [1, 3, 2, S(3)/2], [1 + y, y, 2, y + 3]
  565. >>> G_Function(a, b, [2], [y]).compute_buckets()
  566. ({0: [3, 2, 1], 1/2: [3/2]},
  567. {0: [2], y: [y, y + 1, y + 3]}, {0: [2]}, {y: [y]})
  568. """
  569. dicts = pan, pap, pbm, pbq = [defaultdict(list) for i in range(4)]
  570. for dic, lis in zip(dicts, (self.an, self.ap, self.bm, self.bq)):
  571. for x in lis:
  572. dic[_mod1(x)].append(x)
  573. for dic, flip in zip(dicts, (True, False, False, True)):
  574. for m, items in dic.items():
  575. x0 = items[0]
  576. items.sort(key=lambda x: x - x0, reverse=flip)
  577. dic[m] = items
  578. return tuple([dict(w) for w in dicts])
  579. @property
  580. def signature(self):
  581. return (len(self.an), len(self.ap), len(self.bm), len(self.bq))
  582. # Dummy variable.
  583. _x = Dummy('x')
  584. class Formula:
  585. """
  586. This class represents hypergeometric formulae.
  587. Explanation
  588. ===========
  589. Its data members are:
  590. - z, the argument
  591. - closed_form, the closed form expression
  592. - symbols, the free symbols (parameters) in the formula
  593. - func, the function
  594. - B, C, M (see _compute_basis)
  595. Examples
  596. ========
  597. >>> from sympy.abc import a, b, z
  598. >>> from sympy.simplify.hyperexpand import Formula, Hyper_Function
  599. >>> func = Hyper_Function((a/2, a/3 + b, (1+a)/2), (a, b, (a+b)/7))
  600. >>> f = Formula(func, z, None, [a, b])
  601. """
  602. def _compute_basis(self, closed_form):
  603. """
  604. Compute a set of functions B=(f1, ..., fn), a nxn matrix M
  605. and a 1xn matrix C such that:
  606. closed_form = C B
  607. z d/dz B = M B.
  608. """
  609. afactors = [_x + a for a in self.func.ap]
  610. bfactors = [_x + b - 1 for b in self.func.bq]
  611. expr = _x*Mul(*bfactors) - self.z*Mul(*afactors)
  612. poly = Poly(expr, _x)
  613. n = poly.degree() - 1
  614. b = [closed_form]
  615. for _ in range(n):
  616. b.append(self.z*b[-1].diff(self.z))
  617. self.B = Matrix(b)
  618. self.C = Matrix([[1] + [0]*n])
  619. m = eye(n)
  620. m = m.col_insert(0, zeros(n, 1))
  621. l = poly.all_coeffs()[1:]
  622. l.reverse()
  623. self.M = m.row_insert(n, -Matrix([l])/poly.all_coeffs()[0])
  624. def __init__(self, func, z, res, symbols, B=None, C=None, M=None):
  625. z = sympify(z)
  626. res = sympify(res)
  627. symbols = [x for x in sympify(symbols) if func.has(x)]
  628. self.z = z
  629. self.symbols = symbols
  630. self.B = B
  631. self.C = C
  632. self.M = M
  633. self.func = func
  634. # TODO with symbolic parameters, it could be advantageous
  635. # (for prettier answers) to compute a basis only *after*
  636. # instantiation
  637. if res is not None:
  638. self._compute_basis(res)
  639. @property
  640. def closed_form(self):
  641. return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
  642. def find_instantiations(self, func):
  643. """
  644. Find substitutions of the free symbols that match ``func``.
  645. Return the substitution dictionaries as a list. Note that the returned
  646. instantiations need not actually match, or be valid!
  647. """
  648. from sympy.solvers import solve
  649. ap = func.ap
  650. bq = func.bq
  651. if len(ap) != len(self.func.ap) or len(bq) != len(self.func.bq):
  652. raise TypeError('Cannot instantiate other number of parameters')
  653. symbol_values = []
  654. for a in self.symbols:
  655. if a in self.func.ap.args:
  656. symbol_values.append(ap)
  657. elif a in self.func.bq.args:
  658. symbol_values.append(bq)
  659. else:
  660. raise ValueError("At least one of the parameters of the "
  661. "formula must be equal to %s" % (a,))
  662. base_repl = [dict(list(zip(self.symbols, values)))
  663. for values in product(*symbol_values)]
  664. abuckets, bbuckets = [sift(params, _mod1) for params in [ap, bq]]
  665. a_inv, b_inv = [{a: len(vals) for a, vals in bucket.items()}
  666. for bucket in [abuckets, bbuckets]]
  667. critical_values = [[0] for _ in self.symbols]
  668. result = []
  669. _n = Dummy()
  670. for repl in base_repl:
  671. symb_a, symb_b = [sift(params, lambda x: _mod1(x.xreplace(repl)))
  672. for params in [self.func.ap, self.func.bq]]
  673. for bucket, obucket in [(abuckets, symb_a), (bbuckets, symb_b)]:
  674. for mod in set(list(bucket.keys()) + list(obucket.keys())):
  675. if (mod not in bucket) or (mod not in obucket) \
  676. or len(bucket[mod]) != len(obucket[mod]):
  677. break
  678. for a, vals in zip(self.symbols, critical_values):
  679. if repl[a].free_symbols:
  680. continue
  681. exprs = [expr for expr in obucket[mod] if expr.has(a)]
  682. repl0 = repl.copy()
  683. repl0[a] += _n
  684. for expr in exprs:
  685. for target in bucket[mod]:
  686. n0, = solve(expr.xreplace(repl0) - target, _n)
  687. if n0.free_symbols:
  688. raise ValueError("Value should not be true")
  689. vals.append(n0)
  690. else:
  691. values = []
  692. for a, vals in zip(self.symbols, critical_values):
  693. a0 = repl[a]
  694. min_ = floor(min(vals))
  695. max_ = ceiling(max(vals))
  696. values.append([a0 + n for n in range(min_, max_ + 1)])
  697. result.extend(dict(list(zip(self.symbols, l))) for l in product(*values))
  698. return result
  699. class FormulaCollection:
  700. """ A collection of formulae to use as origins. """
  701. def __init__(self):
  702. """ Doing this globally at module init time is a pain ... """
  703. self.symbolic_formulae = {}
  704. self.concrete_formulae = {}
  705. self.formulae = []
  706. add_formulae(self.formulae)
  707. # Now process the formulae into a helpful form.
  708. # These dicts are indexed by (p, q).
  709. for f in self.formulae:
  710. sizes = f.func.sizes
  711. if len(f.symbols) > 0:
  712. self.symbolic_formulae.setdefault(sizes, []).append(f)
  713. else:
  714. inv = f.func.build_invariants()
  715. self.concrete_formulae.setdefault(sizes, {})[inv] = f
  716. def lookup_origin(self, func):
  717. """
  718. Given the suitable target ``func``, try to find an origin in our
  719. knowledge base.
  720. Examples
  721. ========
  722. >>> from sympy.simplify.hyperexpand import (FormulaCollection,
  723. ... Hyper_Function)
  724. >>> f = FormulaCollection()
  725. >>> f.lookup_origin(Hyper_Function((), ())).closed_form
  726. exp(_z)
  727. >>> f.lookup_origin(Hyper_Function([1], ())).closed_form
  728. HyperRep_power1(-1, _z)
  729. >>> from sympy import S
  730. >>> i = Hyper_Function([S('1/4'), S('3/4 + 4')], [S.Half])
  731. >>> f.lookup_origin(i).closed_form
  732. HyperRep_sqrts1(-1/4, _z)
  733. """
  734. inv = func.build_invariants()
  735. sizes = func.sizes
  736. if sizes in self.concrete_formulae and \
  737. inv in self.concrete_formulae[sizes]:
  738. return self.concrete_formulae[sizes][inv]
  739. # We don't have a concrete formula. Try to instantiate.
  740. if sizes not in self.symbolic_formulae:
  741. return None # Too bad...
  742. possible = []
  743. for f in self.symbolic_formulae[sizes]:
  744. repls = f.find_instantiations(func)
  745. for repl in repls:
  746. func2 = f.func.xreplace(repl)
  747. if not func2._is_suitable_origin():
  748. continue
  749. diff = func2.difficulty(func)
  750. if diff == -1:
  751. continue
  752. possible.append((diff, repl, f, func2))
  753. # find the nearest origin
  754. possible.sort(key=lambda x: x[0])
  755. for _, repl, f, func2 in possible:
  756. f2 = Formula(func2, f.z, None, [], f.B.subs(repl),
  757. f.C.subs(repl), f.M.subs(repl))
  758. if not any(e.has(S.NaN, oo, -oo, zoo) for e in [f2.B, f2.M, f2.C]):
  759. return f2
  760. return None
  761. class MeijerFormula:
  762. """
  763. This class represents a Meijer G-function formula.
  764. Its data members are:
  765. - z, the argument
  766. - symbols, the free symbols (parameters) in the formula
  767. - func, the function
  768. - B, C, M (c/f ordinary Formula)
  769. """
  770. def __init__(self, an, ap, bm, bq, z, symbols, B, C, M, matcher):
  771. an, ap, bm, bq = [Tuple(*list(map(expand, w))) for w in [an, ap, bm, bq]]
  772. self.func = G_Function(an, ap, bm, bq)
  773. self.z = z
  774. self.symbols = symbols
  775. self._matcher = matcher
  776. self.B = B
  777. self.C = C
  778. self.M = M
  779. @property
  780. def closed_form(self):
  781. return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
  782. def try_instantiate(self, func):
  783. """
  784. Try to instantiate the current formula to (almost) match func.
  785. This uses the _matcher passed on init.
  786. """
  787. if func.signature != self.func.signature:
  788. return None
  789. res = self._matcher(func)
  790. if res is not None:
  791. subs, newfunc = res
  792. return MeijerFormula(newfunc.an, newfunc.ap, newfunc.bm, newfunc.bq,
  793. self.z, [],
  794. self.B.subs(subs), self.C.subs(subs),
  795. self.M.subs(subs), None)
  796. class MeijerFormulaCollection:
  797. """
  798. This class holds a collection of meijer g formulae.
  799. """
  800. def __init__(self):
  801. formulae = []
  802. add_meijerg_formulae(formulae)
  803. self.formulae = defaultdict(list)
  804. for formula in formulae:
  805. self.formulae[formula.func.signature].append(formula)
  806. self.formulae = dict(self.formulae)
  807. def lookup_origin(self, func):
  808. """ Try to find a formula that matches func. """
  809. if func.signature not in self.formulae:
  810. return None
  811. for formula in self.formulae[func.signature]:
  812. res = formula.try_instantiate(func)
  813. if res is not None:
  814. return res
  815. class Operator:
  816. """
  817. Base class for operators to be applied to our functions.
  818. Explanation
  819. ===========
  820. These operators are differential operators. They are by convention
  821. expressed in the variable D = z*d/dz (although this base class does
  822. not actually care).
  823. Note that when the operator is applied to an object, we typically do
  824. *not* blindly differentiate but instead use a different representation
  825. of the z*d/dz operator (see make_derivative_operator).
  826. To subclass from this, define a __init__ method that initializes a
  827. self._poly variable. This variable stores a polynomial. By convention
  828. the generator is z*d/dz, and acts to the right of all coefficients.
  829. Thus this poly
  830. x**2 + 2*z*x + 1
  831. represents the differential operator
  832. (z*d/dz)**2 + 2*z**2*d/dz.
  833. This class is used only in the implementation of the hypergeometric
  834. function expansion algorithm.
  835. """
  836. def apply(self, obj, op):
  837. """
  838. Apply ``self`` to the object ``obj``, where the generator is ``op``.
  839. Examples
  840. ========
  841. >>> from sympy.simplify.hyperexpand import Operator
  842. >>> from sympy.polys.polytools import Poly
  843. >>> from sympy.abc import x, y, z
  844. >>> op = Operator()
  845. >>> op._poly = Poly(x**2 + z*x + y, x)
  846. >>> op.apply(z**7, lambda f: f.diff(z))
  847. y*z**7 + 7*z**7 + 42*z**5
  848. """
  849. coeffs = self._poly.all_coeffs()
  850. coeffs.reverse()
  851. diffs = [obj]
  852. for c in coeffs[1:]:
  853. diffs.append(op(diffs[-1]))
  854. r = coeffs[0]*diffs[0]
  855. for c, d in zip(coeffs[1:], diffs[1:]):
  856. r += c*d
  857. return r
  858. class MultOperator(Operator):
  859. """ Simply multiply by a "constant" """
  860. def __init__(self, p):
  861. self._poly = Poly(p, _x)
  862. class ShiftA(Operator):
  863. """ Increment an upper index. """
  864. def __init__(self, ai):
  865. ai = sympify(ai)
  866. if ai == 0:
  867. raise ValueError('Cannot increment zero upper index.')
  868. self._poly = Poly(_x/ai + 1, _x)
  869. def __str__(self):
  870. return '<Increment upper %s.>' % (1/self._poly.all_coeffs()[0])
  871. class ShiftB(Operator):
  872. """ Decrement a lower index. """
  873. def __init__(self, bi):
  874. bi = sympify(bi)
  875. if bi == 1:
  876. raise ValueError('Cannot decrement unit lower index.')
  877. self._poly = Poly(_x/(bi - 1) + 1, _x)
  878. def __str__(self):
  879. return '<Decrement lower %s.>' % (1/self._poly.all_coeffs()[0] + 1)
  880. class UnShiftA(Operator):
  881. """ Decrement an upper index. """
  882. def __init__(self, ap, bq, i, z):
  883. """ Note: i counts from zero! """
  884. ap, bq, i = list(map(sympify, [ap, bq, i]))
  885. self._ap = ap
  886. self._bq = bq
  887. self._i = i
  888. ap = list(ap)
  889. bq = list(bq)
  890. ai = ap.pop(i) - 1
  891. if ai == 0:
  892. raise ValueError('Cannot decrement unit upper index.')
  893. m = Poly(z*ai, _x)
  894. for a in ap:
  895. m *= Poly(_x + a, _x)
  896. A = Dummy('A')
  897. n = D = Poly(ai*A - ai, A)
  898. for b in bq:
  899. n *= D + (b - 1).as_poly(A)
  900. b0 = -n.nth(0)
  901. if b0 == 0:
  902. raise ValueError('Cannot decrement upper index: '
  903. 'cancels with lower')
  904. n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, _x/ai + 1), _x)
  905. self._poly = Poly((n - m)/b0, _x)
  906. def __str__(self):
  907. return '<Decrement upper index #%s of %s, %s.>' % (self._i,
  908. self._ap, self._bq)
  909. class UnShiftB(Operator):
  910. """ Increment a lower index. """
  911. def __init__(self, ap, bq, i, z):
  912. """ Note: i counts from zero! """
  913. ap, bq, i = list(map(sympify, [ap, bq, i]))
  914. self._ap = ap
  915. self._bq = bq
  916. self._i = i
  917. ap = list(ap)
  918. bq = list(bq)
  919. bi = bq.pop(i) + 1
  920. if bi == 0:
  921. raise ValueError('Cannot increment -1 lower index.')
  922. m = Poly(_x*(bi - 1), _x)
  923. for b in bq:
  924. m *= Poly(_x + b - 1, _x)
  925. B = Dummy('B')
  926. D = Poly((bi - 1)*B - bi + 1, B)
  927. n = Poly(z, B)
  928. for a in ap:
  929. n *= (D + a.as_poly(B))
  930. b0 = n.nth(0)
  931. if b0 == 0:
  932. raise ValueError('Cannot increment index: cancels with upper')
  933. n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
  934. B, _x/(bi - 1) + 1), _x)
  935. self._poly = Poly((m - n)/b0, _x)
  936. def __str__(self):
  937. return '<Increment lower index #%s of %s, %s.>' % (self._i,
  938. self._ap, self._bq)
  939. class MeijerShiftA(Operator):
  940. """ Increment an upper b index. """
  941. def __init__(self, bi):
  942. bi = sympify(bi)
  943. self._poly = Poly(bi - _x, _x)
  944. def __str__(self):
  945. return '<Increment upper b=%s.>' % (self._poly.all_coeffs()[1])
  946. class MeijerShiftB(Operator):
  947. """ Decrement an upper a index. """
  948. def __init__(self, bi):
  949. bi = sympify(bi)
  950. self._poly = Poly(1 - bi + _x, _x)
  951. def __str__(self):
  952. return '<Decrement upper a=%s.>' % (1 - self._poly.all_coeffs()[1])
  953. class MeijerShiftC(Operator):
  954. """ Increment a lower b index. """
  955. def __init__(self, bi):
  956. bi = sympify(bi)
  957. self._poly = Poly(-bi + _x, _x)
  958. def __str__(self):
  959. return '<Increment lower b=%s.>' % (-self._poly.all_coeffs()[1])
  960. class MeijerShiftD(Operator):
  961. """ Decrement a lower a index. """
  962. def __init__(self, bi):
  963. bi = sympify(bi)
  964. self._poly = Poly(bi - 1 - _x, _x)
  965. def __str__(self):
  966. return '<Decrement lower a=%s.>' % (self._poly.all_coeffs()[1] + 1)
  967. class MeijerUnShiftA(Operator):
  968. """ Decrement an upper b index. """
  969. def __init__(self, an, ap, bm, bq, i, z):
  970. """ Note: i counts from zero! """
  971. an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
  972. self._an = an
  973. self._ap = ap
  974. self._bm = bm
  975. self._bq = bq
  976. self._i = i
  977. an = list(an)
  978. ap = list(ap)
  979. bm = list(bm)
  980. bq = list(bq)
  981. bi = bm.pop(i) - 1
  982. m = Poly(1, _x) * prod(Poly(b - _x, _x) for b in bm) * prod(Poly(_x - b, _x) for b in bq)
  983. A = Dummy('A')
  984. D = Poly(bi - A, A)
  985. n = Poly(z, A) * prod((D + 1 - a) for a in an) * prod((-D + a - 1) for a in ap)
  986. b0 = n.nth(0)
  987. if b0 == 0:
  988. raise ValueError('Cannot decrement upper b index (cancels)')
  989. n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, bi - _x), _x)
  990. self._poly = Poly((m - n)/b0, _x)
  991. def __str__(self):
  992. return '<Decrement upper b index #%s of %s, %s, %s, %s.>' % (self._i,
  993. self._an, self._ap, self._bm, self._bq)
  994. class MeijerUnShiftB(Operator):
  995. """ Increment an upper a index. """
  996. def __init__(self, an, ap, bm, bq, i, z):
  997. """ Note: i counts from zero! """
  998. an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
  999. self._an = an
  1000. self._ap = ap
  1001. self._bm = bm
  1002. self._bq = bq
  1003. self._i = i
  1004. an = list(an)
  1005. ap = list(ap)
  1006. bm = list(bm)
  1007. bq = list(bq)
  1008. ai = an.pop(i) + 1
  1009. m = Poly(z, _x)
  1010. for a in an:
  1011. m *= Poly(1 - a + _x, _x)
  1012. for a in ap:
  1013. m *= Poly(a - 1 - _x, _x)
  1014. B = Dummy('B')
  1015. D = Poly(B + ai - 1, B)
  1016. n = Poly(1, B)
  1017. for b in bm:
  1018. n *= (-D + b)
  1019. for b in bq:
  1020. n *= (D - b)
  1021. b0 = n.nth(0)
  1022. if b0 == 0:
  1023. raise ValueError('Cannot increment upper a index (cancels)')
  1024. n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
  1025. B, 1 - ai + _x), _x)
  1026. self._poly = Poly((m - n)/b0, _x)
  1027. def __str__(self):
  1028. return '<Increment upper a index #%s of %s, %s, %s, %s.>' % (self._i,
  1029. self._an, self._ap, self._bm, self._bq)
  1030. class MeijerUnShiftC(Operator):
  1031. """ Decrement a lower b index. """
  1032. # XXX this is "essentially" the same as MeijerUnShiftA. This "essentially"
  1033. # can be made rigorous using the functional equation G(1/z) = G'(z),
  1034. # where G' denotes a G function of slightly altered parameters.
  1035. # However, sorting out the details seems harder than just coding it
  1036. # again.
  1037. def __init__(self, an, ap, bm, bq, i, z):
  1038. """ Note: i counts from zero! """
  1039. an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
  1040. self._an = an
  1041. self._ap = ap
  1042. self._bm = bm
  1043. self._bq = bq
  1044. self._i = i
  1045. an = list(an)
  1046. ap = list(ap)
  1047. bm = list(bm)
  1048. bq = list(bq)
  1049. bi = bq.pop(i) - 1
  1050. m = Poly(1, _x)
  1051. for b in bm:
  1052. m *= Poly(b - _x, _x)
  1053. for b in bq:
  1054. m *= Poly(_x - b, _x)
  1055. C = Dummy('C')
  1056. D = Poly(bi + C, C)
  1057. n = Poly(z, C)
  1058. for a in an:
  1059. n *= (D + 1 - a)
  1060. for a in ap:
  1061. n *= (-D + a - 1)
  1062. b0 = n.nth(0)
  1063. if b0 == 0:
  1064. raise ValueError('Cannot decrement lower b index (cancels)')
  1065. n = Poly(Poly(n.all_coeffs()[:-1], C).as_expr().subs(C, _x - bi), _x)
  1066. self._poly = Poly((m - n)/b0, _x)
  1067. def __str__(self):
  1068. return '<Decrement lower b index #%s of %s, %s, %s, %s.>' % (self._i,
  1069. self._an, self._ap, self._bm, self._bq)
  1070. class MeijerUnShiftD(Operator):
  1071. """ Increment a lower a index. """
  1072. # XXX This is essentially the same as MeijerUnShiftA.
  1073. # See comment at MeijerUnShiftC.
  1074. def __init__(self, an, ap, bm, bq, i, z):
  1075. """ Note: i counts from zero! """
  1076. an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
  1077. self._an = an
  1078. self._ap = ap
  1079. self._bm = bm
  1080. self._bq = bq
  1081. self._i = i
  1082. an = list(an)
  1083. ap = list(ap)
  1084. bm = list(bm)
  1085. bq = list(bq)
  1086. ai = ap.pop(i) + 1
  1087. m = Poly(z, _x)
  1088. for a in an:
  1089. m *= Poly(1 - a + _x, _x)
  1090. for a in ap:
  1091. m *= Poly(a - 1 - _x, _x)
  1092. B = Dummy('B') # - this is the shift operator `D_I`
  1093. D = Poly(ai - 1 - B, B)
  1094. n = Poly(1, B)
  1095. for b in bm:
  1096. n *= (-D + b)
  1097. for b in bq:
  1098. n *= (D - b)
  1099. b0 = n.nth(0)
  1100. if b0 == 0:
  1101. raise ValueError('Cannot increment lower a index (cancels)')
  1102. n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
  1103. B, ai - 1 - _x), _x)
  1104. self._poly = Poly((m - n)/b0, _x)
  1105. def __str__(self):
  1106. return '<Increment lower a index #%s of %s, %s, %s, %s.>' % (self._i,
  1107. self._an, self._ap, self._bm, self._bq)
  1108. class ReduceOrder(Operator):
  1109. """ Reduce Order by cancelling an upper and a lower index. """
  1110. def __new__(cls, ai, bj):
  1111. """ For convenience if reduction is not possible, return None. """
  1112. ai = sympify(ai)
  1113. bj = sympify(bj)
  1114. n = ai - bj
  1115. if not n.is_Integer or n < 0:
  1116. return None
  1117. if bj.is_integer and bj.is_nonpositive:
  1118. return None
  1119. expr = Operator.__new__(cls)
  1120. p = S.One
  1121. for k in range(n):
  1122. p *= (_x + bj + k)/(bj + k)
  1123. expr._poly = Poly(p, _x)
  1124. expr._a = ai
  1125. expr._b = bj
  1126. return expr
  1127. @classmethod
  1128. def _meijer(cls, b, a, sign):
  1129. """ Cancel b + sign*s and a + sign*s
  1130. This is for meijer G functions. """
  1131. b = sympify(b)
  1132. a = sympify(a)
  1133. n = b - a
  1134. if n.is_negative or not n.is_Integer:
  1135. return None
  1136. expr = Operator.__new__(cls)
  1137. p = S.One
  1138. for k in range(n):
  1139. p *= (sign*_x + a + k)
  1140. expr._poly = Poly(p, _x)
  1141. if sign == -1:
  1142. expr._a = b
  1143. expr._b = a
  1144. else:
  1145. expr._b = Add(1, a - 1, evaluate=False)
  1146. expr._a = Add(1, b - 1, evaluate=False)
  1147. return expr
  1148. @classmethod
  1149. def meijer_minus(cls, b, a):
  1150. return cls._meijer(b, a, -1)
  1151. @classmethod
  1152. def meijer_plus(cls, a, b):
  1153. return cls._meijer(1 - a, 1 - b, 1)
  1154. def __str__(self):
  1155. return '<Reduce order by cancelling upper %s with lower %s.>' % \
  1156. (self._a, self._b)
  1157. def _reduce_order(ap, bq, gen, key):
  1158. """ Order reduction algorithm used in Hypergeometric and Meijer G """
  1159. ap = list(ap)
  1160. bq = list(bq)
  1161. ap.sort(key=key)
  1162. bq.sort(key=key)
  1163. nap = []
  1164. # we will edit bq in place
  1165. operators = []
  1166. for a in ap:
  1167. op = None
  1168. for i in range(len(bq)):
  1169. op = gen(a, bq[i])
  1170. if op is not None:
  1171. bq.pop(i)
  1172. break
  1173. if op is None:
  1174. nap.append(a)
  1175. else:
  1176. operators.append(op)
  1177. return nap, bq, operators
  1178. def reduce_order(func):
  1179. """
  1180. Given the hypergeometric function ``func``, find a sequence of operators to
  1181. reduces order as much as possible.
  1182. Explanation
  1183. ===========
  1184. Return (newfunc, [operators]), where applying the operators to the
  1185. hypergeometric function newfunc yields func.
  1186. Examples
  1187. ========
  1188. >>> from sympy.simplify.hyperexpand import reduce_order, Hyper_Function
  1189. >>> reduce_order(Hyper_Function((1, 2), (3, 4)))
  1190. (Hyper_Function((1, 2), (3, 4)), [])
  1191. >>> reduce_order(Hyper_Function((1,), (1,)))
  1192. (Hyper_Function((), ()), [<Reduce order by cancelling upper 1 with lower 1.>])
  1193. >>> reduce_order(Hyper_Function((2, 4), (3, 3)))
  1194. (Hyper_Function((2,), (3,)), [<Reduce order by cancelling
  1195. upper 4 with lower 3.>])
  1196. """
  1197. nap, nbq, operators = _reduce_order(func.ap, func.bq, ReduceOrder, default_sort_key)
  1198. return Hyper_Function(Tuple(*nap), Tuple(*nbq)), operators
  1199. def reduce_order_meijer(func):
  1200. """
  1201. Given the Meijer G function parameters, ``func``, find a sequence of
  1202. operators that reduces order as much as possible.
  1203. Return newfunc, [operators].
  1204. Examples
  1205. ========
  1206. >>> from sympy.simplify.hyperexpand import (reduce_order_meijer,
  1207. ... G_Function)
  1208. >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 2]))[0]
  1209. G_Function((4, 3), (5, 6), (3, 4), (2, 1))
  1210. >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 8]))[0]
  1211. G_Function((3,), (5, 6), (3, 4), (1,))
  1212. >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [1, 5]))[0]
  1213. G_Function((3,), (), (), (1,))
  1214. >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [5, 3]))[0]
  1215. G_Function((), (), (), ())
  1216. """
  1217. nan, nbq, ops1 = _reduce_order(func.an, func.bq, ReduceOrder.meijer_plus,
  1218. lambda x: default_sort_key(-x))
  1219. nbm, nap, ops2 = _reduce_order(func.bm, func.ap, ReduceOrder.meijer_minus,
  1220. default_sort_key)
  1221. return G_Function(nan, nap, nbm, nbq), ops1 + ops2
  1222. def make_derivative_operator(M, z):
  1223. """ Create a derivative operator, to be passed to Operator.apply. """
  1224. def doit(C):
  1225. r = z*C.diff(z) + C*M
  1226. r = r.applyfunc(make_simp(z))
  1227. return r
  1228. return doit
  1229. def apply_operators(obj, ops, op):
  1230. """
  1231. Apply the list of operators ``ops`` to object ``obj``, substituting
  1232. ``op`` for the generator.
  1233. """
  1234. res = obj
  1235. for o in reversed(ops):
  1236. res = o.apply(res, op)
  1237. return res
  1238. def devise_plan(target, origin, z):
  1239. """
  1240. Devise a plan (consisting of shift and un-shift operators) to be applied
  1241. to the hypergeometric function ``target`` to yield ``origin``.
  1242. Returns a list of operators.
  1243. Examples
  1244. ========
  1245. >>> from sympy.simplify.hyperexpand import devise_plan, Hyper_Function
  1246. >>> from sympy.abc import z
  1247. Nothing to do:
  1248. >>> devise_plan(Hyper_Function((1, 2), ()), Hyper_Function((1, 2), ()), z)
  1249. []
  1250. >>> devise_plan(Hyper_Function((), (1, 2)), Hyper_Function((), (1, 2)), z)
  1251. []
  1252. Very simple plans:
  1253. >>> devise_plan(Hyper_Function((2,), ()), Hyper_Function((1,), ()), z)
  1254. [<Increment upper 1.>]
  1255. >>> devise_plan(Hyper_Function((), (2,)), Hyper_Function((), (1,)), z)
  1256. [<Increment lower index #0 of [], [1].>]
  1257. Several buckets:
  1258. >>> from sympy import S
  1259. >>> devise_plan(Hyper_Function((1, S.Half), ()),
  1260. ... Hyper_Function((2, S('3/2')), ()), z) #doctest: +NORMALIZE_WHITESPACE
  1261. [<Decrement upper index #0 of [3/2, 1], [].>,
  1262. <Decrement upper index #0 of [2, 3/2], [].>]
  1263. A slightly more complicated plan:
  1264. >>> devise_plan(Hyper_Function((1, 3), ()), Hyper_Function((2, 2), ()), z)
  1265. [<Increment upper 2.>, <Decrement upper index #0 of [2, 2], [].>]
  1266. Another more complicated plan: (note that the ap have to be shifted first!)
  1267. >>> devise_plan(Hyper_Function((1, -1), (2,)), Hyper_Function((3, -2), (4,)), z)
  1268. [<Decrement lower 3.>, <Decrement lower 4.>,
  1269. <Decrement upper index #1 of [-1, 2], [4].>,
  1270. <Decrement upper index #1 of [-1, 3], [4].>, <Increment upper -2.>]
  1271. """
  1272. abuckets, bbuckets, nabuckets, nbbuckets = [sift(params, _mod1) for
  1273. params in (target.ap, target.bq, origin.ap, origin.bq)]
  1274. if len(list(abuckets.keys())) != len(list(nabuckets.keys())) or \
  1275. len(list(bbuckets.keys())) != len(list(nbbuckets.keys())):
  1276. raise ValueError('%s not reachable from %s' % (target, origin))
  1277. ops = []
  1278. def do_shifts(fro, to, inc, dec):
  1279. ops = []
  1280. for i in range(len(fro)):
  1281. if to[i] - fro[i] > 0:
  1282. sh = inc
  1283. ch = 1
  1284. else:
  1285. sh = dec
  1286. ch = -1
  1287. while to[i] != fro[i]:
  1288. ops += [sh(fro, i)]
  1289. fro[i] += ch
  1290. return ops
  1291. def do_shifts_a(nal, nbk, al, aother, bother):
  1292. """ Shift us from (nal, nbk) to (al, nbk). """
  1293. return do_shifts(nal, al, lambda p, i: ShiftA(p[i]),
  1294. lambda p, i: UnShiftA(p + aother, nbk + bother, i, z))
  1295. def do_shifts_b(nal, nbk, bk, aother, bother):
  1296. """ Shift us from (nal, nbk) to (nal, bk). """
  1297. return do_shifts(nbk, bk,
  1298. lambda p, i: UnShiftB(nal + aother, p + bother, i, z),
  1299. lambda p, i: ShiftB(p[i]))
  1300. for r in sorted(list(abuckets.keys()) + list(bbuckets.keys()), key=default_sort_key):
  1301. al = ()
  1302. nal = ()
  1303. bk = ()
  1304. nbk = ()
  1305. if r in abuckets:
  1306. al = abuckets[r]
  1307. nal = nabuckets[r]
  1308. if r in bbuckets:
  1309. bk = bbuckets[r]
  1310. nbk = nbbuckets[r]
  1311. if len(al) != len(nal) or len(bk) != len(nbk):
  1312. raise ValueError('%s not reachable from %s' % (target, origin))
  1313. al, nal, bk, nbk = [sorted(w, key=default_sort_key)
  1314. for w in [al, nal, bk, nbk]]
  1315. def others(dic, key):
  1316. l = []
  1317. for k, value in dic.items():
  1318. if k != key:
  1319. l += list(dic[k])
  1320. return l
  1321. aother = others(nabuckets, r)
  1322. bother = others(nbbuckets, r)
  1323. if len(al) == 0:
  1324. # there can be no complications, just shift the bs as we please
  1325. ops += do_shifts_b([], nbk, bk, aother, bother)
  1326. elif len(bk) == 0:
  1327. # there can be no complications, just shift the as as we please
  1328. ops += do_shifts_a(nal, [], al, aother, bother)
  1329. else:
  1330. namax = nal[-1]
  1331. amax = al[-1]
  1332. if nbk[0] - namax <= 0 or bk[0] - amax <= 0:
  1333. raise ValueError('Non-suitable parameters.')
  1334. if namax - amax > 0:
  1335. # we are going to shift down - first do the as, then the bs
  1336. ops += do_shifts_a(nal, nbk, al, aother, bother)
  1337. ops += do_shifts_b(al, nbk, bk, aother, bother)
  1338. else:
  1339. # we are going to shift up - first do the bs, then the as
  1340. ops += do_shifts_b(nal, nbk, bk, aother, bother)
  1341. ops += do_shifts_a(nal, bk, al, aother, bother)
  1342. nabuckets[r] = al
  1343. nbbuckets[r] = bk
  1344. ops.reverse()
  1345. return ops
  1346. def try_shifted_sum(func, z):
  1347. """ Try to recognise a hypergeometric sum that starts from k > 0. """
  1348. abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
  1349. if len(abuckets[S.Zero]) != 1:
  1350. return None
  1351. r = abuckets[S.Zero][0]
  1352. if r <= 0:
  1353. return None
  1354. if S.Zero not in bbuckets:
  1355. return None
  1356. l = list(bbuckets[S.Zero])
  1357. l.sort()
  1358. k = l[0]
  1359. if k <= 0:
  1360. return None
  1361. nap = list(func.ap)
  1362. nap.remove(r)
  1363. nbq = list(func.bq)
  1364. nbq.remove(k)
  1365. k -= 1
  1366. nap = [x - k for x in nap]
  1367. nbq = [x - k for x in nbq]
  1368. ops = []
  1369. for n in range(r - 1):
  1370. ops.append(ShiftA(n + 1))
  1371. ops.reverse()
  1372. fac = factorial(k)/z**k
  1373. fac *= Mul(*[rf(b, k) for b in nbq])
  1374. fac /= Mul(*[rf(a, k) for a in nap])
  1375. ops += [MultOperator(fac)]
  1376. p = 0
  1377. for n in range(k):
  1378. m = z**n/factorial(n)
  1379. m *= Mul(*[rf(a, n) for a in nap])
  1380. m /= Mul(*[rf(b, n) for b in nbq])
  1381. p += m
  1382. return Hyper_Function(nap, nbq), ops, -p
  1383. def try_polynomial(func, z):
  1384. """ Recognise polynomial cases. Returns None if not such a case.
  1385. Requires order to be fully reduced. """
  1386. abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
  1387. a0 = abuckets[S.Zero]
  1388. b0 = bbuckets[S.Zero]
  1389. a0.sort()
  1390. b0.sort()
  1391. al0 = [x for x in a0 if x <= 0]
  1392. bl0 = [x for x in b0 if x <= 0]
  1393. if bl0 and all(a < bl0[-1] for a in al0):
  1394. return oo
  1395. if not al0:
  1396. return None
  1397. a = al0[-1]
  1398. fac = 1
  1399. res = S.One
  1400. for n in Tuple(*list(range(-a))):
  1401. fac *= z
  1402. fac /= n + 1
  1403. fac *= Mul(*[a + n for a in func.ap])
  1404. fac /= Mul(*[b + n for b in func.bq])
  1405. res += fac
  1406. return res
  1407. def try_lerchphi(func):
  1408. """
  1409. Try to find an expression for Hyper_Function ``func`` in terms of Lerch
  1410. Transcendents.
  1411. Return None if no such expression can be found.
  1412. """
  1413. # This is actually quite simple, and is described in Roach's paper,
  1414. # section 18.
  1415. # We don't need to implement the reduction to polylog here, this
  1416. # is handled by expand_func.
  1417. # First we need to figure out if the summation coefficient is a rational
  1418. # function of the summation index, and construct that rational function.
  1419. abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
  1420. paired = {}
  1421. for key, value in abuckets.items():
  1422. if key != 0 and key not in bbuckets:
  1423. return None
  1424. bvalue = bbuckets[key]
  1425. paired[key] = (list(value), list(bvalue))
  1426. bbuckets.pop(key, None)
  1427. if bbuckets != {}:
  1428. return None
  1429. if S.Zero not in abuckets:
  1430. return None
  1431. aints, bints = paired[S.Zero]
  1432. # Account for the additional n! in denominator
  1433. paired[S.Zero] = (aints, bints + [1])
  1434. t = Dummy('t')
  1435. numer = S.One
  1436. denom = S.One
  1437. for key, (avalue, bvalue) in paired.items():
  1438. if len(avalue) != len(bvalue):
  1439. return None
  1440. # Note that since order has been reduced fully, all the b are
  1441. # bigger than all the a they differ from by an integer. In particular
  1442. # if there are any negative b left, this function is not well-defined.
  1443. for a, b in zip(avalue, bvalue):
  1444. if (a - b).is_positive:
  1445. k = a - b
  1446. numer *= rf(b + t, k)
  1447. denom *= rf(b, k)
  1448. else:
  1449. k = b - a
  1450. numer *= rf(a, k)
  1451. denom *= rf(a + t, k)
  1452. # Now do a partial fraction decomposition.
  1453. # We assemble two structures: a list monomials of pairs (a, b) representing
  1454. # a*t**b (b a non-negative integer), and a dict terms, where
  1455. # terms[a] = [(b, c)] means that there is a term b/(t-a)**c.
  1456. part = apart(numer/denom, t)
  1457. args = Add.make_args(part)
  1458. monomials = []
  1459. terms = {}
  1460. for arg in args:
  1461. numer, denom = arg.as_numer_denom()
  1462. if not denom.has(t):
  1463. p = Poly(numer, t)
  1464. if not p.is_monomial:
  1465. raise TypeError("p should be monomial")
  1466. ((b, ), a) = p.LT()
  1467. monomials += [(a/denom, b)]
  1468. continue
  1469. if numer.has(t):
  1470. raise NotImplementedError('Need partial fraction decomposition'
  1471. ' with linear denominators')
  1472. indep, [dep] = denom.as_coeff_mul(t)
  1473. n = 1
  1474. if dep.is_Pow:
  1475. n = dep.exp
  1476. dep = dep.base
  1477. if dep == t:
  1478. a == 0
  1479. elif dep.is_Add:
  1480. a, tmp = dep.as_independent(t)
  1481. b = 1
  1482. if tmp != t:
  1483. b, _ = tmp.as_independent(t)
  1484. if dep != b*t + a:
  1485. raise NotImplementedError('unrecognised form %s' % dep)
  1486. a /= b
  1487. indep *= b**n
  1488. else:
  1489. raise NotImplementedError('unrecognised form of partial fraction')
  1490. terms.setdefault(a, []).append((numer/indep, n))
  1491. # Now that we have this information, assemble our formula. All the
  1492. # monomials yield rational functions and go into one basis element.
  1493. # The terms[a] are related by differentiation. If the largest exponent is
  1494. # n, we need lerchphi(z, k, a) for k = 1, 2, ..., n.
  1495. # deriv maps a basis to its derivative, expressed as a C(z)-linear
  1496. # combination of other basis elements.
  1497. deriv = {}
  1498. coeffs = {}
  1499. z = Dummy('z')
  1500. monomials.sort(key=lambda x: x[1])
  1501. mon = {0: 1/(1 - z)}
  1502. if monomials:
  1503. for k in range(monomials[-1][1]):
  1504. mon[k + 1] = z*mon[k].diff(z)
  1505. for a, n in monomials:
  1506. coeffs.setdefault(S.One, []).append(a*mon[n])
  1507. for a, l in terms.items():
  1508. for c, k in l:
  1509. coeffs.setdefault(lerchphi(z, k, a), []).append(c)
  1510. l.sort(key=lambda x: x[1])
  1511. for k in range(2, l[-1][1] + 1):
  1512. deriv[lerchphi(z, k, a)] = [(-a, lerchphi(z, k, a)),
  1513. (1, lerchphi(z, k - 1, a))]
  1514. deriv[lerchphi(z, 1, a)] = [(-a, lerchphi(z, 1, a)),
  1515. (1/(1 - z), S.One)]
  1516. trans = {}
  1517. for n, b in enumerate([S.One] + list(deriv.keys())):
  1518. trans[b] = n
  1519. basis = [expand_func(b) for (b, _) in sorted(trans.items(),
  1520. key=lambda x:x[1])]
  1521. B = Matrix(basis)
  1522. C = Matrix([[0]*len(B)])
  1523. for b, c in coeffs.items():
  1524. C[trans[b]] = Add(*c)
  1525. M = zeros(len(B))
  1526. for b, l in deriv.items():
  1527. for c, b2 in l:
  1528. M[trans[b], trans[b2]] = c
  1529. return Formula(func, z, None, [], B, C, M)
  1530. def build_hypergeometric_formula(func):
  1531. """
  1532. Create a formula object representing the hypergeometric function ``func``.
  1533. """
  1534. # We know that no `ap` are negative integers, otherwise "detect poly"
  1535. # would have kicked in. However, `ap` could be empty. In this case we can
  1536. # use a different basis.
  1537. # I'm not aware of a basis that works in all cases.
  1538. z = Dummy('z')
  1539. if func.ap:
  1540. afactors = [_x + a for a in func.ap]
  1541. bfactors = [_x + b - 1 for b in func.bq]
  1542. expr = _x*Mul(*bfactors) - z*Mul(*afactors)
  1543. poly = Poly(expr, _x)
  1544. n = poly.degree()
  1545. basis = []
  1546. M = zeros(n)
  1547. for k in range(n):
  1548. a = func.ap[0] + k
  1549. basis += [hyper([a] + list(func.ap[1:]), func.bq, z)]
  1550. if k < n - 1:
  1551. M[k, k] = -a
  1552. M[k, k + 1] = a
  1553. B = Matrix(basis)
  1554. C = Matrix([[1] + [0]*(n - 1)])
  1555. derivs = [eye(n)]
  1556. for k in range(n):
  1557. derivs.append(M*derivs[k])
  1558. l = poly.all_coeffs()
  1559. l.reverse()
  1560. res = [0]*n
  1561. for k, c in enumerate(l):
  1562. for r, d in enumerate(C*derivs[k]):
  1563. res[r] += c*d
  1564. for k, c in enumerate(res):
  1565. M[n - 1, k] = -c/derivs[n - 1][0, n - 1]/poly.all_coeffs()[0]
  1566. return Formula(func, z, None, [], B, C, M)
  1567. else:
  1568. # Since there are no `ap`, none of the `bq` can be non-positive
  1569. # integers.
  1570. basis = []
  1571. bq = list(func.bq[:])
  1572. for i in range(len(bq)):
  1573. basis += [hyper([], bq, z)]
  1574. bq[i] += 1
  1575. basis += [hyper([], bq, z)]
  1576. B = Matrix(basis)
  1577. n = len(B)
  1578. C = Matrix([[1] + [0]*(n - 1)])
  1579. M = zeros(n)
  1580. M[0, n - 1] = z/Mul(*func.bq)
  1581. for k in range(1, n):
  1582. M[k, k - 1] = func.bq[k - 1]
  1583. M[k, k] = -func.bq[k - 1]
  1584. return Formula(func, z, None, [], B, C, M)
  1585. def hyperexpand_special(ap, bq, z):
  1586. """
  1587. Try to find a closed-form expression for hyper(ap, bq, z), where ``z``
  1588. is supposed to be a "special" value, e.g. 1.
  1589. This function tries various of the classical summation formulae
  1590. (Gauss, Saalschuetz, etc).
  1591. """
  1592. # This code is very ad-hoc. There are many clever algorithms
  1593. # (notably Zeilberger's) related to this problem.
  1594. # For now we just want a few simple cases to work.
  1595. p, q = len(ap), len(bq)
  1596. z_ = z
  1597. z = unpolarify(z)
  1598. if z == 0:
  1599. return S.One
  1600. from sympy.simplify.simplify import simplify
  1601. if p == 2 and q == 1:
  1602. # 2F1
  1603. a, b, c = ap + bq
  1604. if z == 1:
  1605. # Gauss
  1606. return gamma(c - a - b)*gamma(c)/gamma(c - a)/gamma(c - b)
  1607. if z == -1 and simplify(b - a + c) == 1:
  1608. b, a = a, b
  1609. if z == -1 and simplify(a - b + c) == 1:
  1610. # Kummer
  1611. if b.is_integer and b.is_negative:
  1612. return 2*cos(pi*b/2)*gamma(-b)*gamma(b - a + 1) \
  1613. /gamma(-b/2)/gamma(b/2 - a + 1)
  1614. else:
  1615. return gamma(b/2 + 1)*gamma(b - a + 1) \
  1616. /gamma(b + 1)/gamma(b/2 - a + 1)
  1617. # TODO tons of more formulae
  1618. # investigate what algorithms exist
  1619. return hyper(ap, bq, z_)
  1620. _collection = None
  1621. def _hyperexpand(func, z, ops0=[], z0=Dummy('z0'), premult=1, prem=0,
  1622. rewrite='default'):
  1623. """
  1624. Try to find an expression for the hypergeometric function ``func``.
  1625. Explanation
  1626. ===========
  1627. The result is expressed in terms of a dummy variable ``z0``. Then it
  1628. is multiplied by ``premult``. Then ``ops0`` is applied.
  1629. ``premult`` must be a*z**prem for some a independent of ``z``.
  1630. """
  1631. if z.is_zero:
  1632. return S.One
  1633. from sympy.simplify.simplify import simplify
  1634. z = polarify(z, subs=False)
  1635. if rewrite == 'default':
  1636. rewrite = 'nonrepsmall'
  1637. def carryout_plan(f, ops):
  1638. C = apply_operators(f.C.subs(f.z, z0), ops,
  1639. make_derivative_operator(f.M.subs(f.z, z0), z0))
  1640. C = apply_operators(C, ops0,
  1641. make_derivative_operator(f.M.subs(f.z, z0)
  1642. + prem*eye(f.M.shape[0]), z0))
  1643. if premult == 1:
  1644. C = C.applyfunc(make_simp(z0))
  1645. r = reduce(lambda s,m: s+m[0]*m[1], zip(C, f.B.subs(f.z, z0)), S.Zero)*premult
  1646. res = r.subs(z0, z)
  1647. if rewrite:
  1648. res = res.rewrite(rewrite)
  1649. return res
  1650. # TODO
  1651. # The following would be possible:
  1652. # *) PFD Duplication (see Kelly Roach's paper)
  1653. # *) In a similar spirit, try_lerchphi() can be generalised considerably.
  1654. global _collection
  1655. if _collection is None:
  1656. _collection = FormulaCollection()
  1657. debug('Trying to expand hypergeometric function ', func)
  1658. # First reduce order as much as possible.
  1659. func, ops = reduce_order(func)
  1660. if ops:
  1661. debug(' Reduced order to ', func)
  1662. else:
  1663. debug(' Could not reduce order.')
  1664. # Now try polynomial cases
  1665. res = try_polynomial(func, z0)
  1666. if res is not None:
  1667. debug(' Recognised polynomial.')
  1668. p = apply_operators(res, ops, lambda f: z0*f.diff(z0))
  1669. p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
  1670. return unpolarify(simplify(p).subs(z0, z))
  1671. # Try to recognise a shifted sum.
  1672. p = S.Zero
  1673. res = try_shifted_sum(func, z0)
  1674. if res is not None:
  1675. func, nops, p = res
  1676. debug(' Recognised shifted sum, reduced order to ', func)
  1677. ops += nops
  1678. # apply the plan for poly
  1679. p = apply_operators(p, ops, lambda f: z0*f.diff(z0))
  1680. p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
  1681. p = simplify(p).subs(z0, z)
  1682. # Try special expansions early.
  1683. if unpolarify(z) in [1, -1] and (len(func.ap), len(func.bq)) == (2, 1):
  1684. f = build_hypergeometric_formula(func)
  1685. r = carryout_plan(f, ops).replace(hyper, hyperexpand_special)
  1686. if not r.has(hyper):
  1687. return r + p
  1688. # Try to find a formula in our collection
  1689. formula = _collection.lookup_origin(func)
  1690. # Now try a lerch phi formula
  1691. if formula is None:
  1692. formula = try_lerchphi(func)
  1693. if formula is None:
  1694. debug(' Could not find an origin. ',
  1695. 'Will return answer in terms of '
  1696. 'simpler hypergeometric functions.')
  1697. formula = build_hypergeometric_formula(func)
  1698. debug(' Found an origin: ', formula.closed_form, ' ', formula.func)
  1699. # We need to find the operators that convert formula into func.
  1700. ops += devise_plan(func, formula.func, z0)
  1701. # Now carry out the plan.
  1702. r = carryout_plan(formula, ops) + p
  1703. return powdenest(r, polar=True).replace(hyper, hyperexpand_special)
  1704. def devise_plan_meijer(fro, to, z):
  1705. """
  1706. Find operators to convert G-function ``fro`` into G-function ``to``.
  1707. Explanation
  1708. ===========
  1709. It is assumed that ``fro`` and ``to`` have the same signatures, and that in fact
  1710. any corresponding pair of parameters differs by integers, and a direct path
  1711. is possible. I.e. if there are parameters a1 b1 c1 and a2 b2 c2 it is
  1712. assumed that a1 can be shifted to a2, etc. The only thing this routine
  1713. determines is the order of shifts to apply, nothing clever will be tried.
  1714. It is also assumed that ``fro`` is suitable.
  1715. Examples
  1716. ========
  1717. >>> from sympy.simplify.hyperexpand import (devise_plan_meijer,
  1718. ... G_Function)
  1719. >>> from sympy.abc import z
  1720. Empty plan:
  1721. >>> devise_plan_meijer(G_Function([1], [2], [3], [4]),
  1722. ... G_Function([1], [2], [3], [4]), z)
  1723. []
  1724. Very simple plans:
  1725. >>> devise_plan_meijer(G_Function([0], [], [], []),
  1726. ... G_Function([1], [], [], []), z)
  1727. [<Increment upper a index #0 of [0], [], [], [].>]
  1728. >>> devise_plan_meijer(G_Function([0], [], [], []),
  1729. ... G_Function([-1], [], [], []), z)
  1730. [<Decrement upper a=0.>]
  1731. >>> devise_plan_meijer(G_Function([], [1], [], []),
  1732. ... G_Function([], [2], [], []), z)
  1733. [<Increment lower a index #0 of [], [1], [], [].>]
  1734. Slightly more complicated plans:
  1735. >>> devise_plan_meijer(G_Function([0], [], [], []),
  1736. ... G_Function([2], [], [], []), z)
  1737. [<Increment upper a index #0 of [1], [], [], [].>,
  1738. <Increment upper a index #0 of [0], [], [], [].>]
  1739. >>> devise_plan_meijer(G_Function([0], [], [0], []),
  1740. ... G_Function([-1], [], [1], []), z)
  1741. [<Increment upper b=0.>, <Decrement upper a=0.>]
  1742. Order matters:
  1743. >>> devise_plan_meijer(G_Function([0], [], [0], []),
  1744. ... G_Function([1], [], [1], []), z)
  1745. [<Increment upper a index #0 of [0], [], [1], [].>, <Increment upper b=0.>]
  1746. """
  1747. # TODO for now, we use the following simple heuristic: inverse-shift
  1748. # when possible, shift otherwise. Give up if we cannot make progress.
  1749. def try_shift(f, t, shifter, diff, counter):
  1750. """ Try to apply ``shifter`` in order to bring some element in ``f``
  1751. nearer to its counterpart in ``to``. ``diff`` is +/- 1 and
  1752. determines the effect of ``shifter``. Counter is a list of elements
  1753. blocking the shift.
  1754. Return an operator if change was possible, else None.
  1755. """
  1756. for idx, (a, b) in enumerate(zip(f, t)):
  1757. if (
  1758. (a - b).is_integer and (b - a)/diff > 0 and
  1759. all(a != x for x in counter)):
  1760. sh = shifter(idx)
  1761. f[idx] += diff
  1762. return sh
  1763. fan = list(fro.an)
  1764. fap = list(fro.ap)
  1765. fbm = list(fro.bm)
  1766. fbq = list(fro.bq)
  1767. ops = []
  1768. change = True
  1769. while change:
  1770. change = False
  1771. op = try_shift(fan, to.an,
  1772. lambda i: MeijerUnShiftB(fan, fap, fbm, fbq, i, z),
  1773. 1, fbm + fbq)
  1774. if op is not None:
  1775. ops += [op]
  1776. change = True
  1777. continue
  1778. op = try_shift(fap, to.ap,
  1779. lambda i: MeijerUnShiftD(fan, fap, fbm, fbq, i, z),
  1780. 1, fbm + fbq)
  1781. if op is not None:
  1782. ops += [op]
  1783. change = True
  1784. continue
  1785. op = try_shift(fbm, to.bm,
  1786. lambda i: MeijerUnShiftA(fan, fap, fbm, fbq, i, z),
  1787. -1, fan + fap)
  1788. if op is not None:
  1789. ops += [op]
  1790. change = True
  1791. continue
  1792. op = try_shift(fbq, to.bq,
  1793. lambda i: MeijerUnShiftC(fan, fap, fbm, fbq, i, z),
  1794. -1, fan + fap)
  1795. if op is not None:
  1796. ops += [op]
  1797. change = True
  1798. continue
  1799. op = try_shift(fan, to.an, lambda i: MeijerShiftB(fan[i]), -1, [])
  1800. if op is not None:
  1801. ops += [op]
  1802. change = True
  1803. continue
  1804. op = try_shift(fap, to.ap, lambda i: MeijerShiftD(fap[i]), -1, [])
  1805. if op is not None:
  1806. ops += [op]
  1807. change = True
  1808. continue
  1809. op = try_shift(fbm, to.bm, lambda i: MeijerShiftA(fbm[i]), 1, [])
  1810. if op is not None:
  1811. ops += [op]
  1812. change = True
  1813. continue
  1814. op = try_shift(fbq, to.bq, lambda i: MeijerShiftC(fbq[i]), 1, [])
  1815. if op is not None:
  1816. ops += [op]
  1817. change = True
  1818. continue
  1819. if fan != list(to.an) or fap != list(to.ap) or fbm != list(to.bm) or \
  1820. fbq != list(to.bq):
  1821. raise NotImplementedError('Could not devise plan.')
  1822. ops.reverse()
  1823. return ops
  1824. _meijercollection = None
  1825. def _meijergexpand(func, z0, allow_hyper=False, rewrite='default',
  1826. place=None):
  1827. """
  1828. Try to find an expression for the Meijer G function specified
  1829. by the G_Function ``func``. If ``allow_hyper`` is True, then returning
  1830. an expression in terms of hypergeometric functions is allowed.
  1831. Currently this just does Slater's theorem.
  1832. If expansions exist both at zero and at infinity, ``place``
  1833. can be set to ``0`` or ``zoo`` for the preferred choice.
  1834. """
  1835. global _meijercollection
  1836. if _meijercollection is None:
  1837. _meijercollection = MeijerFormulaCollection()
  1838. if rewrite == 'default':
  1839. rewrite = None
  1840. func0 = func
  1841. debug('Try to expand Meijer G function corresponding to ', func)
  1842. # We will play games with analytic continuation - rather use a fresh symbol
  1843. z = Dummy('z')
  1844. func, ops = reduce_order_meijer(func)
  1845. if ops:
  1846. debug(' Reduced order to ', func)
  1847. else:
  1848. debug(' Could not reduce order.')
  1849. # Try to find a direct formula
  1850. f = _meijercollection.lookup_origin(func)
  1851. if f is not None:
  1852. debug(' Found a Meijer G formula: ', f.func)
  1853. ops += devise_plan_meijer(f.func, func, z)
  1854. # Now carry out the plan.
  1855. C = apply_operators(f.C.subs(f.z, z), ops,
  1856. make_derivative_operator(f.M.subs(f.z, z), z))
  1857. C = C.applyfunc(make_simp(z))
  1858. r = C*f.B.subs(f.z, z)
  1859. r = r[0].subs(z, z0)
  1860. return powdenest(r, polar=True)
  1861. debug(" Could not find a direct formula. Trying Slater's theorem.")
  1862. # TODO the following would be possible:
  1863. # *) Paired Index Theorems
  1864. # *) PFD Duplication
  1865. # (See Kelly Roach's paper for details on either.)
  1866. #
  1867. # TODO Also, we tend to create combinations of gamma functions that can be
  1868. # simplified.
  1869. def can_do(pbm, pap):
  1870. """ Test if slater applies. """
  1871. for i in pbm:
  1872. if len(pbm[i]) > 1:
  1873. l = 0
  1874. if i in pap:
  1875. l = len(pap[i])
  1876. if l + 1 < len(pbm[i]):
  1877. return False
  1878. return True
  1879. def do_slater(an, bm, ap, bq, z, zfinal):
  1880. # zfinal is the value that will eventually be substituted for z.
  1881. # We pass it to _hyperexpand to improve performance.
  1882. func = G_Function(an, bm, ap, bq)
  1883. _, pbm, pap, _ = func.compute_buckets()
  1884. if not can_do(pbm, pap):
  1885. return S.Zero, False
  1886. cond = len(an) + len(ap) < len(bm) + len(bq)
  1887. if len(an) + len(ap) == len(bm) + len(bq):
  1888. cond = abs(z) < 1
  1889. if cond is False:
  1890. return S.Zero, False
  1891. res = S.Zero
  1892. for m in pbm:
  1893. if len(pbm[m]) == 1:
  1894. bh = pbm[m][0]
  1895. fac = 1
  1896. bo = list(bm)
  1897. bo.remove(bh)
  1898. for bj in bo:
  1899. fac *= gamma(bj - bh)
  1900. for aj in an:
  1901. fac *= gamma(1 + bh - aj)
  1902. for bj in bq:
  1903. fac /= gamma(1 + bh - bj)
  1904. for aj in ap:
  1905. fac /= gamma(aj - bh)
  1906. nap = [1 + bh - a for a in list(an) + list(ap)]
  1907. nbq = [1 + bh - b for b in list(bo) + list(bq)]
  1908. k = polar_lift(S.NegativeOne**(len(ap) - len(bm)))
  1909. harg = k*zfinal
  1910. # NOTE even though k "is" +-1, this has to be t/k instead of
  1911. # t*k ... we are using polar numbers for consistency!
  1912. premult = (t/k)**bh
  1913. hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
  1914. t, premult, bh, rewrite=None)
  1915. res += fac * hyp
  1916. else:
  1917. b_ = pbm[m][0]
  1918. ki = [bi - b_ for bi in pbm[m][1:]]
  1919. u = len(ki)
  1920. li = [ai - b_ for ai in pap[m][:u + 1]]
  1921. bo = list(bm)
  1922. for b in pbm[m]:
  1923. bo.remove(b)
  1924. ao = list(ap)
  1925. for a in pap[m][:u]:
  1926. ao.remove(a)
  1927. lu = li[-1]
  1928. di = [l - k for (l, k) in zip(li, ki)]
  1929. # We first work out the integrand:
  1930. s = Dummy('s')
  1931. integrand = z**s
  1932. for b in bm:
  1933. if not Mod(b, 1) and b.is_Number:
  1934. b = int(round(b))
  1935. integrand *= gamma(b - s)
  1936. for a in an:
  1937. integrand *= gamma(1 - a + s)
  1938. for b in bq:
  1939. integrand /= gamma(1 - b + s)
  1940. for a in ap:
  1941. integrand /= gamma(a - s)
  1942. # Now sum the finitely many residues:
  1943. # XXX This speeds up some cases - is it a good idea?
  1944. integrand = expand_func(integrand)
  1945. for r in range(int(round(lu))):
  1946. resid = residue(integrand, s, b_ + r)
  1947. resid = apply_operators(resid, ops, lambda f: z*f.diff(z))
  1948. res -= resid
  1949. # Now the hypergeometric term.
  1950. au = b_ + lu
  1951. k = polar_lift(S.NegativeOne**(len(ao) + len(bo) + 1))
  1952. harg = k*zfinal
  1953. premult = (t/k)**au
  1954. nap = [1 + au - a for a in list(an) + list(ap)] + [1]
  1955. nbq = [1 + au - b for b in list(bm) + list(bq)]
  1956. hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
  1957. t, premult, au, rewrite=None)
  1958. C = S.NegativeOne**(lu)/factorial(lu)
  1959. for i in range(u):
  1960. C *= S.NegativeOne**di[i]/rf(lu - li[i] + 1, di[i])
  1961. for a in an:
  1962. C *= gamma(1 - a + au)
  1963. for b in bo:
  1964. C *= gamma(b - au)
  1965. for a in ao:
  1966. C /= gamma(a - au)
  1967. for b in bq:
  1968. C /= gamma(1 - b + au)
  1969. res += C*hyp
  1970. return res, cond
  1971. t = Dummy('t')
  1972. slater1, cond1 = do_slater(func.an, func.bm, func.ap, func.bq, z, z0)
  1973. def tr(l):
  1974. return [1 - x for x in l]
  1975. for op in ops:
  1976. op._poly = Poly(op._poly.subs({z: 1/t, _x: -_x}), _x)
  1977. slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
  1978. t, 1/z0)
  1979. slater1 = powdenest(slater1.subs(z, z0), polar=True)
  1980. slater2 = powdenest(slater2.subs(t, 1/z0), polar=True)
  1981. if not isinstance(cond2, bool):
  1982. cond2 = cond2.subs(t, 1/z)
  1983. m = func(z)
  1984. if m.delta > 0 or \
  1985. (m.delta == 0 and len(m.ap) == len(m.bq) and
  1986. (re(m.nu) < -1) is not False and polar_lift(z0) == polar_lift(1)):
  1987. # The condition delta > 0 means that the convergence region is
  1988. # connected. Any expression we find can be continued analytically
  1989. # to the entire convergence region.
  1990. # The conditions delta==0, p==q, re(nu) < -1 imply that G is continuous
  1991. # on the positive reals, so the values at z=1 agree.
  1992. if cond1 is not False:
  1993. cond1 = True
  1994. if cond2 is not False:
  1995. cond2 = True
  1996. if cond1 is True:
  1997. slater1 = slater1.rewrite(rewrite or 'nonrep')
  1998. else:
  1999. slater1 = slater1.rewrite(rewrite or 'nonrepsmall')
  2000. if cond2 is True:
  2001. slater2 = slater2.rewrite(rewrite or 'nonrep')
  2002. else:
  2003. slater2 = slater2.rewrite(rewrite or 'nonrepsmall')
  2004. if cond1 is not False and cond2 is not False:
  2005. # If one condition is False, there is no choice.
  2006. if place == 0:
  2007. cond2 = False
  2008. if place == zoo:
  2009. cond1 = False
  2010. if not isinstance(cond1, bool):
  2011. cond1 = cond1.subs(z, z0)
  2012. if not isinstance(cond2, bool):
  2013. cond2 = cond2.subs(z, z0)
  2014. def weight(expr, cond):
  2015. if cond is True:
  2016. c0 = 0
  2017. elif cond is False:
  2018. c0 = 1
  2019. else:
  2020. c0 = 2
  2021. if expr.has(oo, zoo, -oo, nan):
  2022. # XXX this actually should not happen, but consider
  2023. # S('meijerg(((0, -1/2, 0, -1/2, 1/2), ()), ((0,),
  2024. # (-1/2, -1/2, -1/2, -1)), exp_polar(I*pi))/4')
  2025. c0 = 3
  2026. return (c0, expr.count(hyper), expr.count_ops())
  2027. w1 = weight(slater1, cond1)
  2028. w2 = weight(slater2, cond2)
  2029. if min(w1, w2) <= (0, 1, oo):
  2030. if w1 < w2:
  2031. return slater1
  2032. else:
  2033. return slater2
  2034. if max(w1[0], w2[0]) <= 1 and max(w1[1], w2[1]) <= 1:
  2035. return Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
  2036. # We couldn't find an expression without hypergeometric functions.
  2037. # TODO it would be helpful to give conditions under which the integral
  2038. # is known to diverge.
  2039. r = Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
  2040. if r.has(hyper) and not allow_hyper:
  2041. debug(' Could express using hypergeometric functions, '
  2042. 'but not allowed.')
  2043. if not r.has(hyper) or allow_hyper:
  2044. return r
  2045. return func0(z0)
  2046. def hyperexpand(f, allow_hyper=False, rewrite='default', place=None):
  2047. """
  2048. Expand hypergeometric functions. If allow_hyper is True, allow partial
  2049. simplification (that is a result different from input,
  2050. but still containing hypergeometric functions).
  2051. If a G-function has expansions both at zero and at infinity,
  2052. ``place`` can be set to ``0`` or ``zoo`` to indicate the
  2053. preferred choice.
  2054. Examples
  2055. ========
  2056. >>> from sympy.simplify.hyperexpand import hyperexpand
  2057. >>> from sympy.functions import hyper
  2058. >>> from sympy.abc import z
  2059. >>> hyperexpand(hyper([], [], z))
  2060. exp(z)
  2061. Non-hyperegeometric parts of the expression and hypergeometric expressions
  2062. that are not recognised are left unchanged:
  2063. >>> hyperexpand(1 + hyper([1, 1, 1], [], z))
  2064. hyper((1, 1, 1), (), z) + 1
  2065. """
  2066. f = sympify(f)
  2067. def do_replace(ap, bq, z):
  2068. r = _hyperexpand(Hyper_Function(ap, bq), z, rewrite=rewrite)
  2069. if r is None:
  2070. return hyper(ap, bq, z)
  2071. else:
  2072. return r
  2073. def do_meijer(ap, bq, z):
  2074. r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
  2075. allow_hyper, rewrite=rewrite, place=place)
  2076. if not r.has(nan, zoo, oo, -oo):
  2077. return r
  2078. return f.replace(hyper, do_replace).replace(meijerg, do_meijer)