Python numpy.core.umath.add() Examples

The following are code examples for showing how to use numpy.core.umath.add(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 6 votes vote down vote up
def test_ufunc_override_not_implemented(self):

        class A(object):
            def __array_ufunc__(self, *args, **kwargs):
                return NotImplemented

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.negative(A())

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
               "out=(1,)): 'A', 'object', 'int'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.add(A(), object(), out=1) 
Example 2
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 6 votes vote down vote up
def test_ufunc_override_not_implemented(self):

        class A(object):
            def __array_ufunc__(self, *args, **kwargs):
                return NotImplemented

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.negative(A())

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
               "out=(1,)): 'A', 'object', 'int'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.add(A(), object(), out=1) 
Example 3
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 6 votes vote down vote up
def test_ufunc_override_not_implemented(self):

        class A(object):
            def __array_ufunc__(self, *args, **kwargs):
                return NotImplemented

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.negative(A())

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
               "out=(1,)): 'A', 'object', 'int'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.add(A(), object(), out=1) 
Example 4
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 6 votes vote down vote up
def test_ufunc_override_not_implemented(self):

        class A(object):
            def __array_ufunc__(self, *args, **kwargs):
                return NotImplemented

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.negative(A())

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
               "out=(1,)): 'A', 'object', 'int'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.add(A(), object(), out=1) 
Example 5
Project: vnpy_crypto   Author: birforce   File: test_umath.py    MIT License 6 votes vote down vote up
def test_ufunc_override_not_implemented(self):

        class A(object):
            def __array_ufunc__(self, *args, **kwargs):
                return NotImplemented

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.negative(A())

        msg = ("operand type(s) all returned NotImplemented from "
               "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
               "out=(1,)): 'A', 'object', 'int'")
        with assert_raises_regex(TypeError, fnmatch.translate(msg)):
            np.add(A(), object(), out=1) 
Example 6
Project: LaserTOF   Author: kyleuckert   File: core.py    MIT License 5 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= domain(da, db)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result 
Example 7
Project: LaserTOF   Author: kyleuckert   File: core.py    MIT License 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 8
Project: LaserTOF   Author: kyleuckert   File: core.py    MIT License 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 9
Project: LaserTOF   Author: kyleuckert   File: test_umath.py    MIT License 5 votes vote down vote up
def test_prepare(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                # make sure we can return a new
                return np.array(arr).view(type=with_prepare)

        a = np.array(1).view(type=with_prepare)
        x = np.add(a, a)
        assert_equal(x, np.array(2))
        assert_equal(type(x), with_prepare) 
Example 10
Project: LaserTOF   Author: kyleuckert   File: test_umath.py    MIT License 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.__doc__.startswith('add(x1, x2[, out])\n\n'))
        self.assertTrue(add.ntypes >= 18)  # don't fail if types added
        self.assertTrue('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 11
Project: LaserTOF   Author: kyleuckert   File: test_umath.py    MIT License 5 votes vote down vote up
def test_reduceat():
    """Test bug in reduceat when structured arrays are not copied."""
    db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)])
    a = np.empty([100], dtype=db)
    a['name'] = 'Simple'
    a['time'] = 10
    a['value'] = 100
    indx = [0, 7, 15, 25]

    h2 = []
    val1 = indx[0]
    for val2 in indx[1:]:
        h2.append(np.add.reduce(a['value'][val1:val2]))
        val1 = val2
    h2.append(np.add.reduce(a['value'][val1:]))
    h2 = np.array(h2)

    # test buffered -- this should work
    h1 = np.add.reduceat(a['value'], indx)
    assert_array_almost_equal(h1, h2)

    # This is when the error occurs.
    # test no buffer
    np.setbufsize(32)
    h1 = np.add.reduceat(a['value'], indx)
    np.setbufsize(np.UFUNC_BUFSIZE_DEFAULT)
    assert_array_almost_equal(h1, h2) 
Example 12
Project: LaserTOF   Author: kyleuckert   File: test_umath.py    MIT License 5 votes vote down vote up
def test_reduceat_empty():
    """Reduceat should work with empty arrays"""
    indices = np.array([], 'i4')
    x = np.array([], 'f8')
    result = np.add.reduceat(x, indices)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0,))
    # Another case with a slightly different zero-sized shape
    x = np.ones((5, 2))
    result = np.add.reduceat(x, [], axis=0)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0, 2))
    result = np.add.reduceat(x, [], axis=1)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (5, 0)) 
