utils.py 86 KB

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