utils.py 83 KB

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