Example 13
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: core.py    MIT License 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 14
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: core.py    MIT License 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 15
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 16
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 5 votes vote down vote up
def test_ufunc_override_disabled(self):

        class OptOut(object):
            __array_ufunc__ = None

        opt_out = OptOut()

        # ufuncs always raise
        msg = "operand 'OptOut' does not support ufuncs"
        with assert_raises_regex(TypeError, msg):
            np.add(opt_out, 1)
        with assert_raises_regex(TypeError, msg):
            np.add(1, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.negative(opt_out)

        # opt-outs still hold even when other arguments have pathological
        # __array_ufunc__ implementations

        class GreedyArray(object):
            def __array_ufunc__(self, *args, **kwargs):
                return self

        greedy = GreedyArray()
        assert_(np.negative(greedy) is greedy)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, 1, out=opt_out) 
Example 17
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.ntypes >= 18)  # don't fail if types added
        assert_('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 18
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example 19
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 5 votes vote down vote up
def test_reduceat_empty():
    """Reduceat should work with empty arrays"""
    indices = np.array([], 'i4')
    x = np.array([], 'f8')
    result = np.add.reduceat(x, indices)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0,))
    # Another case with a slightly different zero-sized shape
    x = np.ones((5, 2))
    result = np.add.reduceat(x, [], axis=0)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0, 2))
    result = np.add.reduceat(x, [], axis=1)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (5, 0)) 
Example 20
Project: recruit   Author: Frank-qlu   File: core.py    Apache License 2.0 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 21
Project: recruit   Author: Frank-qlu   File: core.py    Apache License 2.0 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 22
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 23
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 5 votes vote down vote up
def test_ufunc_override_disabled(self):

        class OptOut(object):
            __array_ufunc__ = None

        opt_out = OptOut()

        # ufuncs always raise
        msg = "operand 'OptOut' does not support ufuncs"
        with assert_raises_regex(TypeError, msg):
            np.add(opt_out, 1)
        with assert_raises_regex(TypeError, msg):
            np.add(1, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.negative(opt_out)

        # opt-outs still hold even when other arguments have pathological
        # __array_ufunc__ implementations

        class GreedyArray(object):
            def __array_ufunc__(self, *args, **kwargs):
                return self

        greedy = GreedyArray()
        assert_(np.negative(greedy) is greedy)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, 1, out=opt_out) 
Example 24
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.ntypes >= 18)  # don't fail if types added
        assert_('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example 26
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 5 votes vote down vote up
def test_reduceat_empty():
    """Reduceat should work with empty arrays"""
    indices = np.array([], 'i4')
    x = np.array([], 'f8')
    result = np.add.reduceat(x, indices)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0,))
    # Another case with a slightly different zero-sized shape
    x = np.ones((5, 2))
    result = np.add.reduceat(x, [], axis=0)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0, 2))
    result = np.add.reduceat(x, [], axis=1)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (5, 0)) 
Example 27
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: core.py    GNU General Public License v3.0 5 votes vote down vote up
def __add__(self, other):
        "Add other to self, and return a new masked array."
        return add(self, other)
    # 
Example 28
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: core.py    GNU General Public License v3.0 5 votes vote down vote up
def __radd__(self, other):
        "Add other to self, and return a new masked array."
        return add(self, other)
    # 
Example 29
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_out_subok(self):
        for b in (True, False):
            aout = np.array(0.5)

            r = np.add(aout, 2, out=aout)
            assert_(r is aout)
            assert_array_equal(r, aout)

            r = np.add(aout, 2, out=aout, subok=b)
            assert_(r is aout)
            assert_array_equal(r, aout)

            r = np.add(aout, 2, aout, subok=False)
            assert_(r is aout)
            assert_array_equal(r, aout)

            d = np.ones(5)
            o1 = np.zeros(5)
            o2 = np.zeros(5, dtype=np.int32)
            r1, r2 = np.frexp(d, o1, o2, subok=b)
            assert_(r1 is o1)
            assert_array_equal(r1, o1)
            assert_(r2 is o2)
            assert_array_equal(r2, o2)

            r1, r2 = np.frexp(d, out=o1, subok=b)
            assert_(r1 is o1)
            assert_array_equal(r1, o1) 
Example 30
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_prepare(self):
        class with_prepare(np.ndarray):
            __array_priority__ = 10
            def __array_prepare__(self, arr, context):
                # make sure we can return a new
                return np.array(arr).view(type=with_prepare)
        a = np.array(1).view(type=with_prepare)
        x = np.add(a, a)
        assert_equal(x, np.array(2))
        assert_equal(type(x), with_prepare) 
