utilities.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from contextlib import contextmanager
  2. from threading import local
  3. from sympy.core.function import expand_mul
  4. from sympy.simplify.simplify import dotprodsimp as _dotprodsimp
  5. class DotProdSimpState(local):
  6. def __init__(self):
  7. self.state = None
  8. _dotprodsimp_state = DotProdSimpState()
  9. @contextmanager
  10. def dotprodsimp(x):
  11. old = _dotprodsimp_state.state
  12. try:
  13. _dotprodsimp_state.state = x
  14. yield
  15. finally:
  16. _dotprodsimp_state.state = old
  17. def _get_intermediate_simp(deffunc=lambda x: x, offfunc=lambda x: x,
  18. onfunc=_dotprodsimp, dotprodsimp=None):
  19. """Support function for controlling intermediate simplification. Returns a
  20. simplification function according to the global setting of dotprodsimp
  21. operation.
  22. ``deffunc`` - Function to be used by default.
  23. ``offfunc`` - Function to be used if dotprodsimp has been turned off.
  24. ``onfunc`` - Function to be used if dotprodsimp has been turned on.
  25. ``dotprodsimp`` - True, False or None. Will be overridden by global
  26. _dotprodsimp_state.state if that is not None.
  27. """
  28. if dotprodsimp is False or _dotprodsimp_state.state is False:
  29. return offfunc
  30. if dotprodsimp is True or _dotprodsimp_state.state is True:
  31. return onfunc
  32. return deffunc # None, None
  33. def _get_intermediate_simp_bool(default=False, dotprodsimp=None):
  34. """Same as ``_get_intermediate_simp`` but returns bools instead of functions
  35. by default."""
  36. return _get_intermediate_simp(default, False, True, dotprodsimp)
  37. def _iszero(x):
  38. """Returns True if x is zero."""
  39. return getattr(x, 'is_zero', None)
  40. def _is_zero_after_expand_mul(x):
  41. """Tests by expand_mul only, suitable for polynomials and rational
  42. functions."""
  43. return expand_mul(x) == 0