• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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."""
16from __future__ import absolute_import
17
18from mindspore.ops import functional as F
19from mindspore.common import dtype as mstype
20from mindspore.common import Tensor
21from mindspore.ops import operations as P
22
23from mindspore.numpy.math_ops import _apply_tensor_op
24from mindspore.numpy.array_creations import zeros, ones, asarray
25from mindspore.numpy.utils import _check_input_tensor, _to_tensor, _isnan
26from mindspore.numpy.utils_const import _raise_type_error, _check_same_type, \
27    _check_axis_type, _canonicalize_axis, _can_broadcast, _isscalar
28
29
30def not_equal(x1, x2, dtype=None):
31    """
32    Returns (x1 != x2) element-wise.
33
34    Note:
35        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
36        and `extobj` are not supported.
37
38    Args:
39        x1 (Tensor): First input tensor to be compared.
40        x2 (Tensor): Second input tensor to be compared.
41        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
42            output Tensor.
43
44    Returns:
45       Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
46       bool, unless `dtype` is passed. This is a scalar if both `x1` and `x2` are
47       scalars.
48
49    Raises:
50        TypeError: If the input is not a tensor.
51
52    Supported Platforms:
53        ``Ascend`` ``GPU`` ``CPU``
54
55    Examples:
56        >>> import mindspore.numpy as np
57        >>> a = np.asarray([1, 2])
58        >>> b = np.asarray([[1, 3],[1, 4]])
59        >>> print(np.not_equal(a, b))
60        [[False  True]
61        [False  True]]
62    """
63    _check_input_tensor(x1, x2)
64    return _apply_tensor_op(F.not_equal, x1, x2, dtype=dtype)
65
66
67def less_equal(x1, x2, dtype=None):
68    """
69    Returns the truth value of ``(x1 <= x2)`` element-wise.
70
71    Note:
72        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
73        and `extobj` are not supported.
74
75    Args:
76        x1 (Tensor): Input array.
77        x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
78            broadcastable to a common shape (which becomes the shape of the output).
79        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
80            output Tensor.
81
82    Returns:
83       Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
84       bool, unless `dtype` is passed. This is a scalar if both `x1` and `x2` are
85       scalars.
86
87    Supported Platforms:
88        ``Ascend`` ``GPU`` ``CPU``
89
90    Examples:
91        >>> import mindspore.numpy as np
92        >>> output = np.less_equal(np.array([4, 2, 1]), np.array([2, 2, 2]))
93        >>> print(output)
94        [False  True  True]
95    """
96    _check_input_tensor(x1, x2)
97    return _apply_tensor_op(F.tensor_le, x1, x2, dtype=dtype)
98
99
100def less(x1, x2, dtype=None):
101    """
102    Returns the truth value of ``(x1 < x2)`` element-wise.
103
104    Note:
105        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
106        and `extobj` are not supported.
107
108    Args:
109        x1 (Tensor): input array.
110        x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
111            broadcastable to a common shape (which becomes the shape of the output).
112        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
113            output Tensor.
114
115    Returns:
116       Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
117       bool, unless `dtype` is passed. This is a scalar if both `x1` and `x2` are
118       scalars.
119
120    Supported Platforms:
121        ``Ascend`` ``GPU`` ``CPU``
122
123    Examples:
124        >>> import mindspore.numpy as np
125        >>> output = np.less(np.array([1, 2]), np.array([2, 2]))
126        >>> print(output)
127        [ True False]
128    """
129    return _apply_tensor_op(F.tensor_lt, x1, x2, dtype=dtype)
130
131
132def greater_equal(x1, x2, dtype=None):
133    """
134    Returns the truth value of ``(x1 >= x2)`` element-wise.
135
136    Note:
137        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
138        and `extobj` are not supported.
139
140    Args:
141        x1 (Tensor): Input array.
142        x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
143            broadcastable to a common shape (which becomes the shape of the output).
144        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
145            output Tensor.
146
147    Returns:
148       Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
149       bool, unless `dtype` is passed. This is a scalar if both `x1` and `x2` are
150       scalars.
151
152    Supported Platforms:
153        ``Ascend`` ``GPU`` ``CPU``
154
155    Examples:
156        >>> import mindspore.numpy as np
157        >>> output = np.greater_equal(np.array([4, 2, 1]), np.array([2, 2, 2]))
158        >>> print(output)
159        [ True  True False]
160    """
161    return _apply_tensor_op(F.tensor_ge, x1, x2, dtype=dtype)
162
163
164def greater(x1, x2, dtype=None):
165    """
166    Returns the truth value of ``(x1 > x2)`` element-wise.
167
168    Note:
169        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
170        and `extobj` are not supported.
171
172    Args:
173        x1 (Tensor): Input array.
174        x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
175            broadcastable to a common shape (which becomes the shape of the output).
176        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
177            output Tensor.
178
179    Returns:
180       Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
181       bool, unless `dtype` is passed. This is a scalar if both `x1` and `x2` are
182       scalars.
183
184    Supported Platforms:
185        ``Ascend`` ``GPU`` ``CPU``
186
187    Examples:
188        >>> import mindspore.numpy as np
189        >>> output = np.greater(np.array([4, 2]), np.array([2, 2]))
190        >>> print(output)
191        [ True False]
192    """
193    return _apply_tensor_op(F.tensor_gt, x1, x2, dtype=dtype)
194
195
196def equal(x1, x2, dtype=None):
197    """
198    Returns the truth value of ``(x1 == x2)`` element-wise.
199
200    Note:
201        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
202        and `extobj` are not supported.
203
204    Args:
205        x1 (Tensor): Input array.
206        x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be
207            broadcastable to a common shape (which becomes the shape of the output).
208        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
209            output Tensor.
210
211    Returns:
212       Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
213       bool, unless `dtype` is passed. This is a scalar if both `x1` and `x2` are
214       scalars.
215
216    Supported Platforms:
217        ``Ascend`` ``GPU`` ``CPU``
218
219    Examples:
220        >>> import mindspore.numpy as np
221        >>> output = np.equal(np.array([0, 1, 3]), np.arange(3))
222        >>> print(output)
223        [ True  True False]
224    """
225    return _apply_tensor_op(F.equal, x1, x2, dtype=dtype)
226
227
228def isfinite(x, dtype=None):
229    """
230    Tests element-wise for finiteness (not infinity or not Not a Number).
231
232    The result is returned as a boolean array.
233
234    Note:
235        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
236        and `extobj` are not supported.
237        On GPU, the supported dtypes are np.float16, and np.float32.
238
239    Args:
240        x (Tensor): Input values.
241        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
242            output Tensor.
243
244    Returns:
245       Tensor or scalar, true where `x` is not positive infinity, negative infinity,
246       or NaN; false otherwise. This is a scalar if `x` is a scalar.
247
248    Supported Platforms:
249        ``Ascend`` ``GPU`` ``CPU``
250
251    Examples:
252        >>> import mindspore.numpy as np
253        >>> output = np.isfinite(np.array([np.inf, 1., np.nan]).astype('float32'))
254        >>> print(output)
255        [False  True False]
256    """
257    return _apply_tensor_op(F.isfinite, x, dtype=dtype)
258
259
260def isnan(x, dtype=None):
261    """
262    Tests element-wise for NaN and return result as a boolean array.
263
264    Note:
265        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
266        and `extobj` are not supported.
267        Only np.float32 is currently supported.
268
269    Args:
270        x (Tensor): Input values.
271        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
272            output Tensor.
273
274    Returns:
275       Tensor or scalar, true where `x` is NaN, false otherwise. This is a scalar if
276       `x` is a scalar.
277
278    Supported Platforms:
279        ``GPU`` ``CPU``
280
281    Examples:
282        >>> import mindspore.numpy as np
283        >>> output = np.isnan(np.array(np.nan, np.float32))
284        >>> print(output)
285        True
286        >>> output = np.isnan(np.array(np.inf, np.float32))
287        >>> print(output)
288        False
289    """
290    return _apply_tensor_op(_isnan, x, dtype=dtype)
291
292
293def _isinf(x):
294    """Computes isinf without applying keyword arguments."""
295    shape = F.shape(x)
296    zeros_tensor = zeros(shape, mstype.float32)
297    ones_tensor = ones(shape, mstype.float32)
298    not_inf = F.isfinite(x)
299    is_nan = _isnan(x)
300    res = F.select(not_inf, zeros_tensor, ones_tensor)
301    res = F.select(is_nan, zeros_tensor, res)
302    return F.cast(res, mstype.bool_)
303
304
305def isinf(x, dtype=None):
306    """
307    Tests element-wise for positive or negative infinity.
308
309    Returns a boolean array of the same shape as `x`, True where ``x == +/-inf``, otherwise False.
310
311    Note:
312        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
313        and `extobj` are not supported.
314        Only np.float32 is currently supported.
315
316    Args:
317        x (Tensor): Input values.
318        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
319            output Tensor.
320
321    Returns:
322       Tensor or scalar, true where `x` is positive or negative infinity, false
323       otherwise. This is a scalar if `x` is a scalar.
324
325    Supported Platforms:
326        ``GPU`` ``CPU``
327
328    Examples:
329        >>> import mindspore.numpy as np
330        >>> output = np.isinf(np.array(np.inf, np.float32))
331        >>> print(output)
332        True
333        >>> output = np.isinf(np.array([np.inf, -np.inf, 1.0, np.nan], np.float32))
334        >>> print(output)
335        [ True  True False False]
336    """
337    return _apply_tensor_op(_isinf, x, dtype=dtype)
338
339
340def _is_sign_inf(x, fn):
341    """Tests element-wise for inifinity with sign."""
342    shape = F.shape(x)
343    zeros_tensor = zeros(shape, mstype.float32)
344    ones_tensor = ones(shape, mstype.float32)
345    not_inf = F.isfinite(x)
346    is_sign = fn(x, zeros_tensor)
347    res = F.select(not_inf, zeros_tensor, ones_tensor)
348    res = F.select(is_sign, res, zeros_tensor)
349    return F.cast(res, mstype.bool_)
350
351
352def isposinf(x):
353    """
354    Tests element-wise for positive infinity, returns result as bool array.
355
356    Note:
357        Numpy argument `out` is not supported.
358        Only np.float32 is currently supported.
359
360    Args:
361        x (Tensor): Input values.
362
363    Returns:
364       Tensor or scalar, true where `x` is positive infinity, false otherwise.
365       This is a scalar if `x` is a scalar.
366
367    Raises:
368        TypeError: If the input is not a tensor.
369
370    Supported Platforms:
371        ``GPU`` ``CPU``
372
373    Examples:
374        >>> import mindspore.numpy as np
375        >>> output = np.isposinf(np.array([-np.inf, 0., np.inf, np.nan], np.float32))
376        >>> print(output)
377        [False False  True False]
378    """
379    _check_input_tensor(x)
380    return _is_sign_inf(x, F.tensor_gt)
381
382
383def isneginf(x):
384    """
385    Tests element-wise for negative infinity, returns result as bool array.
386
387    Note:
388        Numpy argument `out` is not supported.
389        Only np.float32 is currently supported.
390
391    Args:
392        x (Tensor): Input values.
393
394    Returns:
395       Tensor or scalar, true where `x` is negative infinity, false otherwise.
396       This is a scalar if `x` is a scalar.
397
398    Raises:
399        TypeError: If the input is not a tensor.
400
401    Supported Platforms:
402        ``GPU`` ``CPU``
403
404    Examples:
405        >>> import mindspore.numpy as np
406        >>> output = np.isneginf(np.array([-np.inf, 0., np.inf, np.nan], np.float32))
407        >>> print(output)
408        [ True False False False]
409    """
410    return _is_sign_inf(x, F.tensor_lt)
411
412
413def isscalar(element):
414    """
415    Returns True if the type of element is a scalar type.
416
417    Note:
418        Only object types recognized by the mindspore parser are supported,
419        which includes objects, types, methods and functions defined within
420        the scope of mindspore. Other built-in types are not supported.
421
422    Args:
423        element (any): Input argument, can be of any type and shape.
424
425    Returns:
426        Boolean, True if `element` is a scalar type, False if it is not.
427
428    Raises:
429        TypeError: If the type of `element` is not supported by mindspore parser.
430
431    Supported Platforms:
432        ``Ascend`` ``GPU`` ``CPU``
433
434    Examples:
435        >>> import mindspore.numpy as np
436        >>> output = np.isscalar(3.1)
437        >>> print(output)
438        True
439        >>> output = np.isscalar(np.array(3.1))
440        >>> print(output)
441        False
442        >>> output = np.isscalar(False)
443        >>> print(output)
444        True
445        >>> output = np.isscalar('numpy')
446        >>> print(output)
447        True
448    """
449    obj_type = F.typeof(element)
450    return not isinstance(obj_type, Tensor) and _isscalar(obj_type)
451
452
453def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
454    """
455    Returns a boolean tensor where two tensors are element-wise equal within a tolerance.
456
457    The tolerance values are positive, typically very small numbers. The relative
458    difference (:math:`rtol * abs(b)`) and the absolute difference `atol` are added together
459    to compare against the absolute difference between `a` and `b`.
460
461    Note:
462        For finite values, isclose uses the following equation to test whether two
463        floating point values are equivalent.
464        :math:`absolute(a - b) <= (atol + rtol * absolute(b))`
465        On Ascend, input arrays containing inf or NaN are not supported.
466
467    Args:
468        a (Union[Tensor, list, tuple]): Input first tensor to compare.
469        b (Union[Tensor, list, tuple]): Input second tensor to compare.
470        rtol (numbers.Number): The relative tolerance parameter (see Note).
471        atol (numbers.Number): The absolute tolerance parameter (see Note).
472        equal_nan (bool): Whether to compare ``NaN`` as equal. If True, ``NaN`` in
473            `a` will be considered equal to ``NaN`` in `b` in the output tensor.
474            Default: ``False`` .
475
476    Returns:
477        A ``bool`` tensor of where `a` and `b` are equal within the given tolerance.
478
479    Raises:
480        TypeError: If inputs have types not specified above.
481
482    Supported Platforms:
483        ``Ascend`` ``GPU`` ``CPU``
484
485    Examples:
486        >>> import mindspore.numpy as np
487        >>> a = np.array([0,1,2,float('inf'),float('inf'),float('nan')])
488        >>> b = np.array([0,1,-2,float('-inf'),float('inf'),float('nan')])
489        >>> print(np.isclose(a, b))
490        [ True  True False False  True False]
491        >>> print(np.isclose(a, b, equal_nan=True))
492        [ True  True False False  True  True]
493    """
494    a, b = _to_tensor(a, b)
495    is_close = P.IsClose(rtol=rtol, atol=atol, equal_nan=equal_nan)
496    return is_close(a, b)
497
498
499def in1d(ar1, ar2, invert=False):
500    """
501    Tests whether each element of a 1-D array is also present in a second array.
502
503    Returns a boolean array the same length as `ar1` that is True where an element
504    of `ar1` is in `ar2` and False otherwise.
505
506    Note:
507        Numpy argument `assume_unique` is not supported since the implementation does
508        not rely on the uniqueness of the input arrays.
509
510    Args:
511        ar1 (Union[int, float, bool, list, tuple, Tensor]): Input array with shape `(M,)`.
512        ar2 (Union[int, float, bool, list, tuple, Tensor]): The values against which
513            to test each value of `ar1`.
514        invert (boolean, optional): If True, the values in the returned array are
515            inverted (that is, False where an element of `ar1` is in `ar2` and True
516            otherwise). Default: ``False`` .
517
518    Returns:
519       Tensor, with shape `(M,)`. The values ``ar1[in1d]`` are in `ar2`.
520
521    Supported Platforms:
522        ``Ascend`` ``GPU`` ``CPU``
523
524    Examples:
525        >>> import mindspore.numpy as np
526        >>> test = np.array([0, 1, 2, 5, 0])
527        >>> states = [0, 2]
528        >>> mask = np.in1d(test, states)
529        >>> print(mask)
530        [ True False  True False  True]
531        >>> mask = np.in1d(test, states, invert=True)
532        >>> print(mask)
533        [False  True False  True False]
534    """
535    ar1, ar2 = _to_tensor(ar1, ar2)
536    ar1 = F.expand_dims(ar1.ravel(), -1)
537    ar2 = ar2.ravel()
538    included = F.equal(ar1, ar2)
539    # F.reduce_sum only supports float
540    res = F.reduce_sum(included.astype(mstype.float32), -1).astype(mstype.bool_)
541    if invert:
542        res = F.logical_not(res)
543    return res
544
545
546def isin(element, test_elements, invert=False):
547    """
548    Calculates element in `test_elements`, broadcasting over `element` only. Returns a
549    boolean array of the same shape as `element` that is True where an element of
550    `element` is in `test_elements` and False otherwise.
551
552    Note:
553        Numpy argument `assume_unique` is not supported since the implementation does
554        not rely on the uniqueness of the input arrays.
555
556    Args:
557        element (Union[int, float, bool, list, tuple, Tensor]): Input array.
558        test_elements (Union[int, float, bool, list, tuple, Tensor]): The values against
559            which to test each value of `element`.
560        invert (boolean, optional): If True, the values in the returned array are
561            inverted, as if calculating `element` not in `test_elements`. Default: ``False`` .
562
563    Returns:
564       Tensor, has the same shape as `element`. The values ``element[isin]`` are in
565       `test_elements`.
566
567    Supported Platforms:
568        ``Ascend`` ``GPU`` ``CPU``
569
570    Examples:
571        >>> import mindspore.numpy as np
572        >>> element = 2*np.arange(4).reshape((2, 2))
573        >>> test_elements = [1, 2, 4, 8]
574        >>> mask = np.isin(element, test_elements)
575        >>> print(mask)
576        [[False  True]
577        [ True False]]
578        >>> mask = np.isin(element, test_elements, invert=True)
579        >>> print(mask)
580        [[ True False]
581        [False  True]]
582    """
583    element = _to_tensor(element)
584    res = in1d(element, test_elements, invert=invert)
585    return F.reshape(res, F.shape(element))
586
587
588def logical_not(a, dtype=None):
589    """
590    Computes the truth value of NOT `a` element-wise.
591
592    Note:
593        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
594        not supported.
595
596    Args:
597        a (Tensor): The input tensor whose dtype is bool.
598        dtype (:class:`mindspore.dtype`, optional): Default: ``None``. Overrides the dtype of the
599            output Tensor.
600
601    Returns:
602        Tensor or scalar.
603        Boolean result with the same shape as `a` of the NOT operation on elements of `a`.
604        This is a scalar if `a` is a scalar.
605
606    Raises:
607        TypeError: If the input is not a tensor or its dtype is not bool.
608
609    Supported Platforms:
610        ``Ascend`` ``GPU`` ``CPU``
611
612    Examples:
613        >>> import mindspore.numpy as np
614        >>> a = np.array([True, False])
615        >>> output = np.logical_not(a)
616        >>> print(output)
617        [False  True]
618    """
619    return _apply_tensor_op(F.logical_not, a, dtype=dtype)
620
621
622def logical_or(x1, x2, dtype=None):
623    """
624    Computes the truth value of `x1` OR `x2` element-wise.
625
626    Note:
627        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
628        and `extobj` are not supported.
629
630    Args:
631        x1 (Tensor): Input tensor.
632        x2 (Tensor): Input tensor. If ``x1.shape != x2.shape``, they must be
633            broadcastable to a common shape (which becomes the shape of the output).
634        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
635            output Tensor.
636
637    Returns:
638       Tensor or scalar, element-wise comparison of `x1` and `x2`. Typically of type
639       bool, unless ``dtype=object`` is passed. This is a scalar if both `x1` and `x2` are
640       scalars.
641
642    Supported Platforms:
643        ``Ascend`` ``GPU`` ``CPU``
644
645    Examples:
646        >>> import mindspore.numpy as np
647        >>> x1 = np.array([True, False])
648        >>> x2 = np.array([False, True])
649        >>> output = np.logical_or(x1, x2)
650        >>> print(output)
651        [ True  True]
652    """
653    return _apply_tensor_op(F.logical_or, x1, x2, dtype=dtype)
654
655
656def logical_and(x1, x2, dtype=None):
657    """
658    Computes the truth value of `x1` AND `x2` element-wise.
659
660    Note:
661        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
662        and `extobj` are not supported.
663
664    Args:
665        x1 (Tensor): Input tensor.
666        x2 (Tensor): Input tensor. If ``x1.shape != x2.shape``, they must be
667            broadcastable to a common shape (which becomes the shape of the output).
668        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
669            output Tensor.
670
671    Returns:
672        Tensor or scalar.
673        Boolean result of the logical AND operation applied to the elements of `x1` and `x2`;
674        the shape is determined by broadcasting. This is a scalar if both `x1` and `x2` are scalars.
675
676    Supported Platforms:
677        ``Ascend`` ``GPU`` ``CPU``
678
679    Examples:
680        >>> import mindspore.numpy as np
681        >>> x1 = np.array([True, False])
682        >>> x2 = np.array([False, False])
683        >>> output = np.logical_and(x1, x2)
684        >>> print(output)
685        [False False]
686    """
687    return _apply_tensor_op(F.logical_and, x1, x2, dtype=dtype)
688
689
690def logical_xor(x1, x2, dtype=None):
691    """
692    Computes the truth value of `x1` XOR `x2`, element-wise.
693
694    Note:
695        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`,
696        and `extobj` are not supported.
697
698    Args:
699        x1 (Tensor): Input tensor.
700        x2 (Tensor): Input tensor. If ``x1.shape != x2.shape``, they must be
701            broadcastable to a common shape (which becomes the shape of the output).
702        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
703            output Tensor.
704
705    Returns:
706        Tensor or scalar.
707        Boolean result of the logical AND operation applied to the elements of `x1` and `x2`;
708        the shape is determined by broadcasting. This is a scalar if both `x1` and `x2` are scalars.
709
710    Supported Platforms:
711        ``Ascend`` ``GPU`` ``CPU``
712
713    Examples:
714        >>> import mindspore.numpy as np
715        >>> x1 = np.array([True, False])
716        >>> x2 = np.array([False, False])
717        >>> output = np.logical_xor(x1, x2)
718        >>> print(output)
719        [True False]
720    """
721    _check_input_tensor(x1)
722    _check_input_tensor(x2)
723    y1 = F.logical_or(x1, x2)
724    y2 = F.logical_or(F.logical_not(x1), F.logical_not(x2))
725    return _apply_tensor_op(F.logical_and, y1, y2, dtype=dtype)
726
727
728def array_equal(a1, a2, equal_nan=False):
729    """
730    Returns `True` if input arrays have same shapes and all elements equal.
731
732    Note:
733        In mindspore, a bool tensor is returned instead, since in Graph mode, the
734        value cannot be traced and computed at compile time.
735
736        Since on Ascend, :class:`nan` is treated differently, currently the argument
737        `equal_nan` is not supported on Ascend.
738
739    Args:
740        a1/a2 (Union[int, float, bool, list, tuple, Tensor]): Input arrays.
741        equal_nan (bool): Whether to compare NaN's as equal. Default: ``False`` .
742
743    Returns:
744        Scalar bool tensor, value is `True` if inputs are equal, `False` otherwise.
745
746    Raises:
747        TypeError: If inputs have types not specified above.
748
749    Supported Platforms:
750        ``GPU`` ``CPU`` ``Ascend``
751
752    Examples:
753        >>> import mindspore.numpy as np
754        >>> a = [0,1,2]
755        >>> b = [[0,1,2], [0,1,2]]
756        >>> print(np.array_equal(a,b))
757        False
758    """
759    a1 = asarray(a1)
760    a2 = asarray(a2)
761    if not isinstance(equal_nan, bool):
762        _raise_type_error("equal_nan must be bool.")
763    if a1.shape == a2.shape:
764        res = equal(a1, a2)
765        if equal_nan:
766            res = logical_or(res, logical_and(isnan(a1), isnan(a2)))
767        return res.all()
768    return _to_tensor(False)
769
770
771def array_equiv(a1, a2):
772    """
773    Returns `True` if input arrays are shape consistent and all elements equal.
774
775    Shape consistent means they are either the same shape, or one input array can
776    be broadcasted to create the same shape as the other one.
777
778    Note:
779        In mindspore, a bool tensor is returned instead, since in Graph mode, the
780        value cannot be traced and computed at compile time.
781
782    Args:
783        a1/a2 (Union[int, float, bool, list, tuple, Tensor]): Input arrays.
784
785    Returns:
786        Scalar bool tensor, value is `True` if inputs are equivalent, `False` otherwise.
787
788    Raises:
789        TypeError: If inputs have types not specified above.
790
791    Supported Platforms:
792        ``Ascend`` ``GPU`` ``CPU``
793
794    Examples:
795        >>> import mindspore.numpy as np
796        >>> a = [0,1,2]
797        >>> b = [[0,1,2], [0,1,2]]
798        >>> print(np.array_equiv(a,b))
799        True
800    """
801    a1 = asarray(a1)
802    a2 = asarray(a2)
803    if _can_broadcast(a1.shape, a2.shape):
804        return equal(a1, a2).all()
805    return _to_tensor(False)
806
807
808def signbit(x, dtype=None):
809    """
810    Returns element-wise True where signbit is set (less than zero).
811
812    Note:
813        Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and
814        `extobj` are not supported.
815
816    Args:
817        x (Union[int, float, bool, list, tuple, Tensor]): The input value(s).
818        dtype (:class:`mindspore.dtype`, optional): Default: ``None`` . Overrides the dtype of the
819            output Tensor.
820
821    Returns:
822        Tensor.
823
824    Raises:
825        TypeError: If input is not array_like or `dtype` is not `None` or `bool`.
826
827    Supported Platforms:
828        ``Ascend`` ``GPU`` ``CPU``
829
830    Examples:
831        >>> import mindspore.numpy as np
832        >>> x = np.array([1, -2.3, 2.1]).astype('float32')
833        >>> output = np.signbit(x)
834        >>> print(output)
835        [False  True False]
836    """
837    if dtype is not None and not _check_same_type(dtype, mstype.bool_):
838        _raise_type_error("Casting was not allowed for signbit.")
839    x = _to_tensor(x)
840    res = F.less(x, 0)
841    if dtype is not None and not _check_same_type(F.dtype(res), dtype):
842        res = F.cast(res, dtype)
843    return res
844
845
846def sometrue(a, axis=None, keepdims=False):
847    """
848    Tests whether any array element along a given axis evaluates to True.
849
850    Returns single boolean unless axis is not None
851
852    Args:
853        a (Union[int, float, bool, list, tuple, Tensor]): Input tensor or object that can be converted to an array.
854        axis (Union[None, int, tuple(int)]): Axis or axes along which a logical OR reduction is
855            performed. Default: ``None`` .
856            If None, perform a logical OR over all the dimensions of the input array.
857            If negative, it counts from the last to the first axis.
858            If tuple of integers, a reduction is performed on multiple axes, instead of a single axis or
859            all the axes as before.
860        keepdims (bool): Default: ``False`` .
861            If True, the axes which are reduced are left in the result as dimensions with size one.
862            With this option, the result will broadcast correctly against the input array.
863            If the default value is passed, then keepdims will not be passed through to the any method of
864            sub-classes of ndarray, however any non-default value will be. If the sub-class method does not
865            implement keepdims any exceptions will be raised.
866
867    Returns:
868        Returns single boolean unless axis is not None
869
870    Raises:
871        TypeError: If input is not array_like or `axis` is not int or tuple of integers or
872            `keepdims` is not integer or `initial` is not scalar.
873        ValueError: If any axis is out of range or duplicate axes exist.
874
875    Supported Platforms:
876        ``Ascend`` ``GPU`` ``CPU``
877
878    Examples:
879        >>> import mindspore.numpy as np
880        >>> x = np.array([1, -2.3, 2.1]).astype('float32')
881        >>> output = np.sometrue(x)
882        >>> print(output)
883        True
884    """
885    if not isinstance(keepdims, int):
886        _raise_type_error("integer argument expected, but got ", keepdims)
887    if axis is not None:
888        _check_axis_type(axis, True, True, False)
889        axis = _canonicalize_axis(axis, a.ndim)
890    a = _to_tensor(a)
891    keepdims = keepdims not in (0, False)
892    return F.not_equal(a, 0).any(axis, keepdims)
893
894
895def setdiff1d(ar1, ar2, assume_unique=False):
896    """
897    Find the set difference of two Tensors.
898    Return the unique values in `ar1` that are not in `ar2`.
899
900    Args:
901        ar1 (Union[int, float, bool, list, tuple, Tensor]): Input tensor.
902        ar2 (Union[int, float, bool, list, tuple, Tensor]): Input tensor.
903        assume_unique (bool): If `True`, the input Tensors are assumed to be unique, which can speed up the calculation.
904                              If `True` but `ar1` or `ar2` are not unique,
905                              incorrect results and out-of-bounds indices could result.
906                              Default: ``False``.
907
908    Returns:
909        1D Tensor of values in `ar1` that are not in `ar2`.
910        The result is sorted when `assume_unique` = ``False`` , but otherwise only sorted if the input is sorted.
911
912    Raises:
913        TypeError: If input `ar1` or `ar2` is not array_like.
914        TypeError: If `assume_unique` is not bool.
915
916    Supported Platforms:
917        ``Ascend`` ``GPU`` ``CPU``
918
919    Examples:
920        >>> import mindspore.numpy as np
921        >>> a = np.array([1, 2, 3, 2, 4, 1])
922        >>> b = np.array([3, 4, 5, 6])
923        >>> np.setdiff1d(a, b)
924        Tensor(shape=[2], dtype=Int32, value=[1, 2])
925    """
926    if not isinstance(assume_unique, bool):
927        _raise_type_error("assume_unique is not bool type.")
928    ar1, ar2 = _to_tensor(ar1, ar2)
929    if assume_unique:
930        ar1 = ar1.ravel()
931    else:
932        ar1 = F.unique(ar1)[0].sort()[0]
933        ar2 = F.unique(ar2)[0].sort()[0]
934    mask = in1d(ar1, ar2, invert=True)
935    return F.masked_select(ar1, mask)
936