_ufunc_config.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. """
  2. Functions for changing global ufunc configuration
  3. This provides helpers which wrap `umath.geterrobj` and `umath.seterrobj`
  4. """
  5. import collections.abc
  6. import contextlib
  7. from .overrides import set_module
  8. from .umath import (
  9. UFUNC_BUFSIZE_DEFAULT,
  10. ERR_IGNORE, ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG, ERR_DEFAULT,
  11. SHIFT_DIVIDEBYZERO, SHIFT_OVERFLOW, SHIFT_UNDERFLOW, SHIFT_INVALID,
  12. )
  13. from . import umath
  14. __all__ = [
  15. "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall",
  16. "errstate",
  17. ]
  18. _errdict = {"ignore": ERR_IGNORE,
  19. "warn": ERR_WARN,
  20. "raise": ERR_RAISE,
  21. "call": ERR_CALL,
  22. "print": ERR_PRINT,
  23. "log": ERR_LOG}
  24. _errdict_rev = {value: key for key, value in _errdict.items()}
  25. @set_module('numpy')
  26. def seterr(all=None, divide=None, over=None, under=None, invalid=None):
  27. """
  28. Set how floating-point errors are handled.
  29. Note that operations on integer scalar types (such as `int16`) are
  30. handled like floating point, and are affected by these settings.
  31. Parameters
  32. ----------
  33. all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
  34. Set treatment for all types of floating-point errors at once:
  35. - ignore: Take no action when the exception occurs.
  36. - warn: Print a `RuntimeWarning` (via the Python `warnings` module).
  37. - raise: Raise a `FloatingPointError`.
  38. - call: Call a function specified using the `seterrcall` function.
  39. - print: Print a warning directly to ``stdout``.
  40. - log: Record error in a Log object specified by `seterrcall`.
  41. The default is not to change the current behavior.
  42. divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
  43. Treatment for division by zero.
  44. over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
  45. Treatment for floating-point overflow.
  46. under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
  47. Treatment for floating-point underflow.
  48. invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
  49. Treatment for invalid floating-point operation.
  50. Returns
  51. -------
  52. old_settings : dict
  53. Dictionary containing the old settings.
  54. See also
  55. --------
  56. seterrcall : Set a callback function for the 'call' mode.
  57. geterr, geterrcall, errstate
  58. Notes
  59. -----
  60. The floating-point exceptions are defined in the IEEE 754 standard [1]_:
  61. - Division by zero: infinite result obtained from finite numbers.
  62. - Overflow: result too large to be expressed.
  63. - Underflow: result so close to zero that some precision
  64. was lost.
  65. - Invalid operation: result is not an expressible number, typically
  66. indicates that a NaN was produced.
  67. .. [1] https://en.wikipedia.org/wiki/IEEE_754
  68. Examples
  69. --------
  70. >>> old_settings = np.seterr(all='ignore') #seterr to known value
  71. >>> np.seterr(over='raise')
  72. {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
  73. >>> np.seterr(**old_settings) # reset to default
  74. {'divide': 'ignore', 'over': 'raise', 'under': 'ignore', 'invalid': 'ignore'}
  75. >>> np.int16(32000) * np.int16(3)
  76. 30464
  77. >>> old_settings = np.seterr(all='warn', over='raise')
  78. >>> np.int16(32000) * np.int16(3)
  79. Traceback (most recent call last):
  80. File "<stdin>", line 1, in <module>
  81. FloatingPointError: overflow encountered in short_scalars
  82. >>> from collections import OrderedDict
  83. >>> old_settings = np.seterr(all='print')
  84. >>> OrderedDict(np.geterr())
  85. OrderedDict([('divide', 'print'), ('over', 'print'), ('under', 'print'), ('invalid', 'print')])
  86. >>> np.int16(32000) * np.int16(3)
  87. 30464
  88. """
  89. pyvals = umath.geterrobj()
  90. old = geterr()
  91. if divide is None:
  92. divide = all or old['divide']
  93. if over is None:
  94. over = all or old['over']
  95. if under is None:
  96. under = all or old['under']
  97. if invalid is None:
  98. invalid = all or old['invalid']
  99. maskvalue = ((_errdict[divide] << SHIFT_DIVIDEBYZERO) +
  100. (_errdict[over] << SHIFT_OVERFLOW) +
  101. (_errdict[under] << SHIFT_UNDERFLOW) +
  102. (_errdict[invalid] << SHIFT_INVALID))
  103. pyvals[1] = maskvalue
  104. umath.seterrobj(pyvals)
  105. return old
  106. @set_module('numpy')
  107. def geterr():
  108. """
  109. Get the current way of handling floating-point errors.
  110. Returns
  111. -------
  112. res : dict
  113. A dictionary with keys "divide", "over", "under", and "invalid",
  114. whose values are from the strings "ignore", "print", "log", "warn",
  115. "raise", and "call". The keys represent possible floating-point
  116. exceptions, and the values define how these exceptions are handled.
  117. See Also
  118. --------
  119. geterrcall, seterr, seterrcall
  120. Notes
  121. -----
  122. For complete documentation of the types of floating-point exceptions and
  123. treatment options, see `seterr`.
  124. Examples
  125. --------
  126. >>> from collections import OrderedDict
  127. >>> sorted(np.geterr().items())
  128. [('divide', 'warn'), ('invalid', 'warn'), ('over', 'warn'), ('under', 'ignore')]
  129. >>> np.arange(3.) / np.arange(3.)
  130. array([nan, 1., 1.])
  131. >>> oldsettings = np.seterr(all='warn', over='raise')
  132. >>> OrderedDict(sorted(np.geterr().items()))
  133. OrderedDict([('divide', 'warn'), ('invalid', 'warn'), ('over', 'raise'), ('under', 'warn')])
  134. >>> np.arange(3.) / np.arange(3.)
  135. array([nan, 1., 1.])
  136. """
  137. maskvalue = umath.geterrobj()[1]
  138. mask = 7
  139. res = {}
  140. val = (maskvalue >> SHIFT_DIVIDEBYZERO) & mask
  141. res['divide'] = _errdict_rev[val]
  142. val = (maskvalue >> SHIFT_OVERFLOW) & mask
  143. res['over'] = _errdict_rev[val]
  144. val = (maskvalue >> SHIFT_UNDERFLOW) & mask
  145. res['under'] = _errdict_rev[val]
  146. val = (maskvalue >> SHIFT_INVALID) & mask
  147. res['invalid'] = _errdict_rev[val]
  148. return res
  149. @set_module('numpy')
  150. def setbufsize(size):
  151. """
  152. Set the size of the buffer used in ufuncs.
  153. Parameters
  154. ----------
  155. size : int
  156. Size of buffer.
  157. """
  158. if size > 10e6:
  159. raise ValueError("Buffer size, %s, is too big." % size)
  160. if size < 5:
  161. raise ValueError("Buffer size, %s, is too small." % size)
  162. if size % 16 != 0:
  163. raise ValueError("Buffer size, %s, is not a multiple of 16." % size)
  164. pyvals = umath.geterrobj()
  165. old = getbufsize()
  166. pyvals[0] = size
  167. umath.seterrobj(pyvals)
  168. return old
  169. @set_module('numpy')
  170. def getbufsize():
  171. """
  172. Return the size of the buffer used in ufuncs.
  173. Returns
  174. -------
  175. getbufsize : int
  176. Size of ufunc buffer in bytes.
  177. """
  178. return umath.geterrobj()[0]
  179. @set_module('numpy')
  180. def seterrcall(func):
  181. """
  182. Set the floating-point error callback function or log object.
  183. There are two ways to capture floating-point error messages. The first
  184. is to set the error-handler to 'call', using `seterr`. Then, set
  185. the function to call using this function.
  186. The second is to set the error-handler to 'log', using `seterr`.
  187. Floating-point errors then trigger a call to the 'write' method of
  188. the provided object.
  189. Parameters
  190. ----------
  191. func : callable f(err, flag) or object with write method
  192. Function to call upon floating-point errors ('call'-mode) or
  193. object whose 'write' method is used to log such message ('log'-mode).
  194. The call function takes two arguments. The first is a string describing
  195. the type of error (such as "divide by zero", "overflow", "underflow",
  196. or "invalid value"), and the second is the status flag. The flag is a
  197. byte, whose four least-significant bits indicate the type of error, one
  198. of "divide", "over", "under", "invalid"::
  199. [0 0 0 0 divide over under invalid]
  200. In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
  201. If an object is provided, its write method should take one argument,
  202. a string.
  203. Returns
  204. -------
  205. h : callable, log instance or None
  206. The old error handler.
  207. See Also
  208. --------
  209. seterr, geterr, geterrcall
  210. Examples
  211. --------
  212. Callback upon error:
  213. >>> def err_handler(type, flag):
  214. ... print("Floating point error (%s), with flag %s" % (type, flag))
  215. ...
  216. >>> saved_handler = np.seterrcall(err_handler)
  217. >>> save_err = np.seterr(all='call')
  218. >>> from collections import OrderedDict
  219. >>> np.array([1, 2, 3]) / 0.0
  220. Floating point error (divide by zero), with flag 1
  221. array([inf, inf, inf])
  222. >>> np.seterrcall(saved_handler)
  223. <function err_handler at 0x...>
  224. >>> OrderedDict(sorted(np.seterr(**save_err).items()))
  225. OrderedDict([('divide', 'call'), ('invalid', 'call'), ('over', 'call'), ('under', 'call')])
  226. Log error message:
  227. >>> class Log:
  228. ... def write(self, msg):
  229. ... print("LOG: %s" % msg)
  230. ...
  231. >>> log = Log()
  232. >>> saved_handler = np.seterrcall(log)
  233. >>> save_err = np.seterr(all='log')
  234. >>> np.array([1, 2, 3]) / 0.0
  235. LOG: Warning: divide by zero encountered in true_divide
  236. array([inf, inf, inf])
  237. >>> np.seterrcall(saved_handler)
  238. <numpy.core.numeric.Log object at 0x...>
  239. >>> OrderedDict(sorted(np.seterr(**save_err).items()))
  240. OrderedDict([('divide', 'log'), ('invalid', 'log'), ('over', 'log'), ('under', 'log')])
  241. """
  242. if func is not None and not isinstance(func, collections.abc.Callable):
  243. if (not hasattr(func, 'write') or
  244. not isinstance(func.write, collections.abc.Callable)):
  245. raise ValueError("Only callable can be used as callback")
  246. pyvals = umath.geterrobj()
  247. old = geterrcall()
  248. pyvals[2] = func
  249. umath.seterrobj(pyvals)
  250. return old
  251. @set_module('numpy')
  252. def geterrcall():
  253. """
  254. Return the current callback function used on floating-point errors.
  255. When the error handling for a floating-point error (one of "divide",
  256. "over", "under", or "invalid") is set to 'call' or 'log', the function
  257. that is called or the log instance that is written to is returned by
  258. `geterrcall`. This function or log instance has been set with
  259. `seterrcall`.
  260. Returns
  261. -------
  262. errobj : callable, log instance or None
  263. The current error handler. If no handler was set through `seterrcall`,
  264. ``None`` is returned.
  265. See Also
  266. --------
  267. seterrcall, seterr, geterr
  268. Notes
  269. -----
  270. For complete documentation of the types of floating-point exceptions and
  271. treatment options, see `seterr`.
  272. Examples
  273. --------
  274. >>> np.geterrcall() # we did not yet set a handler, returns None
  275. >>> oldsettings = np.seterr(all='call')
  276. >>> def err_handler(type, flag):
  277. ... print("Floating point error (%s), with flag %s" % (type, flag))
  278. >>> oldhandler = np.seterrcall(err_handler)
  279. >>> np.array([1, 2, 3]) / 0.0
  280. Floating point error (divide by zero), with flag 1
  281. array([inf, inf, inf])
  282. >>> cur_handler = np.geterrcall()
  283. >>> cur_handler is err_handler
  284. True
  285. """
  286. return umath.geterrobj()[2]
  287. class _unspecified:
  288. pass
  289. _Unspecified = _unspecified()
  290. @set_module('numpy')
  291. class errstate(contextlib.ContextDecorator):
  292. """
  293. errstate(**kwargs)
  294. Context manager for floating-point error handling.
  295. Using an instance of `errstate` as a context manager allows statements in
  296. that context to execute with a known error handling behavior. Upon entering
  297. the context the error handling is set with `seterr` and `seterrcall`, and
  298. upon exiting it is reset to what it was before.
  299. .. versionchanged:: 1.17.0
  300. `errstate` is also usable as a function decorator, saving
  301. a level of indentation if an entire function is wrapped.
  302. See :py:class:`contextlib.ContextDecorator` for more information.
  303. Parameters
  304. ----------
  305. kwargs : {divide, over, under, invalid}
  306. Keyword arguments. The valid keywords are the possible floating-point
  307. exceptions. Each keyword should have a string value that defines the
  308. treatment for the particular error. Possible values are
  309. {'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
  310. See Also
  311. --------
  312. seterr, geterr, seterrcall, geterrcall
  313. Notes
  314. -----
  315. For complete documentation of the types of floating-point exceptions and
  316. treatment options, see `seterr`.
  317. Examples
  318. --------
  319. >>> from collections import OrderedDict
  320. >>> olderr = np.seterr(all='ignore') # Set error handling to known state.
  321. >>> np.arange(3) / 0.
  322. array([nan, inf, inf])
  323. >>> with np.errstate(divide='warn'):
  324. ... np.arange(3) / 0.
  325. array([nan, inf, inf])
  326. >>> np.sqrt(-1)
  327. nan
  328. >>> with np.errstate(invalid='raise'):
  329. ... np.sqrt(-1)
  330. Traceback (most recent call last):
  331. File "<stdin>", line 2, in <module>
  332. FloatingPointError: invalid value encountered in sqrt
  333. Outside the context the error handling behavior has not changed:
  334. >>> OrderedDict(sorted(np.geterr().items()))
  335. OrderedDict([('divide', 'ignore'), ('invalid', 'ignore'), ('over', 'ignore'), ('under', 'ignore')])
  336. """
  337. def __init__(self, *, call=_Unspecified, **kwargs):
  338. self.call = call
  339. self.kwargs = kwargs
  340. def __enter__(self):
  341. self.oldstate = seterr(**self.kwargs)
  342. if self.call is not _Unspecified:
  343. self.oldcall = seterrcall(self.call)
  344. def __exit__(self, *exc_info):
  345. seterr(**self.oldstate)
  346. if self.call is not _Unspecified:
  347. seterrcall(self.oldcall)
  348. def _setdef():
  349. defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT, None]
  350. umath.seterrobj(defval)
  351. # set the default values
  352. _setdef()