m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.0 KiB

6 months ago
  1. from sympy.strategies.traverse import (top_down, bottom_up, sall, top_down_once,
  2. 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))) == Basic(S(0), S(0), Basic(x, z))
  16. def test_bottom_up():
  17. _test_global_traversal(bottom_up)
  18. _test_stop_on_non_basics(bottom_up)
  19. def test_top_down():
  20. _test_global_traversal(top_down)
  21. _test_stop_on_non_basics(top_down)
  22. def _test_global_traversal(trav):
  23. zero_all_symbols = trav(zero_symbols)
  24. assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \
  25. Basic(S(0), S(0), Basic(S(0), S(0)))
  26. def _test_stop_on_non_basics(trav):
  27. def add_one_if_can(expr):
  28. try:
  29. return expr + 1
  30. except TypeError:
  31. return expr
  32. expr = Basic(S(1), Str('a'), Basic(S(2), Str('b')))
  33. expected = Basic(S(2), Str('a'), Basic(S(3), Str('b')))
  34. rl = trav(add_one_if_can)
  35. assert rl(expr) == expected
  36. class Basic2(Basic):
  37. pass
  38. rl = lambda x: Basic2(*x.args) if x.args and not isinstance(x.args[0], Integer) else x
  39. def test_top_down_once():
  40. top_rl = top_down_once(rl)
  41. assert top_rl(Basic(S(1.0), S(2.0), Basic(S(3), S(4)))) == Basic2(S(1.0), S(2.0), Basic(S(3), S(4)))
  42. def test_bottom_up_once():
  43. bottom_rl = bottom_up_once(rl)
  44. assert bottom_rl(Basic(S(1), S(2), Basic(S(3.0), S(4.0)))) == Basic(S(1), S(2), Basic2(S(3.0), S(4.0)))
  45. def test_expr_fns():
  46. expr = x + y**3
  47. e = bottom_up(lambda v: v + 1, expr_fns)(expr)
  48. b = bottom_up(lambda v: Basic.__new__(Add, v, S(1)), basic_fns)(expr)
  49. assert rebuild(b) == e