utils.py 75 KB

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