utils.py 76 KB

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