scipy_nodes.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from sympy.core.function import Add, ArgumentIndexError, Function
  2. from sympy.core.power import Pow
  3. from sympy.core.singleton import S
  4. from sympy.functions.elementary.exponential import log
  5. from sympy.functions.elementary.trigonometric import cos, sin
  6. def _cosm1(x, *, evaluate=True):
  7. return Add(cos(x, evaluate=evaluate), -S.One, evaluate=evaluate)
  8. class cosm1(Function):
  9. """ Minus one plus cosine of x, i.e. cos(x) - 1. For use when x is close to zero.
  10. Helper class for use with e.g. scipy.special.cosm1
  11. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.cosm1.html
  12. """
  13. nargs = 1
  14. def fdiff(self, argindex=1):
  15. """
  16. Returns the first derivative of this function.
  17. """
  18. if argindex == 1:
  19. return -sin(*self.args)
  20. else:
  21. raise ArgumentIndexError(self, argindex)
  22. def _eval_rewrite_as_cos(self, x, **kwargs):
  23. return _cosm1(x)
  24. def _eval_evalf(self, *args, **kwargs):
  25. return self.rewrite(cos).evalf(*args, **kwargs)
  26. def _eval_simplify(self, **kwargs):
  27. x, = self.args
  28. candidate = _cosm1(x.simplify(**kwargs))
  29. if candidate != _cosm1(x, evaluate=False):
  30. return candidate
  31. else:
  32. return cosm1(x)
  33. def _powm1(x, y, *, evaluate=True):
  34. return Add(Pow(x, y, evaluate=evaluate), -S.One, evaluate=evaluate)
  35. class powm1(Function):
  36. """ Minus one plus x to the power of y, i.e. x**y - 1. For use when x is close to one or y is close to zero.
  37. Helper class for use with e.g. scipy.special.powm1
  38. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.powm1.html
  39. """
  40. nargs = 2
  41. def fdiff(self, argindex=1):
  42. """
  43. Returns the first derivative of this function.
  44. """
  45. if argindex == 1:
  46. return Pow(self.args[0], self.args[1])*self.args[1]/self.args[0]
  47. elif argindex == 2:
  48. return log(self.args[0])*Pow(*self.args)
  49. else:
  50. raise ArgumentIndexError(self, argindex)
  51. def _eval_rewrite_as_Pow(self, x, y, **kwargs):
  52. return _powm1(x, y)
  53. def _eval_evalf(self, *args, **kwargs):
  54. return self.rewrite(Pow).evalf(*args, **kwargs)
  55. def _eval_simplify(self, **kwargs):
  56. x, y = self.args
  57. candidate = _powm1(x.simplify(**kwargs), y.simplify(**kwargs))
  58. if candidate != _powm1(x, y, evaluate=False):
  59. return candidate
  60. else:
  61. return powm1(x, y)