ufunclike.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. """
  2. Module of functions that are like ufuncs in acting on arrays and optionally
  3. storing results in an output array.
  4. """
  5. __all__ = ['fix', 'isneginf', 'isposinf']
  6. import numpy.core.numeric as nx
  7. from numpy.core.overrides import (
  8. array_function_dispatch, ARRAY_FUNCTION_ENABLED,
  9. )
  10. import warnings
  11. import functools
  12. def _deprecate_out_named_y(f):
  13. """
  14. Allow the out argument to be passed as the name `y` (deprecated)
  15. In future, this decorator should be removed.
  16. """
  17. @functools.wraps(f)
  18. def func(x, out=None, **kwargs):
  19. if 'y' in kwargs:
  20. if 'out' in kwargs:
  21. raise TypeError(
  22. "{} got multiple values for argument 'out'/'y'"
  23. .format(f.__name__)
  24. )
  25. out = kwargs.pop('y')
  26. # NumPy 1.13.0, 2017-04-26
  27. warnings.warn(
  28. "The name of the out argument to {} has changed from `y` to "
  29. "`out`, to match other ufuncs.".format(f.__name__),
  30. DeprecationWarning, stacklevel=3)
  31. return f(x, out=out, **kwargs)
  32. return func
  33. def _fix_out_named_y(f):
  34. """
  35. Allow the out argument to be passed as the name `y` (deprecated)
  36. This decorator should only be used if _deprecate_out_named_y is used on
  37. a corresponding dispatcher function.
  38. """
  39. @functools.wraps(f)
  40. def func(x, out=None, **kwargs):
  41. if 'y' in kwargs:
  42. # we already did error checking in _deprecate_out_named_y
  43. out = kwargs.pop('y')
  44. return f(x, out=out, **kwargs)
  45. return func
  46. def _fix_and_maybe_deprecate_out_named_y(f):
  47. """
  48. Use the appropriate decorator, depending upon if dispatching is being used.
  49. """
  50. if ARRAY_FUNCTION_ENABLED:
  51. return _fix_out_named_y(f)
  52. else:
  53. return _deprecate_out_named_y(f)
  54. @_deprecate_out_named_y
  55. def _dispatcher(x, out=None):
  56. return (x, out)
  57. @array_function_dispatch(_dispatcher, verify=False, module='numpy')
  58. @_fix_and_maybe_deprecate_out_named_y
  59. def fix(x, out=None):
  60. """
  61. Round to nearest integer towards zero.
  62. Round an array of floats element-wise to nearest integer towards zero.
  63. The rounded values are returned as floats.
  64. Parameters
  65. ----------
  66. x : array_like
  67. An array of floats to be rounded
  68. out : ndarray, optional
  69. A location into which the result is stored. If provided, it must have
  70. a shape that the input broadcasts to. If not provided or None, a
  71. freshly-allocated array is returned.
  72. Returns
  73. -------
  74. out : ndarray of floats
  75. A float array with the same dimensions as the input.
  76. If second argument is not supplied then a float array is returned
  77. with the rounded values.
  78. If a second argument is supplied the result is stored there.
  79. The return value `out` is then a reference to that array.
  80. See Also
  81. --------
  82. rint, trunc, floor, ceil
  83. around : Round to given number of decimals
  84. Examples
  85. --------
  86. >>> np.fix(3.14)
  87. 3.0
  88. >>> np.fix(3)
  89. 3.0
  90. >>> np.fix([2.1, 2.9, -2.1, -2.9])
  91. array([ 2., 2., -2., -2.])
  92. """
  93. # promote back to an array if flattened
  94. res = nx.asanyarray(nx.ceil(x, out=out))
  95. res = nx.floor(x, out=res, where=nx.greater_equal(x, 0))
  96. # when no out argument is passed and no subclasses are involved, flatten
  97. # scalars
  98. if out is None and type(res) is nx.ndarray:
  99. res = res[()]
  100. return res
  101. @array_function_dispatch(_dispatcher, verify=False, module='numpy')
  102. @_fix_and_maybe_deprecate_out_named_y
  103. def isposinf(x, out=None):
  104. """
  105. Test element-wise for positive infinity, return result as bool array.
  106. Parameters
  107. ----------
  108. x : array_like
  109. The input array.
  110. out : array_like, optional
  111. A location into which the result is stored. If provided, it must have a
  112. shape that the input broadcasts to. If not provided or None, a
  113. freshly-allocated boolean array is returned.
  114. Returns
  115. -------
  116. out : ndarray
  117. A boolean array with the same dimensions as the input.
  118. If second argument is not supplied then a boolean array is returned
  119. with values True where the corresponding element of the input is
  120. positive infinity and values False where the element of the input is
  121. not positive infinity.
  122. If a second argument is supplied the result is stored there. If the
  123. type of that array is a numeric type the result is represented as zeros
  124. and ones, if the type is boolean then as False and True.
  125. The return value `out` is then a reference to that array.
  126. See Also
  127. --------
  128. isinf, isneginf, isfinite, isnan
  129. Notes
  130. -----
  131. NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
  132. (IEEE 754).
  133. Errors result if the second argument is also supplied when x is a scalar
  134. input, if first and second arguments have different shapes, or if the
  135. first argument has complex values
  136. Examples
  137. --------
  138. >>> np.isposinf(np.PINF)
  139. True
  140. >>> np.isposinf(np.inf)
  141. True
  142. >>> np.isposinf(np.NINF)
  143. False
  144. >>> np.isposinf([-np.inf, 0., np.inf])
  145. array([False, False, True])
  146. >>> x = np.array([-np.inf, 0., np.inf])
  147. >>> y = np.array([2, 2, 2])
  148. >>> np.isposinf(x, y)
  149. array([0, 0, 1])
  150. >>> y
  151. array([0, 0, 1])
  152. """
  153. is_inf = nx.isinf(x)
  154. try:
  155. signbit = ~nx.signbit(x)
  156. except TypeError as e:
  157. dtype = nx.asanyarray(x).dtype
  158. raise TypeError(f'This operation is not supported for {dtype} values '
  159. 'because it would be ambiguous.') from e
  160. else:
  161. return nx.logical_and(is_inf, signbit, out)
  162. @array_function_dispatch(_dispatcher, verify=False, module='numpy')
  163. @_fix_and_maybe_deprecate_out_named_y
  164. def isneginf(x, out=None):
  165. """
  166. Test element-wise for negative infinity, return result as bool array.
  167. Parameters
  168. ----------
  169. x : array_like
  170. The input array.
  171. out : array_like, optional
  172. A location into which the result is stored. If provided, it must have a
  173. shape that the input broadcasts to. If not provided or None, a
  174. freshly-allocated boolean array is returned.
  175. Returns
  176. -------
  177. out : ndarray
  178. A boolean array with the same dimensions as the input.
  179. If second argument is not supplied then a numpy boolean array is
  180. returned with values True where the corresponding element of the
  181. input is negative infinity and values False where the element of
  182. the input is not negative infinity.
  183. If a second argument is supplied the result is stored there. If the
  184. type of that array is a numeric type the result is represented as
  185. zeros and ones, if the type is boolean then as False and True. The
  186. return value `out` is then a reference to that array.
  187. See Also
  188. --------
  189. isinf, isposinf, isnan, isfinite
  190. Notes
  191. -----
  192. NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
  193. (IEEE 754).
  194. Errors result if the second argument is also supplied when x is a scalar
  195. input, if first and second arguments have different shapes, or if the
  196. first argument has complex values.
  197. Examples
  198. --------
  199. >>> np.isneginf(np.NINF)
  200. True
  201. >>> np.isneginf(np.inf)
  202. False
  203. >>> np.isneginf(np.PINF)
  204. False
  205. >>> np.isneginf([-np.inf, 0., np.inf])
  206. array([ True, False, False])
  207. >>> x = np.array([-np.inf, 0., np.inf])
  208. >>> y = np.array([2, 2, 2])
  209. >>> np.isneginf(x, y)
  210. array([1, 0, 0])
  211. >>> y
  212. array([1, 0, 0])
  213. """
  214. is_inf = nx.isinf(x)
  215. try:
  216. signbit = nx.signbit(x)
  217. except TypeError as e:
  218. dtype = nx.asanyarray(x).dtype
  219. raise TypeError(f'This operation is not supported for {dtype} values '
  220. 'because it would be ambiguous.') from e
  221. else:
  222. return nx.logical_and(is_inf, signbit, out)