Example 31
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.__doc__.startswith('add(x1, x2[, out])\n\n'))
        self.assertTrue(add.ntypes >= 18) # don't fail if types added
        self.assertTrue('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 32
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_reduceat_empty():
    """Reduceat should work with empty arrays"""
    indices = np.array([], 'i4')
    x = np.array([], 'f8')
    result = np.add.reduceat(x, indices)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0,))
    # Another case with a slightly different zero-sized shape
    x = np.ones((5, 2))
    result = np.add.reduceat(x, [], axis=0)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0, 2))
    result = np.add.reduceat(x, [], axis=1)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (5, 0)) 
Example 33
Project: FUTU_Stop_Loss   Author: BigtoC   File: core.py    MIT License 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 34
Project: FUTU_Stop_Loss   Author: BigtoC   File: core.py    MIT License 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 35
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 36
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 5 votes vote down vote up
def test_ufunc_override_disabled(self):

        class OptOut(object):
            __array_ufunc__ = None

        opt_out = OptOut()

        # ufuncs always raise
        msg = "operand 'OptOut' does not support ufuncs"
        with assert_raises_regex(TypeError, msg):
            np.add(opt_out, 1)
        with assert_raises_regex(TypeError, msg):
            np.add(1, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.negative(opt_out)

        # opt-outs still hold even when other arguments have pathological
        # __array_ufunc__ implementations

        class GreedyArray(object):
            def __array_ufunc__(self, *args, **kwargs):
                return self

        greedy = GreedyArray()
        assert_(np.negative(greedy) is greedy)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, 1, out=opt_out) 
Example 37
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.ntypes >= 18)  # don't fail if types added
        assert_('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 38
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example 39
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 5 votes vote down vote up
def test_reduceat_empty():
    """Reduceat should work with empty arrays"""
    indices = np.array([], 'i4')
    x = np.array([], 'f8')
    result = np.add.reduceat(x, indices)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0,))
    # Another case with a slightly different zero-sized shape
    x = np.ones((5, 2))
    result = np.add.reduceat(x, [], axis=0)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0, 2))
    result = np.add.reduceat(x, [], axis=1)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (5, 0)) 
Example 40
Project: MARRtino-2.0   Author: DaniAffCH   File: core.py    GNU General Public License v3.0 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 41
Project: MARRtino-2.0   Author: DaniAffCH   File: core.py    GNU General Public License v3.0 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 42
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 43
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_ufunc_override_disabled(self):

        class OptOut(object):
            __array_ufunc__ = None

        opt_out = OptOut()

        # ufuncs always raise
        msg = "operand 'OptOut' does not support ufuncs"
        with assert_raises_regex(TypeError, msg):
            np.add(opt_out, 1)
        with assert_raises_regex(TypeError, msg):
            np.add(1, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.negative(opt_out)

        # opt-outs still hold even when other arguments have pathological
        # __array_ufunc__ implementations

        class GreedyArray(object):
            def __array_ufunc__(self, *args, **kwargs):
                return self

        greedy = GreedyArray()
        assert_(np.negative(greedy) is greedy)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, 1, out=opt_out) 
Example 44
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.ntypes >= 18)  # don't fail if types added
        assert_('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 45
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example 46
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_reduceat_empty():
    """Reduceat should work with empty arrays"""
    indices = np.array([], 'i4')
    x = np.array([], 'f8')
    result = np.add.reduceat(x, indices)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0,))
    # Another case with a slightly different zero-sized shape
    x = np.ones((5, 2))
    result = np.add.reduceat(x, [], axis=0)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0, 2))
    result = np.add.reduceat(x, [], axis=1)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (5, 0)) 
Example 47
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: core.py    MIT License 5 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= filled(domain(da, db), True)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result 
Example 48
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: core.py    MIT License 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 49
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: core.py    MIT License 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 50
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    MIT License 5 votes vote down vote up
def test_ufunc_override_disabled(self):
        # 2016-01-29: NUMPY_UFUNC_DISABLED
        # This test should be removed when __numpy_ufunc__ is re-enabled.

        class MyArray(object):
            def __numpy_ufunc__(self, *args, **kwargs):
                self._numpy_ufunc_called = True

        my_array = MyArray()
        real_array = np.ones(10)
        assert_raises(TypeError, lambda: real_array + my_array)
        assert_raises(TypeError, np.add, real_array, my_array)
        assert not hasattr(my_array, "_numpy_ufunc_called") 
