def test_access_fields(self): h = np.array(self._buffer, dtype=self._descr) if not self.multiple_rows: assert_(h.shape == ()) assert_equal(h['x'], np.array(self._buffer[0], dtype='i4')) assert_equal(h['y'], np.array(self._buffer[1], dtype='f8')) assert_equal(h['z'], np.array(self._buffer[2], dtype='u1')) else: assert_(len(h) == 2) assert_equal( h['x'], np.array([self._buffer[0][0], self._buffer[1][0]], dtype='i4')) assert_equal( h['y'], np.array([self._buffer[0][1], self._buffer[1][1]], dtype='f8')) assert_equal( h['z'], np.array([self._buffer[0][2], self._buffer[1][2]], dtype='u1'))
def test_keepdims(self): for f, g in zip(self.nanfuncs, self.stdfuncs): mat = np.eye(3) for axis in [None, 0, 1]: tgt = f(mat, axis=axis, out=None) res = g(mat, axis=axis, out=None) assert_(res.ndim == tgt.ndim) for f in self.nanfuncs: d = np.ones((3, 5, 7, 11)) # Randomly set some elements to NaN: rs = np.random.RandomState(0) d[rs.rand(*d.shape) < 0.5] = np.nan res = f(d, axis=None) assert_equal(res.shape, (1155,)) for axis in np.arange(4): res = f(d, axis=axis) assert_equal(res.shape, (3, 5, 7, 11))
def test_pure_subclass_info_preservation(self): # Test that ufuncs and methods conserve extra information consistently; # see gh-7122. arr1 = SubMaskedArray('test', data=[1, 2, 3, 4, 5, 6]) arr2 = SubMaskedArray(data=[0, 1, 2, 3, 4, 5]) diff1 = np.subtract(arr1, arr2) assert_('info' in diff1._optinfo) assert_(diff1._optinfo['info'] == 'test') diff2 = arr1 - arr2 assert_('info' in diff2._optinfo) assert_(diff2._optinfo['info'] == 'test')
def test_basic(self): a = mgrid[-1:1:10j] b = mgrid[-1:1:0.1] assert_(a.shape == (10,)) assert_(b.shape == (20,)) assert_(a[0] == -1) assert_almost_equal(a[-1], 1) assert_(b[0] == -1) assert_almost_equal(b[1]-b[0], 0.1, 11) assert_almost_equal(b[-1], b[0]+19*0.1, 11) assert_almost_equal(a[1]-a[0], 2.0/9.0, 11)
def test_simple(self): with temppath('foo.ini') as path: with open(path, 'w') as f: f.write(simple) pkg = os.path.splitext(path)[0] out = read_config(pkg) assert_(out.cflags() == simple_d['cflags']) assert_(out.libs() == simple_d['libflags']) assert_(out.name == simple_d['name']) assert_(out.version == simple_d['version'])
def test_access_top_fields(self): """Check reading the top fields of a nested array""" h = np.array(self._buffer, dtype=self._descr) if not self.multiple_rows: assert_(h.shape == ()) assert_equal(h['x'], np.array(self._buffer[0], dtype='i4')) assert_equal(h['y'], np.array(self._buffer[4], dtype='f8')) assert_equal(h['z'], np.array(self._buffer[5], dtype='u1')) else: assert_(len(h) == 2) assert_equal( h['x'], np.array([self._buffer[0][0], self._buffer[1][0]], dtype='i4')) assert_equal( h['y'], np.array([self._buffer[0][4], self._buffer[1][4]], dtype='f8')) assert_equal( h['z'], np.array([self._buffer[0][5], self._buffer[1][5]], dtype='u1'))
def test_cache_hidden(self): shape = (2, ) a = self.array(shape, intent.cache.hide, None) assert_(a.arr.shape == shape) shape = (2, 3) a = self.array(shape, intent.cache.hide, None) assert_(a.arr.shape == shape) shape = (-1, 3) try: a = self.array(shape, intent.cache.hide, None) except ValueError as msg: if not str(msg).startswith('failed to create intent' '(cache|hide)|optional array'): raise else: raise SystemError( 'intent(cache) should have failed on undefined dimensions')
def test_ppc64_ibm_double_double128(self): # check that the precision decreases once we get into the subnormal # range. Unlike float64, this starts around 1e-292 instead of 1e-308, # which happens when the first double is normal and the second is # subnormal. x = np.float128('2.123123123123123123123123123123123e-286') got = [str(x / np.float128('2e' + str(i))) for i in range(0, 40)] expected = [ "1.06156156156156156156156156156157e-286", "1.06156156156156156156156156156158e-287", "1.06156156156156156156156156156159e-288", "1.0615615615615615615615615615616e-289", "1.06156156156156156156156156156157e-290", "1.06156156156156156156156156156156e-291", "1.0615615615615615615615615615616e-292", "1.0615615615615615615615615615615e-293", "1.061561561561561561561561561562e-294", "1.06156156156156156156156156155e-295", "1.0615615615615615615615615616e-296", "1.06156156156156156156156156e-297", "1.06156156156156156156156157e-298", "1.0615615615615615615615616e-299", "1.06156156156156156156156e-300", "1.06156156156156156156155e-301", "1.0615615615615615615616e-302", "1.061561561561561561562e-303", "1.06156156156156156156e-304", "1.0615615615615615618e-305", "1.06156156156156156e-306", "1.06156156156156157e-307", "1.0615615615615616e-308", "1.06156156156156e-309", "1.06156156156157e-310", "1.0615615615616e-311", "1.06156156156e-312", "1.06156156154e-313", "1.0615615616e-314", "1.06156156e-315", "1.06156155e-316", "1.061562e-317", "1.06156e-318", "1.06155e-319", "1.0617e-320", "1.06e-321", "1.04e-322", "1e-323", "0.0", "0.0" ] assert_equal(got, expected) # Note: we follow glibc behavior, but it (or gcc) might not be right. # In particular we can get two values that print the same but are not # equal: a = np.float128('2') / np.float128('3') b = np.float128(str(a)) assert_equal(str(a), str(b)) assert_(a != b)
def test_concatenate_axis_None(self): a = np.arange(4, dtype=np.float64).reshape((2, 2)) b = list(range(3)) c = ['x'] r = np.concatenate((a, a), axis=None) assert_equal(r.dtype, a.dtype) assert_equal(r.ndim, 1) r = np.concatenate((a, b), axis=None) assert_equal(r.size, a.size + len(b)) assert_equal(r.dtype, a.dtype) r = np.concatenate((a, b, c), axis=None) d = array(['0.0', '1.0', '2.0', '3.0', '0', '1', '2', 'x']) assert_array_equal(r, d) out = np.zeros(a.size + len(b)) r = np.concatenate((a, b), axis=None) rout = np.concatenate((a, b), axis=None, out=out) assert_(out is rout) assert_equal(r, rout)
def test_empty(self): mat = np.zeros((0, 3)) for axis in [0, None]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_(np.isnan(np.nanpercentile(mat, 40, axis=axis)).all()) assert_(len(w) == 1) assert_(issubclass(w[0].category, RuntimeWarning)) for axis in [1]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_equal(np.nanpercentile(mat, 40, axis=axis), np.zeros([])) assert_(len(w) == 0)
def test_void_scalar_structured_data(self): dt = np.dtype([('name', np.unicode_, 16), ('grades', np.float64, (2, ))]) x = np.array(('ndarray_scalar', (1.2, 3.0)), dtype=dt)[()] assert_(isinstance(x, np.void)) mv_x = memoryview(x) expected_size = 16 * np.dtype((np.unicode_, 1)).itemsize expected_size += 2 * np.dtype((np.float64, 1)).itemsize assert_equal(mv_x.itemsize, expected_size) assert_equal(mv_x.ndim, 0) assert_equal(mv_x.shape, ()) assert_equal(mv_x.strides, ()) assert_equal(mv_x.suboffsets, ()) # check scalar format string against ndarray format string a = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt) assert_(isinstance(a, np.ndarray)) mv_a = memoryview(a) assert_equal(mv_x.itemsize, mv_a.itemsize) assert_equal(mv_x.format, mv_a.format)
def test_setitem(self): assign = functools.partial(array_indexing, 1) # Deletion is impossible: assert_raises(ValueError, assign, np.ones(10), 0) # 0-d arrays don't work: assert_raises(IndexError, assign, np.ones(()), 0, 0) # Out of bound values: assert_raises(IndexError, assign, np.ones(10), 11, 0) assert_raises(IndexError, assign, np.ones(10), -11, 0) assert_raises(IndexError, assign, np.ones((10, 10)), 11, 0) assert_raises(IndexError, assign, np.ones((10, 10)), -11, 0) a = np.arange(10) assign(a, 4, 10) assert_(a[4] == 10) a = a.reshape(5, 2) assign(a, 4, 10) assert_array_equal(a[-1], [10, 10])
def test_integer_split_2D_rows(self): a = np.array([np.arange(10), np.arange(10)]) res = array_split(a, 3, axis=0) tgt = [ np.array([np.arange(10)]), np.array([np.arange(10)]), np.zeros((0, 10)) ] compare_results(res, tgt) assert_(a.dtype.type is res[-1].dtype.type) # Same thing for manual splits: res = array_split(a, [0, 1, 2], axis=0) tgt = [ np.zeros((0, 10)), np.array([np.arange(10)]), np.array([np.arange(10)]) ] compare_results(res, tgt) assert_(a.dtype.type is res[-1].dtype.type)
def test_concatenate(self): # Test concatenate function # One sequence returns unmodified (but as array) r4 = list(range(4)) assert_array_equal(concatenate((r4,)), r4) # Any sequence assert_array_equal(concatenate((tuple(r4),)), r4) assert_array_equal(concatenate((array(r4),)), r4) # 1D default concatenation r3 = list(range(3)) assert_array_equal(concatenate((r4, r3)), r4 + r3) # Mixed sequence types assert_array_equal(concatenate((tuple(r4), r3)), r4 + r3) assert_array_equal(concatenate((array(r4), r3)), r4 + r3) # Explicit axis specification assert_array_equal(concatenate((r4, r3), 0), r4 + r3) # Including negative assert_array_equal(concatenate((r4, r3), -1), r4 + r3) # 2D a23 = array([[10, 11, 12], [13, 14, 15]]) a13 = array([[0, 1, 2]]) res = array([[10, 11, 12], [13, 14, 15], [0, 1, 2]]) assert_array_equal(concatenate((a23, a13)), res) assert_array_equal(concatenate((a23, a13), 0), res) assert_array_equal(concatenate((a23.T, a13.T), 1), res.T) assert_array_equal(concatenate((a23.T, a13.T), -1), res.T) # Arrays much match shape assert_raises(ValueError, concatenate, (a23.T, a13.T), 0) # 3D res = arange(2 * 3 * 7).reshape((2, 3, 7)) a0 = res[..., :4] a1 = res[..., 4:6] a2 = res[..., 6:] assert_array_equal(concatenate((a0, a1, a2), 2), res) assert_array_equal(concatenate((a0, a1, a2), -1), res) assert_array_equal(concatenate((a0.T, a1.T, a2.T), 0), res.T) out = res.copy() rout = concatenate((a0, a1, a2), 2, out=out) assert_(out is rout) assert_equal(res, rout)
def test_pandas_duck(self): # This tests a custom np.dtype duck-typed class, such as used by pandas # (pandas.core.dtypes) class PdComplex(np.complex128): pass class PdDtype(object): name = 'category' names = None type = PdComplex kind = 'c' str = '<c16' base = np.dtype('complex128') class DummyPd: @property def dtype(self): return PdDtype dummy = DummyPd() assert_(iscomplexobj(dummy))
def test_testBasic2d(self): # Test of basic array creation and properties in 2 dimensions. for s in [(4, 3), (6, 2)]: (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d x.shape = s y.shape = s xm.shape = s ym.shape = s xf.shape = s assert_(not isMaskedArray(x)) assert_(isMaskedArray(xm)) assert_equal(shape(xm), s) assert_equal(xm.shape, s) assert_equal(xm.size, reduce(lambda x, y:x * y, s)) assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1)) assert_(eq(xm, xf)) assert_(eq(filled(xm, 1.e20), xf)) assert_(eq(x, xm)) self.setup()
def test_integers_to_negative_integer_power(self): # Note that the combination of uint64 with a signed integer # has common type np.float64. The other combinations should all # raise a ValueError for integer ** negative integer. exp = [np.array(-1, dt)[()] for dt in 'bhilq'] # 1 ** -1 possible special case base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype.name != 'uint64': assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, 1.) # -1 ** -1 possible special case base = [np.array(-1, dt)[()] for dt in 'bhilq'] for i1, i2 in itertools.product(base, exp): if i1.dtype.name != 'uint64': assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, -1.) # 2 ** -1 perhaps generic base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ'] for i1, i2 in itertools.product(base, exp): if i1.dtype.name != 'uint64': assert_raises(ValueError, operator.pow, i1, i2) else: res = operator.pow(i1, i2) assert_(res.dtype.type is np.float64) assert_almost_equal(res, .5)
def test_everything_returns_views(self): # Before `...` would return a itself. a = np.arange(5) assert_(a is not a[()]) assert_(a is not a[...]) assert_(a is not a[:])
def test_type(self): # Check the type of the returned histogram a = np.arange(10) + .5 h, b = histogram(a) assert_(np.issubdtype(h.dtype, np.integer)) h, b = histogram(a, density=True) assert_(np.issubdtype(h.dtype, np.floating)) h, b = histogram(a, weights=np.ones(10, int)) assert_(np.issubdtype(h.dtype, np.integer)) h, b = histogram(a, weights=np.ones(10, float)) assert_(np.issubdtype(h.dtype, np.floating))
def test_plausible_finfo(): # Assert that finfo returns reasonable results for all types for ftype in np.sctypes['float'] + np.sctypes['complex']: info = np.finfo(ftype) assert_(info.nmant > 1) assert_(info.minexp < -1) assert_(info.maxexp > 1)
def test_main_versions(): assert_(NumpyVersion('1.8.0') == '1.8.0') for ver in ['1.9.0', '2.0.0', '1.8.1']: assert_(NumpyVersion('1.8.0') < ver) for ver in ['1.7.0', '1.7.1', '0.9.9']: assert_(NumpyVersion('1.8.0') > ver)
def test_basic(self): """Basic test of array2string.""" a = np.arange(3) assert_(np.array2string(a) == '[0 1 2]') assert_( np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]') assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]')
def test_init(self): x = B(1.0) assert_(str(x) == '1.0') y = C(2.0) assert_(str(y) == '2.0') z = D(3.0) assert_(str(z) == '3.0')
def test_bmat_nondefault_str(self): A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) Aresult = np.array([[1, 2, 1, 2], [3, 4, 3, 4], [1, 2, 1, 2], [3, 4, 3, 4]]) mixresult = np.array([[1, 2, 5, 6], [3, 4, 7, 8], [5, 6, 1, 2], [7, 8, 3, 4]]) assert_(np.all(bmat("A,A;A,A") == Aresult)) assert_(np.all(bmat("A,A;A,A", ldict={'A': B}) == Aresult)) assert_raises(TypeError, bmat, "A,A;A,A", gdict={'A': B}) assert_( np.all(bmat("A,A;A,A", ldict={'A': A}, gdict={'A': B}) == Aresult)) b2 = bmat("A,B;C,D", ldict={'A': A, 'B': B}, gdict={'C': B, 'D': A}) assert_(np.all(b2 == mixresult))
def test_list_of_list_of_tuple(self): """Check creation from list of list of tuples""" h = np.array([[self._buffer]], dtype=self._descr) assert_(normalize_descr(self._descr) == h.dtype.descr) if self.multiple_rows: assert_(h.shape == (1, 1, 2)) else: assert_(h.shape == (1, 1))
def test_basic(self): y = linspace(0, 10) assert_(len(y) == 50) y = linspace(2, 10, num=100) assert_(y[-1] == 10) y = linspace(2, 10, endpoint=0) assert_(y[-1] < 10) assert_raises(ValueError, linspace, 0, 10, num=-1)
def test_view(self): fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape) new1 = fp.view() new2 = new1.view() assert_(new1.base is fp) assert_(new2.base is fp) new_array = asarray(fp) assert_(new_array.base is fp)
def test_tuple(self): """Check creation from tuples""" h = np.array(self._buffer, dtype=self._descr) assert_(normalize_descr(self._descr) == h.dtype.descr) if self.multiple_rows: assert_(h.shape == (2, )) else: assert_(h.shape == ())
def test_ellipsis_index(self): a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert_(a[...] is not a) assert_equal(a[...], a) # `a[...]` was `a` in numpy <1.9. assert_(a[...].base is a) # Slicing with ellipsis can skip an # arbitrary number of dimensions assert_equal(a[0, ...], a[0]) assert_equal(a[0, ...], a[0,:]) assert_equal(a[..., 0], a[:, 0]) # Slicing with ellipsis always results # in an array, not a scalar assert_equal(a[0, ..., 1], np.array(2)) # Assignment with `(Ellipsis,)` on 0-d arrays b = np.array(1) b[(Ellipsis,)] = 2 assert_equal(b, 2)
def test_upgrade(self): "Tests the upgrade method." converter = StringConverter() assert_equal(converter._status, 0) # test int assert_equal(converter.upgrade('0'), 0) assert_equal(converter._status, 1) # On systems where long defaults to 32-bit, the statuses will be # offset by one, so we check for this here. import numpy1.core.numeric as nx status_offset = int( nx.dtype(nx.int_).itemsize < nx.dtype(nx.int64).itemsize) # test int > 2**32 assert_equal(converter.upgrade('17179869184'), 17179869184) assert_equal(converter._status, 1 + status_offset) # test float assert_allclose(converter.upgrade('0.'), 0.0) assert_equal(converter._status, 2 + status_offset) # test complex assert_equal(converter.upgrade('0j'), complex('0j')) assert_equal(converter._status, 3 + status_offset) # test str # note that the longdouble type has been skipped, so the # _status increases by 2. Everything should succeed with # unicode conversion (5). for s in ['a', u'a', b'a']: res = converter.upgrade(s) assert_(type(res) is unicode) assert_equal(res, u'a') assert_equal(converter._status, 5 + status_offset)