test_aesaracode.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. """
  2. Important note on tests in this module - the Aesara printing functions use a
  3. global cache by default, which means that tests using it will modify global
  4. state and thus not be independent from each other. Instead of using the "cache"
  5. keyword argument each time, this module uses the aesara_code_ and
  6. aesara_function_ functions defined below which default to using a new, empty
  7. cache instead.
  8. """
  9. import logging
  10. from sympy.external import import_module
  11. from sympy.testing.pytest import raises, SKIP, warns_deprecated_sympy
  12. from sympy.utilities.exceptions import ignore_warnings
  13. aesaralogger = logging.getLogger('aesara.configdefaults')
  14. aesaralogger.setLevel(logging.CRITICAL)
  15. aesara = import_module('aesara')
  16. aesaralogger.setLevel(logging.WARNING)
  17. if aesara:
  18. import numpy as np
  19. aet = aesara.tensor
  20. from aesara.scalar.basic import ScalarType
  21. from aesara.graph.basic import Variable
  22. from aesara.tensor.var import TensorVariable
  23. from aesara.tensor.elemwise import Elemwise, DimShuffle
  24. from aesara.tensor.math import Dot
  25. from sympy.printing.aesaracode import true_divide
  26. xt, yt, zt = [aet.scalar(name, 'floatX') for name in 'xyz']
  27. Xt, Yt, Zt = [aet.tensor('floatX', (False, False), name=n) for n in 'XYZ']
  28. else:
  29. #bin/test will not execute any tests now
  30. disabled = True
  31. import sympy as sy
  32. from sympy.core.singleton import S
  33. from sympy.abc import x, y, z, t
  34. from sympy.printing.aesaracode import (aesara_code, dim_handling,
  35. aesara_function)
  36. # Default set of matrix symbols for testing - make square so we can both
  37. # multiply and perform elementwise operations between them.
  38. X, Y, Z = [sy.MatrixSymbol(n, 4, 4) for n in 'XYZ']
  39. # For testing AppliedUndef
  40. f_t = sy.Function('f')(t)
  41. def aesara_code_(expr, **kwargs):
  42. """ Wrapper for aesara_code that uses a new, empty cache by default. """
  43. kwargs.setdefault('cache', {})
  44. with warns_deprecated_sympy():
  45. return aesara_code(expr, **kwargs)
  46. def aesara_function_(inputs, outputs, **kwargs):
  47. """ Wrapper for aesara_function that uses a new, empty cache by default. """
  48. kwargs.setdefault('cache', {})
  49. with warns_deprecated_sympy():
  50. return aesara_function(inputs, outputs, **kwargs)
  51. def fgraph_of(*exprs):
  52. """ Transform SymPy expressions into Aesara Computation.
  53. Parameters
  54. ==========
  55. exprs
  56. SymPy expressions
  57. Returns
  58. =======
  59. aesara.graph.fg.FunctionGraph
  60. """
  61. outs = list(map(aesara_code_, exprs))
  62. ins = list(aesara.graph.basic.graph_inputs(outs))
  63. ins, outs = aesara.graph.basic.clone(ins, outs)
  64. return aesara.graph.fg.FunctionGraph(ins, outs)
  65. def aesara_simplify(fgraph):
  66. """ Simplify a Aesara Computation.
  67. Parameters
  68. ==========
  69. fgraph : aesara.graph.fg.FunctionGraph
  70. Returns
  71. =======
  72. aesara.graph.fg.FunctionGraph
  73. """
  74. mode = aesara.compile.get_default_mode().excluding("fusion")
  75. fgraph = fgraph.clone()
  76. mode.optimizer.rewrite(fgraph)
  77. return fgraph
  78. def theq(a, b):
  79. """ Test two Aesara objects for equality.
  80. Also accepts numeric types and lists/tuples of supported types.
  81. Note - debugprint() has a bug where it will accept numeric types but does
  82. not respect the "file" argument and in this case and instead prints the number
  83. to stdout and returns an empty string. This can lead to tests passing where
  84. they should fail because any two numbers will always compare as equal. To
  85. prevent this we treat numbers as a separate case.
  86. """
  87. numeric_types = (int, float, np.number)
  88. a_is_num = isinstance(a, numeric_types)
  89. b_is_num = isinstance(b, numeric_types)
  90. # Compare numeric types using regular equality
  91. if a_is_num or b_is_num:
  92. if not (a_is_num and b_is_num):
  93. return False
  94. return a == b
  95. # Compare sequences element-wise
  96. a_is_seq = isinstance(a, (tuple, list))
  97. b_is_seq = isinstance(b, (tuple, list))
  98. if a_is_seq or b_is_seq:
  99. if not (a_is_seq and b_is_seq) or type(a) != type(b):
  100. return False
  101. return list(map(theq, a)) == list(map(theq, b))
  102. # Otherwise, assume debugprint() can handle it
  103. astr = aesara.printing.debugprint(a, file='str')
  104. bstr = aesara.printing.debugprint(b, file='str')
  105. # Check for bug mentioned above
  106. for argname, argval, argstr in [('a', a, astr), ('b', b, bstr)]:
  107. if argstr == '':
  108. raise TypeError(
  109. 'aesara.printing.debugprint(%s) returned empty string '
  110. '(%s is instance of %r)'
  111. % (argname, argname, type(argval))
  112. )
  113. return astr == bstr
  114. def test_example_symbols():
  115. """
  116. Check that the example symbols in this module print to their Aesara
  117. equivalents, as many of the other tests depend on this.
  118. """
  119. assert theq(xt, aesara_code_(x))
  120. assert theq(yt, aesara_code_(y))
  121. assert theq(zt, aesara_code_(z))
  122. assert theq(Xt, aesara_code_(X))
  123. assert theq(Yt, aesara_code_(Y))
  124. assert theq(Zt, aesara_code_(Z))
  125. def test_Symbol():
  126. """ Test printing a Symbol to a aesara variable. """
  127. xx = aesara_code_(x)
  128. assert isinstance(xx, Variable)
  129. assert xx.broadcastable == ()
  130. assert xx.name == x.name
  131. xx2 = aesara_code_(x, broadcastables={x: (False,)})
  132. assert xx2.broadcastable == (False,)
  133. assert xx2.name == x.name
  134. def test_MatrixSymbol():
  135. """ Test printing a MatrixSymbol to a aesara variable. """
  136. XX = aesara_code_(X)
  137. assert isinstance(XX, TensorVariable)
  138. assert XX.broadcastable == (False, False)
  139. @SKIP # TODO - this is currently not checked but should be implemented
  140. def test_MatrixSymbol_wrong_dims():
  141. """ Test MatrixSymbol with invalid broadcastable. """
  142. bcs = [(), (False,), (True,), (True, False), (False, True,), (True, True)]
  143. for bc in bcs:
  144. with raises(ValueError):
  145. aesara_code_(X, broadcastables={X: bc})
  146. def test_AppliedUndef():
  147. """ Test printing AppliedUndef instance, which works similarly to Symbol. """
  148. ftt = aesara_code_(f_t)
  149. assert isinstance(ftt, TensorVariable)
  150. assert ftt.broadcastable == ()
  151. assert ftt.name == 'f_t'
  152. def test_add():
  153. expr = x + y
  154. comp = aesara_code_(expr)
  155. assert comp.owner.op == aesara.tensor.add
  156. def test_trig():
  157. assert theq(aesara_code_(sy.sin(x)), aet.sin(xt))
  158. assert theq(aesara_code_(sy.tan(x)), aet.tan(xt))
  159. def test_many():
  160. """ Test printing a complex expression with multiple symbols. """
  161. expr = sy.exp(x**2 + sy.cos(y)) * sy.log(2*z)
  162. comp = aesara_code_(expr)
  163. expected = aet.exp(xt**2 + aet.cos(yt)) * aet.log(2*zt)
  164. assert theq(comp, expected)
  165. def test_dtype():
  166. """ Test specifying specific data types through the dtype argument. """
  167. for dtype in ['float32', 'float64', 'int8', 'int16', 'int32', 'int64']:
  168. assert aesara_code_(x, dtypes={x: dtype}).type.dtype == dtype
  169. # "floatX" type
  170. assert aesara_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64')
  171. # Type promotion
  172. assert aesara_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32'
  173. assert aesara_code_(x + y, dtypes={x: 'float64', y: 'float32'}).type.dtype == 'float64'
  174. def test_broadcastables():
  175. """ Test the "broadcastables" argument when printing symbol-like objects. """
  176. # No restrictions on shape
  177. for s in [x, f_t]:
  178. for bc in [(), (False,), (True,), (False, False), (True, False)]:
  179. assert aesara_code_(s, broadcastables={s: bc}).broadcastable == bc
  180. # TODO - matrix broadcasting?
  181. def test_broadcasting():
  182. """ Test "broadcastable" attribute after applying element-wise binary op. """
  183. expr = x + y
  184. cases = [
  185. [(), (), ()],
  186. [(False,), (False,), (False,)],
  187. [(True,), (False,), (False,)],
  188. [(False, True), (False, False), (False, False)],
  189. [(True, False), (False, False), (False, False)],
  190. ]
  191. for bc1, bc2, bc3 in cases:
  192. comp = aesara_code_(expr, broadcastables={x: bc1, y: bc2})
  193. assert comp.broadcastable == bc3
  194. def test_MatMul():
  195. expr = X*Y*Z
  196. expr_t = aesara_code_(expr)
  197. assert isinstance(expr_t.owner.op, Dot)
  198. assert theq(expr_t, Xt.dot(Yt).dot(Zt))
  199. def test_Transpose():
  200. assert isinstance(aesara_code_(X.T).owner.op, DimShuffle)
  201. def test_MatAdd():
  202. expr = X+Y+Z
  203. assert isinstance(aesara_code_(expr).owner.op, Elemwise)
  204. def test_Rationals():
  205. assert theq(aesara_code_(sy.Integer(2) / 3), true_divide(2, 3))
  206. assert theq(aesara_code_(S.Half), true_divide(1, 2))
  207. def test_Integers():
  208. assert aesara_code_(sy.Integer(3)) == 3
  209. def test_factorial():
  210. n = sy.Symbol('n')
  211. assert aesara_code_(sy.factorial(n))
  212. def test_Derivative():
  213. with ignore_warnings(UserWarning):
  214. simp = lambda expr: aesara_simplify(fgraph_of(expr))
  215. assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
  216. simp(aesara.grad(aet.sin(xt), xt)))
  217. def test_aesara_function_simple():
  218. """ Test aesara_function() with single output. """
  219. f = aesara_function_([x, y], [x+y])
  220. assert f(2, 3) == 5
  221. def test_aesara_function_multi():
  222. """ Test aesara_function() with multiple outputs. """
  223. f = aesara_function_([x, y], [x+y, x-y])
  224. o1, o2 = f(2, 3)
  225. assert o1 == 5
  226. assert o2 == -1
  227. def test_aesara_function_numpy():
  228. """ Test aesara_function() vs Numpy implementation. """
  229. f = aesara_function_([x, y], [x+y], dim=1,
  230. dtypes={x: 'float64', y: 'float64'})
  231. assert np.linalg.norm(f([1, 2], [3, 4]) - np.asarray([4, 6])) < 1e-9
  232. f = aesara_function_([x, y], [x+y], dtypes={x: 'float64', y: 'float64'},
  233. dim=1)
  234. xx = np.arange(3).astype('float64')
  235. yy = 2*np.arange(3).astype('float64')
  236. assert np.linalg.norm(f(xx, yy) - 3*np.arange(3)) < 1e-9
  237. def test_aesara_function_matrix():
  238. m = sy.Matrix([[x, y], [z, x + y + z]])
  239. expected = np.array([[1.0, 2.0], [3.0, 1.0 + 2.0 + 3.0]])
  240. f = aesara_function_([x, y, z], [m])
  241. np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
  242. f = aesara_function_([x, y, z], [m], scalar=True)
  243. np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
  244. f = aesara_function_([x, y, z], [m, m])
  245. assert isinstance(f(1.0, 2.0, 3.0), type([]))
  246. np.testing.assert_allclose(f(1.0, 2.0, 3.0)[0], expected)
  247. np.testing.assert_allclose(f(1.0, 2.0, 3.0)[1], expected)
  248. def test_dim_handling():
  249. assert dim_handling([x], dim=2) == {x: (False, False)}
  250. assert dim_handling([x, y], dims={x: 1, y: 2}) == {x: (False, True),
  251. y: (False, False)}
  252. assert dim_handling([x], broadcastables={x: (False,)}) == {x: (False,)}
  253. def test_aesara_function_kwargs():
  254. """
  255. Test passing additional kwargs from aesara_function() to aesara.function().
  256. """
  257. import numpy as np
  258. f = aesara_function_([x, y, z], [x+y], dim=1, on_unused_input='ignore',
  259. dtypes={x: 'float64', y: 'float64', z: 'float64'})
  260. assert np.linalg.norm(f([1, 2], [3, 4], [0, 0]) - np.asarray([4, 6])) < 1e-9
  261. f = aesara_function_([x, y, z], [x+y],
  262. dtypes={x: 'float64', y: 'float64', z: 'float64'},
  263. dim=1, on_unused_input='ignore')
  264. xx = np.arange(3).astype('float64')
  265. yy = 2*np.arange(3).astype('float64')
  266. zz = 2*np.arange(3).astype('float64')
  267. assert np.linalg.norm(f(xx, yy, zz) - 3*np.arange(3)) < 1e-9
  268. def test_aesara_function_scalar():
  269. """ Test the "scalar" argument to aesara_function(). """
  270. from aesara.compile.function.types import Function
  271. args = [
  272. ([x, y], [x + y], None, [0]), # Single 0d output
  273. ([X, Y], [X + Y], None, [2]), # Single 2d output
  274. ([x, y], [x + y], {x: 0, y: 1}, [1]), # Single 1d output
  275. ([x, y], [x + y, x - y], None, [0, 0]), # Two 0d outputs
  276. ([x, y, X, Y], [x + y, X + Y], None, [0, 2]), # One 0d output, one 2d
  277. ]
  278. # Create and test functions with and without the scalar setting
  279. for inputs, outputs, in_dims, out_dims in args:
  280. for scalar in [False, True]:
  281. f = aesara_function_(inputs, outputs, dims=in_dims, scalar=scalar)
  282. # Check the aesara_function attribute is set whether wrapped or not
  283. assert isinstance(f.aesara_function, Function)
  284. # Feed in inputs of the appropriate size and get outputs
  285. in_values = [
  286. np.ones([1 if bc else 5 for bc in i.type.broadcastable])
  287. for i in f.aesara_function.input_storage
  288. ]
  289. out_values = f(*in_values)
  290. if not isinstance(out_values, list):
  291. out_values = [out_values]
  292. # Check output types and shapes
  293. assert len(out_dims) == len(out_values)
  294. for d, value in zip(out_dims, out_values):
  295. if scalar and d == 0:
  296. # Should have been converted to a scalar value
  297. assert isinstance(value, np.number)
  298. else:
  299. # Otherwise should be an array
  300. assert isinstance(value, np.ndarray)
  301. assert value.ndim == d
  302. def test_aesara_function_bad_kwarg():
  303. """
  304. Passing an unknown keyword argument to aesara_function() should raise an
  305. exception.
  306. """
  307. raises(Exception, lambda : aesara_function_([x], [x+1], foobar=3))
  308. def test_slice():
  309. assert aesara_code_(slice(1, 2, 3)) == slice(1, 2, 3)
  310. def theq_slice(s1, s2):
  311. for attr in ['start', 'stop', 'step']:
  312. a1 = getattr(s1, attr)
  313. a2 = getattr(s2, attr)
  314. if a1 is None or a2 is None:
  315. if not (a1 is None or a2 is None):
  316. return False
  317. elif not theq(a1, a2):
  318. return False
  319. return True
  320. dtypes = {x: 'int32', y: 'int32'}
  321. assert theq_slice(aesara_code_(slice(x, y), dtypes=dtypes), slice(xt, yt))
  322. assert theq_slice(aesara_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3))
  323. def test_MatrixSlice():
  324. cache = {}
  325. n = sy.Symbol('n', integer=True)
  326. X = sy.MatrixSymbol('X', n, n)
  327. Y = X[1:2:3, 4:5:6]
  328. Yt = aesara_code_(Y, cache=cache)
  329. s = ScalarType('int64')
  330. assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s))
  331. assert Yt.owner.inputs[0] == aesara_code_(X, cache=cache)
  332. # == doesn't work in Aesara like it does in SymPy. You have to use
  333. # equals.
  334. assert all(Yt.owner.inputs[i].data == i for i in range(1, 7))
  335. k = sy.Symbol('k')
  336. aesara_code_(k, dtypes={k: 'int32'})
  337. start, stop, step = 4, k, 2
  338. Y = X[start:stop:step]
  339. Yt = aesara_code_(Y, dtypes={n: 'int32', k: 'int32'})
  340. # assert Yt.owner.op.idx_list[0].stop == kt
  341. def test_BlockMatrix():
  342. n = sy.Symbol('n', integer=True)
  343. A, B, C, D = [sy.MatrixSymbol(name, n, n) for name in 'ABCD']
  344. At, Bt, Ct, Dt = map(aesara_code_, (A, B, C, D))
  345. Block = sy.BlockMatrix([[A, B], [C, D]])
  346. Blockt = aesara_code_(Block)
  347. solutions = [aet.join(0, aet.join(1, At, Bt), aet.join(1, Ct, Dt)),
  348. aet.join(1, aet.join(0, At, Ct), aet.join(0, Bt, Dt))]
  349. assert any(theq(Blockt, solution) for solution in solutions)
  350. @SKIP
  351. def test_BlockMatrix_Inverse_execution():
  352. k, n = 2, 4
  353. dtype = 'float32'
  354. A = sy.MatrixSymbol('A', n, k)
  355. B = sy.MatrixSymbol('B', n, n)
  356. inputs = A, B
  357. output = B.I*A
  358. cutsizes = {A: [(n//2, n//2), (k//2, k//2)],
  359. B: [(n//2, n//2), (n//2, n//2)]}
  360. cutinputs = [sy.blockcut(i, *cutsizes[i]) for i in inputs]
  361. cutoutput = output.subs(dict(zip(inputs, cutinputs)))
  362. dtypes = dict(zip(inputs, [dtype]*len(inputs)))
  363. f = aesara_function_(inputs, [output], dtypes=dtypes, cache={})
  364. fblocked = aesara_function_(inputs, [sy.block_collapse(cutoutput)],
  365. dtypes=dtypes, cache={})
  366. ninputs = [np.random.rand(*x.shape).astype(dtype) for x in inputs]
  367. ninputs = [np.arange(n*k).reshape(A.shape).astype(dtype),
  368. np.eye(n).astype(dtype)]
  369. ninputs[1] += np.ones(B.shape)*1e-5
  370. assert np.allclose(f(*ninputs), fblocked(*ninputs), rtol=1e-5)
  371. def test_DenseMatrix():
  372. from aesara.tensor.basic import Join
  373. t = sy.Symbol('theta')
  374. for MatrixType in [sy.Matrix, sy.ImmutableMatrix]:
  375. X = MatrixType([[sy.cos(t), -sy.sin(t)], [sy.sin(t), sy.cos(t)]])
  376. tX = aesara_code_(X)
  377. assert isinstance(tX, TensorVariable)
  378. assert isinstance(tX.owner.op, Join)
  379. def test_cache_basic():
  380. """ Test single symbol-like objects are cached when printed by themselves. """
  381. # Pairs of objects which should be considered equivalent with respect to caching
  382. pairs = [
  383. (x, sy.Symbol('x')),
  384. (X, sy.MatrixSymbol('X', *X.shape)),
  385. (f_t, sy.Function('f')(sy.Symbol('t'))),
  386. ]
  387. for s1, s2 in pairs:
  388. cache = {}
  389. st = aesara_code_(s1, cache=cache)
  390. # Test hit with same instance
  391. assert aesara_code_(s1, cache=cache) is st
  392. # Test miss with same instance but new cache
  393. assert aesara_code_(s1, cache={}) is not st
  394. # Test hit with different but equivalent instance
  395. assert aesara_code_(s2, cache=cache) is st
  396. def test_global_cache():
  397. """ Test use of the global cache. """
  398. from sympy.printing.aesaracode import global_cache
  399. backup = dict(global_cache)
  400. try:
  401. # Temporarily empty global cache
  402. global_cache.clear()
  403. for s in [x, X, f_t]:
  404. with warns_deprecated_sympy():
  405. st = aesara_code(s)
  406. assert aesara_code(s) is st
  407. finally:
  408. # Restore global cache
  409. global_cache.update(backup)
  410. def test_cache_types_distinct():
  411. """
  412. Test that symbol-like objects of different types (Symbol, MatrixSymbol,
  413. AppliedUndef) are distinguished by the cache even if they have the same
  414. name.
  415. """
  416. symbols = [sy.Symbol('f_t'), sy.MatrixSymbol('f_t', 4, 4), f_t]
  417. cache = {} # Single shared cache
  418. printed = {}
  419. for s in symbols:
  420. st = aesara_code_(s, cache=cache)
  421. assert st not in printed.values()
  422. printed[s] = st
  423. # Check all printed objects are distinct
  424. assert len(set(map(id, printed.values()))) == len(symbols)
  425. # Check retrieving
  426. for s, st in printed.items():
  427. with warns_deprecated_sympy():
  428. assert aesara_code(s, cache=cache) is st
  429. def test_symbols_are_created_once():
  430. """
  431. Test that a symbol is cached and reused when it appears in an expression
  432. more than once.
  433. """
  434. expr = sy.Add(x, x, evaluate=False)
  435. comp = aesara_code_(expr)
  436. assert theq(comp, xt + xt)
  437. assert not theq(comp, xt + aesara_code_(x))
  438. def test_cache_complex():
  439. """
  440. Test caching on a complicated expression with multiple symbols appearing
  441. multiple times.
  442. """
  443. expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y)
  444. symbol_names = {s.name for s in expr.free_symbols}
  445. expr_t = aesara_code_(expr)
  446. # Iterate through variables in the Aesara computational graph that the
  447. # printed expression depends on
  448. seen = set()
  449. for v in aesara.graph.basic.ancestors([expr_t]):
  450. # Owner-less, non-constant variables should be our symbols
  451. if v.owner is None and not isinstance(v, aesara.graph.basic.Constant):
  452. # Check it corresponds to a symbol and appears only once
  453. assert v.name in symbol_names
  454. assert v.name not in seen
  455. seen.add(v.name)
  456. # Check all were present
  457. assert seen == symbol_names
  458. def test_Piecewise():
  459. # A piecewise linear
  460. expr = sy.Piecewise((0, x<0), (x, x<2), (1, True)) # ___/III
  461. result = aesara_code_(expr)
  462. assert result.owner.op == aet.switch
  463. expected = aet.switch(xt<0, 0, aet.switch(xt<2, xt, 1))
  464. assert theq(result, expected)
  465. expr = sy.Piecewise((x, x < 0))
  466. result = aesara_code_(expr)
  467. expected = aet.switch(xt < 0, xt, np.nan)
  468. assert theq(result, expected)
  469. expr = sy.Piecewise((0, sy.And(x>0, x<2)), \
  470. (x, sy.Or(x>2, x<0)))
  471. result = aesara_code_(expr)
  472. expected = aet.switch(aet.and_(xt>0,xt<2), 0, \
  473. aet.switch(aet.or_(xt>2, xt<0), xt, np.nan))
  474. assert theq(result, expected)
  475. def test_Relationals():
  476. assert theq(aesara_code_(sy.Eq(x, y)), aet.eq(xt, yt))
  477. # assert theq(aesara_code_(sy.Ne(x, y)), aet.neq(xt, yt)) # TODO - implement
  478. assert theq(aesara_code_(x > y), xt > yt)
  479. assert theq(aesara_code_(x < y), xt < yt)
  480. assert theq(aesara_code_(x >= y), xt >= yt)
  481. assert theq(aesara_code_(x <= y), xt <= yt)
  482. def test_complexfunctions():
  483. dtypes = {x:'complex128', y:'complex128'}
  484. with warns_deprecated_sympy():
  485. xt, yt = aesara_code(x, dtypes=dtypes), aesara_code(y, dtypes=dtypes)
  486. from sympy.functions.elementary.complexes import conjugate
  487. from aesara.tensor import as_tensor_variable as atv
  488. from aesara.tensor import complex as cplx
  489. with warns_deprecated_sympy():
  490. assert theq(aesara_code(y*conjugate(x), dtypes=dtypes), yt*(xt.conj()))
  491. assert theq(aesara_code((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1)))
  492. def test_constantfunctions():
  493. with warns_deprecated_sympy():
  494. tf = aesara_function([],[1+1j])
  495. assert(tf()==1+1j)