Example 51
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    MIT License 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.__doc__.startswith('add(x1, x2[, out])\n\n'))
        self.assertTrue(add.ntypes >= 18)  # don't fail if types added
        self.assertTrue('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 52
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    MIT License 5 votes vote down vote up
def test_reduceat():
    """Test bug in reduceat when structured arrays are not copied."""
    db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)])
    a = np.empty([100], dtype=db)
    a['name'] = 'Simple'
    a['time'] = 10
    a['value'] = 100
    indx = [0, 7, 15, 25]

    h2 = []
    val1 = indx[0]
    for val2 in indx[1:]:
        h2.append(np.add.reduce(a['value'][val1:val2]))
        val1 = val2
    h2.append(np.add.reduce(a['value'][val1:]))
    h2 = np.array(h2)

    # test buffered -- this should work
    h1 = np.add.reduceat(a['value'], indx)
    assert_array_almost_equal(h1, h2)

    # This is when the error occurs.
    # test no buffer
    np.setbufsize(32)
    h1 = np.add.reduceat(a['value'], indx)
    np.setbufsize(np.UFUNC_BUFSIZE_DEFAULT)
    assert_array_almost_equal(h1, h2) 
Example 53
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    MIT License 5 votes vote down vote up
def test_reduceat_empty():
    """Reduceat should work with empty arrays"""
    indices = np.array([], 'i4')
    x = np.array([], 'f8')
    result = np.add.reduceat(x, indices)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0,))
    # Another case with a slightly different zero-sized shape
    x = np.ones((5, 2))
    result = np.add.reduceat(x, [], axis=0)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (0, 2))
    result = np.add.reduceat(x, [], axis=1)
    assert_equal(result.dtype, x.dtype)
    assert_equal(result.shape, (5, 0)) 
Example 54
Project: vnpy_crypto   Author: birforce   File: core.py    MIT License 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 55
Project: vnpy_crypto   Author: birforce   File: core.py    MIT License 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 56
Project: vnpy_crypto   Author: birforce   File: test_umath.py    MIT License 5 votes vote down vote up
def test_prepare(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                # make sure we can return a new
                return np.array(arr).view(type=with_prepare)

        a = np.array(1).view(type=with_prepare)
        x = np.add(a, a)
        assert_equal(x, np.array(2))
        assert_equal(type(x), with_prepare) 
Example 57
Project: vnpy_crypto   Author: birforce   File: test_umath.py    MIT License 5 votes vote down vote up
def test_ufunc_override_disabled(self):

        class OptOut(object):
            __array_ufunc__ = None

        opt_out = OptOut()

        # ufuncs always raise
        msg = "operand 'OptOut' does not support ufuncs"
        with assert_raises_regex(TypeError, msg):
            np.add(opt_out, 1)
        with assert_raises_regex(TypeError, msg):
            np.add(1, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.negative(opt_out)

        # opt-outs still hold even when other arguments have pathological
        # __array_ufunc__ implementations

        class GreedyArray(object):
            def __array_ufunc__(self, *args, **kwargs):
                return self

        greedy = GreedyArray()
        assert_(np.negative(greedy) is greedy)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, opt_out)
        with assert_raises_regex(TypeError, msg):
            np.add(greedy, 1, out=opt_out) 
Example 58
Project: vnpy_crypto   Author: birforce   File: test_umath.py    MIT License 5 votes vote down vote up
def test_attributes(self):
        add = ncu.add
        assert_equal(add.__name__, 'add')
        assert_(add.ntypes >= 18)  # don't fail if types added
        assert_('ii->i' in add.types)
        assert_equal(add.nin, 2)
        assert_equal(add.nout, 1)
        assert_equal(add.identity, 0) 
Example 59
Project: vnpy_crypto   Author: birforce   File: test_umath.py    MIT License 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example 60
Project: vnpy_crypto   Author: birforce   File: test_umath.py    MIT License 5 votes vote down vote up
def test_reduceat():
    """Test bug in reduceat when structured arrays are not copied."""
    db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)])
    a = np.empty([100], dtype=db)
    a['name'] = 'Simple'
    a['time'] = 10
    a['value'] = 100
    indx = [0, 7, 15, 25]

    h2 = []
    val1 = indx[0]
    for val2 in indx[1:]:
        h2.append(np.add.reduce(a['value'][val1:val2]))
        val1 = val2
    h2.append(np.add.reduce(a['value'][val1:]))
    h2 = np.array(h2)

    # test buffered -- this should work
    h1 = np.add.reduceat(a['value'], indx)
    assert_array_almost_equal(h1, h2)

    # This is when the error occurs.
    # test no buffer
    np.setbufsize(32)
    h1 = np.add.reduceat(a['value'], indx)
    np.setbufsize(np.UFUNC_BUFSIZE_DEFAULT)
    assert_array_almost_equal(h1, h2) 
