Python numpy.int_() Examples

The following are 30 code examples of numpy.int_(). 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: test_linalg.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res, res_v = linalg.eigh(a)
        assert_(res_v.dtype.type is np.float64)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0, 1), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res, res_v = linalg.eigh(a)
        assert_(res_v.dtype.type is np.complex64)
        assert_(res.dtype.type is np.float32)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0,), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray)) 
Example #2
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_custom_getitem(self):
        rng = pd.bdate_range(START, END, freq='C')
        smaller = rng[:5]
        exp = DatetimeIndex(rng.view(np.ndarray)[:5])
        tm.assert_index_equal(smaller, exp)
        assert smaller.freq == rng.freq

        sliced = rng[::5]
        assert sliced.freq == CDay() * 5

        fancy_indexed = rng[[4, 3, 2, 1, 0]]
        assert len(fancy_indexed) == 5
        assert isinstance(fancy_indexed, DatetimeIndex)
        assert fancy_indexed.freq is None

        # 32-bit vs. 64-bit platforms
        assert rng[4] == rng[np.int_(4)] 
Example #3
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_business_getitem(self):
        rng = pd.bdate_range(START, END)
        smaller = rng[:5]
        exp = DatetimeIndex(rng.view(np.ndarray)[:5])
        tm.assert_index_equal(smaller, exp)

        assert smaller.freq == rng.freq

        sliced = rng[::5]
        assert sliced.freq == BDay() * 5

        fancy_indexed = rng[[4, 3, 2, 1, 0]]
        assert len(fancy_indexed) == 5
        assert isinstance(fancy_indexed, DatetimeIndex)
        assert fancy_indexed.freq is None

        # 32-bit vs. 64-bit platforms
        assert rng[4] == rng[np.int_(4)] 
Example #4
Source File: test_core.py    From lambda-packs with MIT License 6 votes vote down vote up
def test_allclose(self):
        # Tests allclose on arrays
        a = np.random.rand(10)
        b = a + np.random.rand(10) * 1e-8
        self.assertTrue(allclose(a, b))
        # Test allclose w/ infs
        a[0] = np.inf
        self.assertTrue(not allclose(a, b))
        b[0] = np.inf
        self.assertTrue(allclose(a, b))
        # Test allclose w/ masked
        a = masked_array(a)
        a[-1] = masked
        self.assertTrue(allclose(a, b, masked_equal=True))
        self.assertTrue(not allclose(a, b, masked_equal=False))
        # Test comparison w/ scalar
        a *= 1e-8
        a[0] = 0
        self.assertTrue(allclose(a, 0, masked_equal=True))

        # Test that the function works for MIN_INT integer typed arrays
        a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
        self.assertTrue(allclose(a, a)) 
Example #5
Source File: test_scalarmath.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_no_seq_repeat_basic_array_like(self):
        # Test that an array-like which does not know how to be multiplied
        # does not attempt sequence repeat (raise TypeError).
        # See also gh-7428.
        class ArrayLike(object):
            def __init__(self, arr):
                self.arr = arr
            def __array__(self):
                return self.arr

        # Test for simple ArrayLike above and memoryviews (original report)
        for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))):
            assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.))
            assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.))
            assert_array_equal(arr_like * np.int_(3), np.full(3, 3))
            assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) 
Example #6
Source File: test_core.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_allclose(self):
        # Tests allclose on arrays
        a = np.random.rand(10)
        b = a + np.random.rand(10) * 1e-8
        self.assertTrue(allclose(a, b))
        # Test allclose w/ infs
        a[0] = np.inf
        self.assertTrue(not allclose(a, b))
        b[0] = np.inf
        self.assertTrue(allclose(a, b))
        # Test allclose w/ masked
        a = masked_array(a)
        a[-1] = masked
        self.assertTrue(allclose(a, b, masked_equal=True))
        self.assertTrue(not allclose(a, b, masked_equal=False))
        # Test comparison w/ scalar
        a *= 1e-8
        a[0] = 0
        self.assertTrue(allclose(a, 0, masked_equal=True))

        # Test that the function works for MIN_INT integer typed arrays
        a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
        self.assertTrue(allclose(a, a)) 
Example #7
Source File: histograms.py    From lambda-packs with MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example #8
Source File: testyamlfe.py    From westpa with MIT License 6 votes vote down vote up
def initialize(self):
        self.pcoord_ndim = 1
        self.pcoord_dtype = numpy.float32
        self.pcoord_len = 5
        self.bin_mapper = RectilinearBinMapper([ list(numpy.arange(0.0, 10.1, 0.1)) ] )
        self.bin_target_counts = numpy.empty((self.bin_mapper.nbins,), numpy.int_)
        self.bin_target_counts[...] = 10
        self.test_variable_2 = "And I'm the second one"

