def test_broadcast_to_succeeds(): data = [ [np.array(0), (0, ), np.array(0)], [np.array(0), (1, ), np.zeros(1)], [np.array(0), (3, ), np.zeros(3)], [np.ones(1), (1, ), np.ones(1)], [np.ones(1), (2, ), np.ones(2)], [np.ones(1), (1, 2, 3), np.ones((1, 2, 3))], [np.arange(3), (3, ), np.arange(3)], [np.arange(3), (1, 3), np.arange(3).reshape(1, -1)], [np.arange(3), (2, 3), np.array([[0, 1, 2], [0, 1, 2]])], # test if shape is not a tuple [np.ones(0), 0, np.ones(0)], [np.ones(1), 1, np.ones(1)], [np.ones(1), 2, np.ones(2)], # these cases with size 0 are strange, but they reproduce the behavior # of broadcasting with ufuncs (see test_same_as_ufunc above) [np.ones(1), (0, ), np.ones(0)], [np.ones((1, 2)), (0, 2), np.ones((0, 2))], [np.ones((2, 1)), (2, 0), np.ones((2, 0))], ] for input_array, shape, expected in data: actual = broadcast_to(input_array, shape) assert_array_equal(expected, actual)
def test_simple(self): x = np.array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], [.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]]) H, edges = histogramdd(x, (2, 3, 3), range=[[-1, 1], [0, 3], [0, 3]]) answer = np.array([[[0, 1, 0], [0, 0, 1], [1, 0, 0]], [[0, 1, 0], [0, 0, 1], [0, 0, 1]]]) assert_array_equal(H, answer) # Check normalization ed = [[-2, 0, 2], [0, 1, 2, 3], [0, 1, 2, 3]] H, edges = histogramdd(x, bins=ed, density=True) assert_(np.all(H == answer / 12.)) # Check that H has the correct shape. H, edges = histogramdd(x, (2, 3, 4), range=[[-1, 1], [0, 3], [0, 4]], density=True) answer = np.array([[[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]], [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0]]]) assert_array_almost_equal(H, answer / 6., 4) # Check that a sequence of arrays is accepted and H has the correct # shape. z = [np.squeeze(y) for y in np.split(x, 3, axis=1)] H, edges = histogramdd(z, bins=(4, 3, 2), range=[[-2, 2], [0, 3], [0, 2]]) answer = np.array([[[0, 0], [0, 0], [0, 0]], [[0, 1], [0, 0], [1, 0]], [[0, 1], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]) assert_array_equal(H, answer) Z = np.zeros((5, 5, 5)) Z[list(range(5)), list(range(5)), list(range(5))] = 1. H, edges = histogramdd([np.arange(5), np.arange(5), np.arange(5)], 5) assert_array_equal(H, Z)
def test_array_richcompare_legacy_weirdness(self): # It doesn't really work to use assert_deprecated here, b/c part of # the point of assert_deprecated is to check that when warnings are # set to "error" mode then the error is propagated -- which is good! # But here we are testing a bunch of code that is deprecated *because* # it has the habit of swallowing up errors and converting them into # different warnings. So assert_warns will have to be sufficient. assert_warns(FutureWarning, lambda: np.arange(2) == "a") assert_warns(FutureWarning, lambda: np.arange(2) != "a") # No warning for scalar comparisons with warnings.catch_warnings(): warnings.filterwarnings("error") assert_(not (np.array(0) == "a")) assert_(np.array(0) != "a") assert_(not (np.int16(0) == "a")) assert_(np.int16(0) != "a") for arg1 in [np.asarray(0), np.int16(0)]: struct = np.zeros(2, dtype="i4,i4") for arg2 in [struct, "a"]: for f in [operator.lt, operator.le, operator.gt, operator.ge]: if sys.version_info[0] >= 3: # py3 with warnings.catch_warnings() as l: warnings.filterwarnings("always") assert_raises(TypeError, f, arg1, arg2) assert_(not l) else: # py2 assert_warns(DeprecationWarning, f, arg1, arg2)
def test_in_cache_from_2casttype(self): for t in self.type.all_types(): if t.elsize != self.type.elsize: continue obj = array(self.num2seq, dtype=t.dtype) shape = (len(self.num2seq), ) a = self.array(shape, intent.in_.c.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) a = self.array(shape, intent.in_.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) obj = array(self.num2seq, dtype=t.dtype, order='F') a = self.array(shape, intent.in_.c.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) a = self.array(shape, intent.in_.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) try: a = self.array(shape, intent.in_.cache, obj[::-1]) except ValueError as msg: if not str(msg).startswith('failed to initialize' ' intent(cache) array'): raise else: raise SystemError( 'intent(cache) should have failed on multisegmented array')
def test_density_non_uniform_2d(self): # Defines the following grid: # # 0 2 8 # 0+-+-----+ # + | + # + | + # 6+-+-----+ # 8+-+-----+ x_edges = np.array([0, 2, 8]) y_edges = np.array([0, 6, 8]) relative_areas = np.array([[3, 9], [1, 3]]) # ensure the number of points in each region is proportional to its area x = np.array([1] + [1] * 3 + [7] * 3 + [7] * 9) y = np.array([7] + [1] * 3 + [7] * 3 + [1] * 9) # sanity check that the above worked as intended hist, edges = histogramdd((y, x), bins=(y_edges, x_edges)) assert_equal(hist, relative_areas) # resulting histogram should be uniform, since counts and areas are propotional hist, edges = histogramdd((y, x), bins=(y_edges, x_edges), density=True) assert_equal(hist, 1 / (8 * 8))
def test_complex(self): x = np.array([complex(1, 2), complex(1, np.nan)]) z = np.array([complex(1, 2), complex(np.nan, 1)]) y = np.array([complex(1, 2), complex(1, 2)]) self._assert_func(x, x) self._test_not_equal(x, y) self._test_not_equal(x, z)
def test_mapdomain(self): # test for real values dom1 = [0, 4] dom2 = [1, 3] tgt = dom2 res = pu.mapdomain(dom1, dom1, dom2) assert_almost_equal(res, tgt) # test for complex values dom1 = [0 - 1j, 2 + 1j] dom2 = [-2, 2] tgt = dom2 x = dom1 res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) # test for multidimensional arrays dom1 = [0, 4] dom2 = [1, 3] tgt = np.array([dom2, dom2]) x = np.array([dom1, dom1]) res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) # test that subtypes are preserved. class MyNDArray(np.ndarray): pass dom1 = [0, 4] dom2 = [1, 3] x = np.array([dom1, dom1]).view(MyNDArray) res = pu.mapdomain(x, dom1, dom2) assert_(isinstance(res, MyNDArray))
def test_unsigned_monotonicity_check(self): # Ensures ValueError is raised if bins not increasing monotonically # when bins contain unsigned values (see #9222) arr = np.array([2]) bins = np.array([1, 3, 1], dtype='uint64') with assert_raises(ValueError): hist, edges = np.histogram(arr, bins=bins)
def test_float_modulus_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for op in [floordiv_and_mod, divmod]: for dt in np.typecodes['Float']: msg = 'op: %s, dtype: %s' % (op.__name__, dt) fa = a.astype(dt) fb = b.astype(dt) # use list comprehension so a_ and b_ are scalars div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)]) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg)
def __getitem__(self, indx): """ Returns all the fields sharing the same fieldname base. The fieldname base is either `_data` or `_mask`. """ _localdict = self.__dict__ _mask = ndarray.__getattribute__(self, '_mask') _data = ndarray.view(self, _localdict['_baseclass']) # We want a field if isinstance(indx, basestring): # Make sure _sharedmask is True to propagate back to _fieldmask # Don't use _set_mask, there are some copies being made that # break propagation Don't force the mask to nomask, that wreaks # easy masking obj = _data[indx].view(MaskedArray) obj._mask = _mask[indx] obj._sharedmask = True fval = _localdict['_fill_value'] if fval is not None: obj._fill_value = fval[indx] # Force to masked if the mask is True if not obj.ndim and obj._mask: return masked return obj # We want some elements. # First, the data. obj = np.array(_data[indx], copy=False).view(mrecarray) obj._mask = np.array(_mask[indx], copy=False).view(recarray) return obj
def test_subclass(self): a = np.array([[1., 2.], [3., 4.]]) b = np.ma.masked_array([[1., 2.], [0., 4.]], [[False, False], [True, False]]) self._assert_func(a, b) self._assert_func(b, a) self._assert_func(b, b) # Test fully masked as well (see gh-11123). a = np.ma.MaskedArray(3.5, mask=True) b = np.array([3., 4., 6.5]) self._test_equal(a, b) self._test_equal(b, a) a = np.ma.masked b = np.array([3., 4., 6.5]) self._test_equal(a, b) self._test_equal(b, a) a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, True, True]) b = np.array([1., 2., 3.]) self._test_equal(a, b) self._test_equal(b, a) a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, True, True]) b = np.array(1.) self._test_equal(a, b) self._test_equal(b, a)
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_simple_flexible(self): # Test recursive_fill_fields on flexible-array a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)]) b = np.zeros((3, ), dtype=a.dtype) test = recursive_fill_fields(a, b) control = np.array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', int), ('B', float)]) assert_equal(test, control)
def test_block_mixed_1d_and_2d(self): a_2d = np.ones((2, 2)) b_1d = np.array([2, 2]) result = block([[a_2d], [b_1d]]) expected = np.array([[1, 1], [1, 1], [2, 2]]) assert_equal(expected, result)
def test_block_with_1d_arrays_column_wise(self): # # # 1-D vectors are treated as row arrays a_1d = np.array([1, 2, 3]) b_1d = np.array([2, 3, 4]) expected = np.array([[1, 2, 3], [2, 3, 4]]) result = block([[a_1d], [b_1d]]) assert_equal(expected, result)
def test_in1d_char_array(self): a = np.array(['a', 'b', 'c', 'd', 'e', 'c', 'e', 'b']) b = np.array(['a', 'c']) ec = np.array([True, False, True, False, False, True, False, False]) c = in1d(a, b) assert_array_equal(c, ec)
def test_diag(self): assert_equal( eye(4, k=1), array([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]])) assert_equal( eye(4, k=-1), array([[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]))
def test_density(self): x = array([1, 2, 3, 1, 2, 3, 1, 2, 3]) y = array([1, 1, 1, 2, 2, 2, 3, 3, 3]) H, xed, yed = histogram2d(x, y, [[1, 2, 3, 5], [1, 2, 3, 5]], density=True) answer = array([[1, 1, .5], [1, 1, .5], [.5, .5, .25]]) / 9. assert_array_almost_equal(H, answer, 3)
def test_w_singlefield(self): # Test single field test = merge_arrays( (np.array([1, 2]).view([('a', int)]), np.array([10., 20., 30.])), ) control = ma.array([(1, 10.), (2, 20.), (-1, 30.)], mask=[(0, 0), (0, 0), (1, 0)], dtype=[('a', int), ('f1', float)]) assert_equal(test, control)
def test_complex(self): lim1 = linspace(1 + 2j, 3 + 4j, 5) t1 = array([1.0 + 2.j, 1.5 + 2.5j, 2.0 + 3j, 2.5 + 3.5j, 3.0 + 4j]) lim2 = linspace(1j, 10, 5) t2 = array( [0.0 + 1.j, 2.5 + 0.75j, 5.0 + 0.5j, 7.5 + 0.25j, 10.0 + 0j]) assert_equal(lim1, t1) assert_equal(lim2, t2)
def test_nan_items(self): anan = np.array(np.nan) aone = np.array(1) ainf = np.array(np.inf) self._assert_func(anan, anan) assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) assert_raises(AssertionError, lambda: self._assert_func(ainf, anan))
def test_simple_arrays(self): x = np.array([1234.22]) y = np.array([1234.23]) self._assert_func(x, y, significant=5) self._assert_func(x, y, significant=6) assert_raises(AssertionError, lambda: self._assert_func(x, y, significant=7))
def test_join_subdtype(self): # tests the bug in https://stackoverflow.com/q/44769632/102441 from numpy1.lib import recfunctions as rfn foo = np.array([(1, )], dtype=[('key', int)]) bar = np.array([(1, np.array([1, 2, 3]))], dtype=[('key', int), ('value', 'uint16', 3)]) res = join_by('key', foo, bar) assert_equal(res, bar.view(ma.MaskedArray))
def test_unpackbits(): # Copied from the docstring. a = np.array([[2], [7], [23]], dtype=np.uint8) b = np.unpackbits(a, axis=1) assert_equal(b.dtype, np.uint8) assert_array_equal(b, np.array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1]]))
def test_mask_indices(): # simple test without offset iu = mask_indices(3, np.triu) a = np.arange(9).reshape(3, 3) assert_array_equal(a[iu], array([0, 1, 2, 4, 5, 8])) # Now with an offset iu1 = mask_indices(3, np.triu, 1) assert_array_equal(a[iu1], array([1, 2, 5]))
def test_simple(self): x = np.array([1234.2222]) y = np.array([1234.2223]) self._assert_func(x, y, decimal=3) self._assert_func(x, y, decimal=4) assert_raises(AssertionError, lambda: self._assert_func(x, y, decimal=5))
def test_single_bool_index(self): # Single boolean index a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert_equal(a[np.array(True)], a[None]) assert_equal(a[np.array(False)], a[None][0:0])
def test_nan(self): anan = np.array([np.nan]) aone = np.array([1]) ainf = np.array([np.inf]) self._assert_func(anan, anan) assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) assert_raises(AssertionError, lambda: self._assert_func(ainf, anan))
def test_common_block(self): self.module.initcb() assert_array_equal(self.module.block.long_bn, np.array(1.0, dtype=np.float64)) assert_array_equal(self.module.block.string_bn, np.array('2', dtype='|S1')) assert_array_equal(self.module.block.ok, np.array(3, dtype=np.int32))
def test_build_err_msg_no_verbose(self): x = np.array([1.00001, 2.00002, 3.00003]) y = np.array([1.00002, 2.00003, 3.00004]) err_msg = 'There is a mismatch' a = build_err_msg([x, y], err_msg, verbose=False) b = '\nItems are not equal: There is a mismatch' assert_equal(a, b)