Example 61
Project: ble5-nrf52-mac   Author: tomasero   File: core.py    MIT License 5 votes vote down vote up
def __add__(self, other):
        """
        Add self to other, and return a new masked array.

        """
        if self._delegate_binop(other):
            return NotImplemented
        return add(self, other) 
Example 62
Project: ble5-nrf52-mac   Author: tomasero   File: core.py    MIT License 5 votes vote down vote up
def __radd__(self, other):
        """
        Add other to self, and return a new masked array.

        """
        # In analogy with __rsub__ and __rdiv__, use original order:
        # we get here from `other + self`.
        return add(other, self) 
Example 63
Project: LaserTOF   Author: kyleuckert   File: test_umath.py    MIT License 4 votes vote down vote up
def test_out_subok(self):
        for subok in (True, False):
            a = np.array(0.5)
            o = np.empty(())

            r = np.add(a, 2, o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=(o,), subok=subok)
            assert_(r is o)

            d = np.array(5.7)
            o1 = np.empty(())
            o2 = np.empty((), dtype=np.int32)

            r1, r2 = np.frexp(d, o1, None, subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, None, o2, subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, o1, o2, subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            with warnings.catch_warnings(record=True) as w:
                warnings.filterwarnings('always', '', DeprecationWarning)
                r1, r2 = np.frexp(d, out=o1, subok=subok)
                assert_(r1 is o1)
                assert_(w[0].category is DeprecationWarning)

            assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
            assert_raises(TypeError, np.add, a, 2, [], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
            o.flags.writeable = False
            assert_raises(ValueError, np.add, a, 2, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) 
Example 64
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: core.py    MIT License 4 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= domain(da, db)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except Exception:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result


# Unary ufuncs 
Example 65
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 4 votes vote down vote up
def test_out_subok(self):
        for subok in (True, False):
            a = np.array(0.5)
            o = np.empty(())

            r = np.add(a, 2, o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=(o,), subok=subok)
            assert_(r is o)

            d = np.array(5.7)
            o1 = np.empty(())
            o2 = np.empty((), dtype=np.int32)

            r1, r2 = np.frexp(d, o1, None, subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, None, o2, subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, o1, o2, subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            with warnings.catch_warnings(record=True) as w:
                warnings.filterwarnings('always', '', DeprecationWarning)
                r1, r2 = np.frexp(d, out=o1, subok=subok)
                assert_(r1 is o1)
                assert_(w[0].category is DeprecationWarning)

            assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
            assert_raises(TypeError, np.add, a, 2, [], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
            o.flags.writeable = False
            assert_raises(ValueError, np.add, a, 2, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) 
Example 66
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_umath.py    MIT License 4 votes vote down vote up
def test_wrap_and_prepare_out(self):
        # Calling convention for out should not affect how special methods are
        # called

        class StoreArrayPrepareWrap(np.ndarray):
            _wrap_args = None
            _prepare_args = None
            def __new__(cls):
                return np.empty(()).view(cls)
            def __array_wrap__(self, obj, context):
                self._wrap_args = context[1]
                return obj
            def __array_prepare__(self, obj, context):
                self._prepare_args = context[1]
                return obj
            @property
            def args(self):
                # We need to ensure these are fetched at the same time, before
                # any other ufuncs are calld by the assertions
                return (self._prepare_args, self._wrap_args)
            def __repr__(self):
                return "a"  # for short test output

        def do_test(f_call, f_expected):
            a = StoreArrayPrepareWrap()
            f_call(a)
            p, w = a.args
            expected = f_expected(a)
            try:
                assert_equal(p, expected)
                assert_equal(w, expected)
            except AssertionError as e:
                # assert_equal produces truly useless error messages
                raise AssertionError("\n".join([
                    "Bad arguments passed in ufunc call",
                    " expected:              {}".format(expected),
                    " __array_prepare__ got: {}".format(p),
                    " __array_wrap__ got:    {}".format(w)
                ]))

        # method not on the out argument
        do_test(lambda a: np.add(a, 0),              lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, None),        lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=None),    lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=(None,)), lambda a: (a, 0))

        # method on the out argument
        do_test(lambda a: np.add(0, 0, a),           lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=a),       lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=(a,)),    lambda a: (0, 0, a)) 
