test_aesaracode.py 21 KB

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