utils.py 76 KB

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