Example 67
Project: recruit   Author: Frank-qlu   File: core.py    Apache License 2.0 4 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= domain(da, db)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except Exception:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result


# Unary ufuncs 
Example 68
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 4 votes vote down vote up
def test_out_subok(self):
        for subok in (True, False):
            a = np.array(0.5)
            o = np.empty(())

            r = np.add(a, 2, o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=(o,), subok=subok)
            assert_(r is o)

            d = np.array(5.7)
            o1 = np.empty(())
            o2 = np.empty((), dtype=np.int32)

            r1, r2 = np.frexp(d, o1, None, subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, None, o2, subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, o1, o2, subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            with warnings.catch_warnings(record=True) as w:
                warnings.filterwarnings('always', '', DeprecationWarning)
                r1, r2 = np.frexp(d, out=o1, subok=subok)
                assert_(r1 is o1)
                assert_(w[0].category is DeprecationWarning)

            assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
            assert_raises(TypeError, np.add, a, 2, [], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
            o.flags.writeable = False
            assert_raises(ValueError, np.add, a, 2, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) 
Example 69
Project: recruit   Author: Frank-qlu   File: test_umath.py    Apache License 2.0 4 votes vote down vote up
def test_wrap_and_prepare_out(self):
        # Calling convention for out should not affect how special methods are
        # called

        class StoreArrayPrepareWrap(np.ndarray):
            _wrap_args = None
            _prepare_args = None
            def __new__(cls):
                return np.empty(()).view(cls)
            def __array_wrap__(self, obj, context):
                self._wrap_args = context[1]
                return obj
            def __array_prepare__(self, obj, context):
                self._prepare_args = context[1]
                return obj
            @property
            def args(self):
                # We need to ensure these are fetched at the same time, before
                # any other ufuncs are calld by the assertions
                return (self._prepare_args, self._wrap_args)
            def __repr__(self):
                return "a"  # for short test output

        def do_test(f_call, f_expected):
            a = StoreArrayPrepareWrap()
            f_call(a)
            p, w = a.args
            expected = f_expected(a)
            try:
                assert_equal(p, expected)
                assert_equal(w, expected)
            except AssertionError as e:
                # assert_equal produces truly useless error messages
                raise AssertionError("\n".join([
                    "Bad arguments passed in ufunc call",
                    " expected:              {}".format(expected),
                    " __array_prepare__ got: {}".format(p),
                    " __array_wrap__ got:    {}".format(w)
                ]))

        # method not on the out argument
        do_test(lambda a: np.add(a, 0),              lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, None),        lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=None),    lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=(None,)), lambda a: (a, 0))

        # method on the out argument
        do_test(lambda a: np.add(0, 0, a),           lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=a),       lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=(a,)),    lambda a: (0, 0, a)) 
Example 70
Project: FUTU_Stop_Loss   Author: BigtoC   File: core.py    MIT License 4 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= domain(da, db)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except Exception:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result


# Unary ufuncs 
Example 71
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 4 votes vote down vote up
def test_out_subok(self):
        for subok in (True, False):
            a = np.array(0.5)
            o = np.empty(())

            r = np.add(a, 2, o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=(o,), subok=subok)
            assert_(r is o)

            d = np.array(5.7)
            o1 = np.empty(())
            o2 = np.empty((), dtype=np.int32)

            r1, r2 = np.frexp(d, o1, None, subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, None, o2, subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, o1, o2, subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            with warnings.catch_warnings(record=True) as w:
                warnings.filterwarnings('always', '', DeprecationWarning)
                r1, r2 = np.frexp(d, out=o1, subok=subok)
                assert_(r1 is o1)
                assert_(w[0].category is DeprecationWarning)

            assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
            assert_raises(TypeError, np.add, a, 2, [], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
            o.flags.writeable = False
            assert_raises(ValueError, np.add, a, 2, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) 
Example 72
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_umath.py    MIT License 4 votes vote down vote up
def test_wrap_and_prepare_out(self):
        # Calling convention for out should not affect how special methods are
        # called

        class StoreArrayPrepareWrap(np.ndarray):
            _wrap_args = None
            _prepare_args = None
            def __new__(cls):
                return np.empty(()).view(cls)
            def __array_wrap__(self, obj, context):
                self._wrap_args = context[1]
                return obj
            def __array_prepare__(self, obj, context):
                self._prepare_args = context[1]
                return obj
            @property
            def args(self):
                # We need to ensure these are fetched at the same time, before
                # any other ufuncs are calld by the assertions
                return (self._prepare_args, self._wrap_args)
            def __repr__(self):
                return "a"  # for short test output

        def do_test(f_call, f_expected):
            a = StoreArrayPrepareWrap()
            f_call(a)
            p, w = a.args
            expected = f_expected(a)
            try:
                assert_equal(p, expected)
                assert_equal(w, expected)
            except AssertionError as e:
                # assert_equal produces truly useless error messages
                raise AssertionError("\n".join([
                    "Bad arguments passed in ufunc call",
                    " expected:              {}".format(expected),
                    " __array_prepare__ got: {}".format(p),
                    " __array_wrap__ got:    {}".format(w)
                ]))

        # method not on the out argument
        do_test(lambda a: np.add(a, 0),              lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, None),        lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=None),    lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=(None,)), lambda a: (a, 0))

        # method on the out argument
        do_test(lambda a: np.add(0, 0, a),           lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=a),       lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=(a,)),    lambda a: (0, 0, a)) 
