utils.py 93 KB

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