utils.py 83 KB

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