utils.py 80 KB

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