maxima.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import re
  2. from sympy.concrete.products import product
  3. from sympy.concrete.summations import Sum
  4. from sympy.core.sympify import sympify
  5. from sympy.functions.elementary.trigonometric import (cos, sin)
  6. class MaximaHelpers:
  7. def maxima_expand(expr):
  8. return expr.expand()
  9. def maxima_float(expr):
  10. return expr.evalf()
  11. def maxima_trigexpand(expr):
  12. return expr.expand(trig=True)
  13. def maxima_sum(a1, a2, a3, a4):
  14. return Sum(a1, (a2, a3, a4)).doit()
  15. def maxima_product(a1, a2, a3, a4):
  16. return product(a1, (a2, a3, a4))
  17. def maxima_csc(expr):
  18. return 1/sin(expr)
  19. def maxima_sec(expr):
  20. return 1/cos(expr)
  21. sub_dict = {
  22. 'pi': re.compile(r'%pi'),
  23. 'E': re.compile(r'%e'),
  24. 'I': re.compile(r'%i'),
  25. '**': re.compile(r'\^'),
  26. 'oo': re.compile(r'\binf\b'),
  27. '-oo': re.compile(r'\bminf\b'),
  28. "'-'": re.compile(r'\bminus\b'),
  29. 'maxima_expand': re.compile(r'\bexpand\b'),
  30. 'maxima_float': re.compile(r'\bfloat\b'),
  31. 'maxima_trigexpand': re.compile(r'\btrigexpand'),
  32. 'maxima_sum': re.compile(r'\bsum\b'),
  33. 'maxima_product': re.compile(r'\bproduct\b'),
  34. 'cancel': re.compile(r'\bratsimp\b'),
  35. 'maxima_csc': re.compile(r'\bcsc\b'),
  36. 'maxima_sec': re.compile(r'\bsec\b')
  37. }
  38. var_name = re.compile(r'^\s*(\w+)\s*:')
  39. def parse_maxima(str, globals=None, name_dict={}):
  40. str = str.strip()
  41. str = str.rstrip('; ')
  42. for k, v in sub_dict.items():
  43. str = v.sub(k, str)
  44. assign_var = None
  45. var_match = var_name.search(str)
  46. if var_match:
  47. assign_var = var_match.group(1)
  48. str = str[var_match.end():].strip()
  49. dct = MaximaHelpers.__dict__.copy()
  50. dct.update(name_dict)
  51. obj = sympify(str, locals=dct)
  52. if assign_var and globals:
  53. globals[assign_var] = obj
  54. return obj