# YAML Front end tests

# Implemented basic tests
#  - returns the correct system 
#    given a system driver
#  - returns the correct system
#    given a yaml system
#  - returns the correct system
#    given both

# A class to test both paths at the same time
# if it works we assure we can load the driver
# AND overwrite it properly 
Example #9
Source File: test_linalg.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res, res_v = linalg.eigh(a)
        assert_(res_v.dtype.type is np.float64)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0, 1), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res, res_v = linalg.eigh(a)
        assert_(res_v.dtype.type is np.complex64)
        assert_(res.dtype.type is np.float32)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0,), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray)) 
Example #10
Source File: test_linalg.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res, res_v = linalg.eig(a)
        assert_(res_v.dtype.type is np.float64)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0, 1), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res, res_v = linalg.eig(a)
        assert_(res_v.dtype.type is np.complex64)
        assert_(res.dtype.type is np.complex64)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0,), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray)) 
Example #11
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 #12
Source File: lattice.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def boundary_conditions(self, bc):
        global bc_choices
        if bc in list(bc_choices.keys()):
            bc = [bc_choices[bc]] * self.dim
            self.bc_shift = None
        else:
            bc = list(bc)  # we modify entries...
            self.bc_shift = np.zeros(self.dim - 1, np.int_)
            for i, bc_i in enumerate(bc):
                if isinstance(bc_i, int):
                    if i == 0:
                        raise ValueError("Invalid bc: first entry can't be a shift")
                    self.bc_shift[i - 1] = bc_i
                    bc[i] = bc_choices['periodic']
                else:
                    bc[i] = bc_choices[bc_i]
            if not np.any(self.bc_shift != 0):
                self.bc_shift = None
        self.bc = np.array(bc) 
Example #13
Source File: histogram.py    From mars with Apache License 2.0 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:  # pragma: no cover
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example #14
Source File: test_datasource_execute.py    From mars with Apache License 2.0 6 votes vote down vote up
def testLinspaceExecution(self):
        a = linspace(2.0, 9.0, num=11, chunk_size=3)

        res = self.executor.execute_tensor(a, concat=True)[0]
        expected = np.linspace(2.0, 9.0, num=11)
        np.testing.assert_allclose(res, expected)

        a = linspace(2.0, 9.0, num=11, endpoint=False, chunk_size=3)

        res = self.executor.execute_tensor(a, concat=True)[0]
        expected = np.linspace(2.0, 9.0, num=11, endpoint=False)
        np.testing.assert_allclose(res, expected)

        a = linspace(2.0, 9.0, num=11, chunk_size=3, dtype=int)

        res = self.executor.execute_tensor(a, concat=True)[0]
        self.assertEqual(res.dtype, np.int_) 
Example #15
Source File: test_linalg.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res = linalg.eigvalsh(a)
        assert_(res.dtype.type is np.float64)
        assert_equal((0, 1), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(res, np.ndarray))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res = linalg.eigvalsh(a)
        assert_(res.dtype.type is np.float32)
        assert_equal((0,), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(res, np.ndarray)) 
Example #16
Source File: test_linalg.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res, res_v = linalg.eig(a)
        assert_(res_v.dtype.type is np.float64)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0, 1), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res, res_v = linalg.eig(a)
        assert_(res_v.dtype.type is np.complex64)
        assert_(res.dtype.type is np.complex64)
        assert_equal(a.shape, res_v.shape)
        assert_equal((0,), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(a, np.ndarray)) 
Example #17
Source File: test_core.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_allclose(self):
        # Tests allclose on arrays
        a = np.random.rand(10)
        b = a + np.random.rand(10) * 1e-8
        assert_(allclose(a, b))
        # Test allclose w/ infs
        a[0] = np.inf
        assert_(not allclose(a, b))
        b[0] = np.inf
        assert_(allclose(a, b))
        # Test allclose w/ masked
        a = masked_array(a)
        a[-1] = masked
        assert_(allclose(a, b, masked_equal=True))
        assert_(not allclose(a, b, masked_equal=False))
        # Test comparison w/ scalar
        a *= 1e-8
        a[0] = 0
        assert_(allclose(a, 0, masked_equal=True))

        # Test that the function works for MIN_INT integer typed arrays
        a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
        assert_(allclose(a, a)) 
