test_theanocode.py 21 KB

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