import tempfile import sys import os import warnings import numpy as np from nose import SkipTest from numpy.core import * from numpy.compat import asbytes from numpy.testing.utils import WarningManager from numpy.compat import asbytes, getexception, strchar from test_print import in_foreign_locale from numpy.core.multiarray_tests import ( test_neighborhood_iterator, test_neighborhood_iterator_oob, test_pydatamem_seteventhook_start, test_pydatamem_seteventhook_end, ) from numpy.testing import ( TestCase, run_module_suite, assert_, assert_raises, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_allclose, runstring, dec ) # Need to test an object that does not fully implement math interface from datetime import timedelta if sys.version_info[:2] > (3, 2): # In Python 3.3 the representation of empty shape, strides and suboffsets # is an empty tuple instead of None. # http://docs.python.org/dev/whatsnew/3.3.html#api-changes EMPTY = () else: EMPTY = None class TestFlags(TestCase): def setUp(self): self.a = arange(10) def test_writeable(self): mydict = locals() self.a.flags.writeable = False self.assertRaises(ValueError, runstring, 'self.a[0] = 3', mydict) self.assertRaises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict) self.a.flags.writeable = True self.a[0] = 5 self.a[0] = 0 def test_otherflags(self): assert_equal(self.a.flags.carray, True) assert_equal(self.a.flags.farray, False) assert_equal(self.a.flags.behaved, True) assert_equal(self.a.flags.fnc, False) assert_equal(self.a.flags.forc, True) assert_equal(self.a.flags.owndata, True) assert_equal(self.a.flags.writeable, True) assert_equal(self.a.flags.aligned, True) assert_equal(self.a.flags.updateifcopy, False) class TestAttributes(TestCase): def setUp(self): self.one = arange(10) self.two = arange(20).reshape(4,5) self.three = arange(60,dtype=float64).reshape(2,5,6) def test_attributes(self): assert_equal(self.one.shape, (10,)) assert_equal(self.two.shape, (4,5)) assert_equal(self.three.shape, (2,5,6)) self.three.shape = (10,3,2) assert_equal(self.three.shape, (10,3,2)) self.three.shape = (2,5,6) assert_equal(self.one.strides, (self.one.itemsize,)) num = self.two.itemsize assert_equal(self.two.strides, (5*num, num)) num = self.three.itemsize assert_equal(self.three.strides, (30*num, 6*num, num)) assert_equal(self.one.ndim, 1) assert_equal(self.two.ndim, 2) assert_equal(self.three.ndim, 3) num = self.two.itemsize assert_equal(self.two.size, 20) assert_equal(self.two.nbytes, 20*num) assert_equal(self.two.itemsize, self.two.dtype.itemsize) assert_equal(self.two.base, arange(20)) def test_dtypeattr(self): assert_equal(self.one.dtype, dtype(int_)) assert_equal(self.three.dtype, dtype(float_)) assert_equal(self.one.dtype.char, 'l') assert_equal(self.three.dtype.char, 'd') self.assertTrue(self.three.dtype.str[0] in '<>') assert_equal(self.one.dtype.str[1], 'i') assert_equal(self.three.dtype.str[1], 'f') def test_stridesattr(self): x = self.one def make_array(size, offset, strides): return ndarray([size], buffer=x, dtype=int, offset=offset*x.itemsize, strides=strides*x.itemsize) assert_equal(make_array(4, 4, -1), array([4, 3, 2, 1])) self.assertRaises(ValueError, make_array, 4, 4, -2) self.assertRaises(ValueError, make_array, 4, 2, -1) self.assertRaises(ValueError, make_array, 8, 3, 1) #self.assertRaises(ValueError, make_array, 8, 3, 0) #self.assertRaises(ValueError, lambda: ndarray([1], strides=4)) def test_set_stridesattr(self): x = self.one def make_array(size, offset, strides): try: r = ndarray([size], dtype=int, buffer=x, offset=offset*x.itemsize) except: raise RuntimeError(getexception()) r.strides = strides=strides*x.itemsize return r assert_equal(make_array(4, 4, -1), array([4, 3, 2, 1])) assert_equal(make_array(7,3,1), array([3, 4, 5, 6, 7, 8, 9])) self.assertRaises(ValueError, make_array, 4, 4, -2) self.assertRaises(ValueError, make_array, 4, 2, -1) self.assertRaises(RuntimeError, make_array, 8, 3, 1) #self.assertRaises(ValueError, make_array, 8, 3, 0) def test_fill(self): for t in "?bhilqpBHILQPfdgFDGO": x = empty((3,2,1), t) y = empty((3,2,1), t) x.fill(1) y[...] = 1 assert_equal(x,y) x = array([(0,0.0), (1,1.0)], dtype='i4,f8') x.fill(x[0]) assert_equal(x['f1'][1], x['f1'][0]) class TestAssignment(TestCase): def test_assignment_broadcasting(self): a = np.arange(6).reshape(2,3) # Broadcasting the input to the output a[...] = np.arange(3) assert_equal(a, [[0,1,2],[0,1,2]]) a[...] = np.arange(2).reshape(2,1) assert_equal(a, [[0,0,0],[1,1,1]]) # For compatibility with <= 1.5, a limited version of broadcasting # the output to the input. # # This behavior is inconsistent with NumPy broadcasting # in general, because it only uses one of the two broadcasting # rules (adding a new "1" dimension to the left of the shape), # applied to the output instead of an input. In NumPy 2.0, this kind # of broadcasting assignment will likely be disallowed. a[...] = np.arange(6)[::-1].reshape(1,2,3) assert_equal(a, [[5,4,3],[2,1,0]]) # The other type of broadcasting would require a reduction operation. def assign(a,b): a[...] = b assert_raises(ValueError, assign, a, np.arange(12).reshape(2,2,3)) class TestDtypedescr(TestCase): def test_construction(self): d1 = dtype('i4') assert_equal(d1, dtype(int32)) d2 = dtype('f8') assert_equal(d2, dtype(float64)) class TestZeroRank(TestCase): def setUp(self): self.d = array(0), array('x', object) def test_ellipsis_subscript(self): a,b = self.d self.assertEqual(a[...], 0) self.assertEqual(b[...], 'x') self.assertTrue(a[...] is a) self.assertTrue(b[...] is b) def test_empty_subscript(self): a,b = self.d self.assertEqual(a[()], 0) self.assertEqual(b[()], 'x') self.assertTrue(type(a[()]) is a.dtype.type) self.assertTrue(type(b[()]) is str) def test_invalid_subscript(self): a,b = self.d self.assertRaises(IndexError, lambda x: x[0], a) self.assertRaises(IndexError, lambda x: x[0], b) self.assertRaises(IndexError, lambda x: x[array([], int)], a) self.assertRaises(IndexError, lambda x: x[array([], int)], b) def test_ellipsis_subscript_assignment(self): a,b = self.d a[...] = 42 self.assertEqual(a, 42) b[...] = '' self.assertEqual(b.item(), '') def test_empty_subscript_assignment(self): a,b = self.d a[()] = 42 self.assertEqual(a, 42) b[()] = '' self.assertEqual(b.item(), '') def test_invalid_subscript_assignment(self): a,b = self.d def assign(x, i, v): x[i] = v self.assertRaises(IndexError, assign, a, 0, 42) self.assertRaises(IndexError, assign, b, 0, '') self.assertRaises(ValueError, assign, a, (), '') def test_newaxis(self): a,b = self.d self.assertEqual(a[newaxis].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ..., newaxis].shape, (1,1)) self.assertEqual(a[..., newaxis, newaxis].shape, (1,1)) self.assertEqual(a[newaxis, newaxis, ...].shape, (1,1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): a,b = self.d def subscript(x, i): x[i] self.assertRaises(IndexError, subscript, a, (newaxis, 0)) self.assertRaises(IndexError, subscript, a, (newaxis,)*50) def test_constructor(self): x = ndarray(()) x[()] = 5 self.assertEqual(x[()], 5) y = ndarray((),buffer=x) y[()] = 6 self.assertEqual(x[()], 6) def test_output(self): x = array(2) self.assertRaises(ValueError, add, x, [1], x) class TestScalarIndexing(TestCase): def setUp(self): self.d = array([0,1])[0] def test_ellipsis_subscript(self): a = self.d self.assertEqual(a[...], 0) self.assertEqual(a[...].shape,()) def test_empty_subscript(self): a = self.d self.assertEqual(a[()], 0) self.assertEqual(a[()].shape,()) def test_invalid_subscript(self): a = self.d self.assertRaises(IndexError, lambda x: x[0], a) self.assertRaises(IndexError, lambda x: x[array([], int)], a) def test_invalid_subscript_assignment(self): a = self.d def assign(x, i, v): x[i] = v self.assertRaises(TypeError, assign, a, 0, 42) def test_newaxis(self): a = self.d self.assertEqual(a[newaxis].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ..., newaxis].shape, (1,1)) self.assertEqual(a[..., newaxis, newaxis].shape, (1,1)) self.assertEqual(a[newaxis, newaxis, ...].shape, (1,1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): a = self.d def subscript(x, i): x[i] self.assertRaises(IndexError, subscript, a, (newaxis, 0)) self.assertRaises(IndexError, subscript, a, (newaxis,)*50) def test_overlapping_assignment(self): # With positive strides a = np.arange(4) a[:-1] = a[1:] assert_equal(a, [1,2,3,3]) a = np.arange(4) a[1:] = a[:-1] assert_equal(a, [0,0,1,2]) # With positive and negative strides a = np.arange(4) a[:] = a[::-1] assert_equal(a, [3,2,1,0]) a = np.arange(6).reshape(2,3) a[::-1,:] = a[:,::-1] assert_equal(a, [[5,4,3],[2,1,0]]) a = np.arange(6).reshape(2,3) a[::-1,::-1] = a[:,::-1] assert_equal(a, [[3,4,5],[0,1,2]]) # With just one element overlapping a = np.arange(5) a[:3] = a[2:] assert_equal(a, [2,3,4,3,4]) a = np.arange(5) a[2:] = a[:3] assert_equal(a, [0,1,0,1,2]) a = np.arange(5) a[2::-1] = a[2:] assert_equal(a, [4,3,2,3,4]) a = np.arange(5) a[2:] = a[2::-1] assert_equal(a, [0,1,2,1,0]) a = np.arange(5) a[2::-1] = a[:1:-1] assert_equal(a, [2,3,4,3,4]) a = np.arange(5) a[:1:-1] = a[2::-1] assert_equal(a, [0,1,0,1,2]) class TestCreation(TestCase): def test_from_attribute(self): class x(object): def __array__(self, dtype=None): pass self.assertRaises(ValueError, array, x()) def test_from_string(self) : types = np.typecodes['AllInteger'] + np.typecodes['Float'] nstr = ['123','123'] result = array([123, 123], dtype=int) for type in types : msg = 'String conversion for %s' % type assert_equal(array(nstr, dtype=type), result, err_msg=msg) def test_void(self): arr = np.array([], dtype='V') assert_equal(arr.dtype.kind, 'V') def test_non_sequence_sequence(self): """Should not segfault. Class Fail breaks the sequence protocol for new style classes, i.e., those derived from object. Class Map is a mapping type indicated by raising a ValueError. At some point we may raise a warning instead of an error in the Fail case. """ class Fail(object): def __len__(self): return 1 def __getitem__(self, index): raise ValueError() class Map(object): def __len__(self): return 1 def __getitem__(self, index): raise KeyError() a = np.array([Map()]) assert_(a.shape == (1,)) assert_(a.dtype == np.dtype(object)) assert_raises(ValueError, np.array, [Fail()]) class TestStructured(TestCase): def test_subarray_field_access(self): a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))]) a['a'] = np.arange(60).reshape(3, 5, 2, 2) # Since the subarray is always in C-order, these aren't equal assert_(np.any(a['a'].T != a.T['a'])) # In Fortran order, the subarray gets appended # like in all other cases, not prepended as a special case b = a.copy(order='F') assert_equal(a['a'].shape, b['a'].shape) assert_equal(a.T['a'].shape, a.T.copy()['a'].shape) def test_subarray_comparison(self): # Check that comparisons between record arrays with # multi-dimensional field types work properly a = np.rec.fromrecords( [([1,2,3],'a', [[1,2],[3,4]]),([3,3,3],'b',[[0,0],[0,0]])], dtype=[('a', ('f4',3)), ('b', np.object), ('c', ('i4',(2,2)))]) b = a.copy() assert_equal(a==b, [True,True]) assert_equal(a!=b, [False,False]) b[1].b = 'c' assert_equal(a==b, [True,False]) assert_equal(a!=b, [False,True]) for i in range(3): b[0].a = a[0].a b[0].a[i] = 5 assert_equal(a==b, [False,False]) assert_equal(a!=b, [True,True]) for i in range(2): for j in range(2): b = a.copy() b[0].c[i,j] = 10 assert_equal(a==b, [False,True]) assert_equal(a!=b, [True,False]) # Check that broadcasting with a subarray works a = np.array([[(0,)],[(1,)]],dtype=[('a','f8')]) b = np.array([(0,),(0,),(1,)],dtype=[('a','f8')]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) a = np.array([[(0,)],[(1,)]],dtype=[('a','f8',(1,))]) b = np.array([(0,),(0,),(1,)],dtype=[('a','f8',(1,))]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) a = np.array([[([0,0],)],[([1,1],)]],dtype=[('a','f8',(2,))]) b = np.array([([0,0],),([0,1],),([1,1],)],dtype=[('a','f8',(2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that broadcasting Fortran-style arrays with a subarray work a = np.array([[([0,0],)],[([1,1],)]],dtype=[('a','f8',(2,))], order='F') b = np.array([([0,0],),([0,1],),([1,1],)],dtype=[('a','f8',(2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that incompatible sub-array shapes don't result to broadcasting x = np.zeros((1,), dtype=[('a', ('f4', (1,2))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) assert_equal(x == y, False) x = np.zeros((1,), dtype=[('a', ('f4', (2,1))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) assert_equal(x == y, False) class TestBool(TestCase): def test_test_interning(self): a0 = bool_(0) b0 = bool_(False) self.assertTrue(a0 is b0) a1 = bool_(1) b1 = bool_(True) self.assertTrue(a1 is b1) self.assertTrue(array([True])[0] is a1) self.assertTrue(array(True)[()] is a1) class TestMethods(TestCase): def test_test_round(self): assert_equal(array([1.2,1.5]).round(), [1,2]) assert_equal(array(1.5).round(), 2) assert_equal(array([12.2,15.5]).round(-1), [10,20]) assert_equal(array([12.15,15.51]).round(1), [12.2,15.5]) def test_transpose(self): a = array([[1,2],[3,4]]) assert_equal(a.transpose(), [[1,3],[2,4]]) self.assertRaises(ValueError, lambda: a.transpose(0)) self.assertRaises(ValueError, lambda: a.transpose(0,0)) self.assertRaises(ValueError, lambda: a.transpose(0,1,2)) def test_sort(self): # test ordering for floats and complex containing nans. It is only # necessary to check the lessthan comparison, so sorts that # only follow the insertion sort path are sufficient. We only # test doubles and complex doubles as the logic is the same. # check doubles msg = "Test real sort order with nans" a = np.array([np.nan, 1, 0]) b = sort(a) assert_equal(b, a[::-1], msg) # check complex msg = "Test complex sort order with nans" a = np.zeros(9, dtype=np.complex128) a.real += [np.nan, np.nan, np.nan, 1, 0, 1, 1, 0, 0] a.imag += [np.nan, 1, 0, np.nan, np.nan, 1, 0, 1, 0] b = sort(a) assert_equal(b, a[::-1], msg) # all c scalar sorts use the same code with different types # so it suffices to run a quick check with one type. The number # of sorted items must be greater than ~50 to check the actual # algorithm because quick and merge sort fall over to insertion # sort for small arrays. a = np.arange(101) b = a[::-1].copy() for kind in ['q','m','h'] : msg = "scalar sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test complex sorts. These use the same code as the scalars # but the compare fuction differs. ai = a*1j + 1 bi = b*1j + 1 for kind in ['q','m','h'] : msg = "complex sort, real part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) c = bi.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) ai = a + 1j bi = b + 1j for kind in ['q','m','h'] : msg = "complex sort, imag part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) c = bi.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) # test string sorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)]) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "string sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test unicode sorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "unicode sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test object array sorts. a = np.empty((101,), dtype=np.object) a[:] = range(101) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test record array sorts. dt = np.dtype([('f',float),('i',int)]) a = array([(i,i) for i in range(101)], dtype = dt) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test datetime64 sorts. a = np.arange(0, 101, dtype='datetime64[D]') b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "datetime64 sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test timedelta64 sorts. a = np.arange(0, 101, dtype='timedelta64[D]') b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "timedelta64 sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # check axis handling. This should be the same for all type # specific sorts, so we only check it for one type and one kind a = np.array([[3,2],[1,0]]) b = np.array([[1,0],[3,2]]) c = np.array([[2,3],[0,1]]) d = a.copy() d.sort(axis=0) assert_equal(d, b, "test sort with axis=0") d = a.copy() d.sort(axis=1) assert_equal(d, c, "test sort with axis=1") d = a.copy() d.sort() assert_equal(d, c, "test sort with default axis") def test_sort_order(self): # Test sorting an array with fields x1=np.array([21,32,14]) x2=np.array(['my','first','name']) x3=np.array([3.1,4.5,6.2]) r=np.rec.fromarrays([x1,x2,x3],names='id,word,number') r.sort(order=['id']) assert_equal(r.id, array([14,21,32])) assert_equal(r.word, array(['name','my','first'])) assert_equal(r.number, array([6.2,3.1,4.5])) r.sort(order=['word']) assert_equal(r.id, array([32,21,14])) assert_equal(r.word, array(['first','my','name'])) assert_equal(r.number, array([4.5,3.1,6.2])) r.sort(order=['number']) assert_equal(r.id, array([21,32,14])) assert_equal(r.word, array(['my','first','name'])) assert_equal(r.number, array([3.1,4.5,6.2])) if sys.byteorder == 'little': strtype = '>i2' else: strtype = 'i4') b = a.searchsorted(np.array(128,dtype='>i4')) assert_equal(b, 1, msg) def test_searchsorted_unicode(self): # Test searchsorted on unicode strings. # 1.6.1 contained a string length miscalculation in # arraytypes.c.src:UNICODE_compare() which manifested as # incorrect/inconsistent results from searchsorted. a = np.array(['P:\\20x_dapi_cy3\\20x_dapi_cy3_20100185_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100186_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100187_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100189_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100190_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100191_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100192_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100193_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100194_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100195_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100196_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100197_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100198_1', 'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100199_1'], dtype=np.unicode) ind = np.arange(len(a)) assert_equal([a.searchsorted(v, 'left') for v in a], ind) assert_equal([a.searchsorted(v, 'right') for v in a], ind + 1) assert_equal([a.searchsorted(a[i], 'left') for i in ind], ind) assert_equal([a.searchsorted(a[i], 'right') for i in ind], ind + 1) def test_searchsorted_with_sorter(self): a = np.array([5,2,1,3,4]) s = np.argsort(a) assert_raises(TypeError, np.searchsorted, a, 0, sorter=(1,(2,3))) assert_raises(TypeError, np.searchsorted, a, 0, sorter=[1.1]) assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1,2,3,4]) assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1,2,3,4,5,6]) # bounds check assert_raises(ValueError, np.searchsorted, a, 4, sorter=[0,1,2,3,5]) assert_raises(ValueError, np.searchsorted, a, 0, sorter=[-1,0,1,2,3]) a = np.random.rand(100) s = a.argsort() b = np.sort(a) k = np.linspace(0, 1, 20) assert_equal(b.searchsorted(k), a.searchsorted(k, sorter=s)) a = np.array([0, 1, 2, 3, 5]*20) s = a.argsort() k = [0, 1, 2, 3, 5] assert_equal(a.searchsorted(k, side='l', sorter=s), [0, 20, 40, 60, 80]) assert_equal(a.searchsorted(k, side='r', sorter=s), [20, 40, 60, 80, 100]) def test_flatten(self): x0 = np.array([[1,2,3],[4,5,6]], np.int32) x1 = np.array([[[1,2],[3,4]],[[5,6],[7,8]]], np.int32) y0 = np.array([1,2,3,4,5,6], np.int32) y0f = np.array([1,4,2,5,3,6], np.int32) y1 = np.array([1,2,3,4,5,6,7,8], np.int32) y1f = np.array([1,5,3,7,2,6,4,8], np.int32) assert_equal(x0.flatten(), y0) assert_equal(x0.flatten('F'), y0f) assert_equal(x0.flatten('F'), x0.T.flatten()) assert_equal(x1.flatten(), y1) assert_equal(x1.flatten('F'), y1f) assert_equal(x1.flatten('F'), x1.T.flatten()) def test_dot(self): a = np.array([[1, 0], [0, 1]]) b = np.array([[0, 1], [1, 0]]) c = np.array([[9, 1], [1, -9]]) assert_equal(np.dot(a, b), a.dot(b)) assert_equal(np.dot(np.dot(a, b), c), a.dot(b).dot(c)) def test_diagonal(self): a = np.arange(12).reshape((3, 4)) assert_equal(a.diagonal(), [0, 5, 10]) assert_equal(a.diagonal(0), [0, 5, 10]) assert_equal(a.diagonal(1), [1, 6, 11]) assert_equal(a.diagonal(-1), [4, 9]) b = np.arange(8).reshape((2, 2, 2)) assert_equal(b.diagonal(), [[0, 6], [1, 7]]) assert_equal(b.diagonal(0), [[0, 6], [1, 7]]) assert_equal(b.diagonal(1), [[2], [3]]) assert_equal(b.diagonal(-1), [[4], [5]]) assert_raises(ValueError, b.diagonal, axis1=0, axis2=0) assert_equal(b.diagonal(0, 1, 2), [[0, 3], [4, 7]]) assert_equal(b.diagonal(0, 0, 1), [[0, 6], [1, 7]]) assert_equal(b.diagonal(offset=1, axis1=0, axis2=2), [[1], [3]]) # Order of axis argument doesn't matter: assert_equal(b.diagonal(0, 2, 1), [[0, 3], [4, 7]]) def test_diagonal_deprecation(self): import warnings from numpy.testing.utils import WarningManager def collect_warning_types(f, *args, **kwargs): ctx = WarningManager(record=True) warning_log = ctx.__enter__() warnings.simplefilter("always") try: f(*args, **kwargs) finally: ctx.__exit__() return [w.category for w in warning_log] a = np.arange(9).reshape(3, 3) # All the different functions raise a warning, but not an error, and # 'a' is not modified: assert_equal(collect_warning_types(a.diagonal().__setitem__, 0, 10), [FutureWarning]) assert_equal(a, np.arange(9).reshape(3, 3)) assert_equal(collect_warning_types(np.diagonal(a).__setitem__, 0, 10), [FutureWarning]) assert_equal(a, np.arange(9).reshape(3, 3)) assert_equal(collect_warning_types(np.diag(a).__setitem__, 0, 10), [FutureWarning]) assert_equal(a, np.arange(9).reshape(3, 3)) # Views also warn d = np.diagonal(a) d_view = d.view() assert_equal(collect_warning_types(d_view.__setitem__, 0, 10), [FutureWarning]) # But the write goes through: assert_equal(d[0], 10) # Only one warning per call to diagonal, though (even if there are # multiple views involved): assert_equal(collect_warning_types(d.__setitem__, 0, 10), []) # Other ways of accessing the data also warn: # .data goes via the C buffer API, gives a read-write # buffer/memoryview. We don't warn until tp_getwritebuf is actually # called, which is not until the buffer is written to. have_memoryview = (hasattr(__builtins__, "memoryview") or "memoryview" in __builtins__) def get_data_and_write(getter): buf_or_memoryview = getter(a.diagonal()) if (have_memoryview and isinstance(buf_or_memoryview, memoryview)): buf_or_memoryview[0] = np.array(1) else: buf_or_memoryview[0] = "x" assert_equal(collect_warning_types(get_data_and_write, lambda d: d.data), [FutureWarning]) if hasattr(np, "getbuffer"): assert_equal(collect_warning_types(get_data_and_write, np.getbuffer), [FutureWarning]) # PEP 3118: if have_memoryview: assert_equal(collect_warning_types(get_data_and_write, memoryview), [FutureWarning]) # Void dtypes can give us a read-write buffer, but only in Python 2: import sys if sys.version_info[0] < 3: aV = np.empty((3, 3), dtype="V10") assert_equal(collect_warning_types(aV.diagonal().item, 0), [FutureWarning]) # XX it seems that direct indexing of a void object returns a void # scalar, which ignores not just WARN_ON_WRITE but even WRITEABLE. # i.e. in this: # a = np.empty(10, dtype="V10") # a.flags.writeable = False # buf = a[0].item() # 'buf' ends up as a writeable buffer. I guess no-one actually # uses void types like this though... # __array_interface also lets a data pointer get away from us log = collect_warning_types(getattr, a.diagonal(), "__array_interface__") assert_equal(log, [FutureWarning]) # ctypeslib goes via __array_interface__: try: # may not exist in python 2.4: import ctypes except ImportError: pass else: log = collect_warning_types(np.ctypeslib.as_ctypes, a.diagonal()) assert_equal(log, [FutureWarning]) # __array_struct__ log = collect_warning_types(getattr, a.diagonal(), "__array_struct__") assert_equal(log, [FutureWarning]) # Make sure that our recommendation to silence the warning by copying # the array actually works: diag_copy = a.diagonal().copy() assert_equal(collect_warning_types(diag_copy.__setitem__, 0, 10), []) # There might be people who get a spurious warning because they are # extracting a buffer, but then use that buffer in a read-only # fashion. And they might get cranky at having to create a superfluous # copy just to work around this spurious warning. A reasonable # solution would be for them to mark their usage as read-only, and # thus safe for both past and future PyArray_Diagonal # semantics. So let's make sure that setting the diagonal array to # non-writeable will suppress these warnings: ro_diag = a.diagonal() ro_diag.flags.writeable = False assert_equal(collect_warning_types(getattr, ro_diag, "data"), []) # __array_interface__ has no way to communicate read-onlyness -- # effectively all __array_interface__ arrays are assumed to be # writeable :-( # ro_diag = a.diagonal() # ro_diag.flags.writeable = False # assert_equal(collect_warning_types(getattr, ro_diag, # "__array_interface__"), []) if hasattr(__builtins__, "memoryview"): ro_diag = a.diagonal() ro_diag.flags.writeable = False assert_equal(collect_warning_types(memoryview, ro_diag), []) ro_diag = a.diagonal() ro_diag.flags.writeable = False assert_equal(collect_warning_types(getattr, ro_diag, "__array_struct__"), []) def test_ravel(self): a = np.array([[0,1],[2,3]]) assert_equal(a.ravel(), [0,1,2,3]) assert_(not a.ravel().flags.owndata) assert_equal(a.ravel('F'), [0,2,1,3]) assert_equal(a.ravel(order='C'), [0,1,2,3]) assert_equal(a.ravel(order='F'), [0,2,1,3]) assert_equal(a.ravel(order='A'), [0,1,2,3]) assert_(not a.ravel(order='A').flags.owndata) assert_equal(a.ravel(order='K'), [0,1,2,3]) assert_(not a.ravel(order='K').flags.owndata) assert_equal(a.ravel(), a.reshape(-1)) a = np.array([[0,1],[2,3]], order='F') assert_equal(a.ravel(), [0,1,2,3]) assert_equal(a.ravel(order='A'), [0,2,1,3]) assert_equal(a.ravel(order='K'), [0,2,1,3]) assert_(not a.ravel(order='A').flags.owndata) assert_(not a.ravel(order='K').flags.owndata) assert_equal(a.ravel(), a.reshape(-1)) assert_equal(a.ravel(order='A'), a.reshape(-1, order='A')) a = np.array([[0,1],[2,3]])[::-1,:] assert_equal(a.ravel(), [2,3,0,1]) assert_equal(a.ravel(order='C'), [2,3,0,1]) assert_equal(a.ravel(order='F'), [2,0,3,1]) assert_equal(a.ravel(order='A'), [2,3,0,1]) # 'K' doesn't reverse the axes of negative strides assert_equal(a.ravel(order='K'), [2,3,0,1]) assert_(a.ravel(order='K').flags.owndata) class TestSubscripting(TestCase): def test_test_zero_rank(self): x = array([1,2,3]) self.assertTrue(isinstance(x[0], np.int_)) if sys.version_info[0] < 3: self.assertTrue(isinstance(x[0], int)) self.assertTrue(type(x[0, ...]) is ndarray) class TestPickling(TestCase): def test_roundtrip(self): import pickle carray = array([[2,9],[7,0],[3,8]]) DATA = [ carray, transpose(carray), array([('xxx', 1, 2.0)], dtype=[('a', (str,3)), ('b', int), ('c', float)]) ] for a in DATA: assert_equal(a, pickle.loads(a.dumps()), err_msg="%r" % a) def _loads(self, obj): if sys.version_info[0] >= 3: return loads(obj, encoding='latin1') else: return loads(obj) # version 0 pickles, using protocol=2 to pickle # version 0 doesn't have a version field def test_version0_int8(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.' a = array([1,2,3,4], dtype=int8) p = self._loads(asbytes(s)) assert_equal(a, p) def test_version0_float32(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(U\x01= g2, [g1[i] >= g2[i] for i in [0,1,2]]) assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) def test_mixed(self): g1 = array(["spam","spa","spammer","and eggs"]) g2 = "spam" assert_array_equal(g1 == g2, [x == g2 for x in g1]) assert_array_equal(g1 != g2, [x != g2 for x in g1]) assert_array_equal(g1 < g2, [x < g2 for x in g1]) assert_array_equal(g1 > g2, [x > g2 for x in g1]) assert_array_equal(g1 <= g2, [x <= g2 for x in g1]) assert_array_equal(g1 >= g2, [x >= g2 for x in g1]) def test_unicode(self): g1 = array([u"This",u"is",u"example"]) g2 = array([u"This",u"was",u"example"]) assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0,1,2]]) assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0,1,2]]) assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0,1,2]]) assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0,1,2]]) assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) class TestArgmax(TestCase): nan_arr = [ ([0, 1, 2, 3, np.nan], 4), ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), ([0, 1, 2, 3, complex(0,np.nan)], 4), ([0, 1, 2, 3, complex(np.nan,0)], 4), ([0, 1, 2, complex(np.nan,0), 3], 3), ([0, 1, 2, complex(0,np.nan), 3], 3), ([complex(0,np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0), ([complex(0, 0), complex(0, 2), complex(0, 1)], 1), ([complex(1, 0), complex(0, 2), complex(0, 1)], 0), ([complex(1, 0), complex(0, 2), complex(1, 1)], 2), ([np.datetime64('1923-04-14T12:43:12'), np.datetime64('1994-06-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('1995-11-25T16:02:16'), np.datetime64('2005-01-04T03:14:12'), np.datetime64('2041-12-03T14:05:03')], 5), ([np.datetime64('1935-09-14T04:40:11'), np.datetime64('1949-10-12T12:32:11'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('2015-11-20T12:20:59'), np.datetime64('1932-09-23T10:10:13'), np.datetime64('2014-10-10T03:50:30')], 3), ([np.datetime64('2059-03-14T12:43:12'), np.datetime64('1996-09-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('2022-12-25T16:02:16'), np.datetime64('1963-10-04T03:14:12'), np.datetime64('2013-05-08T18:15:23')], 0), ([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35), timedelta(days=-1, seconds=23)], 0), ([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5), timedelta(days=5, seconds=14)], 1), ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 2), # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 3), #(['zz', 'a', 'aa', 'a'], 0), #(['aa', 'z', 'zz', 'a'], 2), ] def test_all(self): a = np.random.normal(0,1,(4,5,6,7,8)) for i in xrange(a.ndim): amax = a.max(i) aargmax = a.argmax(i) axes = range(a.ndim) axes.remove(i) assert_(all(amax == aargmax.choose(*a.transpose(i,*axes)))) def test_combinations(self): for arr, pos in self.nan_arr: assert_equal(np.argmax(arr), pos, err_msg="%r"%arr) assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r"%arr) class TestArgmin(TestCase): nan_arr = [ ([0, 1, 2, 3, np.nan], 4), ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), ([0, 1, 2, 3, complex(0,np.nan)], 4), ([0, 1, 2, 3, complex(np.nan,0)], 4), ([0, 1, 2, complex(np.nan,0), 3], 3), ([0, 1, 2, complex(0,np.nan), 3], 3), ([complex(0,np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0), ([complex(0, 0), complex(0, 2), complex(0, 1)], 0), ([complex(1, 0), complex(0, 2), complex(0, 1)], 2), ([complex(1, 0), complex(0, 2), complex(1, 1)], 1), ([np.datetime64('1923-04-14T12:43:12'), np.datetime64('1994-06-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('1995-11-25T16:02:16'), np.datetime64('2005-01-04T03:14:12'), np.datetime64('2041-12-03T14:05:03')], 0), ([np.datetime64('1935-09-14T04:40:11'), np.datetime64('1949-10-12T12:32:11'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('2014-11-20T12:20:59'), np.datetime64('2015-09-23T10:10:13'), np.datetime64('1932-10-10T03:50:30')], 5), ([np.datetime64('2059-03-14T12:43:12'), np.datetime64('1996-09-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('2022-12-25T16:02:16'), np.datetime64('1963-10-04T03:14:12'), np.datetime64('2013-05-08T18:15:23')], 4), ([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35), timedelta(days=-1, seconds=23)], 2), ([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5), timedelta(days=5, seconds=14)], 0), ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 1), # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 0), #(['zz', 'a', 'aa', 'a'], 1), #(['aa', 'z', 'zz', 'a'], 3), ] def test_all(self): a = np.random.normal(0,1,(4,5,6,7,8)) for i in xrange(a.ndim): amin = a.min(i) aargmin = a.argmin(i) axes = range(a.ndim) axes.remove(i) assert_(all(amin == aargmin.choose(*a.transpose(i,*axes)))) def test_combinations(self): for arr, pos in self.nan_arr: assert_equal(np.argmin(arr), pos, err_msg="%r"%arr) assert_equal(arr[np.argmin(arr)], np.min(arr), err_msg="%r"%arr) def test_minimum_signed_integers(self): a = np.array([1, -2**7, -2**7 + 1], dtype=np.int8) assert_equal(np.argmin(a), 1) a = np.array([1, -2**15, -2**15 + 1], dtype=np.int16) assert_equal(np.argmin(a), 1) a = np.array([1, -2**31, -2**31 + 1], dtype=np.int32) assert_equal(np.argmin(a), 1) a = np.array([1, -2**63, -2**63 + 1], dtype=np.int64) assert_equal(np.argmin(a), 1) class TestMinMax(TestCase): def test_scalar(self): assert_raises(ValueError, np.amax, 1, 1) assert_raises(ValueError, np.amin, 1, 1) assert_equal(np.amax(1, axis=0), 1) assert_equal(np.amin(1, axis=0), 1) assert_equal(np.amax(1, axis=None), 1) assert_equal(np.amin(1, axis=None), 1) def test_axis(self): assert_raises(ValueError, np.amax, [1,2,3], 1000) assert_equal(np.amax([[1,2,3]], axis=1), 3) class TestNewaxis(TestCase): def test_basic(self): sk = array([0,-0.1,0.1]) res = 250*sk[:,newaxis] assert_almost_equal(res.ravel(),250*sk) class TestClip(TestCase): def _check_range(self,x,cmin,cmax): assert_(np.all(x >= cmin)) assert_(np.all(x <= cmax)) def _clip_type(self,type_group,array_max, clip_min,clip_max,inplace=False, expected_min=None,expected_max=None): if expected_min is None: expected_min = clip_min if expected_max is None: expected_max = clip_max for T in np.sctypes[type_group]: if sys.byteorder == 'little': byte_orders = ['=','>'] else: byte_orders = ['<','='] for byteorder in byte_orders: dtype = np.dtype(T).newbyteorder(byteorder) x = (np.random.random(1000) * array_max).astype(dtype) if inplace: x.clip(clip_min,clip_max,x) else: x = x.clip(clip_min,clip_max) byteorder = '=' if x.dtype.byteorder == '|': byteorder = '|' assert_equal(x.dtype.byteorder,byteorder) self._check_range(x,expected_min,expected_max) return x def test_basic(self): for inplace in [False, True]: self._clip_type('float',1024,-12.8,100.2, inplace=inplace) self._clip_type('float',1024,0,0, inplace=inplace) self._clip_type('int',1024,-120,100.5, inplace=inplace) self._clip_type('int',1024,0,0, inplace=inplace) x = self._clip_type('uint',1024,-120,100,expected_min=0, inplace=inplace) x = self._clip_type('uint',1024,0,0, inplace=inplace) def test_record_array(self): rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '= 3)) x = val.clip(min=3) assert_(np.all(x >= 3)) x = val.clip(max=4) assert_(np.all(x <= 4)) class TestPutmask(object): def tst_basic(self, x, T, mask, val): np.putmask(x, mask, val) assert_(np.all(x[mask] == T(val))) assert_(x.dtype == T) def test_ip_types(self): unchecked_types = [str, unicode, np.void, object] x = np.random.random(1000)*100 mask = x < 40 for val in [-100,0,15]: for types in np.sctypes.itervalues(): for T in types: if T not in unchecked_types: yield self.tst_basic,x.copy().astype(T),T,mask,val def test_mask_size(self): assert_raises(ValueError, np.putmask, np.array([1,2,3]), [True], 5) def tst_byteorder(self,dtype): x = np.array([1,2,3],dtype) np.putmask(x,[True,False,True],-1) assert_array_equal(x,[-1,2,-1]) def test_ip_byteorder(self): for dtype in ('>i4','f8'), ('z', 'i4','f8'), ('z', ' 1 minute on mechanical hard drive def test_big_binary(self): """Test workarounds for 32-bit limited fwrite, fseek, and ftell calls in windows. These normally would hang doing something like this. See http://projects.scipy.org/numpy/ticket/1660""" if sys.platform != 'win32': return try: # before workarounds, only up to 2**32-1 worked fourgbplus = 2**32 + 2**16 testbytes = np.arange(8, dtype=np.int8) n = len(testbytes) flike = tempfile.NamedTemporaryFile() f = flike.file np.tile(testbytes, fourgbplus // testbytes.nbytes).tofile(f) flike.seek(0) a = np.fromfile(f, dtype=np.int8) flike.close() assert_(len(a) == fourgbplus) # check only start and end for speed: assert_((a[:n] == testbytes).all()) assert_((a[-n:] == testbytes).all()) except (MemoryError, ValueError): pass def test_string(self): self._check_from('1,2,3,4', [1., 2., 3., 4.], sep=',') def test_counted_string(self): self._check_from('1,2,3,4', [1., 2., 3., 4.], count=4, sep=',') self._check_from('1,2,3,4', [1., 2., 3.], count=3, sep=',') self._check_from('1,2,3,4', [1., 2., 3., 4.], count=-1, sep=',') def test_string_with_ws(self): self._check_from('1 2 3 4 ', [1, 2, 3, 4], dtype=int, sep=' ') def test_counted_string_with_ws(self): self._check_from('1 2 3 4 ', [1,2,3], count=3, dtype=int, sep=' ') def test_ascii(self): self._check_from('1 , 2 , 3 , 4', [1.,2.,3.,4.], sep=',') self._check_from('1,2,3,4', [1.,2.,3.,4.], dtype=float, sep=',') def test_malformed(self): self._check_from('1.234 1,234', [1.234, 1.], sep=' ') def test_long_sep(self): self._check_from('1_x_3_x_4_x_5', [1,3,4,5], sep='_x_') def test_dtype(self): v = np.array([1,2,3,4], dtype=np.int_) self._check_from('1,2,3,4', v, sep=',', dtype=np.int_) def test_dtype_bool(self): # can't use _check_from because fromstring can't handle True/False v = np.array([True, False, True, False], dtype=np.bool_) s = '1,0,-2.3,0' f = open(self.filename, 'wb') f.write(asbytes(s)) f.close() y = np.fromfile(self.filename, sep=',', dtype=np.bool_) assert_(y.dtype == '?') assert_array_equal(y, v) def test_tofile_sep(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.0,3.51,4.0') os.unlink(self.filename) def test_tofile_format(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',', format='%.2f') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.00,3.51,4.00') def test_locale(self): in_foreign_locale(self.test_numbers)() in_foreign_locale(self.test_nan)() in_foreign_locale(self.test_inf)() in_foreign_locale(self.test_counted_string)() in_foreign_locale(self.test_ascii)() in_foreign_locale(self.test_malformed)() in_foreign_locale(self.test_tofile_sep)() in_foreign_locale(self.test_tofile_format)() class TestFromBuffer(object): def tst_basic(self,buffer,expected,kwargs): assert_array_equal(np.frombuffer(buffer,**kwargs),expected) def test_ip_basic(self): for byteorder in ['<','>']: for dtype in [float,int,np.complex]: dt = np.dtype(dtype).newbyteorder(byteorder) x = (np.random.random((4,7))*5).astype(dt) buf = x.tostring() yield self.tst_basic, buf, x.flat, {'dtype':dt} def test_empty(self): yield self.tst_basic, asbytes(''), np.array([]), {} class TestFlat(TestCase): def setUp(self): a0 = arange(20.0) a = a0.reshape(4,5) a0.shape = (4,5) a.flags.writeable = False self.a = a self.b = a[::2,::2] self.a0 = a0 self.b0 = a0[::2,::2] def test_contiguous(self): testpassed = False try: self.a.flat[12] = 100.0 except ValueError: testpassed = True assert testpassed assert self.a.flat[12] == 12.0 def test_discontiguous(self): testpassed = False try: self.b.flat[4] = 100.0 except ValueError: testpassed = True assert testpassed assert self.b.flat[4] == 12.0 def test___array__(self): c = self.a.flat.__array__() d = self.b.flat.__array__() e = self.a0.flat.__array__() f = self.b0.flat.__array__() assert c.flags.writeable is False assert d.flags.writeable is False assert e.flags.writeable is True assert f.flags.writeable is True assert c.flags.updateifcopy is False assert d.flags.updateifcopy is False assert e.flags.updateifcopy is False assert f.flags.updateifcopy is True assert f.base is self.b0 class TestResize(TestCase): def test_basic(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) x.resize((5,5)) assert_array_equal(x.flat[:9], np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).flat) assert_array_equal(x[9:].flat,0) def test_check_reference(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) y = x self.assertRaises(ValueError,x.resize,(5,1)) def test_int_shape(self): x = np.eye(3) x.resize(3) assert_array_equal(x, np.eye(3)[0,:]) def test_none_shape(self): x = np.eye(3) x.resize(None) assert_array_equal(x, np.eye(3)) x.resize() assert_array_equal(x, np.eye(3)) def test_invalid_arguements(self): self.assertRaises(TypeError, np.eye(3).resize, 'hi') self.assertRaises(ValueError, np.eye(3).resize, -1) self.assertRaises(TypeError, np.eye(3).resize, order=1) self.assertRaises(TypeError, np.eye(3).resize, refcheck='hi') def test_freeform_shape(self): x = np.eye(3) x.resize(3,2,1) assert_(x.shape == (3,2,1)) def test_zeros_appended(self): x = np.eye(3) x.resize(2,3,3) assert_array_equal(x[0], np.eye(3)) assert_array_equal(x[1], np.zeros((3,3))) class TestRecord(TestCase): def test_field_rename(self): dt = np.dtype([('f',float),('i',int)]) dt.names = ['p','q'] assert_equal(dt.names,['p','q']) if sys.version_info[0] >= 3: def test_bytes_fields(self): # Bytes are not allowed in field names and not recognized in titles # on Py3 assert_raises(TypeError, np.dtype, [(asbytes('a'), int)]) assert_raises(TypeError, np.dtype, [(('b', asbytes('a')), int)]) dt = np.dtype([((asbytes('a'), 'b'), int)]) assert_raises(ValueError, dt.__getitem__, asbytes('a')) x = np.array([(1,), (2,), (3,)], dtype=dt) assert_raises(ValueError, x.__getitem__, asbytes('a')) y = x[0] assert_raises(IndexError, y.__getitem__, asbytes('a')) else: def test_unicode_field_titles(self): # Unicode field titles are added to field dict on Py2 title = unicode('b') dt = np.dtype([((title, 'a'), int)]) dt[title] dt['a'] x = np.array([(1,), (2,), (3,)], dtype=dt) x[title] x['a'] y = x[0] y[title] y['a'] def test_unicode_field_names(self): # Unicode field names are not allowed on Py2 title = unicode('b') assert_raises(TypeError, np.dtype, [(title, int)]) assert_raises(TypeError, np.dtype, [(('a', title), int)]) def test_field_names(self): # Test unicode and 8-bit / byte strings can be used a = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) is_py3 = sys.version_info[0] >= 3 if is_py3: funcs = (str,) # byte string indexing fails gracefully assert_raises(ValueError, a.__setitem__, asbytes('f1'), 1) assert_raises(ValueError, a.__getitem__, asbytes('f1')) assert_raises(ValueError, a['f1'].__setitem__, asbytes('sf1'), 1) assert_raises(ValueError, a['f1'].__getitem__, asbytes('sf1')) else: funcs = (str, unicode) for func in funcs: b = a.copy() fn1 = func('f1') b[fn1] = 1 assert_equal(b[fn1], 1) fnn = func('not at all') assert_raises(ValueError, b.__setitem__, fnn, 1) assert_raises(ValueError, b.__getitem__, fnn) b[0][fn1] = 2 assert_equal(b[fn1], 2) # Subfield assert_raises(IndexError, b[0].__setitem__, fnn, 1) assert_raises(IndexError, b[0].__getitem__, fnn) # Subfield fn3 = func('f3') sfn1 = func('sf1') b[fn3][sfn1] = 1 assert_equal(b[fn3][sfn1], 1) assert_raises(ValueError, b[fn3].__setitem__, fnn, 1) assert_raises(ValueError, b[fn3].__getitem__, fnn) # multiple Subfields fn2 = func('f2') b[fn2] = 3 assert_equal(b[['f1','f2']][0].tolist(), (2, 3)) assert_equal(b[['f2','f1']][0].tolist(), (3, 2)) assert_equal(b[['f1','f3']][0].tolist(), (2, (1,))) # view of subfield view/copy assert_equal(b[['f1','f2']][0].view(('i4',2)).tolist(), (2, 3)) assert_equal(b[['f2','f1']][0].view(('i4',2)).tolist(), (3, 2)) view_dtype=[('f1', 'i4'),('f3', [('', 'i4')])] assert_equal(b[['f1','f3']][0].view(view_dtype).tolist(), (2, (1,))) # non-ascii unicode field indexing is well behaved if not is_py3: raise SkipTest('non ascii unicode field indexing skipped; ' 'raises segfault on python 2.x') else: assert_raises(ValueError, a.__setitem__, u'\u03e0', 1) assert_raises(ValueError, a.__getitem__, u'\u03e0') def test_field_names_deprecation(self): import warnings from numpy.testing.utils import WarningManager def collect_warning_types(f, *args, **kwargs): ctx = WarningManager(record=True) warning_log = ctx.__enter__() warnings.simplefilter("always") try: f(*args, **kwargs) finally: ctx.__exit__() return [w.category for w in warning_log] a = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) a['f1'][0] = 1 a['f2'][0] = 2 a['f3'][0] = (3,) b = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) b['f1'][0] = 1 b['f2'][0] = 2 b['f3'][0] = (3,) # All the different functions raise a warning, but not an error, and # 'a' is not modified: assert_equal(collect_warning_types(a[['f1','f2']].__setitem__, 0, (10,20)), [FutureWarning]) assert_equal(a, b) # Views also warn subset = a[['f1','f2']] subset_view = subset.view() assert_equal(collect_warning_types(subset_view['f1'].__setitem__, 0, 10), [FutureWarning]) # But the write goes through: assert_equal(subset['f1'][0], 10) # Only one warning per multiple field indexing, though (even if there are # multiple views involved): assert_equal(collect_warning_types(subset['f1'].__setitem__, 0, 10), []) class TestView(TestCase): def test_basic(self): x = np.array([(1,2,3,4),(5,6,7,8)],dtype=[('r',np.int8),('g',np.int8), ('b',np.int8),('a',np.int8)]) # We must be specific about the endianness here: y = x.view(dtype='= (2, 6): if sys.version_info[:2] == (2, 6): from numpy.core.multiarray import memorysimpleview as memoryview from numpy.core._internal import _dtype_from_pep3118 class TestPEP3118Dtype(object): def _check(self, spec, wanted): dt = np.dtype(wanted) if isinstance(wanted, list) and isinstance(wanted[-1], tuple): if wanted[-1][0] == '': names = list(dt.names) names[-1] = '' dt.names = tuple(names) assert_equal(_dtype_from_pep3118(spec), dt, err_msg="spec %r != dtype %r" % (spec, wanted)) def test_native_padding(self): align = np.dtype('i').alignment for j in xrange(8): if j == 0: s = 'bi' else: s = 'b%dxi' % j self._check('@'+s, {'f0': ('i1', 0), 'f1': ('i', align*(1 + j//align))}) self._check('='+s, {'f0': ('i1', 0), 'f1': ('i', 1+j)}) def test_native_padding_2(self): # Native padding should work also for structs and sub-arrays self._check('x3T{xi}', {'f0': (({'f0': ('i', 4)}, (3,)), 4)}) self._check('^x3T{xi}', {'f0': (({'f0': ('i', 1)}, (3,)), 1)}) def test_trailing_padding(self): # Trailing padding should be included, *and*, the item size # should match the alignment if in aligned mode align = np.dtype('i').alignment def VV(n): return 'V%d' % (align*(1 + (n-1)//align)) self._check('ix', [('f0', 'i'), ('', VV(1))]) self._check('ixx', [('f0', 'i'), ('', VV(2))]) self._check('ixxx', [('f0', 'i'), ('', VV(3))]) self._check('ixxxx', [('f0', 'i'), ('', VV(4))]) self._check('i7x', [('f0', 'i'), ('', VV(7))]) self._check('^ix', [('f0', 'i'), ('', 'V1')]) self._check('^ixx', [('f0', 'i'), ('', 'V2')]) self._check('^ixxx', [('f0', 'i'), ('', 'V3')]) self._check('^ixxxx', [('f0', 'i'), ('', 'V4')]) self._check('^i7x', [('f0', 'i'), ('', 'V7')]) def test_native_padding_3(self): dt = np.dtype( [('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')], align=True) self._check("T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxxi:c:}", dt) dt = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'), ('e', 'b'), ('sub', np.dtype('b,i', align=True))]) self._check("T{b:a:=i:b:b:c:b:d:b:e:T{b:f0:xxxi:f1:}:sub:}", dt) def test_padding_with_array_inside_struct(self): dt = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')], align=True) self._check("T{b:a:xxxi:b:3b:c:xi:d:}", dt) def test_byteorder_inside_struct(self): # The byte order after @T{=i} should be '=', not '@'. # Check this by noting the absence of native alignment. self._check('@T{^i}xi', {'f0': ({'f0': ('i', 0)}, 0), 'f1': ('i', 5)}) def test_intra_padding(self): # Natively aligned sub-arrays may require some internal padding align = np.dtype('i').alignment def VV(n): return 'V%d' % (align*(1 + (n-1)//align)) self._check('(3)T{ix}', ({'f0': ('i', 0), '': (VV(1), 4)}, (3,))) class TestNewBufferProtocol(object): def _check_roundtrip(self, obj): obj = np.asarray(obj) x = memoryview(obj) y = np.asarray(x) y2 = np.array(x) assert_(not y.flags.owndata) assert_(y2.flags.owndata) assert_equal(y.dtype, obj.dtype) assert_array_equal(obj, y) assert_equal(y2.dtype, obj.dtype) assert_array_equal(obj, y2) def test_roundtrip(self): x = np.array([1,2,3,4,5], dtype='i4') self._check_roundtrip(x) x = np.array([[1,2],[3,4]], dtype=np.float64) self._check_roundtrip(x) x = np.zeros((3,3,3), dtype=np.float32)[:,0,:] self._check_roundtrip(x) dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'), ('i', np.single), ('j', np.double), ('k', np.longdouble), ('ix', np.csingle), ('jx', np.cdouble), ('kx', np.clongdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?'), ('p', np.half), ] x = np.array( [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, asbytes('aaaa'), 'bbbb', asbytes('xxx'), True, 1.0)], dtype=dt) self._check_roundtrip(x) x = np.array(([[1,2],[3,4]],), dtype=[('a', (int, (2,2)))]) self._check_roundtrip(x) x = np.array([1,2,3], dtype='>i2') self._check_roundtrip(x) x = np.array([1,2,3], dtype='i') else: assert_equal(y.format, 'i') x = np.array([1,2,3], dtype='