1import copy 2import sys 3import gc 4import tempfile 5import pytest 6from os import path 7from io import BytesIO 8from itertools import chain 9 10import numpy as np 11from numpy.testing import ( 12 assert_, assert_equal, IS_PYPY, assert_almost_equal, 13 assert_array_equal, assert_array_almost_equal, assert_raises, 14 assert_raises_regex, assert_warns, suppress_warnings, 15 _assert_valid_refcount, HAS_REFCOUNT, 16 ) 17from numpy.testing._private.utils import _no_tracing, requires_memory 18from numpy.compat import asbytes, asunicode, pickle 19 20try: 21 RecursionError 22except NameError: 23 RecursionError = RuntimeError # python < 3.5 24 25class TestRegression: 26 def test_invalid_round(self): 27 # Ticket #3 28 v = 4.7599999999999998 29 assert_array_equal(np.array([v]), np.array(v)) 30 31 def test_mem_empty(self): 32 # Ticket #7 33 np.empty((1,), dtype=[('x', np.int64)]) 34 35 def test_pickle_transposed(self): 36 # Ticket #16 37 a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]])) 38 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 39 with BytesIO() as f: 40 pickle.dump(a, f, protocol=proto) 41 f.seek(0) 42 b = pickle.load(f) 43 assert_array_equal(a, b) 44 45 def test_dtype_names(self): 46 # Ticket #35 47 # Should succeed 48 np.dtype([(('name', 'label'), np.int32, 3)]) 49 50 def test_reduce(self): 51 # Ticket #40 52 assert_almost_equal(np.add.reduce([1., .5], dtype=None), 1.5) 53 54 def test_zeros_order(self): 55 # Ticket #43 56 np.zeros([3], int, 'C') 57 np.zeros([3], order='C') 58 np.zeros([3], int, order='C') 59 60 def test_asarray_with_order(self): 61 # Check that nothing is done when order='F' and array C/F-contiguous 62 a = np.ones(2) 63 assert_(a is np.asarray(a, order='F')) 64 65 def test_ravel_with_order(self): 66 # Check that ravel works when order='F' and array C/F-contiguous 67 a = np.ones(2) 68 assert_(not a.ravel('F').flags.owndata) 69 70 def test_sort_bigendian(self): 71 # Ticket #47 72 a = np.linspace(0, 10, 11) 73 c = a.astype(np.dtype('<f8')) 74 c.sort() 75 assert_array_almost_equal(c, a) 76 77 def test_negative_nd_indexing(self): 78 # Ticket #49 79 c = np.arange(125).reshape((5, 5, 5)) 80 origidx = np.array([-1, 0, 1]) 81 idx = np.array(origidx) 82 c[idx] 83 assert_array_equal(idx, origidx) 84 85 def test_char_dump(self): 86 # Ticket #50 87 ca = np.char.array(np.arange(1000, 1010), itemsize=4) 88 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 89 with BytesIO() as f: 90 pickle.dump(ca, f, protocol=proto) 91 f.seek(0) 92 ca = np.load(f, allow_pickle=True) 93 94 def test_noncontiguous_fill(self): 95 # Ticket #58. 96 a = np.zeros((5, 3)) 97 b = a[:, :2,] 98 99 def rs(): 100 b.shape = (10,) 101 102 assert_raises(AttributeError, rs) 103 104 def test_bool(self): 105 # Ticket #60 106 np.bool_(1) # Should succeed 107 108 def test_indexing1(self): 109 # Ticket #64 110 descr = [('x', [('y', [('z', 'c16', (2,)),]),]),] 111 buffer = ((([6j, 4j],),),) 112 h = np.array(buffer, dtype=descr) 113 h['x']['y']['z'] 114 115 def test_indexing2(self): 116 # Ticket #65 117 descr = [('x', 'i4', (2,))] 118 buffer = ([3, 2],) 119 h = np.array(buffer, dtype=descr) 120 h['x'] 121 122 def test_round(self): 123 # Ticket #67 124 x = np.array([1+2j]) 125 assert_almost_equal(x**(-1), [1/(1+2j)]) 126 127 def test_scalar_compare(self): 128 # Trac Ticket #72 129 # https://github.com/numpy/numpy/issues/565 130 a = np.array(['test', 'auto']) 131 assert_array_equal(a == 'auto', np.array([False, True])) 132 assert_(a[1] == 'auto') 133 assert_(a[0] != 'auto') 134 b = np.linspace(0, 10, 11) 135 # This should return true for now, but will eventually raise an error: 136 with suppress_warnings() as sup: 137 sup.filter(FutureWarning) 138 assert_(b != 'auto') 139 assert_(b[0] != 'auto') 140 141 def test_unicode_swapping(self): 142 # Ticket #79 143 ulen = 1 144 ucs_value = u'\U0010FFFF' 145 ua = np.array([[[ucs_value*ulen]*2]*3]*4, dtype='U%s' % ulen) 146 ua.newbyteorder() # Should succeed. 147 148 def test_object_array_fill(self): 149 # Ticket #86 150 x = np.zeros(1, 'O') 151 x.fill([]) 152 153 def test_mem_dtype_align(self): 154 # Ticket #93 155 assert_raises(TypeError, np.dtype, 156 {'names':['a'], 'formats':['foo']}, align=1) 157 158 def test_endian_bool_indexing(self): 159 # Ticket #105 160 a = np.arange(10., dtype='>f8') 161 b = np.arange(10., dtype='<f8') 162 xa = np.where((a > 2) & (a < 6)) 163 xb = np.where((b > 2) & (b < 6)) 164 ya = ((a > 2) & (a < 6)) 165 yb = ((b > 2) & (b < 6)) 166 assert_array_almost_equal(xa, ya.nonzero()) 167 assert_array_almost_equal(xb, yb.nonzero()) 168 assert_(np.all(a[ya] > 0.5)) 169 assert_(np.all(b[yb] > 0.5)) 170 171 def test_endian_where(self): 172 # GitHub issue #369 173 net = np.zeros(3, dtype='>f4') 174 net[1] = 0.00458849 175 net[2] = 0.605202 176 max_net = net.max() 177 test = np.where(net <= 0., max_net, net) 178 correct = np.array([ 0.60520202, 0.00458849, 0.60520202]) 179 assert_array_almost_equal(test, correct) 180 181 def test_endian_recarray(self): 182 # Ticket #2185 183 dt = np.dtype([ 184 ('head', '>u4'), 185 ('data', '>u4', 2), 186 ]) 187 buf = np.recarray(1, dtype=dt) 188 buf[0]['head'] = 1 189 buf[0]['data'][:] = [1, 1] 190 191 h = buf[0]['head'] 192 d = buf[0]['data'][0] 193 buf[0]['head'] = h 194 buf[0]['data'][0] = d 195 assert_(buf[0]['head'] == 1) 196 197 def test_mem_dot(self): 198 # Ticket #106 199 x = np.random.randn(0, 1) 200 y = np.random.randn(10, 1) 201 # Dummy array to detect bad memory access: 202 _z = np.ones(10) 203 _dummy = np.empty((0, 10)) 204 z = np.lib.stride_tricks.as_strided(_z, _dummy.shape, _dummy.strides) 205 np.dot(x, np.transpose(y), out=z) 206 assert_equal(_z, np.ones(10)) 207 # Do the same for the built-in dot: 208 np.core.multiarray.dot(x, np.transpose(y), out=z) 209 assert_equal(_z, np.ones(10)) 210 211 def test_arange_endian(self): 212 # Ticket #111 213 ref = np.arange(10) 214 x = np.arange(10, dtype='<f8') 215 assert_array_equal(ref, x) 216 x = np.arange(10, dtype='>f8') 217 assert_array_equal(ref, x) 218 219 def test_arange_inf_step(self): 220 ref = np.arange(0, 1, 10) 221 x = np.arange(0, 1, np.inf) 222 assert_array_equal(ref, x) 223 224 ref = np.arange(0, 1, -10) 225 x = np.arange(0, 1, -np.inf) 226 assert_array_equal(ref, x) 227 228 ref = np.arange(0, -1, -10) 229 x = np.arange(0, -1, -np.inf) 230 assert_array_equal(ref, x) 231 232 ref = np.arange(0, -1, 10) 233 x = np.arange(0, -1, np.inf) 234 assert_array_equal(ref, x) 235 236 def test_arange_underflow_stop_and_step(self): 237 finfo = np.finfo(np.float64) 238 239 ref = np.arange(0, finfo.eps, 2 * finfo.eps) 240 x = np.arange(0, finfo.eps, finfo.max) 241 assert_array_equal(ref, x) 242 243 ref = np.arange(0, finfo.eps, -2 * finfo.eps) 244 x = np.arange(0, finfo.eps, -finfo.max) 245 assert_array_equal(ref, x) 246 247 ref = np.arange(0, -finfo.eps, -2 * finfo.eps) 248 x = np.arange(0, -finfo.eps, -finfo.max) 249 assert_array_equal(ref, x) 250 251 ref = np.arange(0, -finfo.eps, 2 * finfo.eps) 252 x = np.arange(0, -finfo.eps, finfo.max) 253 assert_array_equal(ref, x) 254 255 def test_argmax(self): 256 # Ticket #119 257 a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) 258 for i in range(a.ndim): 259 a.argmax(i) # Should succeed 260 261 def test_mem_divmod(self): 262 # Ticket #126 263 for i in range(10): 264 divmod(np.array([i])[0], 10) 265 266 def test_hstack_invalid_dims(self): 267 # Ticket #128 268 x = np.arange(9).reshape((3, 3)) 269 y = np.array([0, 0, 0]) 270 assert_raises(ValueError, np.hstack, (x, y)) 271 272 def test_squeeze_type(self): 273 # Ticket #133 274 a = np.array([3]) 275 b = np.array(3) 276 assert_(type(a.squeeze()) is np.ndarray) 277 assert_(type(b.squeeze()) is np.ndarray) 278 279 def test_add_identity(self): 280 # Ticket #143 281 assert_equal(0, np.add.identity) 282 283 def test_numpy_float_python_long_addition(self): 284 # Check that numpy float and python longs can be added correctly. 285 a = np.float_(23.) + 2**135 286 assert_equal(a, 23. + 2**135) 287 288 def test_binary_repr_0(self): 289 # Ticket #151 290 assert_equal('0', np.binary_repr(0)) 291 292 def test_rec_iterate(self): 293 # Ticket #160 294 descr = np.dtype([('i', int), ('f', float), ('s', '|S3')]) 295 x = np.rec.array([(1, 1.1, '1.0'), 296 (2, 2.2, '2.0')], dtype=descr) 297 x[0].tolist() 298 [i for i in x[0]] 299 300 def test_unicode_string_comparison(self): 301 # Ticket #190 302 a = np.array('hello', np.unicode_) 303 b = np.array('world') 304 a == b 305 306 def test_tobytes_FORTRANORDER_discontiguous(self): 307 # Fix in r2836 308 # Create non-contiguous Fortran ordered array 309 x = np.array(np.random.rand(3, 3), order='F')[:, :2] 310 assert_array_almost_equal(x.ravel(), np.frombuffer(x.tobytes())) 311 312 def test_flat_assignment(self): 313 # Correct behaviour of ticket #194 314 x = np.empty((3, 1)) 315 x.flat = np.arange(3) 316 assert_array_almost_equal(x, [[0], [1], [2]]) 317 x.flat = np.arange(3, dtype=float) 318 assert_array_almost_equal(x, [[0], [1], [2]]) 319 320 def test_broadcast_flat_assignment(self): 321 # Ticket #194 322 x = np.empty((3, 1)) 323 324 def bfa(): 325 x[:] = np.arange(3) 326 327 def bfb(): 328 x[:] = np.arange(3, dtype=float) 329 330 assert_raises(ValueError, bfa) 331 assert_raises(ValueError, bfb) 332 333 def test_nonarray_assignment(self): 334 # See also Issue gh-2870, test for non-array assignment 335 # and equivalent unsafe casted array assignment 336 a = np.arange(10) 337 b = np.ones(10, dtype=bool) 338 r = np.arange(10) 339 340 def assign(a, b, c): 341 a[b] = c 342 343 assert_raises(ValueError, assign, a, b, np.nan) 344 a[b] = np.array(np.nan) # but not this. 345 assert_raises(ValueError, assign, a, r, np.nan) 346 a[r] = np.array(np.nan) 347 348 def test_unpickle_dtype_with_object(self): 349 # Implemented in r2840 350 dt = np.dtype([('x', int), ('y', np.object_), ('z', 'O')]) 351 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 352 with BytesIO() as f: 353 pickle.dump(dt, f, protocol=proto) 354 f.seek(0) 355 dt_ = pickle.load(f) 356 assert_equal(dt, dt_) 357 358 def test_mem_array_creation_invalid_specification(self): 359 # Ticket #196 360 dt = np.dtype([('x', int), ('y', np.object_)]) 361 # Wrong way 362 assert_raises(ValueError, np.array, [1, 'object'], dt) 363 # Correct way 364 np.array([(1, 'object')], dt) 365 366 def test_recarray_single_element(self): 367 # Ticket #202 368 a = np.array([1, 2, 3], dtype=np.int32) 369 b = a.copy() 370 r = np.rec.array(a, shape=1, formats=['3i4'], names=['d']) 371 assert_array_equal(a, b) 372 assert_equal(a, r[0][0]) 373 374 def test_zero_sized_array_indexing(self): 375 # Ticket #205 376 tmp = np.array([]) 377 378 def index_tmp(): 379 tmp[np.array(10)] 380 381 assert_raises(IndexError, index_tmp) 382 383 def test_chararray_rstrip(self): 384 # Ticket #222 385 x = np.chararray((1,), 5) 386 x[0] = b'a ' 387 x = x.rstrip() 388 assert_equal(x[0], b'a') 389 390 def test_object_array_shape(self): 391 # Ticket #239 392 assert_equal(np.array([[1, 2], 3, 4], dtype=object).shape, (3,)) 393 assert_equal(np.array([[1, 2], [3, 4]], dtype=object).shape, (2, 2)) 394 assert_equal(np.array([(1, 2), (3, 4)], dtype=object).shape, (2, 2)) 395 assert_equal(np.array([], dtype=object).shape, (0,)) 396 assert_equal(np.array([[], [], []], dtype=object).shape, (3, 0)) 397 assert_equal(np.array([[3, 4], [5, 6], None], dtype=object).shape, (3,)) 398 399 def test_mem_around(self): 400 # Ticket #243 401 x = np.zeros((1,)) 402 y = [0] 403 decimal = 6 404 np.around(abs(x-y), decimal) <= 10.0**(-decimal) 405 406 def test_character_array_strip(self): 407 # Ticket #246 408 x = np.char.array(("x", "x ", "x ")) 409 for c in x: 410 assert_equal(c, "x") 411 412 def test_lexsort(self): 413 # Lexsort memory error 414 v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 415 assert_equal(np.lexsort(v), 0) 416 417 def test_lexsort_invalid_sequence(self): 418 # Issue gh-4123 419 class BuggySequence: 420 def __len__(self): 421 return 4 422 423 def __getitem__(self, key): 424 raise KeyError 425 426 assert_raises(KeyError, np.lexsort, BuggySequence()) 427 428 def test_lexsort_zerolen_custom_strides(self): 429 # Ticket #14228 430 xs = np.array([], dtype='i8') 431 assert xs.strides == (8,) 432 assert np.lexsort((xs,)).shape[0] == 0 # Works 433 434 xs.strides = (16,) 435 assert np.lexsort((xs,)).shape[0] == 0 # Was: MemoryError 436 437 def test_lexsort_zerolen_custom_strides_2d(self): 438 xs = np.array([], dtype='i8') 439 440 xs.shape = (0, 2) 441 xs.strides = (16, 16) 442 assert np.lexsort((xs,), axis=0).shape[0] == 0 443 444 xs.shape = (2, 0) 445 xs.strides = (16, 16) 446 assert np.lexsort((xs,), axis=0).shape[0] == 2 447 448 def test_lexsort_invalid_axis(self): 449 assert_raises(np.AxisError, np.lexsort, (np.arange(1),), axis=2) 450 assert_raises(np.AxisError, np.lexsort, (np.array([]),), axis=1) 451 assert_raises(np.AxisError, np.lexsort, (np.array(1),), axis=10) 452 453 def test_lexsort_zerolen_element(self): 454 dt = np.dtype([]) # a void dtype with no fields 455 xs = np.empty(4, dt) 456 457 assert np.lexsort((xs,)).shape[0] == xs.shape[0] 458 459 def test_pickle_py2_bytes_encoding(self): 460 # Check that arrays and scalars pickled on Py2 are 461 # unpickleable on Py3 using encoding='bytes' 462 463 test_data = [ 464 # (original, py2_pickle) 465 (np.unicode_('\u6f2c'), 466 b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n" 467 b"(S'U1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI4\nI4\n" 468 b"I0\ntp6\nbS',o\\x00\\x00'\np7\ntp8\nRp9\n."), 469 470 (np.array([9e123], dtype=np.float64), 471 b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\n" 472 b"p1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\n" 473 b"p7\n(S'f8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'<'\np11\nNNNI-1\nI-1\n" 474 b"I0\ntp12\nbI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np13\ntp14\nb."), 475 476 (np.array([(9e123,)], dtype=[('name', float)]), 477 b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n" 478 b"(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n" 479 b"(S'V8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'name'\np12\ntp13\n" 480 b"(dp14\ng12\n(g7\n(S'f8'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'<'\np18\nNNNI-1\n" 481 b"I-1\nI0\ntp19\nbI0\ntp20\nsI8\nI1\nI0\ntp21\n" 482 b"bI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np22\ntp23\nb."), 483 ] 484 485 for original, data in test_data: 486 result = pickle.loads(data, encoding='bytes') 487 assert_equal(result, original) 488 489 if isinstance(result, np.ndarray) and result.dtype.names is not None: 490 for name in result.dtype.names: 491 assert_(isinstance(name, str)) 492 493 def test_pickle_dtype(self): 494 # Ticket #251 495 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 496 pickle.dumps(float, protocol=proto) 497 498 def test_swap_real(self): 499 # Ticket #265 500 assert_equal(np.arange(4, dtype='>c8').imag.max(), 0.0) 501 assert_equal(np.arange(4, dtype='<c8').imag.max(), 0.0) 502 assert_equal(np.arange(4, dtype='>c8').real.max(), 3.0) 503 assert_equal(np.arange(4, dtype='<c8').real.max(), 3.0) 504 505 def test_object_array_from_list(self): 506 # Ticket #270 507 assert_(np.array([1, 'A', None]).shape == (3,)) 508 509 def test_multiple_assign(self): 510 # Ticket #273 511 a = np.zeros((3, 1), int) 512 a[[1, 2]] = 1 513 514 def test_empty_array_type(self): 515 assert_equal(np.array([]).dtype, np.zeros(0).dtype) 516 517 def test_void_copyswap(self): 518 dt = np.dtype([('one', '<i4'), ('two', '<i4')]) 519 x = np.array((1, 2), dtype=dt) 520 x = x.byteswap() 521 assert_(x['one'] > 1 and x['two'] > 2) 522 523 def test_method_args(self): 524 # Make sure methods and functions have same default axis 525 # keyword and arguments 526 funcs1 = ['argmax', 'argmin', 'sum', ('product', 'prod'), 527 ('sometrue', 'any'), 528 ('alltrue', 'all'), 'cumsum', ('cumproduct', 'cumprod'), 529 'ptp', 'cumprod', 'prod', 'std', 'var', 'mean', 530 'round', 'min', 'max', 'argsort', 'sort'] 531 funcs2 = ['compress', 'take', 'repeat'] 532 533 for func in funcs1: 534 arr = np.random.rand(8, 7) 535 arr2 = arr.copy() 536 if isinstance(func, tuple): 537 func_meth = func[1] 538 func = func[0] 539 else: 540 func_meth = func 541 res1 = getattr(arr, func_meth)() 542 res2 = getattr(np, func)(arr2) 543 if res1 is None: 544 res1 = arr 545 546 if res1.dtype.kind in 'uib': 547 assert_((res1 == res2).all(), func) 548 else: 549 assert_(abs(res1-res2).max() < 1e-8, func) 550 551 for func in funcs2: 552 arr1 = np.random.rand(8, 7) 553 arr2 = np.random.rand(8, 7) 554 res1 = None 555 if func == 'compress': 556 arr1 = arr1.ravel() 557 res1 = getattr(arr2, func)(arr1) 558 else: 559 arr2 = (15*arr2).astype(int).ravel() 560 if res1 is None: 561 res1 = getattr(arr1, func)(arr2) 562 res2 = getattr(np, func)(arr1, arr2) 563 assert_(abs(res1-res2).max() < 1e-8, func) 564 565 def test_mem_lexsort_strings(self): 566 # Ticket #298 567 lst = ['abc', 'cde', 'fgh'] 568 np.lexsort((lst,)) 569 570 def test_fancy_index(self): 571 # Ticket #302 572 x = np.array([1, 2])[np.array([0])] 573 assert_equal(x.shape, (1,)) 574 575 def test_recarray_copy(self): 576 # Ticket #312 577 dt = [('x', np.int16), ('y', np.float64)] 578 ra = np.array([(1, 2.3)], dtype=dt) 579 rb = np.rec.array(ra, dtype=dt) 580 rb['x'] = 2. 581 assert_(ra['x'] != rb['x']) 582 583 def test_rec_fromarray(self): 584 # Ticket #322 585 x1 = np.array([[1, 2], [3, 4], [5, 6]]) 586 x2 = np.array(['a', 'dd', 'xyz']) 587 x3 = np.array([1.1, 2, 3]) 588 np.rec.fromarrays([x1, x2, x3], formats="(2,)i4,a3,f8") 589 590 def test_object_array_assign(self): 591 x = np.empty((2, 2), object) 592 x.flat[2] = (1, 2, 3) 593 assert_equal(x.flat[2], (1, 2, 3)) 594 595 def test_ndmin_float64(self): 596 # Ticket #324 597 x = np.array([1, 2, 3], dtype=np.float64) 598 assert_equal(np.array(x, dtype=np.float32, ndmin=2).ndim, 2) 599 assert_equal(np.array(x, dtype=np.float64, ndmin=2).ndim, 2) 600 601 def test_ndmin_order(self): 602 # Issue #465 and related checks 603 assert_(np.array([1, 2], order='C', ndmin=3).flags.c_contiguous) 604 assert_(np.array([1, 2], order='F', ndmin=3).flags.f_contiguous) 605 assert_(np.array(np.ones((2, 2), order='F'), ndmin=3).flags.f_contiguous) 606 assert_(np.array(np.ones((2, 2), order='C'), ndmin=3).flags.c_contiguous) 607 608 def test_mem_axis_minimization(self): 609 # Ticket #327 610 data = np.arange(5) 611 data = np.add.outer(data, data) 612 613 def test_mem_float_imag(self): 614 # Ticket #330 615 np.float64(1.0).imag 616 617 def test_dtype_tuple(self): 618 # Ticket #334 619 assert_(np.dtype('i4') == np.dtype(('i4', ()))) 620 621 def test_dtype_posttuple(self): 622 # Ticket #335 623 np.dtype([('col1', '()i4')]) 624 625 def test_numeric_carray_compare(self): 626 # Ticket #341 627 assert_equal(np.array(['X'], 'c'), b'X') 628 629 def test_string_array_size(self): 630 # Ticket #342 631 assert_raises(ValueError, 632 np.array, [['X'], ['X', 'X', 'X']], '|S1') 633 634 def test_dtype_repr(self): 635 # Ticket #344 636 dt1 = np.dtype(('uint32', 2)) 637 dt2 = np.dtype(('uint32', (2,))) 638 assert_equal(dt1.__repr__(), dt2.__repr__()) 639 640 def test_reshape_order(self): 641 # Make sure reshape order works. 642 a = np.arange(6).reshape(2, 3, order='F') 643 assert_equal(a, [[0, 2, 4], [1, 3, 5]]) 644 a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) 645 b = a[:, 1] 646 assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]]) 647 648 def test_reshape_zero_strides(self): 649 # Issue #380, test reshaping of zero strided arrays 650 a = np.ones(1) 651 a = np.lib.stride_tricks.as_strided(a, shape=(5,), strides=(0,)) 652 assert_(a.reshape(5, 1).strides[0] == 0) 653 654 def test_reshape_zero_size(self): 655 # GitHub Issue #2700, setting shape failed for 0-sized arrays 656 a = np.ones((0, 2)) 657 a.shape = (-1, 2) 658 659 # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. 660 # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous. 661 @pytest.mark.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max, 662 reason="Using relaxed stride checking") 663 def test_reshape_trailing_ones_strides(self): 664 # GitHub issue gh-2949, bad strides for trailing ones of new shape 665 a = np.zeros(12, dtype=np.int32)[::2] # not contiguous 666 strides_c = (16, 8, 8, 8) 667 strides_f = (8, 24, 48, 48) 668 assert_equal(a.reshape(3, 2, 1, 1).strides, strides_c) 669 assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f) 670 assert_equal(np.array(0, dtype=np.int32).reshape(1, 1).strides, (4, 4)) 671 672 def test_repeat_discont(self): 673 # Ticket #352 674 a = np.arange(12).reshape(4, 3)[:, 2] 675 assert_equal(a.repeat(3), [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11]) 676 677 def test_array_index(self): 678 # Make sure optimization is not called in this case. 679 a = np.array([1, 2, 3]) 680 a2 = np.array([[1, 2, 3]]) 681 assert_equal(a[np.where(a == 3)], a2[np.where(a2 == 3)]) 682 683 def test_object_argmax(self): 684 a = np.array([1, 2, 3], dtype=object) 685 assert_(a.argmax() == 2) 686 687 def test_recarray_fields(self): 688 # Ticket #372 689 dt0 = np.dtype([('f0', 'i4'), ('f1', 'i4')]) 690 dt1 = np.dtype([('f0', 'i8'), ('f1', 'i8')]) 691 for a in [np.array([(1, 2), (3, 4)], "i4,i4"), 692 np.rec.array([(1, 2), (3, 4)], "i4,i4"), 693 np.rec.array([(1, 2), (3, 4)]), 694 np.rec.fromarrays([(1, 2), (3, 4)], "i4,i4"), 695 np.rec.fromarrays([(1, 2), (3, 4)])]: 696 assert_(a.dtype in [dt0, dt1]) 697 698 def test_random_shuffle(self): 699 # Ticket #374 700 a = np.arange(5).reshape((5, 1)) 701 b = a.copy() 702 np.random.shuffle(b) 703 assert_equal(np.sort(b, axis=0), a) 704 705 def test_refcount_vdot(self): 706 # Changeset #3443 707 _assert_valid_refcount(np.vdot) 708 709 def test_startswith(self): 710 ca = np.char.array(['Hi', 'There']) 711 assert_equal(ca.startswith('H'), [True, False]) 712 713 def test_noncommutative_reduce_accumulate(self): 714 # Ticket #413 715 tosubtract = np.arange(5) 716 todivide = np.array([2.0, 0.5, 0.25]) 717 assert_equal(np.subtract.reduce(tosubtract), -10) 718 assert_equal(np.divide.reduce(todivide), 16.0) 719 assert_array_equal(np.subtract.accumulate(tosubtract), 720 np.array([0, -1, -3, -6, -10])) 721 assert_array_equal(np.divide.accumulate(todivide), 722 np.array([2., 4., 16.])) 723 724 def test_convolve_empty(self): 725 # Convolve should raise an error for empty input array. 726 assert_raises(ValueError, np.convolve, [], [1]) 727 assert_raises(ValueError, np.convolve, [1], []) 728 729 def test_multidim_byteswap(self): 730 # Ticket #449 731 r = np.array([(1, (0, 1, 2))], dtype="i2,3i2") 732 assert_array_equal(r.byteswap(), 733 np.array([(256, (0, 256, 512))], r.dtype)) 734 735 def test_string_NULL(self): 736 # Changeset 3557 737 assert_equal(np.array("a\x00\x0b\x0c\x00").item(), 738 'a\x00\x0b\x0c') 739 740 def test_junk_in_string_fields_of_recarray(self): 741 # Ticket #483 742 r = np.array([[b'abc']], dtype=[('var1', '|S20')]) 743 assert_(asbytes(r['var1'][0][0]) == b'abc') 744 745 def test_take_output(self): 746 # Ensure that 'take' honours output parameter. 747 x = np.arange(12).reshape((3, 4)) 748 a = np.take(x, [0, 2], axis=1) 749 b = np.zeros_like(a) 750 np.take(x, [0, 2], axis=1, out=b) 751 assert_array_equal(a, b) 752 753 def test_take_object_fail(self): 754 # Issue gh-3001 755 d = 123. 756 a = np.array([d, 1], dtype=object) 757 if HAS_REFCOUNT: 758 ref_d = sys.getrefcount(d) 759 try: 760 a.take([0, 100]) 761 except IndexError: 762 pass 763 if HAS_REFCOUNT: 764 assert_(ref_d == sys.getrefcount(d)) 765 766 def test_array_str_64bit(self): 767 # Ticket #501 768 s = np.array([1, np.nan], dtype=np.float64) 769 with np.errstate(all='raise'): 770 np.array_str(s) # Should succeed 771 772 def test_frompyfunc_endian(self): 773 # Ticket #503 774 from math import radians 775 uradians = np.frompyfunc(radians, 1, 1) 776 big_endian = np.array([83.4, 83.5], dtype='>f8') 777 little_endian = np.array([83.4, 83.5], dtype='<f8') 778 assert_almost_equal(uradians(big_endian).astype(float), 779 uradians(little_endian).astype(float)) 780 781 def test_mem_string_arr(self): 782 # Ticket #514 783 s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 784 t = [] 785 np.hstack((t, s)) 786 787 def test_arr_transpose(self): 788 # Ticket #516 789 x = np.random.rand(*(2,)*16) 790 x.transpose(list(range(16))) # Should succeed 791 792 def test_string_mergesort(self): 793 # Ticket #540 794 x = np.array(['a']*32) 795 assert_array_equal(x.argsort(kind='m'), np.arange(32)) 796 797 def test_argmax_byteorder(self): 798 # Ticket #546 799 a = np.arange(3, dtype='>f') 800 assert_(a[a.argmax()] == a.max()) 801 802 def test_rand_seed(self): 803 # Ticket #555 804 for l in np.arange(4): 805 np.random.seed(l) 806 807 def test_mem_deallocation_leak(self): 808 # Ticket #562 809 a = np.zeros(5, dtype=float) 810 b = np.array(a, dtype=float) 811 del a, b 812 813 def test_mem_on_invalid_dtype(self): 814 "Ticket #583" 815 assert_raises(ValueError, np.fromiter, [['12', ''], ['13', '']], str) 816 817 def test_dot_negative_stride(self): 818 # Ticket #588 819 x = np.array([[1, 5, 25, 125., 625]]) 820 y = np.array([[20.], [160.], [640.], [1280.], [1024.]]) 821 z = y[::-1].copy() 822 y2 = y[::-1] 823 assert_equal(np.dot(x, z), np.dot(x, y2)) 824 825 def test_object_casting(self): 826 # This used to trigger the object-type version of 827 # the bitwise_or operation, because float64 -> object 828 # casting succeeds 829 def rs(): 830 x = np.ones([484, 286]) 831 y = np.zeros([484, 286]) 832 x |= y 833 834 assert_raises(TypeError, rs) 835 836 def test_unicode_scalar(self): 837 # Ticket #600 838 x = np.array(["DROND", "DROND1"], dtype="U6") 839 el = x[1] 840 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 841 new = pickle.loads(pickle.dumps(el, protocol=proto)) 842 assert_equal(new, el) 843 844 def test_arange_non_native_dtype(self): 845 # Ticket #616 846 for T in ('>f4', '<f4'): 847 dt = np.dtype(T) 848 assert_equal(np.arange(0, dtype=dt).dtype, dt) 849 assert_equal(np.arange(0.5, dtype=dt).dtype, dt) 850 assert_equal(np.arange(5, dtype=dt).dtype, dt) 851 852 def test_bool_flat_indexing_invalid_nr_elements(self): 853 s = np.ones(10, dtype=float) 854 x = np.array((15,), dtype=float) 855 856 def ia(x, s, v): 857 x[(s > 0)] = v 858 859 assert_raises(IndexError, ia, x, s, np.zeros(9, dtype=float)) 860 assert_raises(IndexError, ia, x, s, np.zeros(11, dtype=float)) 861 862 # Old special case (different code path): 863 assert_raises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float)) 864 assert_raises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float)) 865 866 def test_mem_scalar_indexing(self): 867 # Ticket #603 868 x = np.array([0], dtype=float) 869 index = np.array(0, dtype=np.int32) 870 x[index] 871 872 def test_binary_repr_0_width(self): 873 assert_equal(np.binary_repr(0, width=3), '000') 874 875 def test_fromstring(self): 876 assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"), 877 [12, 9, 9]) 878 879 def test_searchsorted_variable_length(self): 880 x = np.array(['a', 'aa', 'b']) 881 y = np.array(['d', 'e']) 882 assert_equal(x.searchsorted(y), [3, 3]) 883 884 def test_string_argsort_with_zeros(self): 885 # Check argsort for strings containing zeros. 886 x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2") 887 assert_array_equal(x.argsort(kind='m'), np.array([1, 0])) 888 assert_array_equal(x.argsort(kind='q'), np.array([1, 0])) 889 890 def test_string_sort_with_zeros(self): 891 # Check sort for strings containing zeros. 892 x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2") 893 y = np.frombuffer(b"\x00\x01\x00\x02", dtype="|S2") 894 assert_array_equal(np.sort(x, kind="q"), y) 895 896 def test_copy_detection_zero_dim(self): 897 # Ticket #658 898 np.indices((0, 3, 4)).T.reshape(-1, 3) 899 900 def test_flat_byteorder(self): 901 # Ticket #657 902 x = np.arange(10) 903 assert_array_equal(x.astype('>i4'), x.astype('<i4').flat[:]) 904 assert_array_equal(x.astype('>i4').flat[:], x.astype('<i4')) 905 906 def test_sign_bit(self): 907 x = np.array([0, -0.0, 0]) 908 assert_equal(str(np.abs(x)), '[0. 0. 0.]') 909 910 def test_flat_index_byteswap(self): 911 for dt in (np.dtype('<i4'), np.dtype('>i4')): 912 x = np.array([-1, 0, 1], dtype=dt) 913 assert_equal(x.flat[0].dtype, x[0].dtype) 914 915 def test_copy_detection_corner_case(self): 916 # Ticket #658 917 np.indices((0, 3, 4)).T.reshape(-1, 3) 918 919 # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. 920 # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous, 921 # 0-sized reshape itself is tested elsewhere. 922 @pytest.mark.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max, 923 reason="Using relaxed stride checking") 924 def test_copy_detection_corner_case2(self): 925 # Ticket #771: strides are not set correctly when reshaping 0-sized 926 # arrays 927 b = np.indices((0, 3, 4)).T.reshape(-1, 3) 928 assert_equal(b.strides, (3 * b.itemsize, b.itemsize)) 929 930 def test_object_array_refcounting(self): 931 # Ticket #633 932 if not hasattr(sys, 'getrefcount'): 933 return 934 935 # NB. this is probably CPython-specific 936 937 cnt = sys.getrefcount 938 939 a = object() 940 b = object() 941 c = object() 942 943 cnt0_a = cnt(a) 944 cnt0_b = cnt(b) 945 cnt0_c = cnt(c) 946 947 # -- 0d -> 1-d broadcast slice assignment 948 949 arr = np.zeros(5, dtype=np.object_) 950 951 arr[:] = a 952 assert_equal(cnt(a), cnt0_a + 5) 953 954 arr[:] = b 955 assert_equal(cnt(a), cnt0_a) 956 assert_equal(cnt(b), cnt0_b + 5) 957 958 arr[:2] = c 959 assert_equal(cnt(b), cnt0_b + 3) 960 assert_equal(cnt(c), cnt0_c + 2) 961 962 del arr 963 964 # -- 1-d -> 2-d broadcast slice assignment 965 966 arr = np.zeros((5, 2), dtype=np.object_) 967 arr0 = np.zeros(2, dtype=np.object_) 968 969 arr0[0] = a 970 assert_(cnt(a) == cnt0_a + 1) 971 arr0[1] = b 972 assert_(cnt(b) == cnt0_b + 1) 973 974 arr[:, :] = arr0 975 assert_(cnt(a) == cnt0_a + 6) 976 assert_(cnt(b) == cnt0_b + 6) 977 978 arr[:, 0] = None 979 assert_(cnt(a) == cnt0_a + 1) 980 981 del arr, arr0 982 983 # -- 2-d copying + flattening 984 985 arr = np.zeros((5, 2), dtype=np.object_) 986 987 arr[:, 0] = a 988 arr[:, 1] = b 989 assert_(cnt(a) == cnt0_a + 5) 990 assert_(cnt(b) == cnt0_b + 5) 991 992 arr2 = arr.copy() 993 assert_(cnt(a) == cnt0_a + 10) 994 assert_(cnt(b) == cnt0_b + 10) 995 996 arr2 = arr[:, 0].copy() 997 assert_(cnt(a) == cnt0_a + 10) 998 assert_(cnt(b) == cnt0_b + 5) 999 1000 arr2 = arr.flatten() 1001 assert_(cnt(a) == cnt0_a + 10) 1002 assert_(cnt(b) == cnt0_b + 10) 1003 1004 del arr, arr2 1005 1006 # -- concatenate, repeat, take, choose 1007 1008 arr1 = np.zeros((5, 1), dtype=np.object_) 1009 arr2 = np.zeros((5, 1), dtype=np.object_) 1010 1011 arr1[...] = a 1012 arr2[...] = b 1013 assert_(cnt(a) == cnt0_a + 5) 1014 assert_(cnt(b) == cnt0_b + 5) 1015 1016 tmp = np.concatenate((arr1, arr2)) 1017 assert_(cnt(a) == cnt0_a + 5 + 5) 1018 assert_(cnt(b) == cnt0_b + 5 + 5) 1019 1020 tmp = arr1.repeat(3, axis=0) 1021 assert_(cnt(a) == cnt0_a + 5 + 3*5) 1022 1023 tmp = arr1.take([1, 2, 3], axis=0) 1024 assert_(cnt(a) == cnt0_a + 5 + 3) 1025 1026 x = np.array([[0], [1], [0], [1], [1]], int) 1027 tmp = x.choose(arr1, arr2) 1028 assert_(cnt(a) == cnt0_a + 5 + 2) 1029 assert_(cnt(b) == cnt0_b + 5 + 3) 1030 1031 del tmp # Avoid pyflakes unused variable warning 1032 1033 def test_mem_custom_float_to_array(self): 1034 # Ticket 702 1035 class MyFloat: 1036 def __float__(self): 1037 return 1.0 1038 1039 tmp = np.atleast_1d([MyFloat()]) 1040 tmp.astype(float) # Should succeed 1041 1042 def test_object_array_refcount_self_assign(self): 1043 # Ticket #711 1044 class VictimObject: 1045 deleted = False 1046 1047 def __del__(self): 1048 self.deleted = True 1049 1050 d = VictimObject() 1051 arr = np.zeros(5, dtype=np.object_) 1052 arr[:] = d 1053 del d 1054 arr[:] = arr # refcount of 'd' might hit zero here 1055 assert_(not arr[0].deleted) 1056 arr[:] = arr # trying to induce a segfault by doing it again... 1057 assert_(not arr[0].deleted) 1058 1059 def test_mem_fromiter_invalid_dtype_string(self): 1060 x = [1, 2, 3] 1061 assert_raises(ValueError, 1062 np.fromiter, [xi for xi in x], dtype='S') 1063 1064 def test_reduce_big_object_array(self): 1065 # Ticket #713 1066 oldsize = np.setbufsize(10*16) 1067 a = np.array([None]*161, object) 1068 assert_(not np.any(a)) 1069 np.setbufsize(oldsize) 1070 1071 def test_mem_0d_array_index(self): 1072 # Ticket #714 1073 np.zeros(10)[np.array(0)] 1074 1075 def test_nonnative_endian_fill(self): 1076 # Non-native endian arrays were incorrectly filled with scalars 1077 # before r5034. 1078 if sys.byteorder == 'little': 1079 dtype = np.dtype('>i4') 1080 else: 1081 dtype = np.dtype('<i4') 1082 x = np.empty([1], dtype=dtype) 1083 x.fill(1) 1084 assert_equal(x, np.array([1], dtype=dtype)) 1085 1086 def test_dot_alignment_sse2(self): 1087 # Test for ticket #551, changeset r5140 1088 x = np.zeros((30, 40)) 1089 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 1090 y = pickle.loads(pickle.dumps(x, protocol=proto)) 1091 # y is now typically not aligned on a 8-byte boundary 1092 z = np.ones((1, y.shape[0])) 1093 # This shouldn't cause a segmentation fault: 1094 np.dot(z, y) 1095 1096 def test_astype_copy(self): 1097 # Ticket #788, changeset r5155 1098 # The test data file was generated by scipy.io.savemat. 1099 # The dtype is float64, but the isbuiltin attribute is 0. 1100 data_dir = path.join(path.dirname(__file__), 'data') 1101 filename = path.join(data_dir, "astype_copy.pkl") 1102 with open(filename, 'rb') as f: 1103 xp = pickle.load(f, encoding='latin1') 1104 xpd = xp.astype(np.float64) 1105 assert_((xp.__array_interface__['data'][0] != 1106 xpd.__array_interface__['data'][0])) 1107 1108 def test_compress_small_type(self): 1109 # Ticket #789, changeset 5217. 1110 # compress with out argument segfaulted if cannot cast safely 1111 import numpy as np 1112 a = np.array([[1, 2], [3, 4]]) 1113 b = np.zeros((2, 1), dtype=np.single) 1114 try: 1115 a.compress([True, False], axis=1, out=b) 1116 raise AssertionError("compress with an out which cannot be " 1117 "safely casted should not return " 1118 "successfully") 1119 except TypeError: 1120 pass 1121 1122 def test_attributes(self): 1123 # Ticket #791 1124 class TestArray(np.ndarray): 1125 def __new__(cls, data, info): 1126 result = np.array(data) 1127 result = result.view(cls) 1128 result.info = info 1129 return result 1130 1131 def __array_finalize__(self, obj): 1132 self.info = getattr(obj, 'info', '') 1133 1134 dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba') 1135 assert_(dat.info == 'jubba') 1136 dat.resize((4, 2)) 1137 assert_(dat.info == 'jubba') 1138 dat.sort() 1139 assert_(dat.info == 'jubba') 1140 dat.fill(2) 1141 assert_(dat.info == 'jubba') 1142 dat.put([2, 3, 4], [6, 3, 4]) 1143 assert_(dat.info == 'jubba') 1144 dat.setfield(4, np.int32, 0) 1145 assert_(dat.info == 'jubba') 1146 dat.setflags() 1147 assert_(dat.info == 'jubba') 1148 assert_(dat.all(1).info == 'jubba') 1149 assert_(dat.any(1).info == 'jubba') 1150 assert_(dat.argmax(1).info == 'jubba') 1151 assert_(dat.argmin(1).info == 'jubba') 1152 assert_(dat.argsort(1).info == 'jubba') 1153 assert_(dat.astype(TestArray).info == 'jubba') 1154 assert_(dat.byteswap().info == 'jubba') 1155 assert_(dat.clip(2, 7).info == 'jubba') 1156 assert_(dat.compress([0, 1, 1]).info == 'jubba') 1157 assert_(dat.conj().info == 'jubba') 1158 assert_(dat.conjugate().info == 'jubba') 1159 assert_(dat.copy().info == 'jubba') 1160 dat2 = TestArray([2, 3, 1, 0], 'jubba') 1161 choices = [[0, 1, 2, 3], [10, 11, 12, 13], 1162 [20, 21, 22, 23], [30, 31, 32, 33]] 1163 assert_(dat2.choose(choices).info == 'jubba') 1164 assert_(dat.cumprod(1).info == 'jubba') 1165 assert_(dat.cumsum(1).info == 'jubba') 1166 assert_(dat.diagonal().info == 'jubba') 1167 assert_(dat.flatten().info == 'jubba') 1168 assert_(dat.getfield(np.int32, 0).info == 'jubba') 1169 assert_(dat.imag.info == 'jubba') 1170 assert_(dat.max(1).info == 'jubba') 1171 assert_(dat.mean(1).info == 'jubba') 1172 assert_(dat.min(1).info == 'jubba') 1173 assert_(dat.newbyteorder().info == 'jubba') 1174 assert_(dat.prod(1).info == 'jubba') 1175 assert_(dat.ptp(1).info == 'jubba') 1176 assert_(dat.ravel().info == 'jubba') 1177 assert_(dat.real.info == 'jubba') 1178 assert_(dat.repeat(2).info == 'jubba') 1179 assert_(dat.reshape((2, 4)).info == 'jubba') 1180 assert_(dat.round().info == 'jubba') 1181 assert_(dat.squeeze().info == 'jubba') 1182 assert_(dat.std(1).info == 'jubba') 1183 assert_(dat.sum(1).info == 'jubba') 1184 assert_(dat.swapaxes(0, 1).info == 'jubba') 1185 assert_(dat.take([2, 3, 5]).info == 'jubba') 1186 assert_(dat.transpose().info == 'jubba') 1187 assert_(dat.T.info == 'jubba') 1188 assert_(dat.var(1).info == 'jubba') 1189 assert_(dat.view(TestArray).info == 'jubba') 1190 # These methods do not preserve subclasses 1191 assert_(type(dat.nonzero()[0]) is np.ndarray) 1192 assert_(type(dat.nonzero()[1]) is np.ndarray) 1193 1194 def test_recarray_tolist(self): 1195 # Ticket #793, changeset r5215 1196 # Comparisons fail for NaN, so we can't use random memory 1197 # for the test. 1198 buf = np.zeros(40, dtype=np.int8) 1199 a = np.recarray(2, formats="i4,f8,f8", names="id,x,y", buf=buf) 1200 b = a.tolist() 1201 assert_( a[0].tolist() == b[0]) 1202 assert_( a[1].tolist() == b[1]) 1203 1204 def test_nonscalar_item_method(self): 1205 # Make sure that .item() fails graciously when it should 1206 a = np.arange(5) 1207 assert_raises(ValueError, a.item) 1208 1209 def test_char_array_creation(self): 1210 a = np.array('123', dtype='c') 1211 b = np.array([b'1', b'2', b'3']) 1212 assert_equal(a, b) 1213 1214 def test_unaligned_unicode_access(self): 1215 # Ticket #825 1216 for i in range(1, 9): 1217 msg = 'unicode offset: %d chars' % i 1218 t = np.dtype([('a', 'S%d' % i), ('b', 'U2')]) 1219 x = np.array([(b'a', u'b')], dtype=t) 1220 assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg) 1221 1222 def test_sign_for_complex_nan(self): 1223 # Ticket 794. 1224 with np.errstate(invalid='ignore'): 1225 C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan]) 1226 have = np.sign(C) 1227 want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan]) 1228 assert_equal(have, want) 1229 1230 def test_for_equal_names(self): 1231 # Ticket #674 1232 dt = np.dtype([('foo', float), ('bar', float)]) 1233 a = np.zeros(10, dt) 1234 b = list(a.dtype.names) 1235 b[0] = "notfoo" 1236 a.dtype.names = b 1237 assert_(a.dtype.names[0] == "notfoo") 1238 assert_(a.dtype.names[1] == "bar") 1239 1240 def test_for_object_scalar_creation(self): 1241 # Ticket #816 1242 a = np.object_() 1243 b = np.object_(3) 1244 b2 = np.object_(3.0) 1245 c = np.object_([4, 5]) 1246 d = np.object_([None, {}, []]) 1247 assert_(a is None) 1248 assert_(type(b) is int) 1249 assert_(type(b2) is float) 1250 assert_(type(c) is np.ndarray) 1251 assert_(c.dtype == object) 1252 assert_(d.dtype == object) 1253 1254 def test_array_resize_method_system_error(self): 1255 # Ticket #840 - order should be an invalid keyword. 1256 x = np.array([[0, 1], [2, 3]]) 1257 assert_raises(TypeError, x.resize, (2, 2), order='C') 1258 1259 def test_for_zero_length_in_choose(self): 1260 "Ticket #882" 1261 a = np.array(1) 1262 assert_raises(ValueError, lambda x: x.choose([]), a) 1263 1264 def test_array_ndmin_overflow(self): 1265 "Ticket #947." 1266 assert_raises(ValueError, lambda: np.array([1], ndmin=33)) 1267 1268 def test_void_scalar_with_titles(self): 1269 # No ticket 1270 data = [('john', 4), ('mary', 5)] 1271 dtype1 = [(('source:yy', 'name'), 'O'), (('source:xx', 'id'), int)] 1272 arr = np.array(data, dtype=dtype1) 1273 assert_(arr[0][0] == 'john') 1274 assert_(arr[0][1] == 4) 1275 1276 def test_void_scalar_constructor(self): 1277 #Issue #1550 1278 1279 #Create test string data, construct void scalar from data and assert 1280 #that void scalar contains original data. 1281 test_string = np.array("test") 1282 test_string_void_scalar = np.core.multiarray.scalar( 1283 np.dtype(("V", test_string.dtype.itemsize)), test_string.tobytes()) 1284 1285 assert_(test_string_void_scalar.view(test_string.dtype) == test_string) 1286 1287 #Create record scalar, construct from data and assert that 1288 #reconstructed scalar is correct. 1289 test_record = np.ones((), "i,i") 1290 test_record_void_scalar = np.core.multiarray.scalar( 1291 test_record.dtype, test_record.tobytes()) 1292 1293 assert_(test_record_void_scalar == test_record) 1294 1295 # Test pickle and unpickle of void and record scalars 1296 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 1297 assert_(pickle.loads( 1298 pickle.dumps(test_string, protocol=proto)) == test_string) 1299 assert_(pickle.loads( 1300 pickle.dumps(test_record, protocol=proto)) == test_record) 1301 1302 @_no_tracing 1303 def test_blasdot_uninitialized_memory(self): 1304 # Ticket #950 1305 for m in [0, 1, 2]: 1306 for n in [0, 1, 2]: 1307 for k in range(3): 1308 # Try to ensure that x->data contains non-zero floats 1309 x = np.array([123456789e199], dtype=np.float64) 1310 if IS_PYPY: 1311 x.resize((m, 0), refcheck=False) 1312 else: 1313 x.resize((m, 0)) 1314 y = np.array([123456789e199], dtype=np.float64) 1315 if IS_PYPY: 1316 y.resize((0, n), refcheck=False) 1317 else: 1318 y.resize((0, n)) 1319 1320 # `dot` should just return zero (m, n) matrix 1321 z = np.dot(x, y) 1322 assert_(np.all(z == 0)) 1323 assert_(z.shape == (m, n)) 1324 1325 def test_zeros(self): 1326 # Regression test for #1061. 1327 # Set a size which cannot fit into a 64 bits signed integer 1328 sz = 2 ** 64 1329 with assert_raises_regex(ValueError, 1330 'Maximum allowed dimension exceeded'): 1331 np.empty(sz) 1332 1333 def test_huge_arange(self): 1334 # Regression test for #1062. 1335 # Set a size which cannot fit into a 64 bits signed integer 1336 sz = 2 ** 64 1337 with assert_raises_regex(ValueError, 1338 'Maximum allowed size exceeded'): 1339 np.arange(sz) 1340 assert_(np.size == sz) 1341 1342 def test_fromiter_bytes(self): 1343 # Ticket #1058 1344 a = np.fromiter(list(range(10)), dtype='b') 1345 b = np.fromiter(list(range(10)), dtype='B') 1346 assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) 1347 assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) 1348 1349 def test_array_from_sequence_scalar_array(self): 1350 # Ticket #1078: segfaults when creating an array with a sequence of 1351 # 0d arrays. 1352 a = np.array((np.ones(2), np.array(2)), dtype=object) 1353 assert_equal(a.shape, (2,)) 1354 assert_equal(a.dtype, np.dtype(object)) 1355 assert_equal(a[0], np.ones(2)) 1356 assert_equal(a[1], np.array(2)) 1357 1358 a = np.array(((1,), np.array(1)), dtype=object) 1359 assert_equal(a.shape, (2,)) 1360 assert_equal(a.dtype, np.dtype(object)) 1361 assert_equal(a[0], (1,)) 1362 assert_equal(a[1], np.array(1)) 1363 1364 def test_array_from_sequence_scalar_array2(self): 1365 # Ticket #1081: weird array with strange input... 1366 t = np.array([np.array([]), np.array(0, object)], dtype=object) 1367 assert_equal(t.shape, (2,)) 1368 assert_equal(t.dtype, np.dtype(object)) 1369 1370 def test_array_too_big(self): 1371 # Ticket #1080. 1372 assert_raises(ValueError, np.zeros, [975]*7, np.int8) 1373 assert_raises(ValueError, np.zeros, [26244]*5, np.int8) 1374 1375 def test_dtype_keyerrors_(self): 1376 # Ticket #1106. 1377 dt = np.dtype([('f1', np.uint)]) 1378 assert_raises(KeyError, dt.__getitem__, "f2") 1379 assert_raises(IndexError, dt.__getitem__, 1) 1380 assert_raises(TypeError, dt.__getitem__, 0.0) 1381 1382 def test_lexsort_buffer_length(self): 1383 # Ticket #1217, don't segfault. 1384 a = np.ones(100, dtype=np.int8) 1385 b = np.ones(100, dtype=np.int32) 1386 i = np.lexsort((a[::-1], b)) 1387 assert_equal(i, np.arange(100, dtype=int)) 1388 1389 def test_object_array_to_fixed_string(self): 1390 # Ticket #1235. 1391 a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_) 1392 b = np.array(a, dtype=(np.str_, 8)) 1393 assert_equal(a, b) 1394 c = np.array(a, dtype=(np.str_, 5)) 1395 assert_equal(c, np.array(['abcde', 'ijklm'])) 1396 d = np.array(a, dtype=(np.str_, 12)) 1397 assert_equal(a, d) 1398 e = np.empty((2, ), dtype=(np.str_, 8)) 1399 e[:] = a[:] 1400 assert_equal(a, e) 1401 1402 def test_unicode_to_string_cast(self): 1403 # Ticket #1240. 1404 a = np.array([[u'abc', u'\u03a3'], 1405 [u'asdf', u'erw']], 1406 dtype='U') 1407 assert_raises(UnicodeEncodeError, np.array, a, 'S4') 1408 1409 def test_unicode_to_string_cast_error(self): 1410 # gh-15790 1411 a = np.array([u'\x80'] * 129, dtype='U3') 1412 assert_raises(UnicodeEncodeError, np.array, a, 'S') 1413 b = a.reshape(3, 43)[:-1, :-1] 1414 assert_raises(UnicodeEncodeError, np.array, b, 'S') 1415 1416 def test_mixed_string_unicode_array_creation(self): 1417 a = np.array(['1234', u'123']) 1418 assert_(a.itemsize == 16) 1419 a = np.array([u'123', '1234']) 1420 assert_(a.itemsize == 16) 1421 a = np.array(['1234', u'123', '12345']) 1422 assert_(a.itemsize == 20) 1423 a = np.array([u'123', '1234', u'12345']) 1424 assert_(a.itemsize == 20) 1425 a = np.array([u'123', '1234', u'1234']) 1426 assert_(a.itemsize == 16) 1427 1428 def test_misaligned_objects_segfault(self): 1429 # Ticket #1198 and #1267 1430 a1 = np.zeros((10,), dtype='O,c') 1431 a2 = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 'S10') 1432 a1['f0'] = a2 1433 repr(a1) 1434 np.argmax(a1['f0']) 1435 a1['f0'][1] = "FOO" 1436 a1['f0'] = "FOO" 1437 np.array(a1['f0'], dtype='S') 1438 np.nonzero(a1['f0']) 1439 a1.sort() 1440 copy.deepcopy(a1) 1441 1442 def test_misaligned_scalars_segfault(self): 1443 # Ticket #1267 1444 s1 = np.array(('a', 'Foo'), dtype='c,O') 1445 s2 = np.array(('b', 'Bar'), dtype='c,O') 1446 s1['f1'] = s2['f1'] 1447 s1['f1'] = 'Baz' 1448 1449 def test_misaligned_dot_product_objects(self): 1450 # Ticket #1267 1451 # This didn't require a fix, but it's worth testing anyway, because 1452 # it may fail if .dot stops enforcing the arrays to be BEHAVED 1453 a = np.array([[(1, 'a'), (0, 'a')], [(0, 'a'), (1, 'a')]], dtype='O,c') 1454 b = np.array([[(4, 'a'), (1, 'a')], [(2, 'a'), (2, 'a')]], dtype='O,c') 1455 np.dot(a['f0'], b['f0']) 1456 1457 def test_byteswap_complex_scalar(self): 1458 # Ticket #1259 and gh-441 1459 for dtype in [np.dtype('<'+t) for t in np.typecodes['Complex']]: 1460 z = np.array([2.2-1.1j], dtype) 1461 x = z[0] # always native-endian 1462 y = x.byteswap() 1463 if x.dtype.byteorder == z.dtype.byteorder: 1464 # little-endian machine 1465 assert_equal(x, np.frombuffer(y.tobytes(), dtype=dtype.newbyteorder())) 1466 else: 1467 # big-endian machine 1468 assert_equal(x, np.frombuffer(y.tobytes(), dtype=dtype)) 1469 # double check real and imaginary parts: 1470 assert_equal(x.real, y.real.byteswap()) 1471 assert_equal(x.imag, y.imag.byteswap()) 1472 1473 def test_structured_arrays_with_objects1(self): 1474 # Ticket #1299 1475 stra = 'aaaa' 1476 strb = 'bbbb' 1477 x = np.array([[(0, stra), (1, strb)]], 'i8,O') 1478 x[x.nonzero()] = x.ravel()[:1] 1479 assert_(x[0, 1] == x[0, 0]) 1480 1481 @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") 1482 def test_structured_arrays_with_objects2(self): 1483 # Ticket #1299 second test 1484 stra = 'aaaa' 1485 strb = 'bbbb' 1486 numb = sys.getrefcount(strb) 1487 numa = sys.getrefcount(stra) 1488 x = np.array([[(0, stra), (1, strb)]], 'i8,O') 1489 x[x.nonzero()] = x.ravel()[:1] 1490 assert_(sys.getrefcount(strb) == numb) 1491 assert_(sys.getrefcount(stra) == numa + 2) 1492 1493 def test_duplicate_title_and_name(self): 1494 # Ticket #1254 1495 dtspec = [(('a', 'a'), 'i'), ('b', 'i')] 1496 assert_raises(ValueError, np.dtype, dtspec) 1497 1498 def test_signed_integer_division_overflow(self): 1499 # Ticket #1317. 1500 def test_type(t): 1501 min = np.array([np.iinfo(t).min]) 1502 min //= -1 1503 1504 with np.errstate(divide="ignore"): 1505 for t in (np.int8, np.int16, np.int32, np.int64, int): 1506 test_type(t) 1507 1508 def test_buffer_hashlib(self): 1509 from hashlib import sha256 1510 1511 x = np.array([1, 2, 3], dtype=np.dtype('<i4')) 1512 assert_equal(sha256(x).hexdigest(), '4636993d3e1da4e9d6b8f87b79e8f7c6d018580d52661950eabc3845c5897a4d') 1513 1514 def test_0d_string_scalar(self): 1515 # Bug #1436; the following should succeed 1516 np.asarray('x', '>c') 1517 1518 def test_log1p_compiler_shenanigans(self): 1519 # Check if log1p is behaving on 32 bit intel systems. 1520 assert_(np.isfinite(np.log1p(np.exp2(-53)))) 1521 1522 def test_fromiter_comparison(self): 1523 a = np.fromiter(list(range(10)), dtype='b') 1524 b = np.fromiter(list(range(10)), dtype='B') 1525 assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) 1526 assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) 1527 1528 def test_fromstring_crash(self): 1529 # Ticket #1345: the following should not cause a crash 1530 with assert_warns(DeprecationWarning): 1531 np.fromstring(b'aa, aa, 1.0', sep=',') 1532 1533 def test_ticket_1539(self): 1534 dtypes = [x for x in np.typeDict.values() 1535 if (issubclass(x, np.number) 1536 and not issubclass(x, np.timedelta64))] 1537 a = np.array([], np.bool_) # not x[0] because it is unordered 1538 failures = [] 1539 1540 for x in dtypes: 1541 b = a.astype(x) 1542 for y in dtypes: 1543 c = a.astype(y) 1544 try: 1545 np.dot(b, c) 1546 except TypeError: 1547 failures.append((x, y)) 1548 if failures: 1549 raise AssertionError("Failures: %r" % failures) 1550 1551 def test_ticket_1538(self): 1552 x = np.finfo(np.float32) 1553 for name in 'eps epsneg max min resolution tiny'.split(): 1554 assert_equal(type(getattr(x, name)), np.float32, 1555 err_msg=name) 1556 1557 def test_ticket_1434(self): 1558 # Check that the out= argument in var and std has an effect 1559 data = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9))) 1560 out = np.zeros((3,)) 1561 1562 ret = data.var(axis=1, out=out) 1563 assert_(ret is out) 1564 assert_array_equal(ret, data.var(axis=1)) 1565 1566 ret = data.std(axis=1, out=out) 1567 assert_(ret is out) 1568 assert_array_equal(ret, data.std(axis=1)) 1569 1570 def test_complex_nan_maximum(self): 1571 cnan = complex(0, np.nan) 1572 assert_equal(np.maximum(1, cnan), cnan) 1573 1574 def test_subclass_int_tuple_assignment(self): 1575 # ticket #1563 1576 class Subclass(np.ndarray): 1577 def __new__(cls, i): 1578 return np.ones((i,)).view(cls) 1579 1580 x = Subclass(5) 1581 x[(0,)] = 2 # shouldn't raise an exception 1582 assert_equal(x[0], 2) 1583 1584 def test_ufunc_no_unnecessary_views(self): 1585 # ticket #1548 1586 class Subclass(np.ndarray): 1587 pass 1588 x = np.array([1, 2, 3]).view(Subclass) 1589 y = np.add(x, x, x) 1590 assert_equal(id(x), id(y)) 1591 1592 @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") 1593 def test_take_refcount(self): 1594 # ticket #939 1595 a = np.arange(16, dtype=float) 1596 a.shape = (4, 4) 1597 lut = np.ones((5 + 3, 4), float) 1598 rgba = np.empty(shape=a.shape + (4,), dtype=lut.dtype) 1599 c1 = sys.getrefcount(rgba) 1600 try: 1601 lut.take(a, axis=0, mode='clip', out=rgba) 1602 except TypeError: 1603 pass 1604 c2 = sys.getrefcount(rgba) 1605 assert_equal(c1, c2) 1606 1607 def test_fromfile_tofile_seeks(self): 1608 # On Python 3, tofile/fromfile used to get (#1610) the Python 1609 # file handle out of sync 1610 f0 = tempfile.NamedTemporaryFile() 1611 f = f0.file 1612 f.write(np.arange(255, dtype='u1').tobytes()) 1613 1614 f.seek(20) 1615 ret = np.fromfile(f, count=4, dtype='u1') 1616 assert_equal(ret, np.array([20, 21, 22, 23], dtype='u1')) 1617 assert_equal(f.tell(), 24) 1618 1619 f.seek(40) 1620 np.array([1, 2, 3], dtype='u1').tofile(f) 1621 assert_equal(f.tell(), 43) 1622 1623 f.seek(40) 1624 data = f.read(3) 1625 assert_equal(data, b"\x01\x02\x03") 1626 1627 f.seek(80) 1628 f.read(4) 1629 data = np.fromfile(f, dtype='u1', count=4) 1630 assert_equal(data, np.array([84, 85, 86, 87], dtype='u1')) 1631 1632 f.close() 1633 1634 def test_complex_scalar_warning(self): 1635 for tp in [np.csingle, np.cdouble, np.clongdouble]: 1636 x = tp(1+2j) 1637 assert_warns(np.ComplexWarning, float, x) 1638 with suppress_warnings() as sup: 1639 sup.filter(np.ComplexWarning) 1640 assert_equal(float(x), float(x.real)) 1641 1642 def test_complex_scalar_complex_cast(self): 1643 for tp in [np.csingle, np.cdouble, np.clongdouble]: 1644 x = tp(1+2j) 1645 assert_equal(complex(x), 1+2j) 1646 1647 def test_complex_boolean_cast(self): 1648 # Ticket #2218 1649 for tp in [np.csingle, np.cdouble, np.clongdouble]: 1650 x = np.array([0, 0+0.5j, 0.5+0j], dtype=tp) 1651 assert_equal(x.astype(bool), np.array([0, 1, 1], dtype=bool)) 1652 assert_(np.any(x)) 1653 assert_(np.all(x[1:])) 1654 1655 def test_uint_int_conversion(self): 1656 x = 2**64 - 1 1657 assert_equal(int(np.uint64(x)), x) 1658 1659 def test_duplicate_field_names_assign(self): 1660 ra = np.fromiter(((i*3, i*2) for i in range(10)), dtype='i8,f8') 1661 ra.dtype.names = ('f1', 'f2') 1662 repr(ra) # should not cause a segmentation fault 1663 assert_raises(ValueError, setattr, ra.dtype, 'names', ('f1', 'f1')) 1664 1665 def test_eq_string_and_object_array(self): 1666 # From e-mail thread "__eq__ with str and object" (Keith Goodman) 1667 a1 = np.array(['a', 'b'], dtype=object) 1668 a2 = np.array(['a', 'c']) 1669 assert_array_equal(a1 == a2, [True, False]) 1670 assert_array_equal(a2 == a1, [True, False]) 1671 1672 def test_nonzero_byteswap(self): 1673 a = np.array([0x80000000, 0x00000080, 0], dtype=np.uint32) 1674 a.dtype = np.float32 1675 assert_equal(a.nonzero()[0], [1]) 1676 a = a.byteswap().newbyteorder() 1677 assert_equal(a.nonzero()[0], [1]) # [0] if nonzero() ignores swap 1678 1679 def test_find_common_type_boolean(self): 1680 # Ticket #1695 1681 assert_(np.find_common_type([], ['?', '?']) == '?') 1682 1683 def test_empty_mul(self): 1684 a = np.array([1.]) 1685 a[1:1] *= 2 1686 assert_equal(a, [1.]) 1687 1688 def test_array_side_effect(self): 1689 # The second use of itemsize was throwing an exception because in 1690 # ctors.c, discover_itemsize was calling PyObject_Length without 1691 # checking the return code. This failed to get the length of the 1692 # number 2, and the exception hung around until something checked 1693 # PyErr_Occurred() and returned an error. 1694 assert_equal(np.dtype('S10').itemsize, 10) 1695 np.array([['abc', 2], ['long ', '0123456789']], dtype=np.string_) 1696 assert_equal(np.dtype('S10').itemsize, 10) 1697 1698 def test_any_float(self): 1699 # all and any for floats 1700 a = np.array([0.1, 0.9]) 1701 assert_(np.any(a)) 1702 assert_(np.all(a)) 1703 1704 def test_large_float_sum(self): 1705 a = np.arange(10000, dtype='f') 1706 assert_equal(a.sum(dtype='d'), a.astype('d').sum()) 1707 1708 def test_ufunc_casting_out(self): 1709 a = np.array(1.0, dtype=np.float32) 1710 b = np.array(1.0, dtype=np.float64) 1711 c = np.array(1.0, dtype=np.float32) 1712 np.add(a, b, out=c) 1713 assert_equal(c, 2.0) 1714 1715 def test_array_scalar_contiguous(self): 1716 # Array scalars are both C and Fortran contiguous 1717 assert_(np.array(1.0).flags.c_contiguous) 1718 assert_(np.array(1.0).flags.f_contiguous) 1719 assert_(np.array(np.float32(1.0)).flags.c_contiguous) 1720 assert_(np.array(np.float32(1.0)).flags.f_contiguous) 1721 1722 def test_squeeze_contiguous(self): 1723 # Similar to GitHub issue #387 1724 a = np.zeros((1, 2)).squeeze() 1725 b = np.zeros((2, 2, 2), order='F')[:, :, ::2].squeeze() 1726 assert_(a.flags.c_contiguous) 1727 assert_(a.flags.f_contiguous) 1728 assert_(b.flags.f_contiguous) 1729 1730 def test_squeeze_axis_handling(self): 1731 # Issue #10779 1732 # Ensure proper handling of objects 1733 # that don't support axis specification 1734 # when squeezing 1735 1736 class OldSqueeze(np.ndarray): 1737 1738 def __new__(cls, 1739 input_array): 1740 obj = np.asarray(input_array).view(cls) 1741 return obj 1742 1743 # it is perfectly reasonable that prior 1744 # to numpy version 1.7.0 a subclass of ndarray 1745 # might have been created that did not expect 1746 # squeeze to have an axis argument 1747 # NOTE: this example is somewhat artificial; 1748 # it is designed to simulate an old API 1749 # expectation to guard against regression 1750 def squeeze(self): 1751 return super(OldSqueeze, self).squeeze() 1752 1753 oldsqueeze = OldSqueeze(np.array([[1],[2],[3]])) 1754 1755 # if no axis argument is specified the old API 1756 # expectation should give the correct result 1757 assert_equal(np.squeeze(oldsqueeze), 1758 np.array([1,2,3])) 1759 1760 # likewise, axis=None should work perfectly well 1761 # with the old API expectation 1762 assert_equal(np.squeeze(oldsqueeze, axis=None), 1763 np.array([1,2,3])) 1764 1765 # however, specification of any particular axis 1766 # should raise a TypeError in the context of the 1767 # old API specification, even when using a valid 1768 # axis specification like 1 for this array 1769 with assert_raises(TypeError): 1770 # this would silently succeed for array 1771 # subclasses / objects that did not support 1772 # squeeze axis argument handling before fixing 1773 # Issue #10779 1774 np.squeeze(oldsqueeze, axis=1) 1775 1776 # check for the same behavior when using an invalid 1777 # axis specification -- in this case axis=0 does not 1778 # have size 1, but the priority should be to raise 1779 # a TypeError for the axis argument and NOT a 1780 # ValueError for squeezing a non-empty dimension 1781 with assert_raises(TypeError): 1782 np.squeeze(oldsqueeze, axis=0) 1783 1784 # the new API knows how to handle the axis 1785 # argument and will return a ValueError if 1786 # attempting to squeeze an axis that is not 1787 # of length 1 1788 with assert_raises(ValueError): 1789 np.squeeze(np.array([[1],[2],[3]]), axis=0) 1790 1791 def test_reduce_contiguous(self): 1792 # GitHub issue #387 1793 a = np.add.reduce(np.zeros((2, 1, 2)), (0, 1)) 1794 b = np.add.reduce(np.zeros((2, 1, 2)), 1) 1795 assert_(a.flags.c_contiguous) 1796 assert_(a.flags.f_contiguous) 1797 assert_(b.flags.c_contiguous) 1798 1799 def test_object_array_self_reference(self): 1800 # Object arrays with references to themselves can cause problems 1801 a = np.array(0, dtype=object) 1802 a[()] = a 1803 assert_raises(RecursionError, int, a) 1804 assert_raises(RecursionError, float, a) 1805 a[()] = None 1806 1807 def test_object_array_circular_reference(self): 1808 # Test the same for a circular reference. 1809 a = np.array(0, dtype=object) 1810 b = np.array(0, dtype=object) 1811 a[()] = b 1812 b[()] = a 1813 assert_raises(RecursionError, int, a) 1814 # NumPy has no tp_traverse currently, so circular references 1815 # cannot be detected. So resolve it: 1816 a[()] = None 1817 1818 # This was causing a to become like the above 1819 a = np.array(0, dtype=object) 1820 a[...] += 1 1821 assert_equal(a, 1) 1822 1823 def test_object_array_nested(self): 1824 # but is fine with a reference to a different array 1825 a = np.array(0, dtype=object) 1826 b = np.array(0, dtype=object) 1827 a[()] = b 1828 assert_equal(int(a), int(0)) 1829 assert_equal(float(a), float(0)) 1830 1831 def test_object_array_self_copy(self): 1832 # An object array being copied into itself DECREF'ed before INCREF'ing 1833 # causing segmentation faults (gh-3787) 1834 a = np.array(object(), dtype=object) 1835 np.copyto(a, a) 1836 if HAS_REFCOUNT: 1837 assert_(sys.getrefcount(a[()]) == 2) 1838 a[()].__class__ # will segfault if object was deleted 1839 1840 def test_zerosize_accumulate(self): 1841 "Ticket #1733" 1842 x = np.array([[42, 0]], dtype=np.uint32) 1843 assert_equal(np.add.accumulate(x[:-1, 0]), []) 1844 1845 def test_objectarray_setfield(self): 1846 # Setfield should not overwrite Object fields with non-Object data 1847 x = np.array([1, 2, 3], dtype=object) 1848 assert_raises(TypeError, x.setfield, 4, np.int32, 0) 1849 1850 def test_setting_rank0_string(self): 1851 "Ticket #1736" 1852 s1 = b"hello1" 1853 s2 = b"hello2" 1854 a = np.zeros((), dtype="S10") 1855 a[()] = s1 1856 assert_equal(a, np.array(s1)) 1857 a[()] = np.array(s2) 1858 assert_equal(a, np.array(s2)) 1859 1860 a = np.zeros((), dtype='f4') 1861 a[()] = 3 1862 assert_equal(a, np.array(3)) 1863 a[()] = np.array(4) 1864 assert_equal(a, np.array(4)) 1865 1866 def test_string_astype(self): 1867 "Ticket #1748" 1868 s1 = b'black' 1869 s2 = b'white' 1870 s3 = b'other' 1871 a = np.array([[s1], [s2], [s3]]) 1872 assert_equal(a.dtype, np.dtype('S5')) 1873 b = a.astype(np.dtype('S0')) 1874 assert_equal(b.dtype, np.dtype('S5')) 1875 1876 def test_ticket_1756(self): 1877 # Ticket #1756 1878 s = b'0123456789abcdef' 1879 a = np.array([s]*5) 1880 for i in range(1, 17): 1881 a1 = np.array(a, "|S%d" % i) 1882 a2 = np.array([s[:i]]*5) 1883 assert_equal(a1, a2) 1884 1885 def test_fields_strides(self): 1886 "gh-2355" 1887 r = np.frombuffer(b'abcdefghijklmnop'*4*3, dtype='i4,(2,3)u2') 1888 assert_equal(r[0:3:2]['f1'], r['f1'][0:3:2]) 1889 assert_equal(r[0:3:2]['f1'][0], r[0:3:2][0]['f1']) 1890 assert_equal(r[0:3:2]['f1'][0][()], r[0:3:2][0]['f1'][()]) 1891 assert_equal(r[0:3:2]['f1'][0].strides, r[0:3:2][0]['f1'].strides) 1892 1893 def test_alignment_update(self): 1894 # Check that alignment flag is updated on stride setting 1895 a = np.arange(10) 1896 assert_(a.flags.aligned) 1897 a.strides = 3 1898 assert_(not a.flags.aligned) 1899 1900 def test_ticket_1770(self): 1901 "Should not segfault on python 3k" 1902 import numpy as np 1903 try: 1904 a = np.zeros((1,), dtype=[('f1', 'f')]) 1905 a['f1'] = 1 1906 a['f2'] = 1 1907 except ValueError: 1908 pass 1909 except Exception: 1910 raise AssertionError 1911 1912 def test_ticket_1608(self): 1913 "x.flat shouldn't modify data" 1914 x = np.array([[1, 2], [3, 4]]).T 1915 np.array(x.flat) 1916 assert_equal(x, [[1, 3], [2, 4]]) 1917 1918 def test_pickle_string_overwrite(self): 1919 import re 1920 1921 data = np.array([1], dtype='b') 1922 blob = pickle.dumps(data, protocol=1) 1923 data = pickle.loads(blob) 1924 1925 # Check that loads does not clobber interned strings 1926 s = re.sub("a(.)", "\x01\\1", "a_") 1927 assert_equal(s[0], "\x01") 1928 data[0] = 0xbb 1929 s = re.sub("a(.)", "\x01\\1", "a_") 1930 assert_equal(s[0], "\x01") 1931 1932 def test_pickle_bytes_overwrite(self): 1933 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 1934 data = np.array([1], dtype='b') 1935 data = pickle.loads(pickle.dumps(data, protocol=proto)) 1936 data[0] = 0xdd 1937 bytestring = "\x01 ".encode('ascii') 1938 assert_equal(bytestring[0:1], '\x01'.encode('ascii')) 1939 1940 def test_pickle_py2_array_latin1_hack(self): 1941 # Check that unpickling hacks in Py3 that support 1942 # encoding='latin1' work correctly. 1943 1944 # Python2 output for pickle.dumps(numpy.array([129], dtype='b')) 1945 data = (b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\n" 1946 b"tp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'i1'\np8\n" 1947 b"I0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\x81'\n" 1948 b"p13\ntp14\nb.") 1949 # This should work: 1950 result = pickle.loads(data, encoding='latin1') 1951 assert_array_equal(result, np.array([129], dtype='b')) 1952 # Should not segfault: 1953 assert_raises(Exception, pickle.loads, data, encoding='koi8-r') 1954 1955 def test_pickle_py2_scalar_latin1_hack(self): 1956 # Check that scalar unpickling hack in Py3 that supports 1957 # encoding='latin1' work correctly. 1958 1959 # Python2 output for pickle.dumps(...) 1960 datas = [ 1961 # (original, python2_pickle, koi8r_validity) 1962 (np.unicode_('\u6bd2'), 1963 (b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n" 1964 b"(S'U1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI4\nI4\nI0\n" 1965 b"tp6\nbS'\\xd2k\\x00\\x00'\np7\ntp8\nRp9\n."), 1966 'invalid'), 1967 1968 (np.float64(9e123), 1969 (b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'f8'\n" 1970 b"p2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI-1\nI-1\nI0\ntp6\n" 1971 b"bS'O\\x81\\xb7Z\\xaa:\\xabY'\np7\ntp8\nRp9\n."), 1972 'invalid'), 1973 1974 (np.bytes_(b'\x9c'), # different 8-bit code point in KOI8-R vs latin1 1975 (b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'S1'\np2\n" 1976 b"I0\nI1\ntp3\nRp4\n(I3\nS'|'\np5\nNNNI1\nI1\nI0\ntp6\nbS'\\x9c'\np7\n" 1977 b"tp8\nRp9\n."), 1978 'different'), 1979 ] 1980 for original, data, koi8r_validity in datas: 1981 result = pickle.loads(data, encoding='latin1') 1982 assert_equal(result, original) 1983 1984 # Decoding under non-latin1 encoding (e.g.) KOI8-R can 1985 # produce bad results, but should not segfault. 1986 if koi8r_validity == 'different': 1987 # Unicode code points happen to lie within latin1, 1988 # but are different in koi8-r, resulting to silent 1989 # bogus results 1990 result = pickle.loads(data, encoding='koi8-r') 1991 assert_(result != original) 1992 elif koi8r_validity == 'invalid': 1993 # Unicode code points outside latin1, so results 1994 # to an encoding exception 1995 assert_raises(ValueError, pickle.loads, data, encoding='koi8-r') 1996 else: 1997 raise ValueError(koi8r_validity) 1998 1999 def test_structured_type_to_object(self): 2000 a_rec = np.array([(0, 1), (3, 2)], dtype='i4,i8') 2001 a_obj = np.empty((2,), dtype=object) 2002 a_obj[0] = (0, 1) 2003 a_obj[1] = (3, 2) 2004 # astype records -> object 2005 assert_equal(a_rec.astype(object), a_obj) 2006 # '=' records -> object 2007 b = np.empty_like(a_obj) 2008 b[...] = a_rec 2009 assert_equal(b, a_obj) 2010 # '=' object -> records 2011 b = np.empty_like(a_rec) 2012 b[...] = a_obj 2013 assert_equal(b, a_rec) 2014 2015 def test_assign_obj_listoflists(self): 2016 # Ticket # 1870 2017 # The inner list should get assigned to the object elements 2018 a = np.zeros(4, dtype=object) 2019 b = a.copy() 2020 a[0] = [1] 2021 a[1] = [2] 2022 a[2] = [3] 2023 a[3] = [4] 2024 b[...] = [[1], [2], [3], [4]] 2025 assert_equal(a, b) 2026 # The first dimension should get broadcast 2027 a = np.zeros((2, 2), dtype=object) 2028 a[...] = [[1, 2]] 2029 assert_equal(a, [[1, 2], [1, 2]]) 2030 2031 @pytest.mark.slow_pypy 2032 def test_memoryleak(self): 2033 # Ticket #1917 - ensure that array data doesn't leak 2034 for i in range(1000): 2035 # 100MB times 1000 would give 100GB of memory usage if it leaks 2036 a = np.empty((100000000,), dtype='i1') 2037 del a 2038 2039 @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") 2040 def test_ufunc_reduce_memoryleak(self): 2041 a = np.arange(6) 2042 acnt = sys.getrefcount(a) 2043 np.add.reduce(a) 2044 assert_equal(sys.getrefcount(a), acnt) 2045 2046 def test_search_sorted_invalid_arguments(self): 2047 # Ticket #2021, should not segfault. 2048 x = np.arange(0, 4, dtype='datetime64[D]') 2049 assert_raises(TypeError, x.searchsorted, 1) 2050 2051 def test_string_truncation(self): 2052 # Ticket #1990 - Data can be truncated in creation of an array from a 2053 # mixed sequence of numeric values and strings 2054 for val in [True, 1234, 123.4, complex(1, 234)]: 2055 for tostr in [asunicode, asbytes]: 2056 b = np.array([val, tostr('xx')]) 2057 assert_equal(tostr(b[0]), tostr(val)) 2058 b = np.array([tostr('xx'), val]) 2059 assert_equal(tostr(b[1]), tostr(val)) 2060 2061 # test also with longer strings 2062 b = np.array([val, tostr('xxxxxxxxxx')]) 2063 assert_equal(tostr(b[0]), tostr(val)) 2064 b = np.array([tostr('xxxxxxxxxx'), val]) 2065 assert_equal(tostr(b[1]), tostr(val)) 2066 2067 def test_string_truncation_ucs2(self): 2068 # Ticket #2081. Python compiled with two byte unicode 2069 # can lead to truncation if itemsize is not properly 2070 # adjusted for NumPy's four byte unicode. 2071 a = np.array(['abcd']) 2072 assert_equal(a.dtype.itemsize, 16) 2073 2074 def test_unique_stable(self): 2075 # Ticket #2063 must always choose stable sort for argsort to 2076 # get consistent results 2077 v = np.array(([0]*5 + [1]*6 + [2]*6)*4) 2078 res = np.unique(v, return_index=True) 2079 tgt = (np.array([0, 1, 2]), np.array([ 0, 5, 11])) 2080 assert_equal(res, tgt) 2081 2082 def test_unicode_alloc_dealloc_match(self): 2083 # Ticket #1578, the mismatch only showed up when running 2084 # python-debug for python versions >= 2.7, and then as 2085 # a core dump and error message. 2086 a = np.array(['abc'], dtype=np.unicode_)[0] 2087 del a 2088 2089 def test_refcount_error_in_clip(self): 2090 # Ticket #1588 2091 a = np.zeros((2,), dtype='>i2').clip(min=0) 2092 x = a + a 2093 # This used to segfault: 2094 y = str(x) 2095 # Check the final string: 2096 assert_(y == "[0 0]") 2097 2098 def test_searchsorted_wrong_dtype(self): 2099 # Ticket #2189, it used to segfault, so we check that it raises the 2100 # proper exception. 2101 a = np.array([('a', 1)], dtype='S1, int') 2102 assert_raises(TypeError, np.searchsorted, a, 1.2) 2103 # Ticket #2066, similar problem: 2104 dtype = np.format_parser(['i4', 'i4'], [], []) 2105 a = np.recarray((2, ), dtype) 2106 assert_raises(TypeError, np.searchsorted, a, 1) 2107 2108 def test_complex64_alignment(self): 2109 # Issue gh-2668 (trac 2076), segfault on sparc due to misalignment 2110 dtt = np.complex64 2111 arr = np.arange(10, dtype=dtt) 2112 # 2D array 2113 arr2 = np.reshape(arr, (2, 5)) 2114 # Fortran write followed by (C or F) read caused bus error 2115 data_str = arr2.tobytes('F') 2116 data_back = np.ndarray(arr2.shape, 2117 arr2.dtype, 2118 buffer=data_str, 2119 order='F') 2120 assert_array_equal(arr2, data_back) 2121 2122 def test_structured_count_nonzero(self): 2123 arr = np.array([0, 1]).astype('i4, (2)i4')[:1] 2124 count = np.count_nonzero(arr) 2125 assert_equal(count, 0) 2126 2127 def test_copymodule_preserves_f_contiguity(self): 2128 a = np.empty((2, 2), order='F') 2129 b = copy.copy(a) 2130 c = copy.deepcopy(a) 2131 assert_(b.flags.fortran) 2132 assert_(b.flags.f_contiguous) 2133 assert_(c.flags.fortran) 2134 assert_(c.flags.f_contiguous) 2135 2136 def test_fortran_order_buffer(self): 2137 import numpy as np 2138 a = np.array([['Hello', 'Foob']], dtype='U5', order='F') 2139 arr = np.ndarray(shape=[1, 2, 5], dtype='U1', buffer=a) 2140 arr2 = np.array([[[u'H', u'e', u'l', u'l', u'o'], 2141 [u'F', u'o', u'o', u'b', u'']]]) 2142 assert_array_equal(arr, arr2) 2143 2144 def test_assign_from_sequence_error(self): 2145 # Ticket #4024. 2146 arr = np.array([1, 2, 3]) 2147 assert_raises(ValueError, arr.__setitem__, slice(None), [9, 9]) 2148 arr.__setitem__(slice(None), [9]) 2149 assert_equal(arr, [9, 9, 9]) 2150 2151 def test_format_on_flex_array_element(self): 2152 # Ticket #4369. 2153 dt = np.dtype([('date', '<M8[D]'), ('val', '<f8')]) 2154 arr = np.array([('2000-01-01', 1)], dt) 2155 formatted = '{0}'.format(arr[0]) 2156 assert_equal(formatted, str(arr[0])) 2157 2158 def test_deepcopy_on_0d_array(self): 2159 # Ticket #3311. 2160 arr = np.array(3) 2161 arr_cp = copy.deepcopy(arr) 2162 2163 assert_equal(arr, arr_cp) 2164 assert_equal(arr.shape, arr_cp.shape) 2165 assert_equal(int(arr), int(arr_cp)) 2166 assert_(arr is not arr_cp) 2167 assert_(isinstance(arr_cp, type(arr))) 2168 2169 def test_deepcopy_F_order_object_array(self): 2170 # Ticket #6456. 2171 a = {'a': 1} 2172 b = {'b': 2} 2173 arr = np.array([[a, b], [a, b]], order='F') 2174 arr_cp = copy.deepcopy(arr) 2175 2176 assert_equal(arr, arr_cp) 2177 assert_(arr is not arr_cp) 2178 # Ensure that we have actually copied the item. 2179 assert_(arr[0, 1] is not arr_cp[1, 1]) 2180 # Ensure we are allowed to have references to the same object. 2181 assert_(arr[0, 1] is arr[1, 1]) 2182 # Check the references hold for the copied objects. 2183 assert_(arr_cp[0, 1] is arr_cp[1, 1]) 2184 2185 def test_deepcopy_empty_object_array(self): 2186 # Ticket #8536. 2187 # Deepcopy should succeed 2188 a = np.array([], dtype=object) 2189 b = copy.deepcopy(a) 2190 assert_(a.shape == b.shape) 2191 2192 def test_bool_subscript_crash(self): 2193 # gh-4494 2194 c = np.rec.array([(1, 2, 3), (4, 5, 6)]) 2195 masked = c[np.array([True, False])] 2196 base = masked.base 2197 del masked, c 2198 base.dtype 2199 2200 def test_richcompare_crash(self): 2201 # gh-4613 2202 import operator as op 2203 2204 # dummy class where __array__ throws exception 2205 class Foo: 2206 __array_priority__ = 1002 2207 2208 def __array__(self, *args, **kwargs): 2209 raise Exception() 2210 2211 rhs = Foo() 2212 lhs = np.array(1) 2213 for f in [op.lt, op.le, op.gt, op.ge]: 2214 assert_raises(TypeError, f, lhs, rhs) 2215 assert_(not op.eq(lhs, rhs)) 2216 assert_(op.ne(lhs, rhs)) 2217 2218 def test_richcompare_scalar_and_subclass(self): 2219 # gh-4709 2220 class Foo(np.ndarray): 2221 def __eq__(self, other): 2222 return "OK" 2223 2224 x = np.array([1, 2, 3]).view(Foo) 2225 assert_equal(10 == x, "OK") 2226 assert_equal(np.int32(10) == x, "OK") 2227 assert_equal(np.array([10]) == x, "OK") 2228 2229 def test_pickle_empty_string(self): 2230 # gh-3926 2231 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 2232 test_string = np.string_('') 2233 assert_equal(pickle.loads( 2234 pickle.dumps(test_string, protocol=proto)), test_string) 2235 2236 def test_frompyfunc_many_args(self): 2237 # gh-5672 2238 2239 def passer(*args): 2240 pass 2241 2242 assert_raises(ValueError, np.frompyfunc, passer, 32, 1) 2243 2244 def test_repeat_broadcasting(self): 2245 # gh-5743 2246 a = np.arange(60).reshape(3, 4, 5) 2247 for axis in chain(range(-a.ndim, a.ndim), [None]): 2248 assert_equal(a.repeat(2, axis=axis), a.repeat([2], axis=axis)) 2249 2250 def test_frompyfunc_nout_0(self): 2251 # gh-2014 2252 2253 def f(x): 2254 x[0], x[-1] = x[-1], x[0] 2255 2256 uf = np.frompyfunc(f, 1, 0) 2257 a = np.array([[1, 2, 3], [4, 5], [6, 7, 8, 9]], dtype=object) 2258 assert_equal(uf(a), ()) 2259 expected = np.array([[3, 2, 1], [5, 4], [9, 7, 8, 6]], dtype=object) 2260 assert_array_equal(a, expected) 2261 2262 @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") 2263 def test_leak_in_structured_dtype_comparison(self): 2264 # gh-6250 2265 recordtype = np.dtype([('a', np.float64), 2266 ('b', np.int32), 2267 ('d', (str, 5))]) 2268 2269 # Simple case 2270 a = np.zeros(2, dtype=recordtype) 2271 for i in range(100): 2272 a == a 2273 assert_(sys.getrefcount(a) < 10) 2274 2275 # The case in the bug report. 2276 before = sys.getrefcount(a) 2277 u, v = a[0], a[1] 2278 u == v 2279 del u, v 2280 gc.collect() 2281 after = sys.getrefcount(a) 2282 assert_equal(before, after) 2283 2284 def test_empty_percentile(self): 2285 # gh-6530 / gh-6553 2286 assert_array_equal(np.percentile(np.arange(10), []), np.array([])) 2287 2288 def test_void_compare_segfault(self): 2289 # gh-6922. The following should not segfault 2290 a = np.ones(3, dtype=[('object', 'O'), ('int', '<i2')]) 2291 a.sort() 2292 2293 def test_reshape_size_overflow(self): 2294 # gh-7455 2295 a = np.ones(20)[::2] 2296 if np.dtype(np.intp).itemsize == 8: 2297 # 64 bit. The following are the prime factors of 2**63 + 5, 2298 # plus a leading 2, so when multiplied together as int64, 2299 # the result overflows to a total size of 10. 2300 new_shape = (2, 13, 419, 691, 823, 2977518503) 2301 else: 2302 # 32 bit. The following are the prime factors of 2**31 + 5, 2303 # plus a leading 2, so when multiplied together as int32, 2304 # the result overflows to a total size of 10. 2305 new_shape = (2, 7, 7, 43826197) 2306 assert_raises(ValueError, a.reshape, new_shape) 2307 2308 def test_invalid_structured_dtypes(self): 2309 # gh-2865 2310 # mapping python objects to other dtypes 2311 assert_raises(ValueError, np.dtype, ('O', [('name', 'i8')])) 2312 assert_raises(ValueError, np.dtype, ('i8', [('name', 'O')])) 2313 assert_raises(ValueError, np.dtype, 2314 ('i8', [('name', [('name', 'O')])])) 2315 assert_raises(ValueError, np.dtype, ([('a', 'i4'), ('b', 'i4')], 'O')) 2316 assert_raises(ValueError, np.dtype, ('i8', 'O')) 2317 # wrong number/type of tuple elements in dict 2318 assert_raises(ValueError, np.dtype, 2319 ('i', {'name': ('i', 0, 'title', 'oops')})) 2320 assert_raises(ValueError, np.dtype, 2321 ('i', {'name': ('i', 'wrongtype', 'title')})) 2322 # disallowed as of 1.13 2323 assert_raises(ValueError, np.dtype, 2324 ([('a', 'O'), ('b', 'O')], [('c', 'O'), ('d', 'O')])) 2325 # allowed as a special case due to existing use, see gh-2798 2326 a = np.ones(1, dtype=('O', [('name', 'O')])) 2327 assert_equal(a[0], 1) 2328 # In particular, the above union dtype (and union dtypes in general) 2329 # should mainly behave like the main (object) dtype: 2330 assert a[0] is a.item() 2331 assert type(a[0]) is int 2332 2333 def test_correct_hash_dict(self): 2334 # gh-8887 - __hash__ would be None despite tp_hash being set 2335 all_types = set(np.typeDict.values()) - {np.void} 2336 for t in all_types: 2337 val = t() 2338 2339 try: 2340 hash(val) 2341 except TypeError as e: 2342 assert_equal(t.__hash__, None) 2343 else: 2344 assert_(t.__hash__ != None) 2345 2346 def test_scalar_copy(self): 2347 scalar_types = set(np.sctypeDict.values()) 2348 values = { 2349 np.void: b"a", 2350 np.bytes_: b"a", 2351 np.unicode_: "a", 2352 np.datetime64: "2017-08-25", 2353 } 2354 for sctype in scalar_types: 2355 item = sctype(values.get(sctype, 1)) 2356 item2 = copy.copy(item) 2357 assert_equal(item, item2) 2358 2359 def test_void_item_memview(self): 2360 va = np.zeros(10, 'V4') 2361 x = va[:1].item() 2362 va[0] = b'\xff\xff\xff\xff' 2363 del va 2364 assert_equal(x, b'\x00\x00\x00\x00') 2365 2366 def test_void_getitem(self): 2367 # Test fix for gh-11668. 2368 assert_(np.array([b'a'], 'V1').astype('O') == b'a') 2369 assert_(np.array([b'ab'], 'V2').astype('O') == b'ab') 2370 assert_(np.array([b'abc'], 'V3').astype('O') == b'abc') 2371 assert_(np.array([b'abcd'], 'V4').astype('O') == b'abcd') 2372 2373 def test_structarray_title(self): 2374 # The following used to segfault on pypy, due to NPY_TITLE_KEY 2375 # not working properly and resulting to double-decref of the 2376 # structured array field items: 2377 # See: https://bitbucket.org/pypy/pypy/issues/2789 2378 for j in range(5): 2379 structure = np.array([1], dtype=[(('x', 'X'), np.object_)]) 2380 structure[0]['x'] = np.array([2]) 2381 gc.collect() 2382 2383 def test_dtype_scalar_squeeze(self): 2384 # gh-11384 2385 values = { 2386 'S': b"a", 2387 'M': "2018-06-20", 2388 } 2389 for ch in np.typecodes['All']: 2390 if ch in 'O': 2391 continue 2392 sctype = np.dtype(ch).type 2393 scvalue = sctype(values.get(ch, 3)) 2394 for axis in [None, ()]: 2395 squeezed = scvalue.squeeze(axis=axis) 2396 assert_equal(squeezed, scvalue) 2397 assert_equal(type(squeezed), type(scvalue)) 2398 2399 def test_field_access_by_title(self): 2400 # gh-11507 2401 s = 'Some long field name' 2402 if HAS_REFCOUNT: 2403 base = sys.getrefcount(s) 2404 t = np.dtype([((s, 'f1'), np.float64)]) 2405 data = np.zeros(10, t) 2406 for i in range(10): 2407 str(data[['f1']]) 2408 if HAS_REFCOUNT: 2409 assert_(base <= sys.getrefcount(s)) 2410 2411 @pytest.mark.parametrize('val', [ 2412 # arrays and scalars 2413 np.ones((10, 10), dtype='int32'), 2414 np.uint64(10), 2415 ]) 2416 @pytest.mark.parametrize('protocol', 2417 range(2, pickle.HIGHEST_PROTOCOL + 1) 2418 ) 2419 def test_pickle_module(self, protocol, val): 2420 # gh-12837 2421 s = pickle.dumps(val, protocol) 2422 assert b'_multiarray_umath' not in s 2423 if protocol == 5 and len(val.shape) > 0: 2424 # unpickling ndarray goes through _frombuffer for protocol 5 2425 assert b'numpy.core.numeric' in s 2426 else: 2427 assert b'numpy.core.multiarray' in s 2428 2429 def test_object_casting_errors(self): 2430 # gh-11993 update to ValueError (see gh-16909), since strings can in 2431 # principle be converted to complex, but this string cannot. 2432 arr = np.array(['AAAAA', 18465886.0, 18465886.0], dtype=object) 2433 assert_raises(ValueError, arr.astype, 'c8') 2434 2435 def test_eff1d_casting(self): 2436 # gh-12711 2437 x = np.array([1, 2, 4, 7, 0], dtype=np.int16) 2438 res = np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) 2439 assert_equal(res, [-99, 1, 2, 3, -7, 88, 99]) 2440 2441 # The use of safe casting means, that 1<<20 is cast unsafely, an 2442 # error may be better, but currently there is no mechanism for it. 2443 res = np.ediff1d(x, to_begin=(1<<20), to_end=(1<<20)) 2444 assert_equal(res, [0, 1, 2, 3, -7, 0]) 2445 2446 def test_pickle_datetime64_array(self): 2447 # gh-12745 (would fail with pickle5 installed) 2448 d = np.datetime64('2015-07-04 12:59:59.50', 'ns') 2449 arr = np.array([d]) 2450 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): 2451 dumped = pickle.dumps(arr, protocol=proto) 2452 assert_equal(pickle.loads(dumped), arr) 2453 2454 def test_bad_array_interface(self): 2455 class T: 2456 __array_interface__ = {} 2457 2458 with assert_raises(ValueError): 2459 np.array([T()]) 2460 2461 def test_2d__array__shape(self): 2462 class T(object): 2463 def __array__(self): 2464 return np.ndarray(shape=(0,0)) 2465 2466 # Make sure __array__ is used instead of Sequence methods. 2467 def __iter__(self): 2468 return iter([]) 2469 2470 def __getitem__(self, idx): 2471 raise AssertionError("__getitem__ was called") 2472 2473 def __len__(self): 2474 return 0 2475 2476 2477 t = T() 2478 # gh-13659, would raise in broadcasting [x=t for x in result] 2479 arr = np.array([t]) 2480 assert arr.shape == (1, 0, 0) 2481 2482 @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1, reason='overflows 32-bit python') 2483 @pytest.mark.skipif(sys.platform == 'win32' and sys.version_info[:2] < (3, 8), 2484 reason='overflows on windows, fixed in bpo-16865') 2485 def test_to_ctypes(self): 2486 #gh-14214 2487 arr = np.zeros((2 ** 31 + 1,), 'b') 2488 assert arr.size * arr.itemsize > 2 ** 31 2489 c_arr = np.ctypeslib.as_ctypes(arr) 2490 assert_equal(c_arr._length_, arr.size) 2491 2492 def test_complex_conversion_error(self): 2493 # gh-17068 2494 with pytest.raises(TypeError, match=r"Unable to convert dtype.*"): 2495 complex(np.array("now", np.datetime64)) 2496 2497 def test__array_interface__descr(self): 2498 # gh-17068 2499 dt = np.dtype(dict(names=['a', 'b'], 2500 offsets=[0, 0], 2501 formats=[np.int64, np.int64])) 2502 descr = np.array((1, 1), dtype=dt).__array_interface__['descr'] 2503 assert descr == [('', '|V8')] # instead of [(b'', '|V8')] 2504 2505 @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1, reason='overflows 32-bit python') 2506 @requires_memory(free_bytes=9e9) 2507 def test_dot_big_stride(self): 2508 # gh-17111 2509 # blas stride = stride//itemsize > int32 max 2510 int32_max = np.iinfo(np.int32).max 2511 n = int32_max + 3 2512 a = np.empty([n], dtype=np.float32) 2513 b = a[::n-1] 2514 b[...] = 1 2515 assert b.strides[0] > int32_max * b.dtype.itemsize 2516 assert np.dot(b, b) == 2.0 2517 2518 def test_frompyfunc_name(self): 2519 # name conversion was failing for python 3 strings 2520 # resulting in the default '?' name. Also test utf-8 2521 # encoding using non-ascii name. 2522 def cassé(x): 2523 return x 2524 2525 f = np.frompyfunc(cassé, 1, 1) 2526 assert str(f) == "<ufunc 'cassé (vectorized)'>" 2527