tools.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from . import rl
  2. from .core import do_one, exhaust, switch
  3. from .traverse import top_down
  4. def subs(d, **kwargs):
  5. """ Full simultaneous exact substitution.
  6. Examples
  7. ========
  8. >>> from sympy.strategies.tools import subs
  9. >>> from sympy import Basic, S
  10. >>> mapping = {S(1): S(4), S(4): S(1), Basic(S(5)): Basic(S(6), S(7))}
  11. >>> expr = Basic(S(1), Basic(S(2), S(3)), Basic(S(4), Basic(S(5))))
  12. >>> subs(mapping)(expr)
  13. Basic(4, Basic(2, 3), Basic(1, Basic(6, 7)))
  14. """
  15. if d:
  16. return top_down(do_one(*map(rl.subs, *zip(*d.items()))), **kwargs)
  17. else:
  18. return lambda x: x
  19. def canon(*rules, **kwargs):
  20. """ Strategy for canonicalization.
  21. Explanation
  22. ===========
  23. Apply each rule in a bottom_up fashion through the tree.
  24. Do each one in turn.
  25. Keep doing this until there is no change.
  26. """
  27. return exhaust(top_down(exhaust(do_one(*rules)), **kwargs))
  28. def typed(ruletypes):
  29. """ Apply rules based on the expression type
  30. inputs:
  31. ruletypes -- a dict mapping {Type: rule}
  32. Examples
  33. ========
  34. >>> from sympy.strategies import rm_id, typed
  35. >>> from sympy import Add, Mul
  36. >>> rm_zeros = rm_id(lambda x: x==0)
  37. >>> rm_ones = rm_id(lambda x: x==1)
  38. >>> remove_idents = typed({Add: rm_zeros, Mul: rm_ones})
  39. """
  40. return switch(type, ruletypes)