numerical.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """Numerical Methods for Holonomic Functions"""
  2. from sympy.core.sympify import sympify
  3. from sympy.holonomic.holonomic import DMFsubs
  4. from mpmath import mp
  5. def _evalf(func, points, derivatives=False, method='RK4'):
  6. """
  7. Numerical methods for numerical integration along a given set of
  8. points in the complex plane.
  9. """
  10. ann = func.annihilator
  11. a = ann.order
  12. R = ann.parent.base
  13. K = R.get_field()
  14. if method == 'Euler':
  15. meth = _euler
  16. else:
  17. meth = _rk4
  18. dmf = [K.new(j.to_list()) for j in ann.listofpoly]
  19. red = [-dmf[i] / dmf[a] for i in range(a)]
  20. y0 = func.y0
  21. if len(y0) < a:
  22. raise TypeError("Not Enough Initial Conditions")
  23. x0 = func.x0
  24. sol = [meth(red, x0, points[0], y0, a)]
  25. for i, j in enumerate(points[1:]):
  26. sol.append(meth(red, points[i], j, sol[-1], a))
  27. if not derivatives:
  28. return [sympify(i[0]) for i in sol]
  29. else:
  30. return sympify(sol)
  31. def _euler(red, x0, x1, y0, a):
  32. """
  33. Euler's method for numerical integration.
  34. From x0 to x1 with initial values given at x0 as vector y0.
  35. """
  36. A = sympify(x0)._to_mpmath(mp.prec)
  37. B = sympify(x1)._to_mpmath(mp.prec)
  38. y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
  39. h = B - A
  40. f_0 = y_0[1:]
  41. f_0_n = 0
  42. for i in range(a):
  43. f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
  44. f_0.append(f_0_n)
  45. return [y_0[i] + h * f_0[i] for i in range(a)]
  46. def _rk4(red, x0, x1, y0, a):
  47. """
  48. Runge-Kutta 4th order numerical method.
  49. """
  50. A = sympify(x0)._to_mpmath(mp.prec)
  51. B = sympify(x1)._to_mpmath(mp.prec)
  52. y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
  53. h = B - A
  54. f_0_n = 0
  55. f_1_n = 0
  56. f_2_n = 0
  57. f_3_n = 0
  58. f_0 = y_0[1:]
  59. for i in range(a):
  60. f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
  61. f_0.append(f_0_n)
  62. f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)]
  63. for i in range(a):
  64. f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2)
  65. f_1.append(f_1_n)
  66. f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)]
  67. for i in range(a):
  68. f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2)
  69. f_2.append(f_2_n)
  70. f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)]
  71. for i in range(a):
  72. f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h)
  73. f_3.append(f_3_n)
  74. return [y_0[i] + h*(f_0[i]+2*f_1[i]+2*f_2[i]+f_3[i])/6 for i in range(a)]