utils.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499
  1. """
  2. Utility function to facilitate testing.
  3. """
  4. from __future__ import division, absolute_import, print_function
  5. import os
  6. import sys
  7. import platform
  8. import re
  9. import gc
  10. import operator
  11. import warnings
  12. from functools import partial, wraps
  13. import shutil
  14. import contextlib
  15. from tempfile import mkdtemp, mkstemp
  16. from unittest.case import SkipTest
  17. from warnings import WarningMessage
  18. import pprint
  19. from numpy.core import(
  20. intp, float32, empty, arange, array_repr, ndarray, isnat, array)
  21. import numpy.__config__
  22. if sys.version_info[0] >= 3:
  23. from io import StringIO
  24. else:
  25. from StringIO import StringIO
  26. __all__ = [
  27. 'assert_equal', 'assert_almost_equal', 'assert_approx_equal',
  28. 'assert_array_equal', 'assert_array_less', 'assert_string_equal',
  29. 'assert_array_almost_equal', 'assert_raises', 'build_err_msg',
  30. 'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal',
  31. 'raises', 'rundocs', 'runstring', 'verbose', 'measure',
  32. 'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex',
  33. 'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings',
  34. 'assert_allclose', 'IgnoreException', 'clear_and_catch_warnings',
  35. 'SkipTest', 'KnownFailureException', 'temppath', 'tempdir', 'IS_PYPY',
  36. 'HAS_REFCOUNT', 'suppress_warnings', 'assert_array_compare',
  37. '_assert_valid_refcount', '_gen_alignment_data', 'assert_no_gc_cycles',
  38. 'break_cycles', 'HAS_LAPACK64'
  39. ]
  40. class KnownFailureException(Exception):
  41. '''Raise this exception to mark a test as a known failing test.'''
  42. pass
  43. KnownFailureTest = KnownFailureException # backwards compat
  44. verbose = 0
  45. IS_PYPY = platform.python_implementation() == 'PyPy'
  46. HAS_REFCOUNT = getattr(sys, 'getrefcount', None) is not None
  47. HAS_LAPACK64 = hasattr(numpy.__config__, 'lapack_ilp64_opt_info')
  48. def import_nose():
  49. """ Import nose only when needed.
  50. """
  51. nose_is_good = True
  52. minimum_nose_version = (1, 0, 0)
  53. try:
  54. import nose
  55. except ImportError:
  56. nose_is_good = False
  57. else:
  58. if nose.__versioninfo__ < minimum_nose_version:
  59. nose_is_good = False
  60. if not nose_is_good:
  61. msg = ('Need nose >= %d.%d.%d for tests - see '
  62. 'https://nose.readthedocs.io' %
  63. minimum_nose_version)
  64. raise ImportError(msg)
  65. return nose
  66. def assert_(val, msg=''):
  67. """
  68. Assert that works in release mode.
  69. Accepts callable msg to allow deferring evaluation until failure.
  70. The Python built-in ``assert`` does not work when executing code in
  71. optimized mode (the ``-O`` flag) - no byte-code is generated for it.
  72. For documentation on usage, refer to the Python documentation.
  73. """
  74. __tracebackhide__ = True # Hide traceback for py.test
  75. if not val:
  76. try:
  77. smsg = msg()
  78. except TypeError:
  79. smsg = msg
  80. raise AssertionError(smsg)
  81. def gisnan(x):
  82. """like isnan, but always raise an error if type not supported instead of
  83. returning a TypeError object.
  84. Notes
  85. -----
  86. isnan and other ufunc sometimes return a NotImplementedType object instead
  87. of raising any exception. This function is a wrapper to make sure an
  88. exception is always raised.
  89. This should be removed once this problem is solved at the Ufunc level."""
  90. from numpy.core import isnan
  91. st = isnan(x)
  92. if isinstance(st, type(NotImplemented)):
  93. raise TypeError("isnan not supported for this type")
  94. return st
  95. def gisfinite(x):
  96. """like isfinite, but always raise an error if type not supported instead of
  97. returning a TypeError object.
  98. Notes
  99. -----
  100. isfinite and other ufunc sometimes return a NotImplementedType object instead
  101. of raising any exception. This function is a wrapper to make sure an
  102. exception is always raised.
  103. This should be removed once this problem is solved at the Ufunc level."""
  104. from numpy.core import isfinite, errstate
  105. with errstate(invalid='ignore'):
  106. st = isfinite(x)
  107. if isinstance(st, type(NotImplemented)):
  108. raise TypeError("isfinite not supported for this type")
  109. return st
  110. def gisinf(x):
  111. """like isinf, but always raise an error if type not supported instead of
  112. returning a TypeError object.
  113. Notes
  114. -----
  115. isinf and other ufunc sometimes return a NotImplementedType object instead
  116. of raising any exception. This function is a wrapper to make sure an
  117. exception is always raised.
  118. This should be removed once this problem is solved at the Ufunc level."""
  119. from numpy.core import isinf, errstate
  120. with errstate(invalid='ignore'):
  121. st = isinf(x)
  122. if isinstance(st, type(NotImplemented)):
  123. raise TypeError("isinf not supported for this type")
  124. return st
  125. if os.name == 'nt':
  126. # Code "stolen" from enthought/debug/memusage.py
  127. def GetPerformanceAttributes(object, counter, instance=None,
  128. inum=-1, format=None, machine=None):
  129. # NOTE: Many counters require 2 samples to give accurate results,
  130. # including "% Processor Time" (as by definition, at any instant, a
  131. # thread's CPU usage is either 0 or 100). To read counters like this,
  132. # you should copy this function, but keep the counter open, and call
  133. # CollectQueryData() each time you need to know.
  134. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link)
  135. # My older explanation for this was that the "AddCounter" process forced
  136. # the CPU to 100%, but the above makes more sense :)
  137. import win32pdh
  138. if format is None:
  139. format = win32pdh.PDH_FMT_LONG
  140. path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter))
  141. hq = win32pdh.OpenQuery()
  142. try:
  143. hc = win32pdh.AddCounter(hq, path)
  144. try:
  145. win32pdh.CollectQueryData(hq)
  146. type, val = win32pdh.GetFormattedCounterValue(hc, format)
  147. return val
  148. finally:
  149. win32pdh.RemoveCounter(hc)
  150. finally:
  151. win32pdh.CloseQuery(hq)
  152. def memusage(processName="python", instance=0):
  153. # from win32pdhutil, part of the win32all package
  154. import win32pdh
  155. return GetPerformanceAttributes("Process", "Virtual Bytes",
  156. processName, instance,
  157. win32pdh.PDH_FMT_LONG, None)
  158. elif sys.platform[:5] == 'linux':
  159. def memusage(_proc_pid_stat='/proc/%s/stat' % (os.getpid())):
  160. """
  161. Return virtual memory size in bytes of the running python.
  162. """
  163. try:
  164. f = open(_proc_pid_stat, 'r')
  165. l = f.readline().split(' ')
  166. f.close()
  167. return int(l[22])
  168. except Exception:
  169. return
  170. else:
  171. def memusage():
  172. """
  173. Return memory usage of running python. [Not implemented]
  174. """
  175. raise NotImplementedError
  176. if sys.platform[:5] == 'linux':
  177. def jiffies(_proc_pid_stat='/proc/%s/stat' % (os.getpid()),
  178. _load_time=[]):
  179. """
  180. Return number of jiffies elapsed.
  181. Return number of jiffies (1/100ths of a second) that this
  182. process has been scheduled in user mode. See man 5 proc.
  183. """
  184. import time
  185. if not _load_time:
  186. _load_time.append(time.time())
  187. try:
  188. f = open(_proc_pid_stat, 'r')
  189. l = f.readline().split(' ')
  190. f.close()
  191. return int(l[13])
  192. except Exception:
  193. return int(100*(time.time()-_load_time[0]))
  194. else:
  195. # os.getpid is not in all platforms available.
  196. # Using time is safe but inaccurate, especially when process
  197. # was suspended or sleeping.
  198. def jiffies(_load_time=[]):
  199. """
  200. Return number of jiffies elapsed.
  201. Return number of jiffies (1/100ths of a second) that this
  202. process has been scheduled in user mode. See man 5 proc.
  203. """
  204. import time
  205. if not _load_time:
  206. _load_time.append(time.time())
  207. return int(100*(time.time()-_load_time[0]))
  208. def build_err_msg(arrays, err_msg, header='Items are not equal:',
  209. verbose=True, names=('ACTUAL', 'DESIRED'), precision=8):
  210. msg = ['\n' + header]
  211. if err_msg:
  212. if err_msg.find('\n') == -1 and len(err_msg) < 79-len(header):
  213. msg = [msg[0] + ' ' + err_msg]
  214. else:
  215. msg.append(err_msg)
  216. if verbose:
  217. for i, a in enumerate(arrays):
  218. if isinstance(a, ndarray):
  219. # precision argument is only needed if the objects are ndarrays
  220. r_func = partial(array_repr, precision=precision)
  221. else:
  222. r_func = repr
  223. try:
  224. r = r_func(a)
  225. except Exception as exc:
  226. r = '[repr failed for <{}>: {}]'.format(type(a).__name__, exc)
  227. if r.count('\n') > 3:
  228. r = '\n'.join(r.splitlines()[:3])
  229. r += '...'
  230. msg.append(' %s: %s' % (names[i], r))
  231. return '\n'.join(msg)
  232. def assert_equal(actual, desired, err_msg='', verbose=True):
  233. """
  234. Raises an AssertionError if two objects are not equal.
  235. Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
  236. check that all elements of these objects are equal. An exception is raised
  237. at the first conflicting values.
  238. When one of `actual` and `desired` is a scalar and the other is array_like,
  239. the function checks that each element of the array_like object is equal to
  240. the scalar.
  241. This function handles NaN comparisons as if NaN was a "normal" number.
  242. That is, no assertion is raised if both objects have NaNs in the same
  243. positions. This is in contrast to the IEEE standard on NaNs, which says
  244. that NaN compared to anything must return False.
  245. Parameters
  246. ----------
  247. actual : array_like
  248. The object to check.
  249. desired : array_like
  250. The expected object.
  251. err_msg : str, optional
  252. The error message to be printed in case of failure.
  253. verbose : bool, optional
  254. If True, the conflicting values are appended to the error message.
  255. Raises
  256. ------
  257. AssertionError
  258. If actual and desired are not equal.
  259. Examples
  260. --------
  261. >>> np.testing.assert_equal([4,5], [4,6])
  262. Traceback (most recent call last):
  263. ...
  264. AssertionError:
  265. Items are not equal:
  266. item=1
  267. ACTUAL: 5
  268. DESIRED: 6
  269. The following comparison does not raise an exception. There are NaNs
  270. in the inputs, but they are in the same positions.
  271. >>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
  272. """
  273. __tracebackhide__ = True # Hide traceback for py.test
  274. if isinstance(desired, dict):
  275. if not isinstance(actual, dict):
  276. raise AssertionError(repr(type(actual)))
  277. assert_equal(len(actual), len(desired), err_msg, verbose)
  278. for k, i in desired.items():
  279. if k not in actual:
  280. raise AssertionError(repr(k))
  281. assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg), verbose)
  282. return
  283. if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
  284. assert_equal(len(actual), len(desired), err_msg, verbose)
  285. for k in range(len(desired)):
  286. assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg), verbose)
  287. return
  288. from numpy.core import ndarray, isscalar, signbit
  289. from numpy.lib import iscomplexobj, real, imag
  290. if isinstance(actual, ndarray) or isinstance(desired, ndarray):
  291. return assert_array_equal(actual, desired, err_msg, verbose)
  292. msg = build_err_msg([actual, desired], err_msg, verbose=verbose)
  293. # Handle complex numbers: separate into real/imag to handle
  294. # nan/inf/negative zero correctly
  295. # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
  296. try:
  297. usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
  298. except (ValueError, TypeError):
  299. usecomplex = False
  300. if usecomplex:
  301. if iscomplexobj(actual):
  302. actualr = real(actual)
  303. actuali = imag(actual)
  304. else:
  305. actualr = actual
  306. actuali = 0
  307. if iscomplexobj(desired):
  308. desiredr = real(desired)
  309. desiredi = imag(desired)
  310. else:
  311. desiredr = desired
  312. desiredi = 0
  313. try:
  314. assert_equal(actualr, desiredr)
  315. assert_equal(actuali, desiredi)
  316. except AssertionError:
  317. raise AssertionError(msg)
  318. # isscalar test to check cases such as [np.nan] != np.nan
  319. if isscalar(desired) != isscalar(actual):
  320. raise AssertionError(msg)
  321. try:
  322. isdesnat = isnat(desired)
  323. isactnat = isnat(actual)
  324. dtypes_match = array(desired).dtype.type == array(actual).dtype.type
  325. if isdesnat and isactnat:
  326. # If both are NaT (and have the same dtype -- datetime or
  327. # timedelta) they are considered equal.
  328. if dtypes_match:
  329. return
  330. else:
  331. raise AssertionError(msg)
  332. except (TypeError, ValueError, NotImplementedError):
  333. pass
  334. # Inf/nan/negative zero handling
  335. try:
  336. isdesnan = gisnan(desired)
  337. isactnan = gisnan(actual)
  338. if isdesnan and isactnan:
  339. return # both nan, so equal
  340. # handle signed zero specially for floats
  341. array_actual = array(actual)
  342. array_desired = array(desired)
  343. if (array_actual.dtype.char in 'Mm' or
  344. array_desired.dtype.char in 'Mm'):
  345. # version 1.18
  346. # until this version, gisnan failed for datetime64 and timedelta64.
  347. # Now it succeeds but comparison to scalar with a different type
  348. # emits a DeprecationWarning.
  349. # Avoid that by skipping the next check
  350. raise NotImplementedError('cannot compare to a scalar '
  351. 'with a different type')
  352. if desired == 0 and actual == 0:
  353. if not signbit(desired) == signbit(actual):
  354. raise AssertionError(msg)
  355. except (TypeError, ValueError, NotImplementedError):
  356. pass
  357. try:
  358. # Explicitly use __eq__ for comparison, gh-2552
  359. if not (desired == actual):
  360. raise AssertionError(msg)
  361. except (DeprecationWarning, FutureWarning) as e:
  362. # this handles the case when the two types are not even comparable
  363. if 'elementwise == comparison' in e.args[0]:
  364. raise AssertionError(msg)
  365. else:
  366. raise
  367. def print_assert_equal(test_string, actual, desired):
  368. """
  369. Test if two objects are equal, and print an error message if test fails.
  370. The test is performed with ``actual == desired``.
  371. Parameters
  372. ----------
  373. test_string : str
  374. The message supplied to AssertionError.
  375. actual : object
  376. The object to test for equality against `desired`.
  377. desired : object
  378. The expected result.
  379. Examples
  380. --------
  381. >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1])
  382. >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])
  383. Traceback (most recent call last):
  384. ...
  385. AssertionError: Test XYZ of func xyz failed
  386. ACTUAL:
  387. [0, 1]
  388. DESIRED:
  389. [0, 2]
  390. """
  391. __tracebackhide__ = True # Hide traceback for py.test
  392. import pprint
  393. if not (actual == desired):
  394. msg = StringIO()
  395. msg.write(test_string)
  396. msg.write(' failed\nACTUAL: \n')
  397. pprint.pprint(actual, msg)
  398. msg.write('DESIRED: \n')
  399. pprint.pprint(desired, msg)
  400. raise AssertionError(msg.getvalue())
  401. def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
  402. """
  403. Raises an AssertionError if two items are not equal up to desired
  404. precision.
  405. .. note:: It is recommended to use one of `assert_allclose`,
  406. `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
  407. instead of this function for more consistent floating point
  408. comparisons.
  409. The test verifies that the elements of ``actual`` and ``desired`` satisfy.
  410. ``abs(desired-actual) < 1.5 * 10**(-decimal)``
  411. That is a looser test than originally documented, but agrees with what the
  412. actual implementation in `assert_array_almost_equal` did up to rounding
  413. vagaries. An exception is raised at conflicting values. For ndarrays this
  414. delegates to assert_array_almost_equal
  415. Parameters
  416. ----------
  417. actual : array_like
  418. The object to check.
  419. desired : array_like
  420. The expected object.
  421. decimal : int, optional
  422. Desired precision, default is 7.
  423. err_msg : str, optional
  424. The error message to be printed in case of failure.
  425. verbose : bool, optional
  426. If True, the conflicting values are appended to the error message.
  427. Raises
  428. ------
  429. AssertionError
  430. If actual and desired are not equal up to specified precision.
  431. See Also
  432. --------
  433. assert_allclose: Compare two array_like objects for equality with desired
  434. relative and/or absolute precision.
  435. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  436. Examples
  437. --------
  438. >>> import numpy.testing as npt
  439. >>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
  440. >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
  441. Traceback (most recent call last):
  442. ...
  443. AssertionError:
  444. Arrays are not almost equal to 10 decimals
  445. ACTUAL: 2.3333333333333
  446. DESIRED: 2.33333334
  447. >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
  448. ... np.array([1.0,2.33333334]), decimal=9)
  449. Traceback (most recent call last):
  450. ...
  451. AssertionError:
  452. Arrays are not almost equal to 9 decimals
  453. Mismatch: 50%
  454. Max absolute difference: 6.66669964e-09
  455. Max relative difference: 2.85715698e-09
  456. x: array([1. , 2.333333333])
  457. y: array([1. , 2.33333334])
  458. """
  459. __tracebackhide__ = True # Hide traceback for py.test
  460. from numpy.core import ndarray
  461. from numpy.lib import iscomplexobj, real, imag
  462. # Handle complex numbers: separate into real/imag to handle
  463. # nan/inf/negative zero correctly
  464. # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
  465. try:
  466. usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
  467. except ValueError:
  468. usecomplex = False
  469. def _build_err_msg():
  470. header = ('Arrays are not almost equal to %d decimals' % decimal)
  471. return build_err_msg([actual, desired], err_msg, verbose=verbose,
  472. header=header)
  473. if usecomplex:
  474. if iscomplexobj(actual):
  475. actualr = real(actual)
  476. actuali = imag(actual)
  477. else:
  478. actualr = actual
  479. actuali = 0
  480. if iscomplexobj(desired):
  481. desiredr = real(desired)
  482. desiredi = imag(desired)
  483. else:
  484. desiredr = desired
  485. desiredi = 0
  486. try:
  487. assert_almost_equal(actualr, desiredr, decimal=decimal)
  488. assert_almost_equal(actuali, desiredi, decimal=decimal)
  489. except AssertionError:
  490. raise AssertionError(_build_err_msg())
  491. if isinstance(actual, (ndarray, tuple, list)) \
  492. or isinstance(desired, (ndarray, tuple, list)):
  493. return assert_array_almost_equal(actual, desired, decimal, err_msg)
  494. try:
  495. # If one of desired/actual is not finite, handle it specially here:
  496. # check that both are nan if any is a nan, and test for equality
  497. # otherwise
  498. if not (gisfinite(desired) and gisfinite(actual)):
  499. if gisnan(desired) or gisnan(actual):
  500. if not (gisnan(desired) and gisnan(actual)):
  501. raise AssertionError(_build_err_msg())
  502. else:
  503. if not desired == actual:
  504. raise AssertionError(_build_err_msg())
  505. return
  506. except (NotImplementedError, TypeError):
  507. pass
  508. if abs(desired - actual) >= 1.5 * 10.0**(-decimal):
  509. raise AssertionError(_build_err_msg())
  510. def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
  511. """
  512. Raises an AssertionError if two items are not equal up to significant
  513. digits.
  514. .. note:: It is recommended to use one of `assert_allclose`,
  515. `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
  516. instead of this function for more consistent floating point
  517. comparisons.
  518. Given two numbers, check that they are approximately equal.
  519. Approximately equal is defined as the number of significant digits
  520. that agree.
  521. Parameters
  522. ----------
  523. actual : scalar
  524. The object to check.
  525. desired : scalar
  526. The expected object.
  527. significant : int, optional
  528. Desired precision, default is 7.
  529. err_msg : str, optional
  530. The error message to be printed in case of failure.
  531. verbose : bool, optional
  532. If True, the conflicting values are appended to the error message.
  533. Raises
  534. ------
  535. AssertionError
  536. If actual and desired are not equal up to specified precision.
  537. See Also
  538. --------
  539. assert_allclose: Compare two array_like objects for equality with desired
  540. relative and/or absolute precision.
  541. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  542. Examples
  543. --------
  544. >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
  545. >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
  546. ... significant=8)
  547. >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
  548. ... significant=8)
  549. Traceback (most recent call last):
  550. ...
  551. AssertionError:
  552. Items are not equal to 8 significant digits:
  553. ACTUAL: 1.234567e-21
  554. DESIRED: 1.2345672e-21
  555. the evaluated condition that raises the exception is
  556. >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
  557. True
  558. """
  559. __tracebackhide__ = True # Hide traceback for py.test
  560. import numpy as np
  561. (actual, desired) = map(float, (actual, desired))
  562. if desired == actual:
  563. return
  564. # Normalized the numbers to be in range (-10.0,10.0)
  565. # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
  566. with np.errstate(invalid='ignore'):
  567. scale = 0.5*(np.abs(desired) + np.abs(actual))
  568. scale = np.power(10, np.floor(np.log10(scale)))
  569. try:
  570. sc_desired = desired/scale
  571. except ZeroDivisionError:
  572. sc_desired = 0.0
  573. try:
  574. sc_actual = actual/scale
  575. except ZeroDivisionError:
  576. sc_actual = 0.0
  577. msg = build_err_msg(
  578. [actual, desired], err_msg,
  579. header='Items are not equal to %d significant digits:' % significant,
  580. verbose=verbose)
  581. try:
  582. # If one of desired/actual is not finite, handle it specially here:
  583. # check that both are nan if any is a nan, and test for equality
  584. # otherwise
  585. if not (gisfinite(desired) and gisfinite(actual)):
  586. if gisnan(desired) or gisnan(actual):
  587. if not (gisnan(desired) and gisnan(actual)):
  588. raise AssertionError(msg)
  589. else:
  590. if not desired == actual:
  591. raise AssertionError(msg)
  592. return
  593. except (TypeError, NotImplementedError):
  594. pass
  595. if np.abs(sc_desired - sc_actual) >= np.power(10., -(significant-1)):
  596. raise AssertionError(msg)
  597. def assert_array_compare(comparison, x, y, err_msg='', verbose=True,
  598. header='', precision=6, equal_nan=True,
  599. equal_inf=True):
  600. __tracebackhide__ = True # Hide traceback for py.test
  601. from numpy.core import array, array2string, isnan, inf, bool_, errstate, all, max, object_
  602. x = array(x, copy=False, subok=True)
  603. y = array(y, copy=False, subok=True)
  604. # original array for output formatting
  605. ox, oy = x, y
  606. def isnumber(x):
  607. return x.dtype.char in '?bhilqpBHILQPefdgFDG'
  608. def istime(x):
  609. return x.dtype.char in "Mm"
  610. def func_assert_same_pos(x, y, func=isnan, hasval='nan'):
  611. """Handling nan/inf.
  612. Combine results of running func on x and y, checking that they are True
  613. at the same locations.
  614. """
  615. x_id = func(x)
  616. y_id = func(y)
  617. # We include work-arounds here to handle three types of slightly
  618. # pathological ndarray subclasses:
  619. # (1) all() on `masked` array scalars can return masked arrays, so we
  620. # use != True
  621. # (2) __eq__ on some ndarray subclasses returns Python booleans
  622. # instead of element-wise comparisons, so we cast to bool_() and
  623. # use isinstance(..., bool) checks
  624. # (3) subclasses with bare-bones __array_function__ implementations may
  625. # not implement np.all(), so favor using the .all() method
  626. # We are not committed to supporting such subclasses, but it's nice to
  627. # support them if possible.
  628. if bool_(x_id == y_id).all() != True:
  629. msg = build_err_msg([x, y],
  630. err_msg + '\nx and y %s location mismatch:'
  631. % (hasval), verbose=verbose, header=header,
  632. names=('x', 'y'), precision=precision)
  633. raise AssertionError(msg)
  634. # If there is a scalar, then here we know the array has the same
  635. # flag as it everywhere, so we should return the scalar flag.
  636. if isinstance(x_id, bool) or x_id.ndim == 0:
  637. return bool_(x_id)
  638. elif isinstance(x_id, bool) or y_id.ndim == 0:
  639. return bool_(y_id)
  640. else:
  641. return y_id
  642. try:
  643. cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
  644. if not cond:
  645. msg = build_err_msg([x, y],
  646. err_msg
  647. + '\n(shapes %s, %s mismatch)' % (x.shape,
  648. y.shape),
  649. verbose=verbose, header=header,
  650. names=('x', 'y'), precision=precision)
  651. raise AssertionError(msg)
  652. flagged = bool_(False)
  653. if isnumber(x) and isnumber(y):
  654. if equal_nan:
  655. flagged = func_assert_same_pos(x, y, func=isnan, hasval='nan')
  656. if equal_inf:
  657. flagged |= func_assert_same_pos(x, y,
  658. func=lambda xy: xy == +inf,
  659. hasval='+inf')
  660. flagged |= func_assert_same_pos(x, y,
  661. func=lambda xy: xy == -inf,
  662. hasval='-inf')
  663. elif istime(x) and istime(y):
  664. # If one is datetime64 and the other timedelta64 there is no point
  665. if equal_nan and x.dtype.type == y.dtype.type:
  666. flagged = func_assert_same_pos(x, y, func=isnat, hasval="NaT")
  667. if flagged.ndim > 0:
  668. x, y = x[~flagged], y[~flagged]
  669. # Only do the comparison if actual values are left
  670. if x.size == 0:
  671. return
  672. elif flagged:
  673. # no sense doing comparison if everything is flagged.
  674. return
  675. val = comparison(x, y)
  676. if isinstance(val, bool):
  677. cond = val
  678. reduced = array([val])
  679. else:
  680. reduced = val.ravel()
  681. cond = reduced.all()
  682. # The below comparison is a hack to ensure that fully masked
  683. # results, for which val.ravel().all() returns np.ma.masked,
  684. # do not trigger a failure (np.ma.masked != True evaluates as
  685. # np.ma.masked, which is falsy).
  686. if cond != True:
  687. n_mismatch = reduced.size - reduced.sum(dtype=intp)
  688. n_elements = flagged.size if flagged.ndim != 0 else reduced.size
  689. percent_mismatch = 100 * n_mismatch / n_elements
  690. remarks = [
  691. 'Mismatched elements: {} / {} ({:.3g}%)'.format(
  692. n_mismatch, n_elements, percent_mismatch)]
  693. with errstate(invalid='ignore', divide='ignore'):
  694. # ignore errors for non-numeric types
  695. with contextlib.suppress(TypeError):
  696. error = abs(x - y)
  697. max_abs_error = max(error)
  698. if getattr(error, 'dtype', object_) == object_:
  699. remarks.append('Max absolute difference: '
  700. + str(max_abs_error))
  701. else:
  702. remarks.append('Max absolute difference: '
  703. + array2string(max_abs_error))
  704. # note: this definition of relative error matches that one
  705. # used by assert_allclose (found in np.isclose)
  706. # Filter values where the divisor would be zero
  707. nonzero = bool_(y != 0)
  708. if all(~nonzero):
  709. max_rel_error = array(inf)
  710. else:
  711. max_rel_error = max(error[nonzero] / abs(y[nonzero]))
  712. if getattr(error, 'dtype', object_) == object_:
  713. remarks.append('Max relative difference: '
  714. + str(max_rel_error))
  715. else:
  716. remarks.append('Max relative difference: '
  717. + array2string(max_rel_error))
  718. err_msg += '\n' + '\n'.join(remarks)
  719. msg = build_err_msg([ox, oy], err_msg,
  720. verbose=verbose, header=header,
  721. names=('x', 'y'), precision=precision)
  722. raise AssertionError(msg)
  723. except ValueError:
  724. import traceback
  725. efmt = traceback.format_exc()
  726. header = 'error during assertion:\n\n%s\n\n%s' % (efmt, header)
  727. msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
  728. names=('x', 'y'), precision=precision)
  729. raise ValueError(msg)
  730. def assert_array_equal(x, y, err_msg='', verbose=True):
  731. """
  732. Raises an AssertionError if two array_like objects are not equal.
  733. Given two array_like objects, check that the shape is equal and all
  734. elements of these objects are equal (but see the Notes for the special
  735. handling of a scalar). An exception is raised at shape mismatch or
  736. conflicting values. In contrast to the standard usage in numpy, NaNs
  737. are compared like numbers, no assertion is raised if both objects have
  738. NaNs in the same positions.
  739. The usual caution for verifying equality with floating point numbers is
  740. advised.
  741. Parameters
  742. ----------
  743. x : array_like
  744. The actual object to check.
  745. y : array_like
  746. The desired, expected object.
  747. err_msg : str, optional
  748. The error message to be printed in case of failure.
  749. verbose : bool, optional
  750. If True, the conflicting values are appended to the error message.
  751. Raises
  752. ------
  753. AssertionError
  754. If actual and desired objects are not equal.
  755. See Also
  756. --------
  757. assert_allclose: Compare two array_like objects for equality with desired
  758. relative and/or absolute precision.
  759. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  760. Notes
  761. -----
  762. When one of `x` and `y` is a scalar and the other is array_like, the
  763. function checks that each element of the array_like object is equal to
  764. the scalar.
  765. Examples
  766. --------
  767. The first assert does not raise an exception:
  768. >>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
  769. ... [np.exp(0),2.33333, np.nan])
  770. Assert fails with numerical imprecision with floats:
  771. >>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
  772. ... [1, np.sqrt(np.pi)**2, np.nan])
  773. Traceback (most recent call last):
  774. ...
  775. AssertionError:
  776. Arrays are not equal
  777. Mismatch: 33.3%
  778. Max absolute difference: 4.4408921e-16
  779. Max relative difference: 1.41357986e-16
  780. x: array([1. , 3.141593, nan])
  781. y: array([1. , 3.141593, nan])
  782. Use `assert_allclose` or one of the nulp (number of floating point values)
  783. functions for these cases instead:
  784. >>> np.testing.assert_allclose([1.0,np.pi,np.nan],
  785. ... [1, np.sqrt(np.pi)**2, np.nan],
  786. ... rtol=1e-10, atol=0)
  787. As mentioned in the Notes section, `assert_array_equal` has special
  788. handling for scalars. Here the test checks that each value in `x` is 3:
  789. >>> x = np.full((2, 5), fill_value=3)
  790. >>> np.testing.assert_array_equal(x, 3)
  791. """
  792. __tracebackhide__ = True # Hide traceback for py.test
  793. assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
  794. verbose=verbose, header='Arrays are not equal')
  795. def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
  796. """
  797. Raises an AssertionError if two objects are not equal up to desired
  798. precision.
  799. .. note:: It is recommended to use one of `assert_allclose`,
  800. `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
  801. instead of this function for more consistent floating point
  802. comparisons.
  803. The test verifies identical shapes and that the elements of ``actual`` and
  804. ``desired`` satisfy.
  805. ``abs(desired-actual) < 1.5 * 10**(-decimal)``
  806. That is a looser test than originally documented, but agrees with what the
  807. actual implementation did up to rounding vagaries. An exception is raised
  808. at shape mismatch or conflicting values. In contrast to the standard usage
  809. in numpy, NaNs are compared like numbers, no assertion is raised if both
  810. objects have NaNs in the same positions.
  811. Parameters
  812. ----------
  813. x : array_like
  814. The actual object to check.
  815. y : array_like
  816. The desired, expected object.
  817. decimal : int, optional
  818. Desired precision, default is 6.
  819. err_msg : str, optional
  820. The error message to be printed in case of failure.
  821. verbose : bool, optional
  822. If True, the conflicting values are appended to the error message.
  823. Raises
  824. ------
  825. AssertionError
  826. If actual and desired are not equal up to specified precision.
  827. See Also
  828. --------
  829. assert_allclose: Compare two array_like objects for equality with desired
  830. relative and/or absolute precision.
  831. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  832. Examples
  833. --------
  834. the first assert does not raise an exception
  835. >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
  836. ... [1.0,2.333,np.nan])
  837. >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
  838. ... [1.0,2.33339,np.nan], decimal=5)
  839. Traceback (most recent call last):
  840. ...
  841. AssertionError:
  842. Arrays are not almost equal to 5 decimals
  843. Mismatch: 33.3%
  844. Max absolute difference: 6.e-05
  845. Max relative difference: 2.57136612e-05
  846. x: array([1. , 2.33333, nan])
  847. y: array([1. , 2.33339, nan])
  848. >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
  849. ... [1.0,2.33333, 5], decimal=5)
  850. Traceback (most recent call last):
  851. ...
  852. AssertionError:
  853. Arrays are not almost equal to 5 decimals
  854. x and y nan location mismatch:
  855. x: array([1. , 2.33333, nan])
  856. y: array([1. , 2.33333, 5. ])
  857. """
  858. __tracebackhide__ = True # Hide traceback for py.test
  859. from numpy.core import number, float_, result_type, array
  860. from numpy.core.numerictypes import issubdtype
  861. from numpy.core.fromnumeric import any as npany
  862. def compare(x, y):
  863. try:
  864. if npany(gisinf(x)) or npany( gisinf(y)):
  865. xinfid = gisinf(x)
  866. yinfid = gisinf(y)
  867. if not (xinfid == yinfid).all():
  868. return False
  869. # if one item, x and y is +- inf
  870. if x.size == y.size == 1:
  871. return x == y
  872. x = x[~xinfid]
  873. y = y[~yinfid]
  874. except (TypeError, NotImplementedError):
  875. pass
  876. # make sure y is an inexact type to avoid abs(MIN_INT); will cause
  877. # casting of x later.
  878. dtype = result_type(y, 1.)
  879. y = array(y, dtype=dtype, copy=False, subok=True)
  880. z = abs(x - y)
  881. if not issubdtype(z.dtype, number):
  882. z = z.astype(float_) # handle object arrays
  883. return z < 1.5 * 10.0**(-decimal)
  884. assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
  885. header=('Arrays are not almost equal to %d decimals' % decimal),
  886. precision=decimal)
  887. def assert_array_less(x, y, err_msg='', verbose=True):
  888. """
  889. Raises an AssertionError if two array_like objects are not ordered by less
  890. than.
  891. Given two array_like objects, check that the shape is equal and all
  892. elements of the first object are strictly smaller than those of the
  893. second object. An exception is raised at shape mismatch or incorrectly
  894. ordered values. Shape mismatch does not raise if an object has zero
  895. dimension. In contrast to the standard usage in numpy, NaNs are
  896. compared, no assertion is raised if both objects have NaNs in the same
  897. positions.
  898. Parameters
  899. ----------
  900. x : array_like
  901. The smaller object to check.
  902. y : array_like
  903. The larger object to compare.
  904. err_msg : string
  905. The error message to be printed in case of failure.
  906. verbose : bool
  907. If True, the conflicting values are appended to the error message.
  908. Raises
  909. ------
  910. AssertionError
  911. If actual and desired objects are not equal.
  912. See Also
  913. --------
  914. assert_array_equal: tests objects for equality
  915. assert_array_almost_equal: test objects for equality up to precision
  916. Examples
  917. --------
  918. >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
  919. >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
  920. Traceback (most recent call last):
  921. ...
  922. AssertionError:
  923. Arrays are not less-ordered
  924. Mismatch: 33.3%
  925. Max absolute difference: 1.
  926. Max relative difference: 0.5
  927. x: array([ 1., 1., nan])
  928. y: array([ 1., 2., nan])
  929. >>> np.testing.assert_array_less([1.0, 4.0], 3)
  930. Traceback (most recent call last):
  931. ...
  932. AssertionError:
  933. Arrays are not less-ordered
  934. Mismatch: 50%
  935. Max absolute difference: 2.
  936. Max relative difference: 0.66666667
  937. x: array([1., 4.])
  938. y: array(3)
  939. >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
  940. Traceback (most recent call last):
  941. ...
  942. AssertionError:
  943. Arrays are not less-ordered
  944. (shapes (3,), (1,) mismatch)
  945. x: array([1., 2., 3.])
  946. y: array([4])
  947. """
  948. __tracebackhide__ = True # Hide traceback for py.test
  949. assert_array_compare(operator.__lt__, x, y, err_msg=err_msg,
  950. verbose=verbose,
  951. header='Arrays are not less-ordered',
  952. equal_inf=False)
  953. def runstring(astr, dict):
  954. exec(astr, dict)
  955. def assert_string_equal(actual, desired):
  956. """
  957. Test if two strings are equal.
  958. If the given strings are equal, `assert_string_equal` does nothing.
  959. If they are not equal, an AssertionError is raised, and the diff
  960. between the strings is shown.
  961. Parameters
  962. ----------
  963. actual : str
  964. The string to test for equality against the expected string.
  965. desired : str
  966. The expected string.
  967. Examples
  968. --------
  969. >>> np.testing.assert_string_equal('abc', 'abc')
  970. >>> np.testing.assert_string_equal('abc', 'abcd')
  971. Traceback (most recent call last):
  972. File "<stdin>", line 1, in <module>
  973. ...
  974. AssertionError: Differences in strings:
  975. - abc+ abcd? +
  976. """
  977. # delay import of difflib to reduce startup time
  978. __tracebackhide__ = True # Hide traceback for py.test
  979. import difflib
  980. if not isinstance(actual, str):
  981. raise AssertionError(repr(type(actual)))
  982. if not isinstance(desired, str):
  983. raise AssertionError(repr(type(desired)))
  984. if desired == actual:
  985. return
  986. diff = list(difflib.Differ().compare(actual.splitlines(True), desired.splitlines(True)))
  987. diff_list = []
  988. while diff:
  989. d1 = diff.pop(0)
  990. if d1.startswith(' '):
  991. continue
  992. if d1.startswith('- '):
  993. l = [d1]
  994. d2 = diff.pop(0)
  995. if d2.startswith('? '):
  996. l.append(d2)
  997. d2 = diff.pop(0)
  998. if not d2.startswith('+ '):
  999. raise AssertionError(repr(d2))
  1000. l.append(d2)
  1001. if diff:
  1002. d3 = diff.pop(0)
  1003. if d3.startswith('? '):
  1004. l.append(d3)
  1005. else:
  1006. diff.insert(0, d3)
  1007. if d2[2:] == d1[2:]:
  1008. continue
  1009. diff_list.extend(l)
  1010. continue
  1011. raise AssertionError(repr(d1))
  1012. if not diff_list:
  1013. return
  1014. msg = 'Differences in strings:\n%s' % (''.join(diff_list)).rstrip()
  1015. if actual != desired:
  1016. raise AssertionError(msg)
  1017. def rundocs(filename=None, raise_on_error=True):
  1018. """
  1019. Run doctests found in the given file.
  1020. By default `rundocs` raises an AssertionError on failure.
  1021. Parameters
  1022. ----------
  1023. filename : str
  1024. The path to the file for which the doctests are run.
  1025. raise_on_error : bool
  1026. Whether to raise an AssertionError when a doctest fails. Default is
  1027. True.
  1028. Notes
  1029. -----
  1030. The doctests can be run by the user/developer by adding the ``doctests``
  1031. argument to the ``test()`` call. For example, to run all tests (including
  1032. doctests) for `numpy.lib`:
  1033. >>> np.lib.test(doctests=True) # doctest: +SKIP
  1034. """
  1035. from numpy.compat import npy_load_module
  1036. import doctest
  1037. if filename is None:
  1038. f = sys._getframe(1)
  1039. filename = f.f_globals['__file__']
  1040. name = os.path.splitext(os.path.basename(filename))[0]
  1041. m = npy_load_module(name, filename)
  1042. tests = doctest.DocTestFinder().find(m)
  1043. runner = doctest.DocTestRunner(verbose=False)
  1044. msg = []
  1045. if raise_on_error:
  1046. out = lambda s: msg.append(s)
  1047. else:
  1048. out = None
  1049. for test in tests:
  1050. runner.run(test, out=out)
  1051. if runner.failures > 0 and raise_on_error:
  1052. raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg))
  1053. def raises(*args):
  1054. """Decorator to check for raised exceptions.
  1055. The decorated test function must raise one of the passed exceptions to
  1056. pass. If you want to test many assertions about exceptions in a single
  1057. test, you may want to use `assert_raises` instead.
  1058. .. warning::
  1059. This decorator is nose specific, do not use it if you are using a
  1060. different test framework.
  1061. Parameters
  1062. ----------
  1063. args : exceptions
  1064. The test passes if any of the passed exceptions is raised.
  1065. Raises
  1066. ------
  1067. AssertionError
  1068. Examples
  1069. --------
  1070. Usage::
  1071. @raises(TypeError, ValueError)
  1072. def test_raises_type_error():
  1073. raise TypeError("This test passes")
  1074. @raises(Exception)
  1075. def test_that_fails_by_passing():
  1076. pass
  1077. """
  1078. nose = import_nose()
  1079. return nose.tools.raises(*args)
  1080. #
  1081. # assert_raises and assert_raises_regex are taken from unittest.
  1082. #
  1083. import unittest
  1084. class _Dummy(unittest.TestCase):
  1085. def nop(self):
  1086. pass
  1087. _d = _Dummy('nop')
  1088. def assert_raises(*args, **kwargs):
  1089. """
  1090. assert_raises(exception_class, callable, *args, **kwargs)
  1091. assert_raises(exception_class)
  1092. Fail unless an exception of class exception_class is thrown
  1093. by callable when invoked with arguments args and keyword
  1094. arguments kwargs. If a different type of exception is
  1095. thrown, it will not be caught, and the test case will be
  1096. deemed to have suffered an error, exactly as for an
  1097. unexpected exception.
  1098. Alternatively, `assert_raises` can be used as a context manager:
  1099. >>> from numpy.testing import assert_raises
  1100. >>> with assert_raises(ZeroDivisionError):
  1101. ... 1 / 0
  1102. is equivalent to
  1103. >>> def div(x, y):
  1104. ... return x / y
  1105. >>> assert_raises(ZeroDivisionError, div, 1, 0)
  1106. """
  1107. __tracebackhide__ = True # Hide traceback for py.test
  1108. return _d.assertRaises(*args,**kwargs)
  1109. def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
  1110. """
  1111. assert_raises_regex(exception_class, expected_regexp, callable, *args,
  1112. **kwargs)
  1113. assert_raises_regex(exception_class, expected_regexp)
  1114. Fail unless an exception of class exception_class and with message that
  1115. matches expected_regexp is thrown by callable when invoked with arguments
  1116. args and keyword arguments kwargs.
  1117. Alternatively, can be used as a context manager like `assert_raises`.
  1118. Name of this function adheres to Python 3.2+ reference, but should work in
  1119. all versions down to 2.6.
  1120. Notes
  1121. -----
  1122. .. versionadded:: 1.9.0
  1123. """
  1124. __tracebackhide__ = True # Hide traceback for py.test
  1125. if sys.version_info.major >= 3:
  1126. funcname = _d.assertRaisesRegex
  1127. else:
  1128. # Only present in Python 2.7, missing from unittest in 2.6
  1129. funcname = _d.assertRaisesRegexp
  1130. return funcname(exception_class, expected_regexp, *args, **kwargs)
  1131. def decorate_methods(cls, decorator, testmatch=None):
  1132. """
  1133. Apply a decorator to all methods in a class matching a regular expression.
  1134. The given decorator is applied to all public methods of `cls` that are
  1135. matched by the regular expression `testmatch`
  1136. (``testmatch.search(methodname)``). Methods that are private, i.e. start
  1137. with an underscore, are ignored.
  1138. Parameters
  1139. ----------
  1140. cls : class
  1141. Class whose methods to decorate.
  1142. decorator : function
  1143. Decorator to apply to methods
  1144. testmatch : compiled regexp or str, optional
  1145. The regular expression. Default value is None, in which case the
  1146. nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
  1147. is used.
  1148. If `testmatch` is a string, it is compiled to a regular expression
  1149. first.
  1150. """
  1151. if testmatch is None:
  1152. testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)
  1153. else:
  1154. testmatch = re.compile(testmatch)
  1155. cls_attr = cls.__dict__
  1156. # delayed import to reduce startup time
  1157. from inspect import isfunction
  1158. methods = [_m for _m in cls_attr.values() if isfunction(_m)]
  1159. for function in methods:
  1160. try:
  1161. if hasattr(function, 'compat_func_name'):
  1162. funcname = function.compat_func_name
  1163. else:
  1164. funcname = function.__name__
  1165. except AttributeError:
  1166. # not a function
  1167. continue
  1168. if testmatch.search(funcname) and not funcname.startswith('_'):
  1169. setattr(cls, funcname, decorator(function))
  1170. return
  1171. def measure(code_str, times=1, label=None):
  1172. """
  1173. Return elapsed time for executing code in the namespace of the caller.
  1174. The supplied code string is compiled with the Python builtin ``compile``.
  1175. The precision of the timing is 10 milli-seconds. If the code will execute
  1176. fast on this timescale, it can be executed many times to get reasonable
  1177. timing accuracy.
  1178. Parameters
  1179. ----------
  1180. code_str : str
  1181. The code to be timed.
  1182. times : int, optional
  1183. The number of times the code is executed. Default is 1. The code is
  1184. only compiled once.
  1185. label : str, optional
  1186. A label to identify `code_str` with. This is passed into ``compile``
  1187. as the second argument (for run-time error messages).
  1188. Returns
  1189. -------
  1190. elapsed : float
  1191. Total elapsed time in seconds for executing `code_str` `times` times.
  1192. Examples
  1193. --------
  1194. >>> times = 10
  1195. >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
  1196. >>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP
  1197. Time for a single execution : 0.005 s
  1198. """
  1199. frame = sys._getframe(1)
  1200. locs, globs = frame.f_locals, frame.f_globals
  1201. code = compile(code_str,
  1202. 'Test name: %s ' % label,
  1203. 'exec')
  1204. i = 0
  1205. elapsed = jiffies()
  1206. while i < times:
  1207. i += 1
  1208. exec(code, globs, locs)
  1209. elapsed = jiffies() - elapsed
  1210. return 0.01*elapsed
  1211. def _assert_valid_refcount(op):
  1212. """
  1213. Check that ufuncs don't mishandle refcount of object `1`.
  1214. Used in a few regression tests.
  1215. """
  1216. if not HAS_REFCOUNT:
  1217. return True
  1218. import numpy as np, gc
  1219. b = np.arange(100*100).reshape(100, 100)
  1220. c = b
  1221. i = 1
  1222. gc.disable()
  1223. try:
  1224. rc = sys.getrefcount(i)
  1225. for j in range(15):
  1226. d = op(b, c)
  1227. assert_(sys.getrefcount(i) >= rc)
  1228. finally:
  1229. gc.enable()
  1230. del d # for pyflakes
  1231. def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True,
  1232. err_msg='', verbose=True):
  1233. """
  1234. Raises an AssertionError if two objects are not equal up to desired
  1235. tolerance.
  1236. The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
  1237. that ``allclose`` has different default values). It compares the difference
  1238. between `actual` and `desired` to ``atol + rtol * abs(desired)``.
  1239. .. versionadded:: 1.5.0
  1240. Parameters
  1241. ----------
  1242. actual : array_like
  1243. Array obtained.
  1244. desired : array_like
  1245. Array desired.
  1246. rtol : float, optional
  1247. Relative tolerance.
  1248. atol : float, optional
  1249. Absolute tolerance.
  1250. equal_nan : bool, optional.
  1251. If True, NaNs will compare equal.
  1252. err_msg : str, optional
  1253. The error message to be printed in case of failure.
  1254. verbose : bool, optional
  1255. If True, the conflicting values are appended to the error message.
  1256. Raises
  1257. ------
  1258. AssertionError
  1259. If actual and desired are not equal up to specified precision.
  1260. See Also
  1261. --------
  1262. assert_array_almost_equal_nulp, assert_array_max_ulp
  1263. Examples
  1264. --------
  1265. >>> x = [1e-5, 1e-3, 1e-1]
  1266. >>> y = np.arccos(np.cos(x))
  1267. >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
  1268. """
  1269. __tracebackhide__ = True # Hide traceback for py.test
  1270. import numpy as np
  1271. def compare(x, y):
  1272. return np.core.numeric.isclose(x, y, rtol=rtol, atol=atol,
  1273. equal_nan=equal_nan)
  1274. actual, desired = np.asanyarray(actual), np.asanyarray(desired)
  1275. header = 'Not equal to tolerance rtol=%g, atol=%g' % (rtol, atol)
  1276. assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
  1277. verbose=verbose, header=header, equal_nan=equal_nan)
  1278. def assert_array_almost_equal_nulp(x, y, nulp=1):
  1279. """
  1280. Compare two arrays relatively to their spacing.
  1281. This is a relatively robust method to compare two arrays whose amplitude
  1282. is variable.
  1283. Parameters
  1284. ----------
  1285. x, y : array_like
  1286. Input arrays.
  1287. nulp : int, optional
  1288. The maximum number of unit in the last place for tolerance (see Notes).
  1289. Default is 1.
  1290. Returns
  1291. -------
  1292. None
  1293. Raises
  1294. ------
  1295. AssertionError
  1296. If the spacing between `x` and `y` for one or more elements is larger
  1297. than `nulp`.
  1298. See Also
  1299. --------
  1300. assert_array_max_ulp : Check that all items of arrays differ in at most
  1301. N Units in the Last Place.
  1302. spacing : Return the distance between x and the nearest adjacent number.
  1303. Notes
  1304. -----
  1305. An assertion is raised if the following condition is not met::
  1306. abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))
  1307. Examples
  1308. --------
  1309. >>> x = np.array([1., 1e-10, 1e-20])
  1310. >>> eps = np.finfo(x.dtype).eps
  1311. >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
  1312. >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
  1313. Traceback (most recent call last):
  1314. ...
  1315. AssertionError: X and Y are not equal to 1 ULP (max is 2)
  1316. """
  1317. __tracebackhide__ = True # Hide traceback for py.test
  1318. import numpy as np
  1319. ax = np.abs(x)
  1320. ay = np.abs(y)
  1321. ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
  1322. if not np.all(np.abs(x-y) <= ref):
  1323. if np.iscomplexobj(x) or np.iscomplexobj(y):
  1324. msg = "X and Y are not equal to %d ULP" % nulp
  1325. else:
  1326. max_nulp = np.max(nulp_diff(x, y))
  1327. msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
  1328. raise AssertionError(msg)
  1329. def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
  1330. """
  1331. Check that all items of arrays differ in at most N Units in the Last Place.
  1332. Parameters
  1333. ----------
  1334. a, b : array_like
  1335. Input arrays to be compared.
  1336. maxulp : int, optional
  1337. The maximum number of units in the last place that elements of `a` and
  1338. `b` can differ. Default is 1.
  1339. dtype : dtype, optional
  1340. Data-type to convert `a` and `b` to if given. Default is None.
  1341. Returns
  1342. -------
  1343. ret : ndarray
  1344. Array containing number of representable floating point numbers between
  1345. items in `a` and `b`.
  1346. Raises
  1347. ------
  1348. AssertionError
  1349. If one or more elements differ by more than `maxulp`.
  1350. See Also
  1351. --------
  1352. assert_array_almost_equal_nulp : Compare two arrays relatively to their
  1353. spacing.
  1354. Examples
  1355. --------
  1356. >>> a = np.linspace(0., 1., 100)
  1357. >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
  1358. """
  1359. __tracebackhide__ = True # Hide traceback for py.test
  1360. import numpy as np
  1361. ret = nulp_diff(a, b, dtype)
  1362. if not np.all(ret <= maxulp):
  1363. raise AssertionError("Arrays are not almost equal up to %g ULP" %
  1364. maxulp)
  1365. return ret
  1366. def nulp_diff(x, y, dtype=None):
  1367. """For each item in x and y, return the number of representable floating
  1368. points between them.
  1369. Parameters
  1370. ----------
  1371. x : array_like
  1372. first input array
  1373. y : array_like
  1374. second input array
  1375. dtype : dtype, optional
  1376. Data-type to convert `x` and `y` to if given. Default is None.
  1377. Returns
  1378. -------
  1379. nulp : array_like
  1380. number of representable floating point numbers between each item in x
  1381. and y.
  1382. Examples
  1383. --------
  1384. # By definition, epsilon is the smallest number such as 1 + eps != 1, so
  1385. # there should be exactly one ULP between 1 and 1 + eps
  1386. >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
  1387. 1.0
  1388. """
  1389. import numpy as np
  1390. if dtype:
  1391. x = np.array(x, dtype=dtype)
  1392. y = np.array(y, dtype=dtype)
  1393. else:
  1394. x = np.array(x)
  1395. y = np.array(y)
  1396. t = np.common_type(x, y)
  1397. if np.iscomplexobj(x) or np.iscomplexobj(y):
  1398. raise NotImplementedError("_nulp not implemented for complex array")
  1399. x = np.array(x, dtype=t)
  1400. y = np.array(y, dtype=t)
  1401. if not x.shape == y.shape:
  1402. raise ValueError("x and y do not have the same shape: %s - %s" %
  1403. (x.shape, y.shape))
  1404. def _diff(rx, ry, vdt):
  1405. diff = np.array(rx-ry, dtype=vdt)
  1406. return np.abs(diff)
  1407. rx = integer_repr(x)
  1408. ry = integer_repr(y)
  1409. return _diff(rx, ry, t)
  1410. def _integer_repr(x, vdt, comp):
  1411. # Reinterpret binary representation of the float as sign-magnitude:
  1412. # take into account two-complement representation
  1413. # See also
  1414. # https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
  1415. rx = x.view(vdt)
  1416. if not (rx.size == 1):
  1417. rx[rx < 0] = comp - rx[rx < 0]
  1418. else:
  1419. if rx < 0:
  1420. rx = comp - rx
  1421. return rx
  1422. def integer_repr(x):
  1423. """Return the signed-magnitude interpretation of the binary representation of
  1424. x."""
  1425. import numpy as np
  1426. if x.dtype == np.float16:
  1427. return _integer_repr(x, np.int16, np.int16(-2**15))
  1428. elif x.dtype == np.float32:
  1429. return _integer_repr(x, np.int32, np.int32(-2**31))
  1430. elif x.dtype == np.float64:
  1431. return _integer_repr(x, np.int64, np.int64(-2**63))
  1432. else:
  1433. raise ValueError("Unsupported dtype %s" % x.dtype)
  1434. @contextlib.contextmanager
  1435. def _assert_warns_context(warning_class, name=None):
  1436. __tracebackhide__ = True # Hide traceback for py.test
  1437. with suppress_warnings() as sup:
  1438. l = sup.record(warning_class)
  1439. yield
  1440. if not len(l) > 0:
  1441. name_str = " when calling %s" % name if name is not None else ""
  1442. raise AssertionError("No warning raised" + name_str)
  1443. def assert_warns(warning_class, *args, **kwargs):
  1444. """
  1445. Fail unless the given callable throws the specified warning.
  1446. A warning of class warning_class should be thrown by the callable when
  1447. invoked with arguments args and keyword arguments kwargs.
  1448. If a different type of warning is thrown, it will not be caught.
  1449. If called with all arguments other than the warning class omitted, may be
  1450. used as a context manager:
  1451. with assert_warns(SomeWarning):
  1452. do_something()
  1453. The ability to be used as a context manager is new in NumPy v1.11.0.
  1454. .. versionadded:: 1.4.0
  1455. Parameters
  1456. ----------
  1457. warning_class : class
  1458. The class defining the warning that `func` is expected to throw.
  1459. func : callable
  1460. The callable to test.
  1461. \\*args : Arguments
  1462. Arguments passed to `func`.
  1463. \\*\\*kwargs : Kwargs
  1464. Keyword arguments passed to `func`.
  1465. Returns
  1466. -------
  1467. The value returned by `func`.
  1468. """
  1469. if not args:
  1470. return _assert_warns_context(warning_class)
  1471. func = args[0]
  1472. args = args[1:]
  1473. with _assert_warns_context(warning_class, name=func.__name__):
  1474. return func(*args, **kwargs)
  1475. @contextlib.contextmanager
  1476. def _assert_no_warnings_context(name=None):
  1477. __tracebackhide__ = True # Hide traceback for py.test
  1478. with warnings.catch_warnings(record=True) as l:
  1479. warnings.simplefilter('always')
  1480. yield
  1481. if len(l) > 0:
  1482. name_str = " when calling %s" % name if name is not None else ""
  1483. raise AssertionError("Got warnings%s: %s" % (name_str, l))
  1484. def assert_no_warnings(*args, **kwargs):
  1485. """
  1486. Fail if the given callable produces any warnings.
  1487. If called with all arguments omitted, may be used as a context manager:
  1488. with assert_no_warnings():
  1489. do_something()
  1490. The ability to be used as a context manager is new in NumPy v1.11.0.
  1491. .. versionadded:: 1.7.0
  1492. Parameters
  1493. ----------
  1494. func : callable
  1495. The callable to test.
  1496. \\*args : Arguments
  1497. Arguments passed to `func`.
  1498. \\*\\*kwargs : Kwargs
  1499. Keyword arguments passed to `func`.
  1500. Returns
  1501. -------
  1502. The value returned by `func`.
  1503. """
  1504. if not args:
  1505. return _assert_no_warnings_context()
  1506. func = args[0]
  1507. args = args[1:]
  1508. with _assert_no_warnings_context(name=func.__name__):
  1509. return func(*args, **kwargs)
  1510. def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
  1511. """
  1512. generator producing data with different alignment and offsets
  1513. to test simd vectorization
  1514. Parameters
  1515. ----------
  1516. dtype : dtype
  1517. data type to produce
  1518. type : string
  1519. 'unary': create data for unary operations, creates one input
  1520. and output array
  1521. 'binary': create data for unary operations, creates two input
  1522. and output array
  1523. max_size : integer
  1524. maximum size of data to produce
  1525. Returns
  1526. -------
  1527. if type is 'unary' yields one output, one input array and a message
  1528. containing information on the data
  1529. if type is 'binary' yields one output array, two input array and a message
  1530. containing information on the data
  1531. """
  1532. ufmt = 'unary offset=(%d, %d), size=%d, dtype=%r, %s'
  1533. bfmt = 'binary offset=(%d, %d, %d), size=%d, dtype=%r, %s'
  1534. for o in range(3):
  1535. for s in range(o + 2, max(o + 3, max_size)):
  1536. if type == 'unary':
  1537. inp = lambda: arange(s, dtype=dtype)[o:]
  1538. out = empty((s,), dtype=dtype)[o:]
  1539. yield out, inp(), ufmt % (o, o, s, dtype, 'out of place')
  1540. d = inp()
  1541. yield d, d, ufmt % (o, o, s, dtype, 'in place')
  1542. yield out[1:], inp()[:-1], ufmt % \
  1543. (o + 1, o, s - 1, dtype, 'out of place')
  1544. yield out[:-1], inp()[1:], ufmt % \
  1545. (o, o + 1, s - 1, dtype, 'out of place')
  1546. yield inp()[:-1], inp()[1:], ufmt % \
  1547. (o, o + 1, s - 1, dtype, 'aliased')
  1548. yield inp()[1:], inp()[:-1], ufmt % \
  1549. (o + 1, o, s - 1, dtype, 'aliased')
  1550. if type == 'binary':
  1551. inp1 = lambda: arange(s, dtype=dtype)[o:]
  1552. inp2 = lambda: arange(s, dtype=dtype)[o:]
  1553. out = empty((s,), dtype=dtype)[o:]
  1554. yield out, inp1(), inp2(), bfmt % \
  1555. (o, o, o, s, dtype, 'out of place')
  1556. d = inp1()
  1557. yield d, d, inp2(), bfmt % \
  1558. (o, o, o, s, dtype, 'in place1')
  1559. d = inp2()
  1560. yield d, inp1(), d, bfmt % \
  1561. (o, o, o, s, dtype, 'in place2')
  1562. yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % \
  1563. (o + 1, o, o, s - 1, dtype, 'out of place')
  1564. yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % \
  1565. (o, o + 1, o, s - 1, dtype, 'out of place')
  1566. yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % \
  1567. (o, o, o + 1, s - 1, dtype, 'out of place')
  1568. yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % \
  1569. (o + 1, o, o, s - 1, dtype, 'aliased')
  1570. yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % \
  1571. (o, o + 1, o, s - 1, dtype, 'aliased')
  1572. yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % \
  1573. (o, o, o + 1, s - 1, dtype, 'aliased')
  1574. class IgnoreException(Exception):
  1575. "Ignoring this exception due to disabled feature"
  1576. pass
  1577. @contextlib.contextmanager
  1578. def tempdir(*args, **kwargs):
  1579. """Context manager to provide a temporary test folder.
  1580. All arguments are passed as this to the underlying tempfile.mkdtemp
  1581. function.
  1582. """
  1583. tmpdir = mkdtemp(*args, **kwargs)
  1584. try:
  1585. yield tmpdir
  1586. finally:
  1587. shutil.rmtree(tmpdir)
  1588. @contextlib.contextmanager
  1589. def temppath(*args, **kwargs):
  1590. """Context manager for temporary files.
  1591. Context manager that returns the path to a closed temporary file. Its
  1592. parameters are the same as for tempfile.mkstemp and are passed directly
  1593. to that function. The underlying file is removed when the context is
  1594. exited, so it should be closed at that time.
  1595. Windows does not allow a temporary file to be opened if it is already
  1596. open, so the underlying file must be closed after opening before it
  1597. can be opened again.
  1598. """
  1599. fd, path = mkstemp(*args, **kwargs)
  1600. os.close(fd)
  1601. try:
  1602. yield path
  1603. finally:
  1604. os.remove(path)
  1605. class clear_and_catch_warnings(warnings.catch_warnings):
  1606. """ Context manager that resets warning registry for catching warnings
  1607. Warnings can be slippery, because, whenever a warning is triggered, Python
  1608. adds a ``__warningregistry__`` member to the *calling* module. This makes
  1609. it impossible to retrigger the warning in this module, whatever you put in
  1610. the warnings filters. This context manager accepts a sequence of `modules`
  1611. as a keyword argument to its constructor and:
  1612. * stores and removes any ``__warningregistry__`` entries in given `modules`
  1613. on entry;
  1614. * resets ``__warningregistry__`` to its previous state on exit.
  1615. This makes it possible to trigger any warning afresh inside the context
  1616. manager without disturbing the state of warnings outside.
  1617. For compatibility with Python 3.0, please consider all arguments to be
  1618. keyword-only.
  1619. Parameters
  1620. ----------
  1621. record : bool, optional
  1622. Specifies whether warnings should be captured by a custom
  1623. implementation of ``warnings.showwarning()`` and be appended to a list
  1624. returned by the context manager. Otherwise None is returned by the
  1625. context manager. The objects appended to the list are arguments whose
  1626. attributes mirror the arguments to ``showwarning()``.
  1627. modules : sequence, optional
  1628. Sequence of modules for which to reset warnings registry on entry and
  1629. restore on exit. To work correctly, all 'ignore' filters should
  1630. filter by one of these modules.
  1631. Examples
  1632. --------
  1633. >>> import warnings
  1634. >>> with np.testing.clear_and_catch_warnings(
  1635. ... modules=[np.core.fromnumeric]):
  1636. ... warnings.simplefilter('always')
  1637. ... warnings.filterwarnings('ignore', module='np.core.fromnumeric')
  1638. ... # do something that raises a warning but ignore those in
  1639. ... # np.core.fromnumeric
  1640. """
  1641. class_modules = ()
  1642. def __init__(self, record=False, modules=()):
  1643. self.modules = set(modules).union(self.class_modules)
  1644. self._warnreg_copies = {}
  1645. super(clear_and_catch_warnings, self).__init__(record=record)
  1646. def __enter__(self):
  1647. for mod in self.modules:
  1648. if hasattr(mod, '__warningregistry__'):
  1649. mod_reg = mod.__warningregistry__
  1650. self._warnreg_copies[mod] = mod_reg.copy()
  1651. mod_reg.clear()
  1652. return super(clear_and_catch_warnings, self).__enter__()
  1653. def __exit__(self, *exc_info):
  1654. super(clear_and_catch_warnings, self).__exit__(*exc_info)
  1655. for mod in self.modules:
  1656. if hasattr(mod, '__warningregistry__'):
  1657. mod.__warningregistry__.clear()
  1658. if mod in self._warnreg_copies:
  1659. mod.__warningregistry__.update(self._warnreg_copies[mod])
  1660. class suppress_warnings(object):
  1661. """
  1662. Context manager and decorator doing much the same as
  1663. ``warnings.catch_warnings``.
  1664. However, it also provides a filter mechanism to work around
  1665. https://bugs.python.org/issue4180.
  1666. This bug causes Python before 3.4 to not reliably show warnings again
  1667. after they have been ignored once (even within catch_warnings). It
  1668. means that no "ignore" filter can be used easily, since following
  1669. tests might need to see the warning. Additionally it allows easier
  1670. specificity for testing warnings and can be nested.
  1671. Parameters
  1672. ----------
  1673. forwarding_rule : str, optional
  1674. One of "always", "once", "module", or "location". Analogous to
  1675. the usual warnings module filter mode, it is useful to reduce
  1676. noise mostly on the outmost level. Unsuppressed and unrecorded
  1677. warnings will be forwarded based on this rule. Defaults to "always".
  1678. "location" is equivalent to the warnings "default", match by exact
  1679. location the warning warning originated from.
  1680. Notes
  1681. -----
  1682. Filters added inside the context manager will be discarded again
  1683. when leaving it. Upon entering all filters defined outside a
  1684. context will be applied automatically.
  1685. When a recording filter is added, matching warnings are stored in the
  1686. ``log`` attribute as well as in the list returned by ``record``.
  1687. If filters are added and the ``module`` keyword is given, the
  1688. warning registry of this module will additionally be cleared when
  1689. applying it, entering the context, or exiting it. This could cause
  1690. warnings to appear a second time after leaving the context if they
  1691. were configured to be printed once (default) and were already
  1692. printed before the context was entered.
  1693. Nesting this context manager will work as expected when the
  1694. forwarding rule is "always" (default). Unfiltered and unrecorded
  1695. warnings will be passed out and be matched by the outer level.
  1696. On the outmost level they will be printed (or caught by another
  1697. warnings context). The forwarding rule argument can modify this
  1698. behaviour.
  1699. Like ``catch_warnings`` this context manager is not threadsafe.
  1700. Examples
  1701. --------
  1702. With a context manager::
  1703. with np.testing.suppress_warnings() as sup:
  1704. sup.filter(DeprecationWarning, "Some text")
  1705. sup.filter(module=np.ma.core)
  1706. log = sup.record(FutureWarning, "Does this occur?")
  1707. command_giving_warnings()
  1708. # The FutureWarning was given once, the filtered warnings were
  1709. # ignored. All other warnings abide outside settings (may be
  1710. # printed/error)
  1711. assert_(len(log) == 1)
  1712. assert_(len(sup.log) == 1) # also stored in log attribute
  1713. Or as a decorator::
  1714. sup = np.testing.suppress_warnings()
  1715. sup.filter(module=np.ma.core) # module must match exactly
  1716. @sup
  1717. def some_function():
  1718. # do something which causes a warning in np.ma.core
  1719. pass
  1720. """
  1721. def __init__(self, forwarding_rule="always"):
  1722. self._entered = False
  1723. # Suppressions are either instance or defined inside one with block:
  1724. self._suppressions = []
  1725. if forwarding_rule not in {"always", "module", "once", "location"}:
  1726. raise ValueError("unsupported forwarding rule.")
  1727. self._forwarding_rule = forwarding_rule
  1728. def _clear_registries(self):
  1729. if hasattr(warnings, "_filters_mutated"):
  1730. # clearing the registry should not be necessary on new pythons,
  1731. # instead the filters should be mutated.
  1732. warnings._filters_mutated()
  1733. return
  1734. # Simply clear the registry, this should normally be harmless,
  1735. # note that on new pythons it would be invalidated anyway.
  1736. for module in self._tmp_modules:
  1737. if hasattr(module, "__warningregistry__"):
  1738. module.__warningregistry__.clear()
  1739. def _filter(self, category=Warning, message="", module=None, record=False):
  1740. if record:
  1741. record = [] # The log where to store warnings
  1742. else:
  1743. record = None
  1744. if self._entered:
  1745. if module is None:
  1746. warnings.filterwarnings(
  1747. "always", category=category, message=message)
  1748. else:
  1749. module_regex = module.__name__.replace('.', r'\.') + '$'
  1750. warnings.filterwarnings(
  1751. "always", category=category, message=message,
  1752. module=module_regex)
  1753. self._tmp_modules.add(module)
  1754. self._clear_registries()
  1755. self._tmp_suppressions.append(
  1756. (category, message, re.compile(message, re.I), module, record))
  1757. else:
  1758. self._suppressions.append(
  1759. (category, message, re.compile(message, re.I), module, record))
  1760. return record
  1761. def filter(self, category=Warning, message="", module=None):
  1762. """
  1763. Add a new suppressing filter or apply it if the state is entered.
  1764. Parameters
  1765. ----------
  1766. category : class, optional
  1767. Warning class to filter
  1768. message : string, optional
  1769. Regular expression matching the warning message.
  1770. module : module, optional
  1771. Module to filter for. Note that the module (and its file)
  1772. must match exactly and cannot be a submodule. This may make
  1773. it unreliable for external modules.
  1774. Notes
  1775. -----
  1776. When added within a context, filters are only added inside
  1777. the context and will be forgotten when the context is exited.
  1778. """
  1779. self._filter(category=category, message=message, module=module,
  1780. record=False)
  1781. def record(self, category=Warning, message="", module=None):
  1782. """
  1783. Append a new recording filter or apply it if the state is entered.
  1784. All warnings matching will be appended to the ``log`` attribute.
  1785. Parameters
  1786. ----------
  1787. category : class, optional
  1788. Warning class to filter
  1789. message : string, optional
  1790. Regular expression matching the warning message.
  1791. module : module, optional
  1792. Module to filter for. Note that the module (and its file)
  1793. must match exactly and cannot be a submodule. This may make
  1794. it unreliable for external modules.
  1795. Returns
  1796. -------
  1797. log : list
  1798. A list which will be filled with all matched warnings.
  1799. Notes
  1800. -----
  1801. When added within a context, filters are only added inside
  1802. the context and will be forgotten when the context is exited.
  1803. """
  1804. return self._filter(category=category, message=message, module=module,
  1805. record=True)
  1806. def __enter__(self):
  1807. if self._entered:
  1808. raise RuntimeError("cannot enter suppress_warnings twice.")
  1809. self._orig_show = warnings.showwarning
  1810. self._filters = warnings.filters
  1811. warnings.filters = self._filters[:]
  1812. self._entered = True
  1813. self._tmp_suppressions = []
  1814. self._tmp_modules = set()
  1815. self._forwarded = set()
  1816. self.log = [] # reset global log (no need to keep same list)
  1817. for cat, mess, _, mod, log in self._suppressions:
  1818. if log is not None:
  1819. del log[:] # clear the log
  1820. if mod is None:
  1821. warnings.filterwarnings(
  1822. "always", category=cat, message=mess)
  1823. else:
  1824. module_regex = mod.__name__.replace('.', r'\.') + '$'
  1825. warnings.filterwarnings(
  1826. "always", category=cat, message=mess,
  1827. module=module_regex)
  1828. self._tmp_modules.add(mod)
  1829. warnings.showwarning = self._showwarning
  1830. self._clear_registries()
  1831. return self
  1832. def __exit__(self, *exc_info):
  1833. warnings.showwarning = self._orig_show
  1834. warnings.filters = self._filters
  1835. self._clear_registries()
  1836. self._entered = False
  1837. del self._orig_show
  1838. del self._filters
  1839. def _showwarning(self, message, category, filename, lineno,
  1840. *args, **kwargs):
  1841. use_warnmsg = kwargs.pop("use_warnmsg", None)
  1842. for cat, _, pattern, mod, rec in (
  1843. self._suppressions + self._tmp_suppressions)[::-1]:
  1844. if (issubclass(category, cat) and
  1845. pattern.match(message.args[0]) is not None):
  1846. if mod is None:
  1847. # Message and category match, either recorded or ignored
  1848. if rec is not None:
  1849. msg = WarningMessage(message, category, filename,
  1850. lineno, **kwargs)
  1851. self.log.append(msg)
  1852. rec.append(msg)
  1853. return
  1854. # Use startswith, because warnings strips the c or o from
  1855. # .pyc/.pyo files.
  1856. elif mod.__file__.startswith(filename):
  1857. # The message and module (filename) match
  1858. if rec is not None:
  1859. msg = WarningMessage(message, category, filename,
  1860. lineno, **kwargs)
  1861. self.log.append(msg)
  1862. rec.append(msg)
  1863. return
  1864. # There is no filter in place, so pass to the outside handler
  1865. # unless we should only pass it once
  1866. if self._forwarding_rule == "always":
  1867. if use_warnmsg is None:
  1868. self._orig_show(message, category, filename, lineno,
  1869. *args, **kwargs)
  1870. else:
  1871. self._orig_showmsg(use_warnmsg)
  1872. return
  1873. if self._forwarding_rule == "once":
  1874. signature = (message.args, category)
  1875. elif self._forwarding_rule == "module":
  1876. signature = (message.args, category, filename)
  1877. elif self._forwarding_rule == "location":
  1878. signature = (message.args, category, filename, lineno)
  1879. if signature in self._forwarded:
  1880. return
  1881. self._forwarded.add(signature)
  1882. if use_warnmsg is None:
  1883. self._orig_show(message, category, filename, lineno, *args,
  1884. **kwargs)
  1885. else:
  1886. self._orig_showmsg(use_warnmsg)
  1887. def __call__(self, func):
  1888. """
  1889. Function decorator to apply certain suppressions to a whole
  1890. function.
  1891. """
  1892. @wraps(func)
  1893. def new_func(*args, **kwargs):
  1894. with self:
  1895. return func(*args, **kwargs)
  1896. return new_func
  1897. @contextlib.contextmanager
  1898. def _assert_no_gc_cycles_context(name=None):
  1899. __tracebackhide__ = True # Hide traceback for py.test
  1900. # not meaningful to test if there is no refcounting
  1901. if not HAS_REFCOUNT:
  1902. yield
  1903. return
  1904. assert_(gc.isenabled())
  1905. gc.disable()
  1906. gc_debug = gc.get_debug()
  1907. try:
  1908. for i in range(100):
  1909. if gc.collect() == 0:
  1910. break
  1911. else:
  1912. raise RuntimeError(
  1913. "Unable to fully collect garbage - perhaps a __del__ method is "
  1914. "creating more reference cycles?")
  1915. gc.set_debug(gc.DEBUG_SAVEALL)
  1916. yield
  1917. # gc.collect returns the number of unreachable objects in cycles that
  1918. # were found -- we are checking that no cycles were created in the context
  1919. n_objects_in_cycles = gc.collect()
  1920. objects_in_cycles = gc.garbage[:]
  1921. finally:
  1922. del gc.garbage[:]
  1923. gc.set_debug(gc_debug)
  1924. gc.enable()
  1925. if n_objects_in_cycles:
  1926. name_str = " when calling %s" % name if name is not None else ""
  1927. raise AssertionError(
  1928. "Reference cycles were found{}: {} objects were collected, "
  1929. "of which {} are shown below:{}"
  1930. .format(
  1931. name_str,
  1932. n_objects_in_cycles,
  1933. len(objects_in_cycles),
  1934. ''.join(
  1935. "\n {} object with id={}:\n {}".format(
  1936. type(o).__name__,
  1937. id(o),
  1938. pprint.pformat(o).replace('\n', '\n ')
  1939. ) for o in objects_in_cycles
  1940. )
  1941. )
  1942. )
  1943. def assert_no_gc_cycles(*args, **kwargs):
  1944. """
  1945. Fail if the given callable produces any reference cycles.
  1946. If called with all arguments omitted, may be used as a context manager:
  1947. with assert_no_gc_cycles():
  1948. do_something()
  1949. .. versionadded:: 1.15.0
  1950. Parameters
  1951. ----------
  1952. func : callable
  1953. The callable to test.
  1954. \\*args : Arguments
  1955. Arguments passed to `func`.
  1956. \\*\\*kwargs : Kwargs
  1957. Keyword arguments passed to `func`.
  1958. Returns
  1959. -------
  1960. Nothing. The result is deliberately discarded to ensure that all cycles
  1961. are found.
  1962. """
  1963. if not args:
  1964. return _assert_no_gc_cycles_context()
  1965. func = args[0]
  1966. args = args[1:]
  1967. with _assert_no_gc_cycles_context(name=func.__name__):
  1968. func(*args, **kwargs)
  1969. def break_cycles():
  1970. """
  1971. Break reference cycles by calling gc.collect
  1972. Objects can call other objects' methods (for instance, another object's
  1973. __del__) inside their own __del__. On PyPy, the interpreter only runs
  1974. between calls to gc.collect, so multiple calls are needed to completely
  1975. release all cycles.
  1976. """
  1977. gc.collect()
  1978. if IS_PYPY:
  1979. # interpreter runs now, to call deleted objects' __del__ methods
  1980. gc.collect()
  1981. # one more, just to make sure
  1982. gc.collect()
  1983. def requires_memory(free_bytes):
  1984. """Decorator to skip a test if not enough memory is available"""
  1985. import pytest
  1986. def decorator(func):
  1987. @wraps(func)
  1988. def wrapper(*a, **kw):
  1989. msg = check_free_memory(free_bytes)
  1990. if msg is not None:
  1991. pytest.skip(msg)
  1992. try:
  1993. return func(*a, **kw)
  1994. except MemoryError:
  1995. # Probably ran out of memory regardless: don't regard as failure
  1996. pytest.xfail("MemoryError raised")
  1997. return wrapper
  1998. return decorator
  1999. def check_free_memory(free_bytes):
  2000. """
  2001. Check whether `free_bytes` amount of memory is currently free.
  2002. Returns: None if enough memory available, otherwise error message
  2003. """
  2004. env_var = 'NPY_AVAILABLE_MEM'
  2005. env_value = os.environ.get(env_var)
  2006. if env_value is not None:
  2007. try:
  2008. mem_free = _parse_size(env_value)
  2009. except ValueError as exc:
  2010. raise ValueError('Invalid environment variable {}: {!s}'.format(
  2011. env_var, exc))
  2012. msg = ('{0} GB memory required, but environment variable '
  2013. 'NPY_AVAILABLE_MEM={1} set'.format(
  2014. free_bytes/1e9, env_value))
  2015. else:
  2016. mem_free = _get_mem_available()
  2017. if mem_free is None:
  2018. msg = ("Could not determine available memory; set NPY_AVAILABLE_MEM "
  2019. "environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run "
  2020. "the test.")
  2021. mem_free = -1
  2022. else:
  2023. msg = '{0} GB memory required, but {1} GB available'.format(
  2024. free_bytes/1e9, mem_free/1e9)
  2025. return msg if mem_free < free_bytes else None
  2026. def _parse_size(size_str):
  2027. """Convert memory size strings ('12 GB' etc.) to float"""
  2028. suffixes = {'': 1, 'b': 1,
  2029. 'k': 1000, 'm': 1000**2, 'g': 1000**3, 't': 1000**4,
  2030. 'kb': 1000, 'mb': 1000**2, 'gb': 1000**3, 'tb': 1000**4,
  2031. 'kib': 1024, 'mib': 1024**2, 'gib': 1024**3, 'tib': 1024**4}
  2032. size_re = re.compile(r'^\s*(\d+|\d+\.\d+)\s*({0})\s*$'.format(
  2033. '|'.join(suffixes.keys())), re.I)
  2034. m = size_re.match(size_str.lower())
  2035. if not m or m.group(2) not in suffixes:
  2036. raise ValueError("value {!r} not a valid size".format(size_str))
  2037. return int(float(m.group(1)) * suffixes[m.group(2)])
  2038. def _get_mem_available():
  2039. """Return available memory in bytes, or None if unknown."""
  2040. try:
  2041. import psutil
  2042. return psutil.virtual_memory().available
  2043. except (ImportError, AttributeError):
  2044. pass
  2045. if sys.platform.startswith('linux'):
  2046. info = {}
  2047. with open('/proc/meminfo', 'r') as f:
  2048. for line in f:
  2049. p = line.split()
  2050. info[p[0].strip(':').lower()] = int(p[1]) * 1024
  2051. if 'memavailable' in info:
  2052. # Linux >= 3.14
  2053. return info['memavailable']
  2054. else:
  2055. return info['memfree'] + info['cached']
  2056. return None
  2057. def _no_tracing(func):
  2058. """
  2059. Decorator to temporarily turn off tracing for the duration of a test.
  2060. Needed in tests that check refcounting, otherwise the tracing itself
  2061. influences the refcounts
  2062. """
  2063. if not hasattr(sys, 'gettrace'):
  2064. return func
  2065. else:
  2066. @wraps(func)
  2067. def wrapper(*args, **kwargs):
  2068. original_trace = sys.gettrace()
  2069. try:
  2070. sys.settrace(None)
  2071. return func(*args, **kwargs)
  2072. finally:
  2073. sys.settrace(original_trace)
  2074. return wrapper