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.

361 lines
12 KiB

6 months ago
  1. # -*- coding: utf-8 -*-
  2. import sys
  3. import builtins
  4. import types
  5. from sympy.assumptions import Q
  6. from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq
  7. from sympy.functions import exp, factorial, factorial2, sin, Min, Max
  8. from sympy.logic import And
  9. from sympy.series import Limit
  10. from sympy.testing.pytest import raises, skip
  11. from sympy.parsing.sympy_parser import (
  12. parse_expr, standard_transformations, rationalize, TokenError,
  13. split_symbols, implicit_multiplication, convert_equals_signs,
  14. convert_xor, function_exponentiation, lambda_notation, auto_symbol,
  15. repeated_decimals, implicit_multiplication_application,
  16. auto_number, factorial_notation, implicit_application,
  17. _transformation, T
  18. )
  19. def test_sympy_parser():
  20. x = Symbol('x')
  21. inputs = {
  22. '2*x': 2 * x,
  23. '3.00': Float(3),
  24. '22/7': Rational(22, 7),
  25. '2+3j': 2 + 3*I,
  26. 'exp(x)': exp(x),
  27. 'x!': factorial(x),
  28. 'x!!': factorial2(x),
  29. '(x + 1)! - 1': factorial(x + 1) - 1,
  30. '3.[3]': Rational(10, 3),
  31. '.0[3]': Rational(1, 30),
  32. '3.2[3]': Rational(97, 30),
  33. '1.3[12]': Rational(433, 330),
  34. '1 + 3.[3]': Rational(13, 3),
  35. '1 + .0[3]': Rational(31, 30),
  36. '1 + 3.2[3]': Rational(127, 30),
  37. '.[0011]': Rational(1, 909),
  38. '0.1[00102] + 1': Rational(366697, 333330),
  39. '1.[0191]': Rational(10190, 9999),
  40. '10!': 3628800,
  41. '-(2)': -Integer(2),
  42. '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)],
  43. 'Symbol("x").free_symbols': x.free_symbols,
  44. "S('S(3).n(n=3)')": 3.00,
  45. 'factorint(12, visual=True)': Mul(
  46. Pow(2, 2, evaluate=False),
  47. Pow(3, 1, evaluate=False),
  48. evaluate=False),
  49. 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'),
  50. 'Q.even(x)': Q.even(x),
  51. }
  52. for text, result in inputs.items():
  53. assert parse_expr(text) == result
  54. raises(TypeError, lambda:
  55. parse_expr('x', standard_transformations))
  56. raises(TypeError, lambda:
  57. parse_expr('x', transformations=lambda x,y: 1))
  58. raises(TypeError, lambda:
  59. parse_expr('x', transformations=(lambda x,y: 1,)))
  60. raises(TypeError, lambda: parse_expr('x', transformations=((),)))
  61. raises(TypeError, lambda: parse_expr('x', {}, [], []))
  62. raises(TypeError, lambda: parse_expr('x', [], [], {}))
  63. raises(TypeError, lambda: parse_expr('x', [], [], {}))
  64. def test_rationalize():
  65. inputs = {
  66. '0.123': Rational(123, 1000)
  67. }
  68. transformations = standard_transformations + (rationalize,)
  69. for text, result in inputs.items():
  70. assert parse_expr(text, transformations=transformations) == result
  71. def test_factorial_fail():
  72. inputs = ['x!!!', 'x!!!!', '(!)']
  73. for text in inputs:
  74. try:
  75. parse_expr(text)
  76. assert False
  77. except TokenError:
  78. assert True
  79. def test_repeated_fail():
  80. inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]',
  81. '0.1[[1]]', '0x1.1[1]']
  82. # All are valid Python, so only raise TypeError for invalid indexing
  83. for text in inputs:
  84. raises(TypeError, lambda: parse_expr(text))
  85. inputs = ['0.1[', '0.1[1', '0.1[]']
  86. for text in inputs:
  87. raises((TokenError, SyntaxError), lambda: parse_expr(text))
  88. def test_repeated_dot_only():
  89. assert parse_expr('.[1]') == Rational(1, 9)
  90. assert parse_expr('1 + .[1]') == Rational(10, 9)
  91. def test_local_dict():
  92. local_dict = {
  93. 'my_function': lambda x: x + 2
  94. }
  95. inputs = {
  96. 'my_function(2)': Integer(4)
  97. }
  98. for text, result in inputs.items():
  99. assert parse_expr(text, local_dict=local_dict) == result
  100. def test_local_dict_split_implmult():
  101. t = standard_transformations + (split_symbols, implicit_multiplication,)
  102. w = Symbol('w', real=True)
  103. y = Symbol('y')
  104. assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w
  105. def test_local_dict_symbol_to_fcn():
  106. x = Symbol('x')
  107. d = {'foo': Function('bar')}
  108. assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
  109. d = {'foo': Symbol('baz')}
  110. raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
  111. def test_global_dict():
  112. global_dict = {
  113. 'Symbol': Symbol
  114. }
  115. inputs = {
  116. 'Q & S': And(Symbol('Q'), Symbol('S'))
  117. }
  118. for text, result in inputs.items():
  119. assert parse_expr(text, global_dict=global_dict) == result
  120. def test_no_globals():
  121. # Replicate creating the default global_dict:
  122. default_globals = {}
  123. exec('from sympy import *', default_globals)
  124. builtins_dict = vars(builtins)
  125. for name, obj in builtins_dict.items():
  126. if isinstance(obj, types.BuiltinFunctionType):
  127. default_globals[name] = obj
  128. default_globals['max'] = Max
  129. default_globals['min'] = Min
  130. # Need to include Symbol or parse_expr will not work:
  131. default_globals.pop('Symbol')
  132. global_dict = {'Symbol':Symbol}
  133. for name in default_globals:
  134. obj = parse_expr(name, global_dict=global_dict)
  135. assert obj == Symbol(name)
  136. def test_issue_2515():
  137. raises(TokenError, lambda: parse_expr('(()'))
  138. raises(TokenError, lambda: parse_expr('"""'))
  139. def test_issue_7663():
  140. x = Symbol('x')
  141. e = '2*(x+1)'
  142. assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False)
  143. assert parse_expr(e, evaluate=0).equals(2*(x+1))
  144. def test_recursive_evaluate_false_10560():
  145. inputs = {
  146. '4*-3' : '4*-3',
  147. '-4*3' : '(-4)*3',
  148. "-2*x*y": '(-2)*x*y',
  149. "x*-4*x": "x*(-4)*x"
  150. }
  151. for text, result in inputs.items():
  152. assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
  153. def test_function_evaluate_false():
  154. inputs = [
  155. 'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)',
  156. 'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)',
  157. 'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)',
  158. 'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)',
  159. 'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)',
  160. 'exp(0)', 'log(0)', 'sqrt(0)',
  161. ]
  162. for case in inputs:
  163. expr = parse_expr(case, evaluate=False)
  164. assert case == str(expr) != str(expr.doit())
  165. assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)'
  166. assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)'
  167. def test_issue_10773():
  168. inputs = {
  169. '-10/5': '(-10)/5',
  170. '-10/-5' : '(-10)/(-5)',
  171. }
  172. for text, result in inputs.items():
  173. assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
  174. def test_split_symbols():
  175. transformations = standard_transformations + \
  176. (split_symbols, implicit_multiplication,)
  177. x = Symbol('x')
  178. y = Symbol('y')
  179. xy = Symbol('xy')
  180. assert parse_expr("xy") == xy
  181. assert parse_expr("xy", transformations=transformations) == x*y
  182. def test_split_symbols_function():
  183. transformations = standard_transformations + \
  184. (split_symbols, implicit_multiplication,)
  185. x = Symbol('x')
  186. y = Symbol('y')
  187. a = Symbol('a')
  188. f = Function('f')
  189. assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1)
  190. assert parse_expr("af(x+1)", transformations=transformations,
  191. local_dict={'f':f}) == a*f(x+1)
  192. def test_functional_exponent():
  193. t = standard_transformations + (convert_xor, function_exponentiation)
  194. x = Symbol('x')
  195. y = Symbol('y')
  196. a = Symbol('a')
  197. yfcn = Function('y')
  198. assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2
  199. assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y
  200. assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y
  201. assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x))
  202. assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
  203. def test_match_parentheses_implicit_multiplication():
  204. transformations = standard_transformations + \
  205. (implicit_multiplication,)
  206. raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations))
  207. def test_convert_equals_signs():
  208. transformations = standard_transformations + \
  209. (convert_equals_signs, )
  210. x = Symbol('x')
  211. y = Symbol('y')
  212. assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x)
  213. assert parse_expr("y = x", transformations=transformations) == Eq(y, x)
  214. assert parse_expr("(2*y = x) = False",
  215. transformations=transformations) == Eq(Eq(2*y, x), False)
  216. def test_parse_function_issue_3539():
  217. x = Symbol('x')
  218. f = Function('f')
  219. assert parse_expr('f(x)') == f(x)
  220. def test_split_symbols_numeric():
  221. transformations = (
  222. standard_transformations +
  223. (implicit_multiplication_application,))
  224. n = Symbol('n')
  225. expr1 = parse_expr('2**n * 3**n')
  226. expr2 = parse_expr('2**n3**n', transformations=transformations)
  227. assert expr1 == expr2 == 2**n*3**n
  228. expr1 = parse_expr('n12n34', transformations=transformations)
  229. assert expr1 == n*12*n*34
  230. def test_unicode_names():
  231. assert parse_expr('α') == Symbol('α')
  232. def test_python3_features():
  233. # Make sure the tokenizer can handle Python 3-only features
  234. if sys.version_info < (3, 7):
  235. skip("test_python3_features requires Python 3.7 or newer")
  236. assert parse_expr("123_456") == 123456
  237. assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495)
  238. assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333)
  239. assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99)
  240. assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990)
  241. assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
  242. def test_issue_19501():
  243. x = Symbol('x')
  244. eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=(
  245. standard_transformations +
  246. (implicit_multiplication_application,)))
  247. assert eq.free_symbols == {x}
  248. def test_parsing_definitions():
  249. from sympy.abc import x
  250. assert len(_transformation) == 12 # if this changes, extend below
  251. assert _transformation[0] == lambda_notation
  252. assert _transformation[1] == auto_symbol
  253. assert _transformation[2] == repeated_decimals
  254. assert _transformation[3] == auto_number
  255. assert _transformation[4] == factorial_notation
  256. assert _transformation[5] == implicit_multiplication_application
  257. assert _transformation[6] == convert_xor
  258. assert _transformation[7] == implicit_application
  259. assert _transformation[8] == implicit_multiplication
  260. assert _transformation[9] == convert_equals_signs
  261. assert _transformation[10] == function_exponentiation
  262. assert _transformation[11] == rationalize
  263. assert T[:5] == T[0,1,2,3,4] == standard_transformations
  264. t = _transformation
  265. assert T[-1, 0] == (t[len(t) - 1], t[0])
  266. assert T[:5, 8] == standard_transformations + (t[8],)
  267. assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10
  268. assert parse_expr('sin 3x', transformations='implicit') == sin(3*x)
  269. def test_builtins():
  270. cases = [
  271. ('abs(x)', 'Abs(x)'),
  272. ('max(x, y)', 'Max(x, y)'),
  273. ('min(x, y)', 'Min(x, y)'),
  274. ('pow(x, y)', 'Pow(x, y)'),
  275. ]
  276. for built_in_func_call, sympy_func_call in cases:
  277. assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call)
  278. assert str(parse_expr('pow(38, -1, 97)')) == '23'
  279. def test_issue_22822():
  280. raises(ValueError, lambda: parse_expr('x', {'': 1}))
  281. data = {'some_parameter': None}
  282. assert parse_expr('some_parameter is None', data) is True