You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

logic_ops.py 22 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. # Copyright 2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """logical operations, the function docs are adapted from Numpy API."""
  16. from .math_ops import _apply_tensor_op
  17. from ..ops import functional as F
  18. from ..common import dtype as mstype
  19. from .._c_expression import typing
  20. from .array_creations import zeros, ones
  21. from .utils import _check_input_tensor
  22. def not_equal(x1, x2, out=None, where=True, dtype=None):
  23. """
  24. Returns (x1 != x2) element-wise.
  25. Args:
  26. x1 (Tensor): First input tensor to be compared.
  27. x2 (Tensor): Second input tensor to be compared.
  28. out (Tensor or None, optional), default is None.
  29. where (Tensor or None, optional): For any non-default value of type other
  30. than :class:`Tensor` or :class:`None`, the output retains its original value.
  31. This condition is broadcasted over the input. At locations where the
  32. condition is `True`, the out array will be set to the ufunc result.
  33. Elsewhere, the out array will retain its original value. Note that
  34. if an uninitialized out array is created via the default ``out=None``,
  35. locations within it where the condition is `False` will remain
  36. uninitialized.
  37. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  38. output Tensor.
  39. Returns:
  40. Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
  41. bool, unless `dtype` is passed. This is a scalar if both `x1` and `x2` are
  42. scalars.
  43. Raises:
  44. TypeError: If the input is not a tensor.
  45. Supported Platforms:
  46. ``Ascend`` ``GPU`` ``CPU``
  47. Examples:
  48. >>> import mindspore.numpy as np
  49. >>> a = np.asarray([1, 2])
  50. >>> b = np.asarray([[1, 3],[1, 4]])
  51. >>> print(np.not_equal(a, b))
  52. >>> [[False True]
  53. [False True]]
  54. """
  55. _check_input_tensor(x1, x2)
  56. return _apply_tensor_op(F.not_equal, x1, x2, out=out, where=where, dtype=dtype)
  57. def less_equal(x1, x2, out=None, where=True, dtype=None):
  58. """
  59. Returns the truth value of ``(x1 <= x2)`` element-wise.
  60. Note:
  61. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  62. not supported.
  63. When `where` is provided, `out` must have a tensor value. `out` is not supported
  64. for storing the result, however it can be used in combination with `where` to set
  65. the value at indices for which `where` is set to False.
  66. Args:
  67. x1 (Tensor): Input array.
  68. x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
  69. broadcastable to a common shape (which becomes the shape of the output).
  70. out (Tensor or None, optional): defaults to None.
  71. where (Tensor or None, optional): For any non-default value of type other
  72. than :class:`Tensor` or :class:`None`, the output retains its original value.
  73. This condition is broadcasted over the input. At locations where the
  74. condition is `True`, the out array will be set to the ufunc result.
  75. Elsewhere, the out array will retain its original value. Note that
  76. if an uninitialized out array is created via the default ``out=None``,
  77. locations within it where the condition is `False` will remain
  78. uninitialized.
  79. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  80. output Tensor.
  81. Returns:
  82. Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
  83. bool, unless ``dtype=object`` is passed. This is a scalar if both `x1` and `x2` are
  84. scalars.
  85. Raises:
  86. TypeError: if the input is not a tensor.
  87. Supported Platforms:
  88. ``Ascend`` ``GPU`` ``CPU``
  89. Examples:
  90. >>> output = np.less_equal(np.array([4, 2, 1]), np.array([2, 2, 2]))
  91. >>> print(output)
  92. [False True True]
  93. """
  94. _check_input_tensor(x1, x2)
  95. return _apply_tensor_op(F.tensor_le, x1, x2, out=out, where=where, dtype=dtype)
  96. def less(x1, x2, out=None, where=True, dtype=None):
  97. """
  98. Returns the truth value of ``(x1 < x2)`` element-wise.
  99. Note:
  100. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  101. not supported.
  102. When `where` is provided, `out` must have a tensor value. `out` is not supported
  103. for storing the result, however it can be used in combination with `where` to set
  104. the value at indices for which `where` is set to False.
  105. Args:
  106. x1 (Tensor): input array.
  107. x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
  108. broadcastable to a common shape (which becomes the shape of the output).
  109. out (Tensor or None, optional): defaults to None.
  110. where (Tensor or None, optional): For any non-default value of type other
  111. than :class:`Tensor` or :class:`None`, the output retains its original value.
  112. This condition is broadcasted over the input. At locations where the
  113. condition is `True`, the out array will be set to the ufunc result.
  114. Elsewhere, the out array will retain its original value. Note that
  115. if an uninitialized out array is created via the default ``out=None``,
  116. locations within it where the condition is `False` will remain
  117. uninitialized.
  118. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  119. output Tensor.
  120. Returns:
  121. Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
  122. bool, unless ``dtype=object`` is passed. This is a scalar if both `x1` and `x2` are
  123. scalars.
  124. Raises:
  125. TypeError: if the input is not a tensor.
  126. Supported Platforms:
  127. ``Ascend`` ``GPU`` ``CPU``
  128. Examples:
  129. >>> output = np.less(np.array([1, 2]), np.array([2, 2]))
  130. >>> print(output)
  131. [ True False]
  132. """
  133. return _apply_tensor_op(F.tensor_lt, x1, x2, out=out, where=where, dtype=dtype)
  134. def greater_equal(x1, x2, out=None, where=True, dtype=None):
  135. """
  136. Returns the truth value of ``(x1 >= x2)`` element-wise.
  137. Note:
  138. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  139. not supported.
  140. When `where` is provided, `out` must have a tensor value. `out` is not supported
  141. for storing the result, however it can be used in combination with `where` to set
  142. the value at indices for which `where` is set to False.
  143. Args:
  144. x1 (Tensor): Input array.
  145. x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
  146. broadcastable to a common shape (which becomes the shape of the output).
  147. out (Tensor or None, optional): defaults to None.
  148. where (Tensor or None, optional): For any non-default value of type other
  149. than :class:`Tensor` or :class:`None`, the output retains its original value.
  150. This condition is broadcasted over the input. At locations where the
  151. condition is `True`, the out array will be set to the ufunc result.
  152. Elsewhere, the out array will retain its original value. Note that
  153. if an uninitialized out array is created via the default ``out=None``,
  154. locations within it where the condition is `False` will remain
  155. uninitialized.
  156. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  157. output Tensor.
  158. Returns:
  159. Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
  160. bool, unless ``dtype=object`` is passed. This is a scalar if both `x1` and `x2` are
  161. scalars.
  162. Raises:
  163. TypeError: if the input is not a tensor.
  164. Supported Platforms:
  165. ``Ascend`` ``GPU`` ``CPU``
  166. Examples:
  167. >>> output = np.greater_equal(np.array([4, 2, 1]), np.array([2, 2, 2]))
  168. >>> print(output)
  169. [ True True False]
  170. """
  171. return _apply_tensor_op(F.tensor_ge, x1, x2, out=out, where=where, dtype=dtype)
  172. def greater(x1, x2, out=None, where=True, dtype=None):
  173. """
  174. Returns the truth value of ``(x1 > x2)`` element-wise.
  175. Note:
  176. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  177. not supported.
  178. When `where` is provided, `out` must have a tensor value. `out` is not supported
  179. for storing the result, however it can be used in combination with `where` to set
  180. the value at indices for which `where` is set to False.
  181. Args:
  182. x1 (Tensor): Input array.
  183. x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
  184. broadcastable to a common shape (which becomes the shape of the output).
  185. out (Tensor or None, optional): defaults to None.
  186. where (Tensor or None, optional): For any non-default value of type other
  187. than :class:`Tensor` or :class:`None`, the output retains its original value.
  188. This condition is broadcasted over the input. At locations where the
  189. condition is `True`, the out array will be set to the ufunc result.
  190. Elsewhere, the out array will retain its original value. Note that
  191. if an uninitialized out array is created via the default ``out=None``,
  192. locations within it where the condition is `False` will remain
  193. uninitialized.
  194. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  195. output Tensor.
  196. Returns:
  197. Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
  198. bool, unless ``dtype=object`` is passed. This is a scalar if both `x1` and `x2` are
  199. scalars.
  200. Raises:
  201. TypeError: if the input is not a tensor.
  202. Supported Platforms:
  203. ``Ascend`` ``GPU`` ``CPU``
  204. Examples:
  205. >>> output = np.greater(np.array([4, 2]), np.array([2, 2]))
  206. >>> print(output)
  207. [ True False]
  208. """
  209. return _apply_tensor_op(F.tensor_gt, x1, x2, out=out, where=where, dtype=dtype)
  210. def equal(x1, x2, out=None, where=True, dtype=None):
  211. """
  212. Returns the truth value of ``(x1 == x2)`` element-wise.
  213. Note:
  214. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  215. not supported.
  216. When `where` is provided, `out` must have a tensor value. `out` is not supported
  217. for storing the result, however it can be used in combination with `where` to set
  218. the value at indices for which `where` is set to False.
  219. Args:
  220. x1 (Tensor): Input array.
  221. x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
  222. broadcastable to a common shape (which becomes the shape of the output).
  223. out (Tensor or None, optional): defaults to None.
  224. where (Tensor or None, optional): For any non-default value of type other
  225. than :class:`Tensor` or :class:`None`, the output retains its original value.
  226. This condition is broadcasted over the input. At locations where the
  227. condition is `True`, the out array will be set to the ufunc result.
  228. Elsewhere, the out array will retain its original value. Note that
  229. if an uninitialized out array is created via the default ``out=None``,
  230. locations within it where the condition is `False` will remain
  231. uninitialized.
  232. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  233. output Tensor.
  234. Returns:
  235. Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
  236. bool, unless ``dtype=object`` is passed. This is a scalar if both `x1` and `x2` are
  237. scalars.
  238. Raises:
  239. TypeError: if the input is not a tensor.
  240. Supported Platforms:
  241. ``Ascend`` ``GPU`` ``CPU``
  242. Examples:
  243. >>> output = np.equal(np.array([0, 1, 3]), np.arange(3))
  244. >>> print(output)
  245. [ True True False]
  246. """
  247. return _apply_tensor_op(F.equal, x1, x2, out=out, where=where, dtype=dtype)
  248. def isfinite(x, out=None, where=True, dtype=None):
  249. """
  250. Tests element-wise for finiteness (not infinity or not Not a Number).
  251. The result is returned as a boolean array.
  252. Note:
  253. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  254. not supported.
  255. When `where` is provided, `out` must have a tensor value. `out` is not supported
  256. for storing the result, however it can be used in combination with `where` to set
  257. the value at indices for which `where` is set to False.
  258. On GPU, the supported dtypes are np.float16, and np.float32.
  259. Args:
  260. x (Tensor): Input values.
  261. out (Tensor or None, optional): defaults to None.
  262. where (Tensor or None, optional): For any non-default value of type other
  263. than :class:`Tensor` or :class:`None`, the output retains its original value.
  264. This condition is broadcasted over the input. At locations where the
  265. condition is `True`, the out array will be set to the ufunc result.
  266. Elsewhere, the out array will retain its original value. Note that
  267. if an uninitialized out array is created via the default ``out=None``,
  268. locations within it where the condition is `False` will remain
  269. uninitialized.
  270. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  271. output Tensor.
  272. Returns:
  273. Tensor or scalar, true where `x` is not positive infinity, negative infinity,
  274. or NaN; false otherwise. This is a scalar if `x` is a scalar.
  275. Raises:
  276. TypeError: if the input is not a tensor.
  277. Supported Platforms:
  278. ``Ascend`` ``GPU`` ``CPU``
  279. Examples:
  280. >>> output = np.isfinite(np.array([np.inf, 1., np.nan]).astype('float32'))
  281. >>> print(output)
  282. [False True False]
  283. >>> output = np.isfinite(np.log(np.array(-1.).astype('float32')))
  284. >>> print(output)
  285. False
  286. """
  287. return _apply_tensor_op(F.isfinite, x, out=out, where=where, dtype=dtype)
  288. def _isnan(x):
  289. """Computes isnan without applying keyword arguments."""
  290. return F.not_equal(x, x)
  291. def isnan(x, out=None, where=True, dtype=None):
  292. """
  293. Tests element-wise for NaN and return result as a boolean array.
  294. Note:
  295. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  296. not supported.
  297. When `where` is provided, `out` must have a tensor value. `out` is not supported
  298. for storing the result, however it can be used in combination with `where` to set
  299. the value at indices for which `where` is set to False.
  300. Only np.float32 is currently supported.
  301. Args:
  302. x (Tensor): Input values.
  303. out (Tensor or None, optional): defaults to None.
  304. where (Tensor or None, optional): For any non-default value of type other
  305. than :class:`Tensor` or :class:`None`, the output retains its original value.
  306. This condition is broadcasted over the input. At locations where the
  307. condition is `True`, the out array will be set to the ufunc result.
  308. Elsewhere, the out array will retain its original value. Note that
  309. if an uninitialized out array is created via the default ``out=None``,
  310. locations within it where the condition is `False` will remain
  311. uninitialized.
  312. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  313. output Tensor.
  314. Returns:
  315. Tensor or scalar, true where `x` is NaN, false otherwise. This is a scalar if
  316. `x` is a scalar.
  317. Raises:
  318. TypeError: if the input is not a tensor.
  319. Supported Platforms:
  320. ``GPU`` ``CPU``
  321. Examples:
  322. >>> output = np.isnan(np.array(np.nan, np.float32))
  323. >>> print(output)
  324. True
  325. >>> output = np.isnan(np.array(np.inf, np.float32))
  326. >>> print(output)
  327. False
  328. """
  329. return _apply_tensor_op(_isnan, x, out=out, where=where, dtype=dtype)
  330. def _isinf(x):
  331. """Computes isinf without applying keyword arguments."""
  332. shape = F.shape(x)
  333. zeros_tensor = zeros(shape, mstype.float32)
  334. ones_tensor = ones(shape, mstype.float32)
  335. not_inf = F.isfinite(x)
  336. is_nan = _isnan(x)
  337. res = F.select(not_inf, zeros_tensor, ones_tensor)
  338. res = F.select(is_nan, zeros_tensor, res)
  339. return F.cast(res, mstype.bool_)
  340. def isinf(x, out=None, where=True, dtype=None):
  341. """
  342. Tests element-wise for positive or negative infinity.
  343. Returns a boolean array of the same shape as `x`, True where ``x == +/-inf``, otherwise False.
  344. Note:
  345. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  346. not supported.
  347. When `where` is provided, `out` must have a tensor value. `out` is not supported
  348. for storing the result, however it can be used in combination with `where` to set
  349. the value at indices for which `where` is set to False.
  350. Only np.float32 is currently supported.
  351. Args:
  352. x (Tensor): Input values.
  353. out (Tensor or None, optional): defaults to None.
  354. where (Tensor or None, optional): For any non-default value of type other
  355. than :class:`Tensor` or :class:`None`, the output retains its original value.
  356. This condition is broadcasted over the input. At locations where the
  357. condition is `True`, the out array will be set to the ufunc result.
  358. Elsewhere, the out array will retain its original value. Note that
  359. if an uninitialized out array is created via the default ``out=None``,
  360. locations within it where the condition is `False` will remain
  361. uninitialized.
  362. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  363. output Tensor.
  364. Returns:
  365. Tensor or scalar, true where `x` is positive or negative infinity, false
  366. otherwise. This is a scalar if `x` is a scalar.
  367. Raises:
  368. TypeError: if the input is not a tensor.
  369. Supported Platforms:
  370. ``GPU`` ``CPU``
  371. Examples:
  372. >>> output = np.isinf(np.array(np.inf, np.float32))
  373. >>> print(output)
  374. True
  375. >>> output = np.isinf(np.array([np.inf, -np.inf, 1.0, np.nan], np.float32))
  376. >>> print(output)
  377. [ True True False False]
  378. """
  379. return _apply_tensor_op(_isinf, x, out=out, where=where, dtype=dtype)
  380. def _is_sign_inf(x, fn):
  381. """Tests element-wise for inifinity with sign."""
  382. shape = F.shape(x)
  383. zeros_tensor = zeros(shape, mstype.float32)
  384. ones_tensor = ones(shape, mstype.float32)
  385. not_inf = F.isfinite(x)
  386. is_sign = fn(x, zeros_tensor)
  387. res = F.select(not_inf, zeros_tensor, ones_tensor)
  388. res = F.select(is_sign, res, zeros_tensor)
  389. return F.cast(res, mstype.bool_)
  390. def isposinf(x):
  391. """
  392. Tests element-wise for positive infinity, returns result as bool array.
  393. Note:
  394. Numpy argument `out` is not supported.
  395. Only np.float32 is currently supported.
  396. Args:
  397. x (Tensor): Input values.
  398. Returns:
  399. Tensor or scalar, true where `x` is positive infinity, false otherwise.
  400. This is a scalar if `x` is a scalar.
  401. Raises:
  402. TypeError: if the input is not a tensor.
  403. Supported Platforms:
  404. ``GPU`` ``CPU``
  405. Examples:
  406. >>> output = np.isposinf(np.array([-np.inf, 0., np.inf], np.float32))
  407. >>> print(output)
  408. [False False True]
  409. """
  410. _check_input_tensor(x)
  411. return _is_sign_inf(x, F.tensor_gt)
  412. def isneginf(x):
  413. """
  414. Tests element-wise for negative infinity, returns result as bool array.
  415. Note:
  416. Numpy argument `out` is not supported.
  417. Only np.float32 is currently supported.
  418. Args:
  419. x (Tensor): Input values.
  420. Returns:
  421. Tensor or scalar, true where `x` is negative infinity, false otherwise.
  422. This is a scalar if `x` is a scalar.
  423. Raises:
  424. TypeError: if the input is not a tensor.
  425. Supported Platforms:
  426. ``GPU`` ``CPU``
  427. Examples:
  428. >>> output = np.isneginf(np.array([-np.inf, 0., np.inf], np.float32))
  429. >>> print(output)
  430. [ True False False]
  431. """
  432. return _is_sign_inf(x, F.tensor_lt)
  433. def isscalar(element):
  434. """
  435. Returns True if the type of element is a scalar type.
  436. Note:
  437. Only object types recognized by the mindspore parser are supported,
  438. which includes objects, types, methods and functions defined within
  439. the scope of mindspore. Other built-in types are not supported.
  440. Args:
  441. element (any): Input argument, can be of any type and shape.
  442. Returns:
  443. Boolean, True if `element` is a scalar type, False if it is not.
  444. Raises:
  445. TypeError: if the type of `element` is not supported by mindspore parser.
  446. Supported Platforms:
  447. ``Ascend`` ``GPU`` ``CPU``
  448. Examples:
  449. >>> output = np.isscalar(3.1)
  450. >>> print(output)
  451. True
  452. >>> output = np.isscalar(np.array(3.1))
  453. >>> print(output)
  454. False
  455. >>> output = np.isscalar(False)
  456. >>> print(output)
  457. True
  458. >>> output = np.isscalar('numpy')
  459. >>> print(output)
  460. True
  461. """
  462. return isinstance(F.typeof(element), (typing.Number, typing.Int, typing.UInt,
  463. typing.Float, typing.Bool, typing.String))