Example 73
Project: MARRtino-2.0   Author: DaniAffCH   File: core.py    GNU General Public License v3.0 4 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= domain(da, db)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except Exception:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result


# Unary ufuncs 
Example 74
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 4 votes vote down vote up
def test_out_subok(self):
        for subok in (True, False):
            a = np.array(0.5)
            o = np.empty(())

            r = np.add(a, 2, o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=(o,), subok=subok)
            assert_(r is o)

            d = np.array(5.7)
            o1 = np.empty(())
            o2 = np.empty((), dtype=np.int32)

            r1, r2 = np.frexp(d, o1, None, subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, None, o2, subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, o1, o2, subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            with warnings.catch_warnings(record=True) as w:
                warnings.filterwarnings('always', '', DeprecationWarning)
                r1, r2 = np.frexp(d, out=o1, subok=subok)
                assert_(r1 is o1)
                assert_(w[0].category is DeprecationWarning)

            assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
            assert_raises(TypeError, np.add, a, 2, [], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
            o.flags.writeable = False
            assert_raises(ValueError, np.add, a, 2, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) 
Example 75
Project: MARRtino-2.0   Author: DaniAffCH   File: test_umath.py    GNU General Public License v3.0 4 votes vote down vote up
def test_wrap_and_prepare_out(self):
        # Calling convention for out should not affect how special methods are
        # called

        class StoreArrayPrepareWrap(np.ndarray):
            _wrap_args = None
            _prepare_args = None
            def __new__(cls):
                return np.empty(()).view(cls)
            def __array_wrap__(self, obj, context):
                self._wrap_args = context[1]
                return obj
            def __array_prepare__(self, obj, context):
                self._prepare_args = context[1]
                return obj
            @property
            def args(self):
                # We need to ensure these are fetched at the same time, before
                # any other ufuncs are calld by the assertions
                return (self._prepare_args, self._wrap_args)
            def __repr__(self):
                return "a"  # for short test output

        def do_test(f_call, f_expected):
            a = StoreArrayPrepareWrap()
            f_call(a)
            p, w = a.args
            expected = f_expected(a)
            try:
                assert_equal(p, expected)
                assert_equal(w, expected)
            except AssertionError as e:
                # assert_equal produces truly useless error messages
                raise AssertionError("\n".join([
                    "Bad arguments passed in ufunc call",
                    " expected:              {}".format(expected),
                    " __array_prepare__ got: {}".format(p),
                    " __array_wrap__ got:    {}".format(w)
                ]))

        # method not on the out argument
        do_test(lambda a: np.add(a, 0),              lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, None),        lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=None),    lambda a: (a, 0))
        do_test(lambda a: np.add(a, 0, out=(None,)), lambda a: (a, 0))

        # method on the out argument
        do_test(lambda a: np.add(0, 0, a),           lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=a),       lambda a: (0, 0, a))
        do_test(lambda a: np.add(0, 0, out=(a,)),    lambda a: (0, 0, a)) 
