PageRenderTime 47ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/feature_extractors/matlab_feature_extractor_with_dependencies/mlabwrap-1.1/tests/test_mlabwrap.py

https://bitbucket.org/ronw/gordon
Python | 428 lines | 355 code | 16 blank | 57 comment | 19 complexity | 9ce2b87517ffef17a43e3037ae0f63b1 MD5 | raw file
Possible License(s): GPL-3.0, GPL-2.0
  1. ##############################################################################
  2. ################### test_mlabwrap: unittests for mlabwrap ####################
  3. ##############################################################################
  4. ##
  5. ## o authors: Alexander Schmolck, Vivek Rathod
  6. ## o created: 2003-07-00 00:00:00+00:00
  7. import sys, os, re
  8. import gc
  9. from pdb import pm # for debugging test failures
  10. try:
  11. import numpy
  12. from numpy.random import rand, randn
  13. toscalar = lambda a:a.item()
  14. except ImportError:
  15. import Numeric as numpy
  16. from MLab import rand, randn
  17. toscalar = lambda a:a.toscalar()
  18. from tempfile import mktemp
  19. try: # python >= 2.3 has better mktemp
  20. from tempfile import mkstemp as _mkstemp
  21. mktemp = lambda *args,**kwargs: _mkstemp(*args, **kwargs)[1]
  22. except ImportError: pass
  23. degensym_proxy = lambda s, rex=re.compile(r'(PROXY_VAL)\d+'): rex.sub(r'\1',s)
  24. import unittest
  25. TestCase = unittest.TestCase
  26. TestSuite = unittest.TestSuite
  27. try:
  28. import awmstest
  29. TestCase = awmstest.PermeableTestCase2
  30. TestSuite = awmstest.RotatingTestSuite
  31. except ImportError: pass
  32. from awmstools import indexme, without
  33. from mlabwrap import *
  34. BUFSIZE=4096 # must be the same as in mlabraw.cpp
  35. #XXX for testing in running session with existing mlab
  36. ## mlab
  37. ## mlab = MlabWrap()
  38. mlab._dont_proxy['cell'] = True
  39. WHO_AT_STARTUP = mlab.who()
  40. mlab._dont_proxy['cell'] = False
  41. # FIXME should do this differentlya
  42. funnies = without(WHO_AT_STARTUP, ['HOME', 'V', 'WLVERBOSE', 'MLABRAW_ERROR_'])
  43. if funnies:
  44. print >> sys.stderr, "Hmm, got some funny stuff in matlab env: %s" % funnies
  45. #FIXME both below untested
  46. def fitString(s, maxCol=79, newlineReplacement="\\n"):
  47. if newlineReplacement or isinstance(newlineReplacement, basestring):
  48. s = s.replace("\n", newlineReplacement)
  49. if maxCol is not None and len(s) > maxCol:
  50. s = "%s..." % s[:maxCol-3]
  51. return s
  52. class NumericTestCase(TestCase):
  53. """Simple extensio to TestCase to handle array equality tests 'correctly'
  54. (i.e. work around rich comparisons). Since array repr's can also be
  55. very large, the printing of large reprs is controlled by
  56. ``maxReprLength`` (None to print everything) and
  57. ``reprNewlineReplacement`` (None not to replace newlines in the repr).
  58. """
  59. maxReprLength = 30 #
  60. reprNewlineReplacement = "\\n"
  61. def _reallyEqual(self, first, second, testShape=True):
  62. #FIXME should this check for identical argument type, too?
  63. res = first == second
  64. # find out if are dealing with a sized object; looking for a __len__
  65. # attr does *NOT* work, because of #$@-C extension crap
  66. try:
  67. len(res)
  68. except TypeError:
  69. return res
  70. else:
  71. # HACK
  72. if len(first) == len(second) == 0:
  73. return `first` == `second` # deal with empty arrays
  74. res = ((not testShape or numpy.shape(first) == numpy.shape(second)) and
  75. # it is necessary to exclude 0 element arrays, because
  76. # identical zero-element arrays don't compare true (``and True`` normalizes)
  77. (not len(first) and not len(second)
  78. or bool(numpy.alltrue((numpy.ravel(first == second))))))
  79. return res
  80. def _smallRepr(self, *args):
  81. return tuple([fitString(repr(arg), maxCol=self.maxReprLength,
  82. newlineReplacement=self.reprNewlineReplacement)
  83. for arg in args])
  84. def assertEqual(self, first, second, msg=None):
  85. if not self._reallyEqual(first, second):
  86. raise self.failureException, \
  87. (msg or '%s != %s' % self._smallRepr(first, second))
  88. assertEqual = failUnlessEqual = assertEqual
  89. def assertNotEqual(self, first, second, msg=None):
  90. if self._reallyEqual(first, second):
  91. raise self.failureException, \
  92. (msg or '%s == %s' % self._smallRepr(first, second))
  93. assertNotEquals = failIfEqual = assertNotEqual
  94. def assertAlmostEqual(self, first, second, places=7, msg=None):
  95. if not (numpy.shape(first) == numpy.shape(second) and \
  96. self._reallyEqual(numpy.around(second-first, places), 0, testShape=False)):
  97. raise self.failureException, \
  98. (msg or '%s != %s within %s places' % self._smallRepr(first,second,places))
  99. assertAlmostEquals = failUnlessAlmostEqual = assertAlmostEqual
  100. def assertNotAlmostEqual(self, first, second, places=7, msg=None):
  101. if not (numpy.shape(first) == numpy.shape(second) and \
  102. not self._reallyEqual(numpy.around(second-first, places), 0, testShape=False)):
  103. raise self.failureException, \
  104. (msg or '%s == %s within %s places' % self._smallRepr(first,second,places))
  105. failIfAlmostEqual = assertNotAlmostEquals = assertNotAlmostEqual
  106. def _canonicalMShape(a):
  107. """Matlab arrays are rank-less (rank is specified by indexing), so all
  108. arrays w/ trailing 1s in their shape are equivalent. This returns the
  109. canonical form for comparison purposes: no trailing 1s in the shape,
  110. unless the array would otherwise become a scalar or vector.
  111. """
  112. s = list(a.shape)
  113. if len(s) < 2: s.append(1)
  114. while s[2:] and s[-1] == 1: s.pop()
  115. return a.reshape(s)
  116. class mlabwrapTC(NumericTestCase):
  117. ## def assertEqual(self, first, second):
  118. ## res = first == second
  119. ## if len(res):
  120. ## res = numpy.shape(first) == numpy.shape(second) and \
  121. ## bool(numpy.alltrue((numpy.ravel(a1 == a2))))
  122. ## super(TestCase, self).assertEquals(res, True)
  123. def testBasic(self):
  124. """Test basic behavior."""
  125. array = numpy.array
  126. from random import randrange
  127. for isComplex in [False, True]:
  128. for i in range(30):
  129. #flat vector
  130. if i % 3:
  131. nDims = 1
  132. dims = randrange(1, 20)
  133. #2 - 6 dimensions.
  134. else:
  135. nDims = randrange(2, 7)
  136. dims = [randrange(1, 7) for j in range(nDims)]
  137. a = numpy.random.random(dims)
  138. if isComplex: a = a + 1j*numpy.random.random(dims)
  139. a1 = a.copy()
  140. mlab._set('a', a)
  141. #### test simple get ####
  142. self.assertEqual(_canonicalMShape(a), mlab._get('a'))
  143. self.assertEqual(a,a1)
  144. ### test sliced arrays (stride handling test) ###
  145. b = a1.copy()
  146. for i in range(nDims):
  147. z=0
  148. while not z: z = randrange(-3,4)
  149. b = b[::z]
  150. mlab._set('b',b)
  151. self.assertEqual(_canonicalMShape(b),mlab._get('b'))
  152. self.assertEqual(a1,a)
  153. ########## test for aliasing problems ##########
  154. if nDims > 1:
  155. newA = mlab._get('a')
  156. newA -= 1e4
  157. if len(newA):
  158. self.assertNotEqual(newA, mlab._get('a'))
  159. self.assertEqual(a,a1)
  160. mlab.clear('a')
  161. mlab.clear('b')
  162. # the tricky diversity of empty arrays
  163. mlab._set('a', [[]])
  164. self.assertEqual(mlab._get('a'), numpy.zeros((1, 0), 'd'))
  165. mlab._set('a', numpy.zeros((0,0)))
  166. self.assertEqual(mlab._get('a'), numpy.zeros((0, 0), 'd'))
  167. mlab._set('a', [])
  168. self.assertEqual(mlab._get('a'), numpy.zeros((0, 0), 'd'))
  169. # complex empty
  170. mlab._set('a', numpy.zeros((0,0), 'D'))
  171. self.assertEqual(mlab._get('a'), numpy.zeros((0, 0), 'd')) #XXX
  172. # 0d
  173. mlab._set('a', -2)
  174. self.assertEqual(mlab._get('a'), array([ [-2.]]))
  175. mlab._set('a', array(-2))
  176. self.assertEqual(mlab._get('a'), array([ [-2.]]))
  177. mlab.clear('a')
  178. # try basic error handling
  179. self.failUnlessRaises(MlabError, mlab._get, 'dontexist')
  180. self.failUnlessRaises(MlabError,mlab.round)
  181. assert toscalar(mlab.round(1.6)) == 2.0
  182. self.assertEqual(mlab.max([20,10],nout=2), (numpy.array([[20]]), array([[1]])))
  183. self.assertEqual(mlab.max([20,10]), numpy.array([[20]]))
  184. def testDoc(self):
  185. """Test that docstring extraction works OK."""
  186. mlab.who.__doc__.index('WHO lists the variables in the current workspace')
  187. def setUp(self):
  188. """Back up options."""
  189. self.backup = {}
  190. for opt in """\
  191. _array_cast
  192. _autosync_dirs
  193. _flatten_row_vecs
  194. _flatten_col_vecs
  195. _clear_call_args
  196. _session
  197. _proxies
  198. _proxy_count
  199. _mlabraw_can_convert
  200. _dont_proxy""".split():
  201. self.backup[opt] = mlab.__dict__[opt]
  202. mlab.addpath(os.path.dirname(__file__)) # XXX
  203. print "ADDPATHed", os.path.dirname(__file__)
  204. def tearDown(self):
  205. """Reset options."""
  206. mlab.__dict__.update(self.backup)
  207. def testCallArgs(self):
  208. mlab._dont_proxy['cell'] = True
  209. try:
  210. mlab._clear_call_args = False
  211. mlab.sin(1.23)
  212. assert mlab._get('arg0__', True) == 1.23
  213. mlab._clear_call_args = True
  214. mlab.sin(1.23)
  215. assert not 'arg0__' in mlab.who()
  216. finally:
  217. mlab._clear_call_args = True
  218. mlab._dont_proxy['cell'] = False
  219. def testXXXSubtler(self):
  220. """test more subtle stuff. This must come last, hence the XXX"""
  221. import os, cPickle
  222. array = numpy.array
  223. # simple strings:
  224. assert (mlab._do("''"), mlab._do("'foobar'")) == ('', 'foobar')
  225. self.assertEqual(mlab.sort(1), numpy.array([[1.]]))
  226. self.assertEqual(mlab.sort([3,1,2]), numpy.array([[1.], [2.], [3.]]))
  227. self.assertEqual(mlab.sort(numpy.array([3,1,2])), numpy.array([[1.], [2.], [3.]]))
  228. sct = mlab._do("struct('type',{'big','little'},'color','red','x',{3 4})")
  229. bct = mlab._do("struct('type',{'BIG','little'},'color','red')")
  230. self.assertEqual(sct[1].x, numpy.array([[4]]))
  231. self.assertEqual(sct[0].x, numpy.array([[3]]))
  232. #FIXME sct[:].x wouldn't work, but currently I'm not sure that's my fault
  233. sct[1].x = 'New Value'
  234. assert sct[1].x == 'New Value'
  235. assert bct[0].type == 'BIG' and sct[0].type == 'big'
  236. mlab._set('foo', 1)
  237. assert mlab._get('foo') == numpy.array([1.])
  238. assert (mlab._do("{'A', 'b', {3,4, {5,6}}}") !=
  239. ['A', 'b', [array([[ 3.]]), array([[ 4.]]),
  240. [array([[ 5.]]), array([[ 6.]])]]])
  241. mlab._dont_proxy['cell'] = True
  242. self.assertEquals(mlab._do("{'a', 'b', {3,4, {5,6}}}"),
  243. ['a', 'b', [array([ 3.]), array([ 4.]),
  244. [array([ 5.]), array([ 6.])]]])
  245. mlab._dont_proxy['cell'] = False
  246. mlab.clear('foo')
  247. self.assertRaises(MlabError, mlab._get, 'foo')
  248. # XXX: note to self: ``format compact`` in startup.m will cause this
  249. # test to fail, but should otherwise be harmless.
  250. self.assertEquals(degensym_proxy(repr(sct)),
  251. "<MlabObjectProxy of matlab-class: 'struct'; "
  252. "internal name: 'PROXY_VAL__'; has parent: no>\n"
  253. "1x2 struct array with fields:\n"
  254. " type\n color\n x\n\n")
  255. #FIXME: add tests for assigning and nesting proxies
  256. ## ensure proxies work OK as arguments
  257. self.assertEqual(mlab.size(sct), array([[1., 2.]]))
  258. self.assertEqual(mlab.size(sct, 1), array([[1]]))
  259. # test that exceptions on calls with proxy arguments don't result in
  260. # trouble
  261. self.assertRaises(MlabError, mlab.svd, sct)
  262. self.assertEqual(mlab.size(sct, [2]), array([[2]]))
  263. mlab._dont_proxy['cell'] = True
  264. gc.collect()
  265. assert map(degensym_proxy,without(mlab.who(), WHO_AT_STARTUP)) == (
  266. ['PROXY_VAL__', 'PROXY_VAL__'])
  267. # test pickling
  268. pickleFilename = mktemp()
  269. f = open(pickleFilename, 'wb')
  270. try:
  271. cPickle.dump({'sct': sct, 'bct': bct},f,1)
  272. f.close()
  273. f = open(pickleFilename, 'rb')
  274. namespace = cPickle.load(f)
  275. f.close()
  276. finally:
  277. os.remove(pickleFilename)
  278. gc.collect()
  279. assert len(mlab._proxies) == 4, "%d proxies!" % len(mlab._proxies)
  280. assert namespace['sct'][1].x == 'New Value'
  281. namespace['sct'][1].x = 'Even Newer Value'
  282. assert namespace['sct'][1].x == 'Even Newer Value'
  283. assert sct[1].x == 'New Value'
  284. del sct
  285. del bct
  286. del namespace['sct']
  287. del namespace['bct']
  288. mlab._set('bar', '1234')
  289. x = []
  290. mlab._do("disp 'hallo'" ,nout=0, handle_out=x.append)
  291. assert x[0] == 'hallo\n'
  292. mlab._dont_proxy['cell'] = False
  293. self.assertRaises(ValueError, getattr, mlab, "buggy('ipython lookup')")
  294. def testSparseArrays(self):
  295. """Make sure sparse arrays work."""
  296. s = mlab.sparse(numpy.zeros([100,100]))
  297. self.assertEqual(mlab.full(s), numpy.zeros([100,100]))
  298. # FIXME: add these once we have multi-dimensional proxying
  299. ## s = mlab.sparse(numpy.zeros([100,100]))
  300. ## self.assertEqual(s[0,0], 0.0)
  301. ## self.assertEqual(s[99,99], 0.0)
  302. ## t = mlab.sparse(numpy.array([[1.,2,3],[0,0,0],[4,5,6]]))
  303. ## self.assertEqual(t[0,0], 1.0)
  304. ## self.assertEqual(t[1,1], 0)
  305. ## self.assertEqual(t[2,2], 6)
  306. def testProxyIndexing(self):
  307. "indexing and co: time for some advanced proxied __getitem__ and __setitem__ etc.."
  308. p=mlab.proxyTest(mlab.struct('a', 1, 'b', '2'))
  309. p.c = [[4,5]]
  310. assert p.a == 1.0
  311. assert p.b == '2'
  312. assert list(p.c.flat) == [4,5]
  313. # test all combinations of 1D indexing
  314. sv = mlab.proxyTest(range(4))
  315. assert sv[0] == 0
  316. sv[0] = -33
  317. assert sv[0] == -33
  318. # test curly indexing; the proxyTest class in matlab arbitrarily uses
  319. # string conversion on ``{}`` indexing to have something to distinguish
  320. # it from "normal" ``()`` indexing
  321. sv._[0] = '0'
  322. assert sv._[0] == '0' == str(int(toscalar(sv[0])))
  323. assert sv["some'string\nwith\\funny\tstuff"] == (
  324. "you ()-indexed with the string <<some'string\nwith\\funny\tstuff>>")
  325. # FIXME this is something to potentially add, but that also raises issues
  326. ## assert numpy.ndim(sv) == 2 # FIXME change that to 1?
  327. ## assert numpy.shape(sv[:]) == (4,1) # FIXME change that to 1?
  328. assert list(sv[:].flat) == range(4)
  329. # more complicated "open-ended" slices aren't supported (yet)
  330. self.assertEqual(sv[0:], sv[:])
  331. self.assertEqual(sv[:-1], sv[0:-1])
  332. self.assertEqual(sv[0:-1:1], sv[:-1])
  333. self.assertEqual(sv[-4:], sv[:])
  334. self.assertEqual(sv[-4:-3], sv[0:1])
  335. for b in [None] + range(-4,4):
  336. for e in [None] + range(-4,4):
  337. for s in [None,1]:
  338. assert list(sv[b:e:s].flat) == range(4)[b:e:s], (
  339. "sv[b:e:s]: %s (b,e,s): %s" % (sv[b:e:s], (b,e,s)))
  340. sv[:-1] = -numpy.arange(3)
  341. assert list(sv[:].flat) == [-x for x in range(3)] + [3]
  342. sv[:] = numpy.arange(4)
  343. assert list(sv[:].flat) == range(4)
  344. sv[-2:] = numpy.arange(2)+10
  345. assert list(sv[:].flat) == [0,1,10,11]
  346. # FIXME math ops aren't yet implemented
  347. # sv *= 10
  348. # sv[1:3] *= 10 # FIXME
  349. # sv + 3
  350. # FIXME multi-D stuff isn't either
  351. ## sm = mlab.proxyTest(arange(6).reshape(3,2))
  352. ## assert sm.ndim == 2
  353. ## assert sm.shape == (3,2)
  354. ## assert len(sm) == 3
  355. ## assert len(sm).T
  356. ## p.sv = sv
  357. ## assert p.sv is sv
  358. ## assert p.sv[:]
  359. def testRawMlabraw(self):
  360. """A few explicit tests for mlabraw"""
  361. import mlabraw
  362. #print "test mlabraw"
  363. self.assertRaises(TypeError, mlabraw.put, 33, 'a',1)
  364. self.assertRaises(TypeError, mlabraw.get, object(), 'a')
  365. self.assertRaises(TypeError, mlabraw.eval, object(), '1')
  366. # -100 is picked kinda arbitrarily to account for internal "overhead";
  367. # I don't want to hardcode the exact value; users can assume 1000
  368. # chars is safe
  369. mlabraw.eval(mlab._session, '1'*(BUFSIZE-100))
  370. assert numpy.inf == mlabraw.get(mlab._session, 'ans');
  371. # test for buffer overflow detection
  372. self.assertRaises(Exception, mlabraw.eval, mlab._session, '1'*BUFSIZE)
  373. self.assertEqual(mlabraw.eval(mlab._session, r"fprintf('1\n')"),'1\n')
  374. try:
  375. self.assertEqual(mlabraw.eval(mlab._session, r"1"),'')
  376. finally:
  377. mlabraw.eval(mlab._session,'clear ans')
  378. #print "tested mlabraw"
  379. def testOrder(self):
  380. """Testing order flags cause no problems"""
  381. try: import numpy
  382. except ImportError: return
  383. fa=numpy.array([[1,2,3],[4,5,6]],order='F')
  384. self.assertEqual(mlab.conj(fa),fa)
  385. self.assertEqual([[2]],mlab.subsref(fa, mlab.struct('type', '()', 'subs',mlab._do('{{1,2}}'))))
  386. suite = TestSuite(map(unittest.makeSuite,
  387. (mlabwrapTC,
  388. )))
  389. unittest.TextTestRunner(verbosity=2).run(suite)
  390. #FIXME strangely enough we can't test this in the function!
  391. gc.collect()
  392. mlab._dont_proxy['cell'] = True
  393. # XXX got no idea where HOME comes from, not there under win
  394. assert without(mlab.who(), WHO_AT_STARTUP) == ['bar'], "who is:%r" % mlab.who()
  395. mlab.clear()
  396. assert without(mlab.who(), ['MLABRAW_ERROR_']) == [] == mlab._do('{}'),(
  397. "who is:%r" % mlab.who())
  398. mlab._dont_proxy['cell'] = False