Python numpy.frexp() Examples

The following are 30 code examples for showing how to use numpy.frexp(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 2
Project: pylogit   Author: timothyb0912   File: choice_calcs.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def robust_outer_product(vec_1, vec_2):
    """
    Calculates a 'robust' outer product of two vectors that may or may not
    contain very small values.

    Parameters
    ----------
    vec_1 : 1D ndarray
    vec_2 : 1D ndarray

    Returns
    -------
    outer_prod : 2D ndarray. The outer product of vec_1 and vec_2
    """
    mantissa_1, exponents_1 = np.frexp(vec_1)
    mantissa_2, exponents_2 = np.frexp(vec_2)
    new_mantissas = mantissa_1[None, :] * mantissa_2[:, None]
    new_exponents = exponents_1[None, :] + exponents_2[:, None]
    return new_mantissas * np.exp2(new_exponents) 
Example 3
Project: mars   Author: mars-project   File: test_arithmetic.py    License: Apache License 2.0 6 votes vote down vote up
def testFrexp(self):
        t1 = ones((3, 4, 5), chunk_size=2)
        t2 = empty((3, 4, 5), dtype=np.float_, chunk_size=2)
        op_type = type(t1.op)

        o1, o2 = frexp(t1)

        self.assertIs(o1.op, o2.op)
        self.assertNotEqual(o1.dtype, o2.dtype)

        o1, o2 = frexp(t1, t1)

        self.assertIs(o1, t1)
        self.assertIsNot(o1.inputs[0], t1)
        self.assertIsInstance(o1.inputs[0].op, op_type)
        self.assertIsNot(o2.inputs[0], t1)

        o1, o2 = frexp(t1, t2, where=t1 > 0)

        op_type = type(t2.op)
        self.assertIs(o1, t2)
        self.assertIsNot(o1.inputs[0], t1)
        self.assertIsInstance(o1.inputs[0].op, op_type)
        self.assertIsNot(o2.inputs[0], t1) 
Example 4
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 5
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 6
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_decomp.py    License: MIT License 6 votes vote down vote up
def clear_fuss(ar, fuss_binary_bits=7):
    """Clears trailing `fuss_binary_bits` of mantissa of a floating number"""
    x = np.asanyarray(ar)
    if np.iscomplexobj(x):
        return clear_fuss(x.real) + 1j * clear_fuss(x.imag)

    significant_binary_bits = np.finfo(x.dtype).nmant
    x_mant, x_exp = np.frexp(x)
    f = 2.0**(significant_binary_bits - fuss_binary_bits)
    x_mant *= f
    np.rint(x_mant, out=x_mant)
    x_mant /= f

    return np.ldexp(x_mant, x_exp)


# XXX: This function should be available through numpy.testing 
Example 7
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 8
Project: pySINDy   Author: luckystarufo   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 9
Project: coffeegrindsize   Author: jgagneastro   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 10
Project: Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda   Author: PacktPublishing   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 11
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

        class Ok(np.ndarray):
            def __array_wrap__(self, obj):
                return singleton

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

        ok = np.empty(1).view(Ok)
        bad = np.empty(1).view(Bad)

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example 12
Project: recruit   Author: Frank-qlu   File: test_mixins.py    License: Apache License 2.0 5 votes vote down vote up
def test_ufunc_two_outputs(self):
        mantissa, exponent = np.frexp(2 ** -3)
        expected = (ArrayLike(mantissa), ArrayLike(exponent))
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(2 ** -3)), expected)
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(np.array(2 ** -3))), expected) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: 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 14
Project: mars   Author: mars-project   File: frexp.py    License: Apache License 2.0 5 votes vote down vote up
def execute(cls, ctx, op):
        inputs, device_id, xp = as_same_device(
            [ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)

        with device(device_id):
            kw = {'casting': op.casting}

            inputs_iter = iter(inputs)
            input = next(inputs_iter)
            if op.out1 is not None:
                out1 = next(inputs_iter)
            else:
                out1 = None
            if op.out2 is not None:
                out2 = next(inputs_iter)
            else:
                out2 = None
            if op.where is not None:
                where = kw['where'] = next(inputs_iter)
            else:
                where = None
            kw['order'] = op.order

            try:
                args = [input]
                if out1 is not None:
                    args.append(out1)
                if out2 is not None:
                    args.append(out2)
                mantissa, exponent = xp.frexp(*args, **kw)
            except TypeError:
                if where is None:
                    raise
                mantissa, exponent = xp.frexp(input)
                mantissa, exponent = xp.where(where, mantissa, out1), xp.where(where, exponent, out2)

            for c, res in zip(op.outputs, (mantissa, exponent)):
                ctx[c.key] = res 
Example 15
Project: mars   Author: mars-project   File: test_arithmetic_execution.py    License: Apache License 2.0 5 votes vote down vote up
def testFrexpExecution(self):
        data1 = np.random.random((5, 9, 4))

        arr1 = tensor(data1.copy(), chunk_size=3)

        o1, o2 = frexp(arr1)
        o = o1 + o2

        res = self.executor.execute_tensor(o, concat=True)[0]
        expected = sum(np.frexp(data1))
        self.assertTrue(np.allclose(res, expected))

        arr1 = tensor(data1.copy(), chunk_size=3)
        o1 = zeros(data1.shape, chunk_size=3)
        o2 = zeros(data1.shape, dtype='i8', chunk_size=3)
        frexp(arr1, o1, o2)
        o = o1 + o2

        res = self.executor.execute_tensor(o, concat=True)[0]
        expected = sum(np.frexp(data1))
        self.assertTrue(np.allclose(res, expected))

        data1 = sps.random(5, 9, density=.1)

        arr1 = tensor(data1.copy(), chunk_size=3)

        o1, o2 = frexp(arr1)
        o = o1 + o2

        res = self.executor.execute_tensor(o, concat=True)[0]
        expected = sum(np.frexp(data1.toarray()))
        np.testing.assert_equal(res.toarray(), expected) 
Example 16
Project: mars   Author: mars-project   File: test_arithmetic_execution.py    License: Apache License 2.0 5 votes vote down vote up
def testFrexpOrderExecution(self):
        data1 = np.random.random((5, 9))
        t = tensor(data1, chunk_size=3)

        o1, o2 = frexp(t, order='F')
        res1, res2 = self.executor.execute_tileables([o1, o2])
        expected1, expected2 = np.frexp(data1, order='F')
        np.testing.assert_allclose(res1, expected1)
        self.assertTrue(res1.flags['F_CONTIGUOUS'])
        self.assertFalse(res1.flags['C_CONTIGUOUS'])
        np.testing.assert_allclose(res2, expected2)
        self.assertTrue(res2.flags['F_CONTIGUOUS'])
        self.assertFalse(res2.flags['C_CONTIGUOUS']) 
Example 17
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_ufunc_override_out(self):
        # 2016-01-29: NUMPY_UFUNC_DISABLED
        return

        class A(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs

        class B(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs

        a = A()
        b = B()
        res0 = np.multiply(a, b, 'out_arg')
        res1 = np.multiply(a, b, out='out_arg')
        res2 = np.multiply(2, b, 'out_arg')
        res3 = np.multiply(3, b, out='out_arg')
        res4 = np.multiply(a, 4, 'out_arg')
        res5 = np.multiply(a, 5, out='out_arg')

        assert_equal(res0['out'], 'out_arg')
        assert_equal(res1['out'], 'out_arg')
        assert_equal(res2['out'], 'out_arg')
        assert_equal(res3['out'], 'out_arg')
        assert_equal(res4['out'], 'out_arg')
        assert_equal(res5['out'], 'out_arg')

        # ufuncs with multiple output modf and frexp.
        res6 = np.modf(a, 'out0', 'out1')
        res7 = np.frexp(a, 'out0', 'out1')
        assert_equal(res6['out'][0], 'out0')
        assert_equal(res6['out'][1], 'out1')
        assert_equal(res7['out'][0], 'out0')
        assert_equal(res7['out'][1], 'out1') 
Example 18
Project: vnpy_crypto   Author: birforce   File: test_mixins.py    License: MIT License 5 votes vote down vote up
def test_ufunc_two_outputs(self):
        mantissa, exponent = np.frexp(2 ** -3)
        expected = (ArrayLike(mantissa), ArrayLike(exponent))
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(2 ** -3)), expected)
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(np.array(2 ** -3))), expected) 
Example 19
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: 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 20
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_mixins.py    License: MIT License 5 votes vote down vote up
def test_ufunc_two_outputs(self):
        mantissa, exponent = np.frexp(2 ** -3)
        expected = (ArrayLike(mantissa), ArrayLike(exponent))
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(2 ** -3)), expected)
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(np.array(2 ** -3))), expected) 
Example 21
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: 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 22
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_mixins.py    License: MIT License 5 votes vote down vote up
def test_ufunc_two_outputs(self):
        mantissa, exponent = np.frexp(2 ** -3)
        expected = (ArrayLike(mantissa), ArrayLike(exponent))
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(2 ** -3)), expected)
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(np.array(2 ** -3))), expected) 
Example 23
def test_ufunc_two_outputs(self):
        mantissa, exponent = np.frexp(2 ** -3)
        expected = (ArrayLike(mantissa), ArrayLike(exponent))
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(2 ** -3)), expected)
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(np.array(2 ** -3))), expected) 
Example 24
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 25
Project: DeepHDR   Author: elliottwu   File: utils.py    License: MIT License 5 votes vote down vote up
def radiance_writer(out_path, image):
    with open(out_path, "wb") as f:
        f.write(b"#?RADIANCE\n# Made with Python & Numpy\nFORMAT=32-bit_rle_rgbe\n\n")
        f.write(b"-Y %d +X %d\n" %(image.shape[0], image.shape[1]))

        brightest = np.maximum(np.maximum(image[...,0], image[...,1]), image[...,2])
        mantissa = np.zeros_like(brightest)
        exponent = np.zeros_like(brightest)
        np.frexp(brightest, mantissa, exponent)
        scaled_mantissa = mantissa * 255.0 / brightest
        rgbe = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
        rgbe[...,0:3] = np.around(image[...,0:3] * scaled_mantissa[...,None])
        rgbe[...,3] = np.around(exponent + 128)

        rgbe.flatten().tofile(f) 