Example #18
Source File: image_process.py    From Advanced_Lane_Lines with MIT License 6 votes vote down vote up
def draw_lane_fit(undist, warped ,Minv, left_fitx, right_fitx, ploty):
	# Drawing
	# Create an image to draw the lines on
	warp_zero = np.zeros_like(warped).astype(np.uint8)
	color_warp = np.dstack((warp_zero, warp_zero, warp_zero))

	# Recast the x and y points into usable format for cv2.fillPoly()
	pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
	pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
	pts = np.hstack((pts_left, pts_right))

	# Draw the lane onto the warped blank image
	cv2.fillPoly(color_warp, np.int_([pts]), (0,255,0))

	# Warp the blank back to original image space using inverse perspective matrix(Minv)
	newwarp = cv2.warpPerspective(color_warp, Minv, (undist.shape[1], undist.shape[0]))
	# Combine the result with the original image
	result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)

	return result 
Example #19
Source File: test_core.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_allclose(self):
        # Tests allclose on arrays
        a = np.random.rand(10)
        b = a + np.random.rand(10) * 1e-8
        assert_(allclose(a, b))
        # Test allclose w/ infs
        a[0] = np.inf
        assert_(not allclose(a, b))
        b[0] = np.inf
        assert_(allclose(a, b))
        # Test allclose w/ masked
        a = masked_array(a)
        a[-1] = masked
        assert_(allclose(a, b, masked_equal=True))
        assert_(not allclose(a, b, masked_equal=False))
        # Test comparison w/ scalar
        a *= 1e-8
        a[0] = 0
        assert_(allclose(a, 0, masked_equal=True))

        # Test that the function works for MIN_INT integer typed arrays
        a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
        assert_(allclose(a, a)) 
Example #20
Source File: test_linalg.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res = linalg.eigvals(a)
        assert_(res.dtype.type is np.float64)
        assert_equal((0, 1), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(res, np.ndarray))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res = linalg.eigvals(a)
        assert_(res.dtype.type is np.complex64)
        assert_equal((0,), res.shape)
        # This is just for documentation, it might make sense to change:
        assert_(isinstance(res, np.ndarray)) 
Example #21
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 #22
Source File: test_regression.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_intp(self,level=rlevel):
        # Ticket #99
        i_width = np.int_(0).nbytes*2 - 1
        np.intp('0x' + 'f'*i_width, 16)
        self.assertRaises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16)
        self.assertRaises(ValueError, np.intp, '0x1', 32)
        assert_equal(255, np.intp('0xFF', 16))
        assert_equal(1024, np.intp(1024)) 
Example #23
Source File: test_datasource_execute.py    From mars with Apache License 2.0 5 votes vote down vote up
def testCreateSparseExecution(self):
        mat = sps.csr_matrix([[0, 0, 2], [2, 0, 0]])
        t = tensor(mat, dtype='f8', chunk_size=2)

        res = self.executor.execute_tensor(t)
        self.assertIsInstance(res[0], SparseNDArray)
        self.assertEqual(res[0].dtype, np.float64)
        np.testing.assert_array_equal(res[0].toarray(), mat[..., :2].toarray())
        np.testing.assert_array_equal(res[1].toarray(), mat[..., 2:].toarray())

        t2 = ones_like(t, dtype='f4')

        res = self.executor.execute_tensor(t2)
        expected = sps.csr_matrix([[0, 0, 1], [1, 0, 0]])
        self.assertIsInstance(res[0], SparseNDArray)
        self.assertEqual(res[0].dtype, np.float32)
        np.testing.assert_array_equal(res[0].toarray(), expected[..., :2].toarray())
        np.testing.assert_array_equal(res[1].toarray(), expected[..., 2:].toarray())

        t3 = tensor(np.array([[0, 0, 2], [2, 0, 0]]), chunk_size=2).tosparse()

        res = self.executor.execute_tensor(t3)
        self.assertIsInstance(res[0], SparseNDArray)
        self.assertEqual(res[0].dtype, np.int_)
        np.testing.assert_array_equal(res[0].toarray(), mat[..., :2].toarray())
        np.testing.assert_array_equal(res[1].toarray(), mat[..., 2:].toarray()) 
Example #24
Source File: test_nanfunctions.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_out_dtype_error(self):
        for f in self.nanfuncs:
            for dtype in [np.bool_, np.int_, np.object_]:
                out = np.empty(_ndat.shape[0], dtype=dtype)
                assert_raises(TypeError, f, _ndat, axis=1, out=out) 
Example #25
Source File: test_nanfunctions.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_dtype_error(self):
        for f in self.nanfuncs:
            for dtype in [np.bool_, np.int_, np.object_]:
                assert_raises(TypeError, f, _ndat, axis=1, dtype=dtype) 
