test_traverse.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from sympy.strategies.traverse import (
  2. top_down, bottom_up, sall, top_down_once, bottom_up_once, basic_fns)
  3. from sympy.strategies.rl import rebuild
  4. from sympy.strategies.util import expr_fns
  5. from sympy.core.add import Add
  6. from sympy.core.basic import Basic
  7. from sympy.core.numbers import Integer
  8. from sympy.core.singleton import S
  9. from sympy.core.symbol import Str, Symbol
  10. from sympy.abc import x, y, z
  11. def zero_symbols(expression):
  12. return S.Zero if isinstance(expression, Symbol) else expression
  13. def test_sall():
  14. zero_onelevel = sall(zero_symbols)
  15. assert zero_onelevel(Basic(x, y, Basic(x, z))) == \
  16. Basic(S(0), S(0), Basic(x, z))
  17. def test_bottom_up():
  18. _test_global_traversal(bottom_up)
  19. _test_stop_on_non_basics(bottom_up)
  20. def test_top_down():
  21. _test_global_traversal(top_down)
  22. _test_stop_on_non_basics(top_down)
  23. def _test_global_traversal(trav):
  24. zero_all_symbols = trav(zero_symbols)
  25. assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \
  26. Basic(S(0), S(0), Basic(S(0), S(0)))
  27. def _test_stop_on_non_basics(trav):
  28. def add_one_if_can(expr):
  29. try:
  30. return expr + 1
  31. except TypeError:
  32. return expr
  33. expr = Basic(S(1), Str('a'), Basic(S(2), Str('b')))
  34. expected = Basic(S(2), Str('a'), Basic(S(3), Str('b')))
  35. rl = trav(add_one_if_can)
  36. assert rl(expr) == expected
  37. class Basic2(Basic):
  38. pass
  39. def rl(x):
  40. if x.args and not isinstance(x.args[0], Integer):
  41. return Basic2(*x.args)
  42. return x
  43. def test_top_down_once():
  44. top_rl = top_down_once(rl)
  45. assert top_rl(Basic(S(1.0), S(2.0), Basic(S(3), S(4)))) == \
  46. Basic2(S(1.0), S(2.0), Basic(S(3), S(4)))
  47. def test_bottom_up_once():
  48. bottom_rl = bottom_up_once(rl)
  49. assert bottom_rl(Basic(S(1), S(2), Basic(S(3.0), S(4.0)))) == \
  50. Basic(S(1), S(2), Basic2(S(3.0), S(4.0)))
  51. def test_expr_fns():
  52. expr = x + y**3
  53. e = bottom_up(lambda v: v + 1, expr_fns)(expr)
  54. b = bottom_up(lambda v: Basic.__new__(Add, v, S(1)), basic_fns)(expr)
  55. assert rebuild(b) == e