Python numpy.float_() Examples

The following are 30 code examples of numpy.float_(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: numpy_fenics.py    From torch-fenics with GNU General Public License v3.0 7 votes vote down vote up
def fenics_to_numpy(fenics_var):
    """Convert FEniCS variable to numpy array"""
    if isinstance(fenics_var, (fenics.Constant, fenics_adjoint.Constant)):
        return fenics_var.values()

    if isinstance(fenics_var, (fenics.Function, fenics_adjoint.Constant)):
        np_array = fenics_var.vector().get_local()
        n_sub = fenics_var.function_space().num_sub_spaces()
        # Reshape if function is multi-component
        if n_sub != 0:
            np_array = np.reshape(np_array, (len(np_array) // n_sub, n_sub))
        return np_array

    if isinstance(fenics_var, fenics.GenericVector):
        return fenics_var.get_local()

    if isinstance(fenics_var, fenics_adjoint.AdjFloat):
        return np.array(float(fenics_var), dtype=np.float_)

    raise ValueError('Cannot convert ' + str(type(fenics_var))) 
Example #2
Source File: testutils.py    From lambda-packs with MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example #3
Source File: testutils.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example #4
Source File: testutils.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """
    Returns true if all components of a and b are equal to given tolerances.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.  The relative error rtol should
    be positive and << 1.0 The absolute error atol comes into play for
    those elements of b that are very small or zero; it says how small a
    must be also.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel() 
Example #5
Source File: test_arithmetic.py    From mars with 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 #6
Source File: test_session.py    From mars with Apache License 2.0 6 votes vote down vote up
def testArrayProtocol(self):
        arr = mt.ones((10, 20))

        result = np.asarray(arr)
        np.testing.assert_array_equal(result, np.ones((10, 20)))

        arr2 = mt.ones((10, 20))

        result = np.asarray(arr2, mt.bool_)
        np.testing.assert_array_equal(result, np.ones((10, 20), dtype=np.bool_))

        arr3 = mt.ones((10, 20)).sum()

        result = np.asarray(arr3)
        np.testing.assert_array_equal(result, np.asarray(200))

        arr4 = mt.ones((10, 20)).sum()

        result = np.asarray(arr4, dtype=np.float_)
        np.testing.assert_array_equal(result, np.asarray(200, dtype=np.float_)) 
Example #7
Source File: test_indexing.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_empty_tuple_index(self):
        # Empty tuple index creates a view
        a = np.array([1, 2, 3])
        assert_equal(a[()], a)
        assert_(a[()].base is a)
        a = np.array(0)
        assert_(isinstance(a[()], np.int_))

        # Regression, it needs to fall through integer and fancy indexing
        # cases, so need the with statement to ignore the non-integer error.
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', '', DeprecationWarning)
            a = np.array([1.])
            assert_(isinstance(a[0.], np.float_))

            a = np.array([np.array(1)], dtype=object)
            assert_(isinstance(a[0.], np.ndarray)) 
Example #8
Source File: test_constructors.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_fromValue(self, datetime_series):

        nans = Series(np.NaN, index=datetime_series.index)
        assert nans.dtype == np.float_
        assert len(nans) == len(datetime_series)

        strings = Series('foo', index=datetime_series.index)
        assert strings.dtype == np.object_
        assert len(strings) == len(datetime_series)

        d = datetime.now()
        dates = Series(d, index=datetime_series.index)
        assert dates.dtype == 'M8[ns]'
        assert len(dates) == len(datetime_series)

        # GH12336
        # Test construction of categorical series from value
        categorical = Series(0, index=datetime_series.index, dtype="category")
        expected = Series(0, index=datetime_series.index).astype("category")
        assert categorical.dtype == 'category'
        assert len(categorical) == len(datetime_series)
        tm.assert_series_equal(categorical, expected) 
Example #9
Source File: testutils.py    From lambda-packs with MIT License 6 votes vote down vote up
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """
    Returns true if all components of a and b are equal to given tolerances.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.  The relative error rtol should
    be positive and << 1.0 The absolute error atol comes into play for
    those elements of b that are very small or zero; it says how small a
    must be also.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel() 
Example #10
Source File: testutils.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example #11
Source File: testutils.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """
    Returns true if all components of a and b are equal to given tolerances.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.  The relative error rtol should
    be positive and << 1.0 The absolute error atol comes into play for
    those elements of b that are very small or zero; it says how small a
    must be also.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel() 
Example #12
Source File: testutils.py    From recruit with Apache License 2.0 6 votes vote down vote up
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """
    Returns true if all components of a and b are equal to given tolerances.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.  The relative error rtol should
    be positive and << 1.0 The absolute error atol comes into play for
    those elements of b that are very small or zero; it says how small a
    must be also.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel() 
Example #13
Source File: testutils.py    From lambda-packs with MIT License 6 votes vote down vote up
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """
    Returns true if all components of a and b are equal to given tolerances.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.  The relative error rtol should
    be positive and << 1.0 The absolute error atol comes into play for
    those elements of b that are very small or zero; it says how small a
    must be also.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel() 
Example #14
Source File: testutils.py    From lambda-packs with MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example #15
Source File: test_linalg.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_nan(self):
        # nans should be passed through, not converted to infs
        ps = [None, 1, -1, 2, -2, 'fro']
        p_pos = [None, 1, 2, 'fro']

        A = np.ones((2, 2))
        A[0,1] = np.nan
        for p in ps:
            c = linalg.cond(A, p)
            assert_(isinstance(c, np.float_))
            assert_(np.isnan(c))

        A = np.ones((3, 2, 2))
        A[1,0,1] = np.nan
        for p in ps:
            c = linalg.cond(A, p)
            assert_(np.isnan(c[1]))
            if p in p_pos:
                assert_(c[0] > 1e15)
                assert_(c[2] > 1e15)
            else:
                assert_(not np.isnan(c[0]))
                assert_(not np.isnan(c[2])) 
Example #16
Source File: test_regression.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_numpy_float_python_long_addition(self):
        # Check that numpy float and python longs can be added correctly.
        a = np.float_(23.) + 2**135
        assert_equal(a, 23. + 2**135) 
Example #17
Source File: test_extras.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_testAverage2(self):
        # More tests of average.
        w1 = [0, 1, 1, 1, 1, 0]
        w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
        x = arange(6, dtype=np.float_)
        assert_equal(average(x, axis=0), 2.5)
        assert_equal(average(x, axis=0, weights=w1), 2.5)
        y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
        assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
        assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
        assert_equal(average(y, axis=1),
                     [average(x, axis=0), average(x, axis=0) * 2.0])
        assert_equal(average(y, None, weights=w2), 20. / 6.)
        assert_equal(average(y, axis=0, weights=w2),
                     [0., 1., 2., 3., 4., 10.])
        assert_equal(average(y, axis=1),
                     [average(x, axis=0), average(x, axis=0) * 2.0])
        m1 = zeros(6)
        m2 = [0, 0, 1, 1, 0, 0]
        m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
        m4 = ones(6)
        m5 = [0, 1, 1, 1, 1, 1]
        assert_equal(average(masked_array(x, m1), axis=0), 2.5)
        assert_equal(average(masked_array(x, m2), axis=0), 2.5)
        assert_equal(average(masked_array(x, m4), axis=0).mask, [True])
        assert_equal(average(masked_array(x, m5), axis=0), 0.0)
        assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
        z = masked_array(y, m3)
        assert_equal(average(z, None), 20. / 6.)
        assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
        assert_equal(average(z, axis=1), [2.5, 5.0])
        assert_equal(average(z, axis=0, weights=w2),
                     [0., 1., 99., 99., 4.0, 10.0]) 
Example #18
Source File: solution_classes.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self,  obj):

        if isinstance(obj, SolutionPool):

            self._P = obj.P
            self._objvals = obj.objvals
            self._solutions = obj.solutions

        elif isinstance(obj, int):

            assert obj >= 1
            self._P = int(obj)
            self._objvals = np.empty(0)
            self._solutions = np.empty(shape = (0, self._P))

        elif isinstance(obj, dict):

            assert len(obj) == 2
            objvals = np.copy(obj['objvals']).flatten().astype(dtype = np.float_)
            solutions = np.copy(obj['solutions'])
            n = objvals.size
            if solutions.ndim == 2:
                assert n in solutions.shape
                if solutions.shape[1] == n and solutions.shape[0] != n:
                    solutions = np.transpose(solutions)
            elif solutions.ndim == 1:
                assert n == 1
                solutions = np.reshape(solutions, (1, solutions.size))
            else:
                raise ValueError('solutions has more than 2 dimensions')

            self._P = solutions.shape[1]
            self._objvals = objvals
            self._solutions = solutions

        else:
            raise ValueError('cannot initialize SolutionPool using %s object' % type(obj)) 
Example #19
Source File: test_indexing.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_scalar_return_type(self):
        # Full scalar indices should return scalars and object
        # arrays should not call PyArray_Return on their items
        class Zero(object):
            # The most basic valid indexing
            def __index__(self):
                return 0

        z = Zero()

        class ArrayLike(object):
            # Simple array, should behave like the array
            def __array__(self):
                return np.array(0)

        a = np.zeros(())
        assert_(isinstance(a[()], np.float_))
        a = np.zeros(1)
        assert_(isinstance(a[z], np.float_))
        a = np.zeros((1, 1))
        assert_(isinstance(a[z, np.array(0)], np.float_))
        assert_(isinstance(a[z, ArrayLike()], np.float_))

        # And object arrays do not call it too often:
        b = np.array(0)
        a = np.array(0, dtype=object)
        a[()] = b
        assert_(isinstance(a[()], np.ndarray))
        a = np.array([b, None])
        assert_(isinstance(a[z], np.ndarray))
        a = np.array([[b, None]])
        assert_(isinstance(a[z, np.array(0)], np.ndarray))
        assert_(isinstance(a[z, ArrayLike()], np.ndarray)) 
Example #20
Source File: test_deprecations.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_non_integer_sequence_multiplication(self):
        # Numpy scalar sequence multiply should not work with non-integers
        def mult(a, b):
            return a * b

        self.assert_deprecated(mult, args=([1], np.float_(3)))
        self.assert_not_deprecated(mult, args=([1], np.int_(3))) 
Example #21
Source File: data.py    From justcopy-backend with MIT License 5 votes vote down vote up
def __iter__(self):
        lengths = np.array(
            [(-l[0], -l[1], np.random.random()) for l in self.lengths],
            dtype=[('l1', np.int_), ('l2', np.int_), ('rand', np.float_)]
        )
        indices = np.argsort(lengths, order=('l1', 'l2', 'rand'))
        batches = [indices[i:i + self.batch_size]
                   for i in range(0, len(indices), self.batch_size)]
        if self.shuffle:
            np.random.shuffle(batches)
        return iter([i for batch in batches for i in batch]) 
Example #22
Source File: test_old_ma.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_ptp(self):
        (x, X, XX, m, mx, mX, mXX,) = self.d
        (n, m) = X.shape
        self.assertEqual(mx.ptp(), mx.compressed().ptp())
        rows = np.zeros(n, np.float_)
        cols = np.zeros(m, np.float_)
        for k in range(m):
            cols[k] = mX[:, k].compressed().ptp()
        for k in range(n):
            rows[k] = mX[k].compressed().ptp()
        self.assertTrue(eq(mX.ptp(0), cols))
        self.assertTrue(eq(mX.ptp(1), rows)) 
Example #23
Source File: test_extras.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_testAverage2(self):
        # More tests of average.
        w1 = [0, 1, 1, 1, 1, 0]
        w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
        x = arange(6, dtype=np.float_)
        assert_equal(average(x, axis=0), 2.5)
        assert_equal(average(x, axis=0, weights=w1), 2.5)
        y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
        assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
        assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
        assert_equal(average(y, axis=1),
                     [average(x, axis=0), average(x, axis=0) * 2.0])
        assert_equal(average(y, None, weights=w2), 20. / 6.)
        assert_equal(average(y, axis=0, weights=w2),
                     [0., 1., 2., 3., 4., 10.])
        assert_equal(average(y, axis=1),
                     [average(x, axis=0), average(x, axis=0) * 2.0])
        m1 = zeros(6)
        m2 = [0, 0, 1, 1, 0, 0]
        m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
        m4 = ones(6)
        m5 = [0, 1, 1, 1, 1, 1]
        assert_equal(average(masked_array(x, m1), axis=0), 2.5)
        assert_equal(average(masked_array(x, m2), axis=0), 2.5)
        assert_equal(average(masked_array(x, m4), axis=0).mask, [True])
        assert_equal(average(masked_array(x, m5), axis=0), 0.0)
        assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
        z = masked_array(y, m3)
        assert_equal(average(z, None), 20. / 6.)
        assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
        assert_equal(average(z, axis=1), [2.5, 5.0])
        assert_equal(average(z, axis=0, weights=w2),
                     [0., 1., 99., 99., 4.0, 10.0]) 
Example #24
Source File: test_extras.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_testAverage2(self):
        # More tests of average.
        w1 = [0, 1, 1, 1, 1, 0]
        w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
        x = arange(6, dtype=np.float_)
        assert_equal(average(x, axis=0), 2.5)
        assert_equal(average(x, axis=0, weights=w1), 2.5)
        y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
        assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
        assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
        assert_equal(average(y, axis=1),
                     [average(x, axis=0), average(x, axis=0) * 2.0])
        assert_equal(average(y, None, weights=w2), 20. / 6.)
        assert_equal(average(y, axis=0, weights=w2),
                     [0., 1., 2., 3., 4., 10.])
        assert_equal(average(y, axis=1),
                     [average(x, axis=0), average(x, axis=0) * 2.0])
        m1 = zeros(6)
        m2 = [0, 0, 1, 1, 0, 0]
        m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
        m4 = ones(6)
        m5 = [0, 1, 1, 1, 1, 1]
        assert_equal(average(masked_array(x, m1), axis=0), 2.5)
        assert_equal(average(masked_array(x, m2), axis=0), 2.5)
        assert_equal(average(masked_array(x, m4), axis=0).mask, [True])
        assert_equal(average(masked_array(x, m5), axis=0), 0.0)
        assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
        z = masked_array(y, m3)
        assert_equal(average(z, None), 20. / 6.)
        assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
        assert_equal(average(z, axis=1), [2.5, 5.0])
        assert_equal(average(z, axis=0, weights=w2),
                     [0., 1., 99., 99., 4.0, 10.0]) 
Example #25
Source File: rbf.py    From lambda-packs with MIT License 5 votes vote down vote up
def __call__(self, *args):
        args = [np.asarray(x) for x in args]
        if not all([x.shape == y.shape for x in args for y in args]):
            raise ValueError("Array lengths must be equal")
        shp = args[0].shape
        xa = np.asarray([a.flatten() for a in args], dtype=np.float_)
        r = self._call_norm(xa, self.xi)
        return np.dot(self._function(r), self.nodes).reshape(shp) 
Example #26
Source File: rbf.py    From lambda-packs with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.xi = np.asarray([np.asarray(a, dtype=np.float_).flatten()
                           for a in args[:-1]])
        self.N = self.xi.shape[-1]
        self.di = np.asarray(args[-1]).flatten()

        if not all([x.size == self.di.size for x in self.xi]):
            raise ValueError("All arrays must be equal length.")

        self.norm = kwargs.pop('norm', self._euclidean_norm)
        self.epsilon = kwargs.pop('epsilon', None)
        if self.epsilon is None:
            # default epsilon is the "the average distance between nodes" based
            # on a bounding hypercube
            dim = self.xi.shape[0]
            ximax = np.amax(self.xi, axis=1)
            ximin = np.amin(self.xi, axis=1)
            edges = ximax-ximin
            edges = edges[np.nonzero(edges)]
            self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size)
        self.smooth = kwargs.pop('smooth', 0.0)

        self.function = kwargs.pop('function', 'multiquadric')

        # attach anything left in kwargs to self
        #  for use by any user-callable function or
        #  to save on the object returned.
        for item, value in kwargs.items():
            setattr(self, item, value)

        self.nodes = linalg.solve(self.A, self.di) 
Example #27
Source File: sputils.py    From lambda-packs with MIT License 5 votes vote down vote up
def get_sum_dtype(dtype):
    """Mimic numpy's casting for np.sum"""
    if np.issubdtype(dtype, np.float_):
        return np.float_
    if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
        return np.uint
    if np.can_cast(dtype, np.int_):
        return np.int_
    return dtype 
Example #28
Source File: observable_array.py    From paramz with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __new__(cls, input_array, *a, **kw):
        # allways make a copy of input paramters, as we need it to be in C order:
        if not isinstance(input_array, ObsAr):
            try:
                # try to cast ints to floats
                obj = np.atleast_1d(np.require(input_array, dtype=np.float_, requirements=['W', 'C'])).view(cls)
            except ValueError:
                # do we have other dtypes in the array?
                obj = np.atleast_1d(np.require(input_array, requirements=['W', 'C'])).view(cls)
        else: obj = input_array
        super(ObsAr, obj).__init__(*a, **kw)
        return obj 
Example #29
Source File: observable_tests.py    From paramz with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_casting(self):
        ints = np.array(range(10))
        self.assertEqual(ints.dtype, np.int_)
        floats = np.arange(0,5,.5)
        self.assertEqual(floats.dtype, np.float_)
        strings = np.array(list('testing'))
        self.assertEqual(strings.dtype.type, np.str_)

        self.assertEqual(ObsAr(ints).dtype, np.float_)
        self.assertEqual(ObsAr(floats).dtype, np.float_)
        self.assertEqual(ObsAr(strings).dtype.type, np.str_) 
Example #30
Source File: core.py    From mars with Apache License 2.0 5 votes vote down vote up
def mutable_tensor(name, shape=None, dtype=np.float_, fill_value=None, chunk_size=None):
    """
    Create or get a mutable tensor using the local or default session.

    When `shape` is `None`, it will try to get the mutable tensor with name `name`. Otherwise,
    it will try to create a mutable tensor using the provided `name` and `shape`.

    Parameters
    ----------
    name : str
        Name of the mutable tensor.
    shape : int or sequence of ints
        Shape of the new mutable tensor, e.g., ``(2, 3)`` or ``2``.
    dtype : data-type, optional
        The desired data-type for the mutable tensor, e.g., `mt.int8`.  Default is `mt.float_`.
    chunk_size: int or tuple of ints, optional
        Specifies chunk size for each dimension.
    fill_value: scalar, optional
        The created mutable tensor will be filled by `fill_value` defaultly, if the parameter is None,
        the newly created mutable tensor will be initialized with `np.zeros`. See also `numpy.full`.
    """
    from ..session import Session
    session = Session.default_or_local()

    if shape is None:
        return session.get_mutable_tensor(name)
    else:
        return session.create_mutable_tensor(name, shape=shape, dtype=dtype,
                                             fill_value=fill_value, chunk_size=chunk_size)