Example #26
Source File: _discrete_distns.py    From lambda-packs with MIT License 5 votes vote down vote up
def _rvs(self, low, high):
        """An array of *size* random integers >= ``low`` and < ``high``."""
        if self._size is not None:
            # Numpy's RandomState.randint() doesn't broadcast its arguments.
            # Use `broadcast_to()` to extend the shapes of low and high
            # up to self._size.  Then we can use the numpy.vectorize'd
            # randint without needing to pass it a `size` argument.
            low = broadcast_to(low, self._size)
            high = broadcast_to(high, self._size)
        randint = np.vectorize(self._random_state.randint, otypes=[np.int_])
        return randint(low, high) 
Example #27
Source File: w_succ.py    From westpa with MIT License 5 votes vote down vote up
def find_successful_trajs(self):
        pcoord_formats = {'u8': '%20d',
                          'i8': '%20d',
                          'u4': '%10d',
                          'i4': '%11d',
                          'u2': '%5d',
                          'i2': '%6d',
                          'f4': '%14.7g',
                          'f8': '%23.15g'}
        
        if not self.output_suppress_headers:
            self.output_file.write('''\
# successful (recycled) segments 
# column 0:    iteration
# column 1:    seg_id
# column 2:    weight
# column>2:    final progress coordinate value
''')
        for n_iter in range(1, self.data_manager.current_iteration):
            seg_index = self.get_seg_index(n_iter)
            all_seg_ids = numpy.arange(len(seg_index), dtype=numpy.int_)
            recycled_seg_ids = all_seg_ids[seg_index[:]['endpoint_type'] == west.Segment.SEG_ENDPOINT_RECYCLED]

            if len(recycled_seg_ids) == 0:
                # Attemping to retrieve a 0-length selection from HDF5 (the pcoords below) fails
                continue
            
            pcoord_ds = self.get_pcoord_dataset(n_iter)
            pcoord_len = pcoord_ds.shape[1]
            pcoord_ndim = pcoord_ds.shape[2]
            final_pcoords = self.get_pcoord_dataset(n_iter)[recycled_seg_ids,pcoord_len-1,:]
            # The above HDF5 selection always returns a vector; we want a 2-d array
            final_pcoords.shape = (len(recycled_seg_ids),pcoord_ndim)
            
            for (ipc, seg_id) in enumerate(recycled_seg_ids):
                self.output_file.write('%8d    %8d    %20.14g' % (n_iter, seg_id, seg_index[seg_id]['weight']))
                fields = ['']
                for field in final_pcoords[ipc]:
                    fields.append(pcoord_formats.get(field.dtype.str[1:], '%s') % field)
                self.output_file.write('    '.join(fields))
                self.output_file.write('\n') 
Example #28
Source File: np_conserved.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def sparse_stats(self):
        """Returns a string detailing the sparse statistics."""
        total = np.prod(self.shape)
        if total == 0:
            return "Array without entries, one axis is empty."
        nblocks = self.stored_blocks
        stored = self.size
        nonzero = np.sum([np.count_nonzero(t) for t in self._data], dtype=np.int_)
        bs = np.array([t.size for t in self._data], dtype=np.float)
        if nblocks > 0:
            captsparse = float(nonzero) / stored
            bs_min = int(np.min(bs))
            bs_max = int(np.max(bs))
            bs_mean = np.sum(bs) / nblocks
            bs_med = np.median(bs)
            bs_var = np.var(bs)
        else:
            captsparse = 1.
            bs_min = bs_max = bs_mean = bs_med = bs_var = 0
        res = "{nonzero:d} of {total:d} entries (={nztotal:g}) nonzero,\n" \
            "stored in {nblocks:d} blocks with {stored:d} entries.\n" \
            "Captured sparsity: {captsparse:g}\n"  \
            "Block sizes min:{bs_min:d} mean:{bs_mean:.2f} median:{bs_med:.1f} " \
            "max:{bs_max:d} var:{bs_var:.2f}"

        return res.format(nonzero=nonzero,
                          total=total,
                          nztotal=nonzero / total,
                          nblocks=nblocks,
                          stored=stored,
                          captsparse=captsparse,
                          bs_min=bs_min,
                          bs_max=bs_max,
                          bs_mean=bs_mean,
                          bs_med=bs_med,
                          bs_var=bs_var)

    # accessing entries ======================================================= 
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: lists_and_dicts.py    From paramz with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def intarray_default_factory():
    import numpy as np
    return np.int_([])