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_iter_allocate_output_subtype(): # Make sure that the subtype with priority wins # 2018-04-29: moved here from core.tests.test_nditer, given the # matrix specific shape test. # matrix vs ndarray a = np.matrix([[1, 2], [3, 4]]) b = np.arange(4).reshape(2, 2).T i = np.nditer([a, b, None], [], [['readonly'], ['readonly'], ['writeonly', 'allocate']]) assert_(type(i.operands[2]) is np.matrix) assert_(type(i.operands[2]) is not np.ndarray) assert_equal(i.operands[2].shape, (2, 2)) # matrix always wants things to be 2D b = np.arange(4).reshape(1, 2, 2) assert_raises(RuntimeError, np.nditer, [a, b, None], [], [['readonly'], ['readonly'], ['writeonly', 'allocate']]) # but if subtypes are disabled, the result can still work i = np.nditer([a, b, None], [], [['readonly'], ['readonly'], ['writeonly', 'allocate', 'no_subtype']]) assert_(type(i.operands[2]) is np.ndarray) assert_(type(i.operands[2]) is not np.matrix) assert_equal(i.operands[2].shape, (1, 2, 2))
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_weights(self): v = np.random.rand(100) w = np.ones(100) * 5 a, b = histogram(v) na, nb = histogram(v, density=True) wa, wb = histogram(v, weights=w) nwa, nwb = histogram(v, weights=w, density=True) assert_array_almost_equal(a * 5, wa) assert_array_almost_equal(na, nwa) # Check weights are properly applied. v = np.linspace(0, 10, 10) w = np.concatenate((np.zeros(5), np.ones(5))) wa, wb = histogram(v, bins=np.arange(11), weights=w) assert_array_almost_equal(wa, w) # Check with integer weights wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1]) assert_array_equal(wa, [4, 5, 0, 1]) wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1], density=True) assert_array_almost_equal(wa, np.array([4, 5, 0, 1]) / 10. / 3. * 4) # Check weights with non-uniform bin widths a, b = histogram(np.arange(9), [0, 1, 3, 6, 10], weights=[2, 1, 1, 1, 1, 1, 1, 1, 1], density=True) assert_almost_equal(a, [.2, .1, .1, .075])
def test_unique_axis_errors(self): assert_raises(TypeError, self._run_axis_tests, object) assert_raises(TypeError, self._run_axis_tests, [('a', int), ('b', object)]) assert_raises(np.AxisError, unique, np.arange(10), axis=2) assert_raises(np.AxisError, unique, np.arange(10), axis=-2)
def test_axis_insertion(self, cls=np.ndarray): def f1to2(x): """produces an asymmetric non-square matrix from x""" assert_equal(x.ndim, 1) return (x[::-1] * x[1:, None]).view(cls) a2d = np.arange(6 * 3).reshape((6, 3)) # 2d insertion along first axis actual = apply_along_axis(f1to2, 0, a2d) expected = np.stack([f1to2(a2d[:, i]) for i in range(a2d.shape[1])], axis=-1).view(cls) assert_equal(type(actual), type(expected)) assert_equal(actual, expected) # 2d insertion along last axis actual = apply_along_axis(f1to2, 1, a2d) expected = np.stack([f1to2(a2d[i, :]) for i in range(a2d.shape[0])], axis=0).view(cls) assert_equal(type(actual), type(expected)) assert_equal(actual, expected) # 3d insertion along middle axis a3d = np.arange(6 * 5 * 3).reshape((6, 5, 3)) actual = apply_along_axis(f1to2, 1, a3d) expected = np.stack([ np.stack([f1to2(a3d[i, :, j]) for i in range(a3d.shape[0])], axis=0) for j in range(a3d.shape[2]) ], axis=-1).view(cls) assert_equal(type(actual), type(expected)) assert_equal(actual, expected)
def test_object_assign(self): # Check that the field and object special case using copyto is active. # The right hand side cannot be converted to an array here. a = np.arange(5, dtype=object) b = a.copy() a[:3] = [1, (1,2), 3] b[[0, 1, 2]] = [1, (1,2), 3] assert_array_equal(a, b) # test same for subspace fancy indexing b = np.arange(5, dtype=object)[None, :] b[[0], :3] = [[1, (1,2), 3]] assert_array_equal(a, b[0]) # Check that swapping of axes works. # There was a bug that made the later assignment throw a ValueError # do to an incorrectly transposed temporary right hand side (gh-5714) b = b.T b[:3, [0]] = [[1], [(1,2)], [3]] assert_array_equal(a, b[:, 0]) # Another test for the memory order of the subspace arr = np.ones((3, 4, 5), dtype=object) # Equivalent slicing assignment for comparison cmp_arr = arr.copy() cmp_arr[:1, ...] = [[[1], [2], [3], [4]]] arr[[0], ...] = [[[1], [2], [3], [4]]] assert_array_equal(arr, cmp_arr) arr = arr.copy('F') arr[[0], ...] = [[[1], [2], [3], [4]]] assert_array_equal(arr, cmp_arr)
def test_density(self): # Check that the integral of the density equals 1. n = 100 v = np.random.rand(n) a, b = histogram(v, density=True) area = np.sum(a * np.diff(b)) assert_almost_equal(area, 1) # Check with non-constant bin widths v = np.arange(10) bins = [0, 1, 3, 6, 10] a, b = histogram(v, bins, density=True) assert_array_equal(a, .1) assert_equal(np.sum(a * np.diff(b)), 1) # Test that passing False works too a, b = histogram(v, bins, density=False) assert_array_equal(a, [1, 2, 3, 4]) # Variale bin widths are especially useful to deal with # infinities. v = np.arange(10) bins = [0, 1, 3, 6, np.inf] a, b = histogram(v, bins, density=True) assert_array_equal(a, [.1, .1, .1, 0.]) # Taken from a bug report from N. Becker on the numpy-discussion # mailing list Aug. 6, 2010. counts, dmy = np.histogram([1, 2, 3, 4], [0.5, 1.5, np.inf], density=True) assert_equal(counts, [.25, 0])
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_legacy_stray_comma(self): np.set_printoptions(legacy='1.13') assert_equal(str(np.arange(10000)), '[ 0 1 2 ..., 9997 9998 9999]') np.set_printoptions(legacy=False) assert_equal(str(np.arange(10000)), '[ 0 1 2 ... 9997 9998 9999]')
def test_reversed_strides_result_allocation(self): # Test a bug when calculating the output strides for a result array # when the subspace size was 1 (and test other cases as well) a = np.arange(10)[:, None] i = np.arange(10)[::-1] assert_array_equal(a[i], a[i.copy('C')]) a = np.arange(20).reshape(-1, 2)
def test_constant_both(self): # non-contiguous should raise error x = np.arange(6, dtype=np.float64)[::2] assert_raises(ValueError, self.module.foo, x) # check values with contiguous array x = np.arange(3, dtype=np.float64) self.module.foo(x) assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
def test_constant_compound_int(self): # non-contiguous should raise error x = np.arange(6, dtype=np.int32)[::2] assert_raises(ValueError, self.module.foo_compound_int, x) # check values with contiguous array x = np.arange(3, dtype=np.int32) self.module.foo_compound_int(x) assert_equal(x, [0 + 1 + 2 * 6, 1, 2])
def test_constant_real_double(self): # non-contiguous should raise error x = np.arange(6, dtype=np.float64)[::2] assert_raises(ValueError, self.module.foo_double, x) # check values with contiguous array x = np.arange(3, dtype=np.float64) self.module.foo_double(x) assert_equal(x, [0 + 1 + 2 * 3, 1, 2])
def test_inout(self): # non-contiguous should raise error x = np.arange(6, dtype=np.float32)[::2] assert_raises(ValueError, self.module.foo, x) # check values with contiguous array x = np.arange(3, dtype=np.float32) self.module.foo(x) assert_equal(x, [3, 1, 2])
def test_constant_integer_long(self): # non-contiguous should raise error x = np.arange(6, dtype=np.int64)[::2] assert_raises(ValueError, self.module.foo_long, x) # check values with contiguous array x = np.arange(3, dtype=np.int64) self.module.foo_long(x) assert_equal(x, [0 + 1 + 2 * 3, 1, 2])
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) assert_(allclose(average(x, axis=0), 2.5)) assert_(allclose(average(x, axis=0, weights=w1), 2.5)) y = array([arange(6), 2.0 * arange(6)]) assert_(allclose(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)) assert_(allclose(average(y, axis=0), np.arange(6) * 3. / 2.)) assert_(allclose(average(y, axis=1), [average(x, axis=0), average(x, axis=0)*2.0])) assert_(allclose(average(y, None, weights=w2), 20. / 6.)) assert_(allclose(average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.])) assert_(allclose(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_(allclose(average(masked_array(x, m1), axis=0), 2.5)) assert_(allclose(average(masked_array(x, m2), axis=0), 2.5)) assert_(average(masked_array(x, m4), axis=0) is masked) 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_(allclose(average(z, None), 20. / 6.)) assert_(allclose(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])) assert_(allclose(average(z, axis=1), [2.5, 5.0])) assert_(allclose(average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0])) a = arange(6) b = arange(6) * 3 r1, w1 = average([[a, b], [b, a]], axis=1, returned=1) assert_equal(shape(r1), shape(w1)) assert_equal(r1.shape, w1.shape) r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=1) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), returned=1) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=1) assert_(shape(w2) == shape(r2)) a2d = array([[1, 2], [0, 4]], float) a2dm = masked_array(a2d, [[0, 0], [1, 0]]) a2da = average(a2d, axis=0) assert_(eq(a2da, [0.5, 3.0])) a2dma = average(a2dm, axis=0) assert_(eq(a2dma, [1.0, 3.0])) a2dma = average(a2dm, axis=None) assert_(eq(a2dma, 7. / 3.)) a2dma = average(a2dm, axis=1) assert_(eq(a2dma, [1.5, 4.0]))
def test_uncontiguous_subspace_assignment(self): # During development there was a bug activating a skip logic # based on ndim instead of size. a = np.full((3, 4, 2), -1) b = np.full((3, 4, 2), -1) a[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T b[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T.copy() assert_equal(a, b)
def test_memory_order(self): # This is not necessary to preserve. Memory layouts for # more complex indices are not as simple. a = np.arange(10) b = np.arange(10).reshape(5,2).T assert_(a[b].flags.f_contiguous) # Takes a different implementation branch: a = a.reshape(-1, 1) assert_(a[b, 0].flags.f_contiguous)
def test_index_split_low_bound(self): a = np.arange(10) indices = [0, 5, 7] res = array_split(a, indices, axis=-1) desired = [ np.array([]), np.arange(0, 5), np.arange(5, 7), np.arange(7, 10) ] compare_results(res, desired)
def test_index_split_simple(self): a = np.arange(10) indices = [1, 5, 7] res = array_split(a, indices, axis=-1) desired = [ np.arange(0, 1), np.arange(1, 5), np.arange(5, 7), np.arange(7, 10) ] compare_results(res, desired)
def test_no_p_overwrite(self): # this is worth retesting, because quantile does not make a copy p0 = np.array([0, 0.75, 0.25, 0.5, 1.0]) p = p0.copy() np.nanquantile(np.arange(100.), p, interpolation="midpoint") assert_array_equal(p, p0) p0 = p0.tolist() p = p.tolist() np.nanquantile(np.arange(100.), p, interpolation="midpoint") assert_array_equal(p, p0)
def test_integer_split_2D_default(self): """ This will fail if we change default axis """ a = np.array([np.arange(10), np.arange(10)]) res = array_split(a, 3) 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)
def test_in1d_ravel(self): # Test that in1d ravels its input arrays. This is not documented # behavior however. The test is to ensure consistentency. a = np.arange(6).reshape(2, 3) b = np.arange(3, 9).reshape(3, 2) long_b = np.arange(3, 63).reshape(30, 2) ec = np.array([False, False, False, True, True, True]) assert_array_equal(in1d(a, b, assume_unique=True), ec) assert_array_equal(in1d(a, b, assume_unique=False), ec) assert_array_equal(in1d(a, long_b, assume_unique=True), ec) assert_array_equal(in1d(a, long_b, assume_unique=False), ec)
def test_cast_equivalence(self): # Yes, normal slicing uses unsafe casting. a = np.arange(5) b = a.copy() a[:3] = np.array(['2', '-3', '-1']) b[[0, 2, 1]] = np.array(['2', '-1', '-3']) assert_array_equal(a, b) # test the same for subspace fancy indexing b = np.arange(5)[None, :] b[[0], :3] = np.array([['2', '-3', '-1']]) assert_array_equal(a, b[0])
def test_binary_ufunc_reduceat_manual(self): def check(ufunc, a, ind, out): c1 = ufunc.reduceat(a.copy(), ind.copy(), out=out.copy()) c2 = ufunc.reduceat(a, ind, out=out) assert_array_equal(c1, c2) # Exactly same input/output arrays a = np.arange(10000, dtype=np.int16) check(np.add, a, a[::-1].copy(), a) # Overlap with index a = np.arange(10000, dtype=np.int16) check(np.add, a, a[::-1], a)
def test_shuffle_of_array_of_objects(self): # Test that permuting an array of objects will not cause # a segfault on garbage collection. # See gh-7719 np.random.seed(1234) a = np.array([np.arange(1), np.arange(4)]) for _ in range(1000): np.random.shuffle(a) # Force Garbage Collection - should not segfault. import gc gc.collect()
def test_trivial_fancy_not_possible(self): # Test that the fast path for trivial assignment is not incorrectly # used when the index is not contiguous or 1D, see also gh-11467. a = np.arange(6) idx = np.arange(6, dtype=np.intp).reshape(2, 1, 3)[:, :, 0] assert_array_equal(a[idx], idx) # this case must not go into the fast path, note that idx is # a non-contiuguous none 1D array here. a[idx] = -1 res = np.arange(6) res[0] = -1 res[3] = -1 assert_array_equal(a, res)
def test_format_function(self): """Test custom format function for each element in array.""" def _format_function(x): if np.abs(x) < 1: return '.' elif np.abs(x) < 2: return 'o' else: return 'O' x = np.arange(3) if sys.version_info[0] >= 3: x_hex = "[0x0 0x1 0x2]" x_oct = "[0o0 0o1 0o2]" else: x_hex = "[0x0L 0x1L 0x2L]" x_oct = "[0L 01L 02L]" assert_( np.array2string(x, formatter={'all': _format_function}) == "[. o O]") assert_( np.array2string(x, formatter={'int_kind': _format_function}) == "[. o O]") assert_( np.array2string(x, formatter={'all': lambda x: "%.4f" % x}) == "[0.0000 1.0000 2.0000]") assert_equal(np.array2string(x, formatter={'int': lambda x: hex(x)}), x_hex) assert_equal(np.array2string(x, formatter={'int': lambda x: oct(x)}), x_oct) x = np.arange(3.) assert_( np.array2string(x, formatter={'float_kind': lambda x: "%.2f" % x}) == "[0.00 1.00 2.00]") assert_( np.array2string(x, formatter={'float': lambda x: "%.2f" % x}) == "[0.00 1.00 2.00]") s = np.array(['abc', 'def']) assert_( np.array2string(s, formatter={'numpystr': lambda s: s * 2}) == '[abcabc defdef]') # check for backcompat that using FloatFormat works and emits warning with assert_warns(DeprecationWarning): fmt = np.core.arrayprint.FloatFormat(x, 9, 'maxprec', False) assert_equal(np.array2string(x, formatter={'float_kind': fmt}), '[0. 1. 2.]')
def test_pointer(self): from ctypes import c_int, cast, POINTER p = cast((c_int * 10)(*range(10)), POINTER(c_int)) a = as_array(p, shape=(10,)) assert_equal(a.shape, (10,)) assert_array_equal(a, np.arange(10)) a = as_array(p, shape=(2, 5)) assert_equal(a.shape, (2, 5)) assert_array_equal(a, np.arange(10).reshape((2, 5))) # shape argument is required assert_raises(TypeError, as_array, p)