Example 76
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: core.py    MIT License 4 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        """
        Execute the call behavior.

        """
        # Get the data, as ndarray
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate():
            np.seterr(divide='ignore', invalid='ignore')
            result = self.f(da, db, *args, **kwargs)
        # Get the mask for the result
        (ma, mb) = (getmask(a), getmask(b))
        if ma is nomask:
            if mb is nomask:
                m = nomask
            else:
                m = umath.logical_or(getmaskarray(a), mb)
        elif mb is nomask:
            m = umath.logical_or(ma, getmaskarray(b))
        else:
            m = umath.logical_or(ma, mb)

        # Case 1. : scalar
        if not result.ndim:
            if m:
                return masked
            return result

        # Case 2. : array
        # Revert result to da where masked
        if m is not nomask and m.any():
            # any errors, just abort; impossible to guarantee masked values
            try:
                np.copyto(result, 0, casting='unsafe', where=m)
                # avoid using "*" since this may be overlaid
                masked_da = umath.multiply(m, da)
                # only add back if it can be cast safely
                if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                    result += masked_da
            except:
                pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result 
Example 77
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    MIT License 4 votes vote down vote up
def test_out_subok(self):
        for subok in (True, False):
            a = np.array(0.5)
            o = np.empty(())

            r = np.add(a, 2, o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=(o,), subok=subok)
            assert_(r is o)

            d = np.array(5.7)
            o1 = np.empty(())
            o2 = np.empty((), dtype=np.int32)

            r1, r2 = np.frexp(d, o1, None, subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, None, o2, subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, o1, o2, subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            with warnings.catch_warnings(record=True) as w:
                warnings.filterwarnings('always', '', DeprecationWarning)
                r1, r2 = np.frexp(d, out=o1, subok=subok)
                assert_(r1 is o1)
                assert_(w[0].category is DeprecationWarning)

            assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
            assert_raises(TypeError, np.add, a, 2, [], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
            o.flags.writeable = False
            assert_raises(ValueError, np.add, a, 2, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) 
Example 78
Project: vnpy_crypto   Author: birforce   File: core.py    MIT License 4 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= domain(da, db)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except Exception:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result


# Unary ufuncs 
Example 79
Project: vnpy_crypto   Author: birforce   File: test_umath.py    MIT License 4 votes vote down vote up
def test_out_subok(self):
        for subok in (True, False):
            a = np.array(0.5)
            o = np.empty(())

            r = np.add(a, 2, o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=o, subok=subok)
            assert_(r is o)
            r = np.add(a, 2, out=(o,), subok=subok)
            assert_(r is o)

            d = np.array(5.7)
            o1 = np.empty(())
            o2 = np.empty((), dtype=np.int32)

            r1, r2 = np.frexp(d, o1, None, subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, None, o2, subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, o1, o2, subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
            assert_(r1 is o1)
            r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
            assert_(r2 is o2)
            r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
            assert_(r1 is o1)
            assert_(r2 is o2)

            with warnings.catch_warnings(record=True) as w:
                warnings.filterwarnings('always', '', DeprecationWarning)
                r1, r2 = np.frexp(d, out=o1, subok=subok)
                assert_(r1 is o1)
                assert_(w[0].category is DeprecationWarning)

            assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
            assert_raises(TypeError, np.add, a, 2, [], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
            assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
            o.flags.writeable = False
            assert_raises(ValueError, np.add, a, 2, o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
            assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) 
Example 80
Project: ble5-nrf52-mac   Author: tomasero   File: core.py    MIT License 4 votes vote down vote up
def __call__(self, a, b, *args, **kwargs):
        "Execute the call behavior."
        # Get the data
        (da, db) = (getdata(a), getdata(b))
        # Get the result
        with np.errstate(divide='ignore', invalid='ignore'):
            result = self.f(da, db, *args, **kwargs)
        # Get the mask as a combination of the source masks and invalid
        m = ~umath.isfinite(result)
        m |= getmask(a)
        m |= getmask(b)
        # Apply the domain
        domain = ufunc_domain.get(self.f, None)
        if domain is not None:
            m |= domain(da, db)
        # Take care of the scalar case first
        if (not m.ndim):
            if m:
                return masked
            else:
                return result
        # When the mask is True, put back da if possible
        # any errors, just abort; impossible to guarantee masked values
        try:
            np.copyto(result, 0, casting='unsafe', where=m)
            # avoid using "*" since this may be overlaid
            masked_da = umath.multiply(m, da)
            # only add back if it can be cast safely
            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
                result += masked_da
        except Exception:
            pass

        # Transforms to a (subclass of) MaskedArray
        masked_result = result.view(get_masked_subclass(a, b))
        masked_result._mask = m
        if isinstance(a, MaskedArray):
            masked_result._update_from(a)
        elif isinstance(b, MaskedArray):
            masked_result._update_from(b)
        return masked_result


# Unary ufuncs