Example 26
Project: cupy   Author: cupy   File: test_floating.py    License: MIT License 5 votes vote down vote up
def test_frexp(self, dtype):
        numpy_a = numpy.array([-300, -20, -10, -1, 0, 1, 10, 20, 300],
                              dtype=dtype)
        numpy_b, numpy_c = numpy.frexp(numpy_a)

        cupy_a = cupy.array(numpy_a)
        cupy_b, cupy_c = cupy.frexp(cupy_a)

        testing.assert_array_equal(cupy_b, numpy_b)
        testing.assert_array_equal(cupy_c, numpy_c) 
Example 27
Project: pySINDy   Author: luckystarufo   File: test_mixins.py    License: MIT License 5 votes vote down vote up
def test_ufunc_two_outputs(self):
        mantissa, exponent = np.frexp(2 ** -3)
        expected = (ArrayLike(mantissa), ArrayLike(exponent))
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(2 ** -3)), expected)
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(np.array(2 ** -3))), expected) 
Example 28
Project: mxnet-lambda   Author: awslabs   File: test_mixins.py    License: Apache License 2.0 5 votes vote down vote up
def test_ufunc_two_outputs(self):
        mantissa, exponent = np.frexp(2 ** -3)
        expected = (ArrayLike(mantissa), ArrayLike(exponent))
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(2 ** -3)), expected)
        _assert_equal_type_and_value(
            np.frexp(ArrayLike(np.array(2 ** -3))), expected) 
Example 29
Project: mxnet-lambda   Author: awslabs   File: test_umath.py    License: 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 30
Project: Maix-EMC   Author: sipeed   File: k210_layer.py    License: Apache License 2.0 5 votes vote down vote up
def pow_next_log_of_2_no_round(value, bound_shift, shift_max_shift=4):
    mul, shift = np.frexp(np.abs(value))    # value = mul(0~1)*(1 << shift)
    ret = bound_shift - 1 - shift           # shift to full bound_shift
    mul = np.sign(value) * mul * np.power(2, bound_shift - 1)   # scale mul
    # value = mul>>ret
    return ret, mul