utils.py 96 KB

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