test_sympy_parser.py 13 KB

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