codekingpro/portable-devtools
114k
1import copy
2import gc
3import pickle
4import sys
5import tempfile
6import warnings
7from io import BytesIO
8from itertools import chain
9from os import path
10
11import pytest
12
13import numpy as np
14from numpy._utils import asbytes, asunicode
15from numpy.exceptions import AxisError, ComplexWarning
16from numpy.lib.stride_tricks import as_strided
17from numpy.testing import (
18 HAS_REFCOUNT,
19 IS_64BIT,
20 IS_PYPY,
21 IS_PYSTON,
22 IS_WASM,
23 _assert_valid_refcount,
24 assert_,
25 assert_almost_equal,
26 assert_array_almost_equal,
27 assert_array_equal,
28 assert_equal,
29 assert_raises,
30 assert_raises_regex,
31)
32from numpy.testing._private.utils import _no_tracing, requires_memory
33
34
35class TestRegression:
36 def test_invalid_round(self):
37 # Ticket #3
38 v = 4.7599999999999998
39 assert_array_equal(np.array([v]), np.array(v))
40
41 def test_mem_empty(self):
42 # Ticket #7
43 np.empty((1,), dtype=[('x', np.int64)])
44
45 def test_pickle_transposed(self):
46 # Ticket #16
47 a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]]))
48 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
49 with BytesIO() as f:
50 pickle.dump(a, f, protocol=proto)
51 f.seek(0)
52 b = pickle.load(f)
53 assert_array_equal(a, b)
54
55 def test_dtype_names(self):
56 # Ticket #35
57 # Should succeed
58 np.dtype([(('name', 'label'), np.int32, 3)])
59
60 def test_reduce(self):
61 # Ticket #40
62 assert_almost_equal(np.add.reduce([1., .5], dtype=None), 1.5)
63
64 def test_zeros_order(self):
65 # Ticket #43
66 np.zeros([3], int, 'C')
67 np.zeros([3], order='C')
68 np.zeros([3], int, order='C')
69
70 def test_asarray_with_order(self):
71 # Check that nothing is done when order='F' and array C/F-contiguous
72 a = np.ones(2)
73 assert_(a is np.asarray(a, order='F'))
74
75 def test_ravel_with_order(self):
76 # Check that ravel works when order='F' and array C/F-contiguous
77 a = np.ones(2)
78 assert_(not a.ravel('F').flags.owndata)
79
80 def test_sort_bigendian(self):
81 # Ticket #47
82 a = np.linspace(0, 10, 11)
83 c = a.astype(np.dtype('<f8'))
84 c.sort()
85 assert_array_almost_equal(c, a)
86
87 def test_negative_nd_indexing(self):
88 # Ticket #49
89 c = np.arange(125).reshape((5, 5, 5))
90 origidx = np.array([-1, 0, 1])
91 idx = np.array(origidx)
92 c[idx]
93 assert_array_equal(idx, origidx)
94
95 def test_char_dump(self):
96 # Ticket #50
97 ca = np.char.array(np.arange(1000, 1010), itemsize=4)
98 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
99 with BytesIO() as f:
100 pickle.dump(ca, f, protocol=proto)
101 f.seek(0)
102 ca = np.load(f, allow_pickle=True)
103
104 def test_noncontiguous_fill(self):
105 # Ticket #58.
106 a = np.zeros((5, 3))
107 b = a[:, :2,]
108
109 def rs():
110 b.shape = (10,)
111
112 assert_raises(AttributeError, rs)
113
114 def test_bool(self):
115 # Ticket #60
116 np.bool(1) # Should succeed
117
118 def test_indexing1(self):
119 # Ticket #64
120 descr = [('x', [('y', [('z', 'c16', (2,)),]),]),]
121 buffer = ((([6j, 4j],),),)
122 h = np.array(buffer, dtype=descr)
123 h['x']['y']['z']
124
125 def test_indexing2(self):
126 # Ticket #65
127 descr = [('x', 'i4', (2,))]
128 buffer = ([3, 2],)
129 h = np.array(buffer, dtype=descr)
130 h['x']
131
132 def test_round(self):
133 # Ticket #67
134 x = np.array([1 + 2j])
135 assert_almost_equal(x**(-1), [1 / (1 + 2j)])
136
137 def test_scalar_compare(self):
138 # Trac Ticket #72
139 # https://github.com/numpy/numpy/issues/565
140 a = np.array(['test', 'auto'])
141 assert_array_equal(a == 'auto', np.array([False, True]))
142 assert_(a[1] == 'auto')
143 assert_(a[0] != 'auto')
144 b = np.linspace(0, 10, 11)
145 assert_array_equal(b != 'auto', np.ones(11, dtype=bool))
146 assert_(b[0] != 'auto')
147
148 def test_unicode_swapping(self):
149 # Ticket #79
150 ulen = 1
151 ucs_value = '\U0010FFFF'
152 ua = np.array([[[ucs_value * ulen] * 2] * 3] * 4, dtype=f'U{ulen}')
153 ua.view(ua.dtype.newbyteorder()) # Should succeed.
154
155 def test_object_array_fill(self):
156 # Ticket #86
157 x = np.zeros(1, 'O')
158 x.fill([])
159
160 def test_mem_dtype_align(self):
161 # Ticket #93
162 with pytest.raises(TypeError):
163 np.dtype({'names': ['a'], 'formats': ['foo']}, align=True)
164
165 def test_endian_bool_indexing(self):
166 # Ticket #105
167 a = np.arange(10., dtype='>f8')
168 b = np.arange(10., dtype='<f8')
169 xa = np.where((a > 2) & (a < 6))
170 xb = np.where((b > 2) & (b < 6))
171 ya = ((a > 2) & (a < 6))
172 yb = ((b > 2) & (b < 6))
173 assert_array_almost_equal(xa, ya.nonzero())
174 assert_array_almost_equal(xb, yb.nonzero())
175 assert_(np.all(a[ya] > 0.5))
176 assert_(np.all(b[yb] > 0.5))
177
178 def test_endian_where(self):
179 # GitHub issue #369
180 net = np.zeros(3, dtype='>f4')
181 net[1] = 0.00458849
182 net[2] = 0.605202
183 max_net = net.max()
184 test = np.where(net <= 0., max_net, net)
185 correct = np.array([0.60520202, 0.00458849, 0.60520202])
186 assert_array_almost_equal(test, correct)
187
188 def test_endian_recarray(self):
189 # Ticket #2185
190 dt = np.dtype([
191 ('head', '>u4'),
192 ('data', '>u4', 2),
193 ])
194 buf = np.recarray(1, dtype=dt)
195 buf[0]['head'] = 1
196 buf[0]['data'][:] = [1, 1]
197
198 h = buf[0]['head']
199 d = buf[0]['data'][0]
200 buf[0]['head'] = h
201 buf[0]['data'][0] = d
202 assert_(buf[0]['head'] == 1)
203
204 def test_mem_dot(self):
205 # Ticket #106
206 x = np.random.randn(0, 1)
207 y = np.random.randn(10, 1)
208 # Dummy array to detect bad memory access:
209 _z = np.ones(10)
210 _dummy = np.empty((0, 10))
211 z = as_strided(_z, _dummy.shape, _dummy.strides)
212 np.dot(x, np.transpose(y), out=z)
213 assert_equal(_z, np.ones(10))
214 # Do the same for the built-in dot:
215 np._core.multiarray.dot(x, np.transpose(y), out=z)
216 assert_equal(_z, np.ones(10))
217
218 def test_arange_endian(self):
219 # Ticket #111
220 ref = np.arange(10)
221 x = np.arange(10, dtype='<f8')
222 assert_array_equal(ref, x)
223 x = np.arange(10, dtype='>f8')
224 assert_array_equal(ref, x)
225
226 def test_arange_inf_step(self):
227 ref = np.arange(0, 1, 10)
228 x = np.arange(0, 1, np.inf)
229 assert_array_equal(ref, x)
230
231 ref = np.arange(0, 1, -10)
232 x = np.arange(0, 1, -np.inf)
233 assert_array_equal(ref, x)
234
235 ref = np.arange(0, -1, -10)
236 x = np.arange(0, -1, -np.inf)
237 assert_array_equal(ref, x)
238
239 ref = np.arange(0, -1, 10)
240 x = np.arange(0, -1, np.inf)
241 assert_array_equal(ref, x)
242
243 def test_arange_underflow_stop_and_step(self):
244 finfo = np.finfo(np.float64)
245
246 ref = np.arange(0, finfo.eps, 2 * finfo.eps)
247 x = np.arange(0, finfo.eps, finfo.max)
248 assert_array_equal(ref, x)
249
250 ref = np.arange(0, finfo.eps, -2 * finfo.eps)
251 x = np.arange(0, finfo.eps, -finfo.max)
252 assert_array_equal(ref, x)
253
254 ref = np.arange(0, -finfo.eps, -2 * finfo.eps)
255 x = np.arange(0, -finfo.eps, -finfo.max)
256 assert_array_equal(ref, x)
257
258 ref = np.arange(0, -finfo.eps, 2 * finfo.eps)
259 x = np.arange(0, -finfo.eps, finfo.max)
260 assert_array_equal(ref, x)
261
262 def test_argmax(self):
263 # Ticket #119
264 a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
265 for i in range(a.ndim):
266 a.argmax(i) # Should succeed
267
268 def test_mem_divmod(self):
269 # Ticket #126
270 for i in range(10):
271 divmod(np.array([i])[0], 10)
272
273 def test_hstack_invalid_dims(self):
274 # Ticket #128
275 x = np.arange(9).reshape((3, 3))
276 y = np.array([0, 0, 0])
277 assert_raises(ValueError, np.hstack, (x, y))
278
279 def test_squeeze_type(self):
280 # Ticket #133
281 a = np.array([3])
282 b = np.array(3)
283 assert_(type(a.squeeze()) is np.ndarray)
284 assert_(type(b.squeeze()) is np.ndarray)
285
286 def test_add_identity(self):
287 # Ticket #143
288 assert_equal(0, np.add.identity)
289
290 def test_numpy_float_python_long_addition(self):
291 # Check that numpy float and python longs can be added correctly.
292 a = np.float64(23.) + 2**135
293 assert_equal(a, 23. + 2**135)
294
295 def test_binary_repr_0(self):
296 # Ticket #151
297 assert_equal('0', np.binary_repr(0))
298
299 def test_rec_iterate(self):
300 # Ticket #160
301 descr = np.dtype([('i', int), ('f', float), ('s', '|S3')])
302 x = np.rec.array([(1, 1.1, '1.0'),
303 (2, 2.2, '2.0')], dtype=descr)
304 x[0].tolist()
305 list(x[0])
306
307 def test_unicode_string_comparison(self):
308 # Ticket #190
309 a = np.array('hello', np.str_)
310 b = np.array('world')
311 a == b
312
313 def test_tobytes_FORTRANORDER_discontiguous(self):
314 # Fix in r2836
315 # Create non-contiguous Fortran ordered array
316 x = np.array(np.random.rand(3, 3), order='F')[:, :2]
317 assert_array_almost_equal(x.ravel(), np.frombuffer(x.tobytes()))
318
319 def test_flat_assignment(self):
320 # Correct behaviour of ticket #194
321 x = np.empty((3, 1))
322 x.flat = np.arange(3)
323 assert_array_almost_equal(x, [[0], [1], [2]])
324 x.flat = np.arange(3, dtype=float)
325 assert_array_almost_equal(x, [[0], [1], [2]])
326
327 def test_broadcast_flat_assignment(self):
328 # Ticket #194
329 x = np.empty((3, 1))
330
331 def bfa():
332 x[:] = np.arange(3)
333
334 def bfb():
335 x[:] = np.arange(3, dtype=float)
336
337 assert_raises(ValueError, bfa)
338 assert_raises(ValueError, bfb)
339
340 @pytest.mark.xfail(IS_WASM, reason="not sure why")
341 @pytest.mark.parametrize("index",
342 [np.ones(10, dtype=bool), np.arange(10)],
343 ids=["boolean-arr-index", "integer-arr-index"])
344 def test_nonarray_assignment(self, index):
345 # See also Issue gh-2870, test for non-array assignment
346 # and equivalent unsafe casted array assignment
347 a = np.arange(10)
348
349 with pytest.raises(ValueError):
350 a[index] = np.nan
351
352 with np.errstate(invalid="warn"):
353 with pytest.warns(RuntimeWarning, match="invalid value"):
354 a[index] = np.array(np.nan) # Only warns
355
356 def test_unpickle_dtype_with_object(self):
357 # Implemented in r2840
358 dt = np.dtype([('x', int), ('y', np.object_), ('z', 'O')])
359 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
360 with BytesIO() as f:
361 pickle.dump(dt, f, protocol=proto)
362 f.seek(0)
363 dt_ = pickle.load(f)
364 assert_equal(dt, dt_)
365
366 def test_mem_array_creation_invalid_specification(self):
367 # Ticket #196
368 dt = np.dtype([('x', int), ('y', np.object_)])
369 # Wrong way
370 assert_raises(ValueError, np.array, [1, 'object'], dt)
371 # Correct way
372 np.array([(1, 'object')], dt)
373
374 def test_recarray_single_element(self):
375 # Ticket #202
376 a = np.array([1, 2, 3], dtype=np.int32)
377 b = a.copy()
378 r = np.rec.array(a, shape=1, formats=['3i4'], names=['d'])
379 assert_array_equal(a, b)
380 assert_equal(a, r[0][0])
381
382 def test_zero_sized_array_indexing(self):
383 # Ticket #205
384 tmp = np.array([])
385
386 def index_tmp():
387 tmp[np.array(10)]
388
389 assert_raises(IndexError, index_tmp)
390
391 def test_chararray_rstrip(self):
392 # Ticket #222
393 x = np.char.chararray((1,), 5)
394 x[0] = b'a '
395 x = x.rstrip()
396 assert_equal(x[0], b'a')
397
398 def test_object_array_shape(self):
399 # Ticket #239
400 assert_equal(np.array([[1, 2], 3, 4], dtype=object).shape, (3,))
401 assert_equal(np.array([[1, 2], [3, 4]], dtype=object).shape, (2, 2))
402 assert_equal(np.array([(1, 2), (3, 4)], dtype=object).shape, (2, 2))
403 assert_equal(np.array([], dtype=object).shape, (0,))
404 assert_equal(np.array([[], [], []], dtype=object).shape, (3, 0))
405 assert_equal(np.array([[3, 4], [5, 6], None], dtype=object).shape, (3,))
406
407 def test_mem_around(self):
408 # Ticket #243
409 x = np.zeros((1,))
410 y = [0]
411 decimal = 6
412 np.around(abs(x - y), decimal) <= 10.0**(-decimal)
413
414 def test_character_array_strip(self):
415 # Ticket #246
416 x = np.char.array(("x", "x ", "x "))
417 for c in x:
418 assert_equal(c, "x")
419
420 def test_lexsort(self):
421 # Lexsort memory error
422 v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
423 assert_equal(np.lexsort(v), 0)
424
425 def test_lexsort_invalid_sequence(self):
426 # Issue gh-4123
427 class BuggySequence:
428 def __len__(self):
429 return 4
430
431 def __getitem__(self, key):
432 raise KeyError
433
434 assert_raises(KeyError, np.lexsort, BuggySequence())
435
436 def test_lexsort_zerolen_custom_strides(self):
437 # Ticket #14228
438 xs = np.array([], dtype='i8')
439 assert np.lexsort((xs,)).shape[0] == 0 # Works
440
441 xs = as_strided(xs, strides=(16,))
442 assert np.lexsort((xs,)).shape[0] == 0 # Was: MemoryError
443
444 def test_lexsort_zerolen_custom_strides_2d(self):
445 xs = np.array([], dtype='i8')
446 xt = as_strided(xs, shape=(0, 2), strides=(16, 16))
447 assert np.lexsort((xt,), axis=0).shape[0] == 0
448
449 xt = as_strided(xs, shape=(2, 0), strides=(16, 16))
450 assert np.lexsort((xt,), axis=0).shape[0] == 2
451
452 def test_lexsort_invalid_axis(self):
453 assert_raises(AxisError, np.lexsort, (np.arange(1),), axis=2)
454 assert_raises(AxisError, np.lexsort, (np.array([]),), axis=1)
455 assert_raises(AxisError, np.lexsort, (np.array(1),), axis=10)
456
457 def test_lexsort_zerolen_element(self):
458 dt = np.dtype([]) # a void dtype with no fields
459 xs = np.empty(4, dt)
460
461 assert np.lexsort((xs,)).shape[0] == xs.shape[0]
462
463 @pytest.mark.filterwarnings(
464 "ignore:.*align should be passed:numpy.exceptions.VisibleDeprecationWarning")
465 def test_pickle_py2_bytes_encoding(self):
466 # Check that arrays and scalars pickled on Py2 are
467 # unpickleable on Py3 using encoding='bytes'
468
469 test_data = [
470 # (original, py2_pickle)
471 (
472 np.str_('\u6f2c'),
473 b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'U1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI4\nI4\nI0\ntp6\nbS',o\\x00\\x00'\np7\ntp8\nRp9\n."
474 ),
475
476 (
477 np.array([9e123], dtype=np.float64),
478 b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'f8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'<'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np13\ntp14\nb."
479 ),
480
481 (
482 np.array([(9e123,)], dtype=[('name', float)]),
483 b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'V8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'name'\np12\ntp13\n(dp14\ng12\n(g7\n(S'f8'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'<'\np18\nNNNI-1\nI-1\nI0\ntp19\nbI0\ntp20\nsI8\nI1\nI0\ntp21\nbI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np22\ntp23\nb."
484 ),
485 ]
486
487 for original, data in test_data:
488 result = pickle.loads(data, encoding='bytes')
489 assert_equal(result, original)
490
491 if isinstance(result, np.ndarray) and result.dtype.names is not None:
492 for name in result.dtype.names:
493 assert_(isinstance(name, str))
494
495 def test_pickle_dtype(self):
496 # Ticket #251
497 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
498 pickle.dumps(float, protocol=proto)
499
500 def test_swap_real(self):
501 # Ticket #265
502 assert_equal(np.arange(4, dtype='>c8').imag.max(), 0.0)
503 assert_equal(np.arange(4, dtype='<c8').imag.max(), 0.0)
504 assert_equal(np.arange(4, dtype='>c8').real.max(), 3.0)
505 assert_equal(np.arange(4, dtype='<c8').real.max(), 3.0)
506
507 def test_object_array_from_list(self):
508 # Ticket #270 (gh-868)
509 assert_(np.array([1, None, 'A']).shape == (3,))
510
511 def test_multiple_assign(self):
512 # Ticket #273
513 a = np.zeros((3, 1), int)
514 a[[1, 2]] = 1
515
516 def test_empty_array_type(self):
517 assert_equal(np.array([]).dtype, np.zeros(0).dtype)
518
519 def test_void_copyswap(self):
520 dt = np.dtype([('one', '<i4'), ('two', '<i4')])
521 x = np.array((1, 2), dtype=dt)
522 x = x.byteswap()
523 assert_(x['one'] > 1 and x['two'] > 2)
524
525 def test_method_args(self):
526 # Make sure methods and functions have same default axis
527 # keyword and arguments
528 funcs1 = ['argmax', 'argmin', 'sum', 'any', 'all', 'cumsum',
529 '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 res1 = getattr(arr, func)()
537 res2 = getattr(np, func)(arr2)
538 if res1 is None:
539 res1 = arr
540
541 if res1.dtype.kind in 'uib':
542 assert_((res1 == res2).all(), func)
543 else:
544 assert_(abs(res1 - res2).max() < 1e-8, func)
545
546 for func in funcs2:
547 arr1 = np.random.rand(8, 7)
548 arr2 = np.random.rand(8, 7)
549 res1 = None
550 if func == 'compress':
551 arr1 = arr1.ravel()
552 res1 = getattr(arr2, func)(arr1)
553 else:
554 arr2 = (15 * arr2).astype(int).ravel()
555 if res1 is None:
556 res1 = getattr(arr1, func)(arr2)
557 res2 = getattr(np, func)(arr1, arr2)
558 assert_(abs(res1 - res2).max() < 1e-8, func)
559
560 def test_mem_lexsort_strings(self):
561 # Ticket #298
562 lst = ['abc', 'cde', 'fgh']
563 np.lexsort((lst,))
564
565 def test_fancy_index(self):
566 # Ticket #302
567 x = np.array([1, 2])[np.array([0])]
568 assert_equal(x.shape, (1,))
569
570 def test_recarray_copy(self):
571 # Ticket #312
572 dt = [('x', np.int16), ('y', np.float64)]
573 ra = np.array([(1, 2.3)], dtype=dt)
574 rb = np.rec.array(ra, dtype=dt)
575 rb['x'] = 2.
576 assert_(ra['x'] != rb['x'])
577
578 def test_rec_fromarray(self):
579 # Ticket #322
580 x1 = np.array([[1, 2], [3, 4], [5, 6]])
581 x2 = np.array(['a', 'dd', 'xyz'])
582 x3 = np.array([1.1, 2, 3])
583 np.rec.fromarrays([x1, x2, x3], formats="(2,)i4,S3,f8")
584
585 def test_object_array_assign(self):
586 x = np.empty((2, 2), object)
587 x.flat[2] = (1, 2, 3)
588 assert_equal(x.flat[2], (1, 2, 3))
589
590 def test_ndmin_float64(self):
591 # Ticket #324
592 x = np.array([1, 2, 3], dtype=np.float64)
593 assert_equal(np.array(x, dtype=np.float32, ndmin=2).ndim, 2)
594 assert_equal(np.array(x, dtype=np.float64, ndmin=2).ndim, 2)
595
596 def test_ndmin_order(self):
597 # Issue #465 and related checks
598 assert_(np.array([1, 2], order='C', ndmin=3).flags.c_contiguous)
599 assert_(np.array([1, 2], order='F', ndmin=3).flags.f_contiguous)
600 assert_(np.array(np.ones((2, 2), order='F'), ndmin=3).flags.f_contiguous)
601 assert_(np.array(np.ones((2, 2), order='C'), ndmin=3).flags.c_contiguous)
602
603 def test_mem_axis_minimization(self):
604 # Ticket #327
605 data = np.arange(5)
606 data = np.add.outer(data, data)
607
608 def test_mem_float_imag(self):
609 # Ticket #330
610 np.float64(1.0).imag
611
612 def test_dtype_tuple(self):
613 # Ticket #334
614 assert_(np.dtype('i4') == np.dtype(('i4', ())))
615
616 def test_dtype_posttuple(self):
617 # Ticket #335
618 np.dtype([('col1', '()i4')])
619
620 def test_numeric_carray_compare(self):
621 # Ticket #341
622 assert_equal(np.array(['X'], 'c'), b'X')
623
624 def test_string_array_size(self):
625 # Ticket #342
626 assert_raises(ValueError,
627 np.array, [['X'], ['X', 'X', 'X']], '|S1')
628
629 def test_dtype_repr(self):
630 # Ticket #344
631 dt1 = np.dtype(('uint32', 2))
632 dt2 = np.dtype(('uint32', (2,)))
633 assert_equal(dt1.__repr__(), dt2.__repr__())
634
635 def test_reshape_order(self):
636 # Make sure reshape order works.
637 a = np.arange(6).reshape(2, 3, order='F')
638 assert_equal(a, [[0, 2, 4], [1, 3, 5]])
639 a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
640 b = a[:, 1]
641 assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]])
642
643 def test_reshape_zero_strides(self):
644 # Issue #380, test reshaping of zero strided arrays
645 a = np.ones(1)
646 a = as_strided(a, shape=(5,), strides=(0,))
647 assert_(a.reshape(5, 1).strides[0] == 0)
648
649 def test_reshape_zero_size(self):
650 # GitHub Issue #2700, setting shape failed for 0-sized arrays
651 a = np.ones((0, 2))
652 a.shape = (-1, 2)
653
654 def test_reshape_trailing_ones_strides(self):
655 # GitHub issue gh-2949, bad strides for trailing ones of new shape
656 a = np.zeros(12, dtype=np.int32)[::2] # not contiguous
657 strides_c = (16, 8, 8, 8)
658 strides_f = (8, 24, 48, 48)
659 assert_equal(a.reshape(3, 2, 1, 1).strides, strides_c)
660 assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f)
661 assert_equal(np.array(0, dtype=np.int32).reshape(1, 1).strides, (4, 4))
662
663 def test_repeat_discont(self):
664 # Ticket #352
665 a = np.arange(12).reshape(4, 3)[:, 2]
666 assert_equal(a.repeat(3), [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11])
667
668 def test_array_index(self):
669 # Make sure optimization is not called in this case.
670 a = np.array([1, 2, 3])
671 a2 = np.array([[1, 2, 3]])
672 assert_equal(a[np.where(a == 3)], a2[np.where(a2 == 3)])
673
674 def test_object_argmax(self):
675 a = np.array([1, 2, 3], dtype=object)
676 assert_(a.argmax() == 2)
677
678 def test_recarray_fields(self):
679 # Ticket #372
680 dt0 = np.dtype([('f0', 'i4'), ('f1', 'i4')])
681 dt1 = np.dtype([('f0', 'i8'), ('f1', 'i8')])
682 for a in [np.array([(1, 2), (3, 4)], "i4,i4"),
683 np.rec.array([(1, 2), (3, 4)], "i4,i4"),
684 np.rec.array([(1, 2), (3, 4)]),
685 np.rec.fromarrays([(1, 2), (3, 4)], "i4,i4"),
686 np.rec.fromarrays([(1, 2), (3, 4)])]:
687 assert_(a.dtype in [dt0, dt1])
688
689 def test_random_shuffle(self):
690 # Ticket #374
691 a = np.arange(5).reshape((5, 1))
692 b = a.copy()
693 np.random.shuffle(b)
694 assert_equal(np.sort(b, axis=0), a)
695
696 def test_refcount_vdot(self):
697 # Changeset #3443
698 _assert_valid_refcount(np.vdot)
699
700 def test_startswith(self):
701 ca = np.char.array(['Hi', 'There'])
702 assert_equal(ca.startswith('H'), [True, False])
703
704 def test_noncommutative_reduce_accumulate(self):
705 # Ticket #413
706 tosubtract = np.arange(5)
707 todivide = np.array([2.0, 0.5, 0.25])
708 assert_equal(np.subtract.reduce(tosubtract), -10)
709 assert_equal(np.divide.reduce(todivide), 16.0)
710 assert_array_equal(np.subtract.accumulate(tosubtract),
711 np.array([0, -1, -3, -6, -10]))
712 assert_array_equal(np.divide.accumulate(todivide),
713 np.array([2., 4., 16.]))
714
715 def test_convolve_empty(self):
716 # Convolve should raise an error for empty input array.
717 assert_raises(ValueError, np.convolve, [], [1])
718 assert_raises(ValueError, np.convolve, [1], [])
719
720 def test_multidim_byteswap(self):
721 # Ticket #449
722 r = np.array([(1, (0, 1, 2))], dtype="i2,3i2")
723 assert_array_equal(r.byteswap(),
724 np.array([(256, (0, 256, 512))], r.dtype))
725
726 def test_string_NULL(self):
727 # Changeset 3557
728 assert_equal(np.array("a\x00\x0b\x0c\x00").item(),
729 'a\x00\x0b\x0c')
730
731 def test_junk_in_string_fields_of_recarray(self):
732 # Ticket #483
733 r = np.array([[b'abc']], dtype=[('var1', '|S20')])
734 assert_(asbytes(r['var1'][0][0]) == b'abc')
735
736 def test_take_output(self):
737 # Ensure that 'take' honours output parameter.
738 x = np.arange(12).reshape((3, 4))
739 a = np.take(x, [0, 2], axis=1)
740 b = np.zeros_like(a)
741 np.take(x, [0, 2], axis=1, out=b)
742 assert_array_equal(a, b)
743
744 def test_take_object_fail(self):
745 # Issue gh-3001
746 d = 123.
747 a = np.array([d, 1], dtype=object)
748 if HAS_REFCOUNT:
749 ref_d = sys.getrefcount(d)
750 try:
751 a.take([0, 100])
752 except IndexError:
753 pass
754 if HAS_REFCOUNT:
755 assert_(ref_d == sys.getrefcount(d))
756
757 def test_array_str_64bit(self):
758 # Ticket #501
759 s = np.array([1, np.nan], dtype=np.float64)
760 with np.errstate(all='raise'):
761 np.array_str(s) # Should succeed
762
763 def test_frompyfunc_endian(self):
764 # Ticket #503
765 from math import radians
766 uradians = np.frompyfunc(radians, 1, 1)
767 big_endian = np.array([83.4, 83.5], dtype='>f8')
768 little_endian = np.array([83.4, 83.5], dtype='<f8')
769 assert_almost_equal(uradians(big_endian).astype(float),
770 uradians(little_endian).astype(float))
771
772 def test_mem_string_arr(self):
773 # Ticket #514
774 s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
775 t = []
776 np.hstack((t, s))
777
778 def test_arr_transpose(self):
779 # Ticket #516
780 x = np.random.rand(*(2,) * 16)
781 x.transpose(list(range(16))) # Should succeed
782
783 def test_string_mergesort(self):
784 # Ticket #540
785 x = np.array(['a'] * 32)
786 assert_array_equal(x.argsort(kind='m'), np.arange(32))
787
788 def test_argmax_byteorder(self):
789 # Ticket #546
790 a = np.arange(3, dtype='>f')
791 assert_(a[a.argmax()] == a.max())
792
793 def test_rand_seed(self):
794 # Ticket #555
795 for l in np.arange(4):
796 np.random.seed(l)
797
798 def test_mem_deallocation_leak(self):
799 # Ticket #562
800 a = np.zeros(5, dtype=float)
801 b = np.array(a, dtype=float)
802 del a, b
803
804 def test_mem_on_invalid_dtype(self):
805 "Ticket #583"
806 assert_raises(ValueError, np.fromiter, [['12', ''], ['13', '']], str)
807
808 def test_dot_negative_stride(self):
809 # Ticket #588
810 x = np.array([[1, 5, 25, 125., 625]])
811 y = np.array([[20.], [160.], [640.], [1280.], [1024.]])
812 z = y[::-1].copy()
813 y2 = y[::-1]
814 assert_equal(np.dot(x, z), np.dot(x, y2))
815
816 def test_object_casting(self):
817 # This used to trigger the object-type version of
818 # the bitwise_or operation, because float64 -> object
819 # casting succeeds
820 def rs():
821 x = np.ones([484, 286])
822 y = np.zeros([484, 286])
823 x |= y
824
825 assert_raises(TypeError, rs)
826
827 def test_unicode_scalar(self):
828 # Ticket #600
829 x = np.array(["DROND", "DROND1"], dtype="U6")
830 el = x[1]
831 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
832 new = pickle.loads(pickle.dumps(el, protocol=proto))
833 assert_equal(new, el)
834
835 def test_arange_non_native_dtype(self):
836 # Ticket #616
837 for T in ('>f4', '<f4'):
838 dt = np.dtype(T)
839 assert_equal(np.arange(0, dtype=dt).dtype, dt)
840 assert_equal(np.arange(0.5, dtype=dt).dtype, dt)
841 assert_equal(np.arange(5, dtype=dt).dtype, dt)
842
843 def test_bool_flat_indexing_invalid_nr_elements(self):
844 s = np.ones(10, dtype=float)
845 x = np.array((15,), dtype=float)
846
847 def ia(x, s, v):
848 x[(s > 0)] = v
849
850 assert_raises(IndexError, ia, x, s, np.zeros(9, dtype=float))
851 assert_raises(IndexError, ia, x, s, np.zeros(11, dtype=float))
852
853 # Old special case (different code path):
854 assert_raises(IndexError, ia, x.flat, s, np.zeros(9, dtype=float))
855 assert_raises(IndexError, ia, x.flat, s, np.zeros(11, dtype=float))
856
857 def test_mem_scalar_indexing(self):
858 # Ticket #603
859 x = np.array([0], dtype=float)
860 index = np.array(0, dtype=np.int32)
861 x[index]
862
863 def test_binary_repr_0_width(self):
864 assert_equal(np.binary_repr(0, width=3), '000')
865
866 def test_fromstring(self):
867 assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"),
868 [12, 9, 9])
869
870 def test_searchsorted_variable_length(self):
871 x = np.array(['a', 'aa', 'b'])
872 y = np.array(['d', 'e'])
873 assert_equal(x.searchsorted(y), [3, 3])
874
875 def test_string_argsort_with_zeros(self):
876 # Check argsort for strings containing zeros.
877 x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2")
878 assert_array_equal(x.argsort(kind='m'), np.array([1, 0]))
879 assert_array_equal(x.argsort(kind='q'), np.array([1, 0]))
880
881 def test_string_sort_with_zeros(self):
882 # Check sort for strings containing zeros.
883 x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2")
884 y = np.frombuffer(b"\x00\x01\x00\x02", dtype="|S2")
885 assert_array_equal(np.sort(x, kind="q"), y)
886
887 def test_copy_detection_zero_dim(self):
888 # Ticket #658
889 np.indices((0, 3, 4)).T.reshape(-1, 3)
890
891 def test_flat_byteorder(self):
892 # Ticket #657
893 x = np.arange(10)
894 assert_array_equal(x.astype('>i4'), x.astype('<i4').flat[:])
895 assert_array_equal(x.astype('>i4').flat[:], x.astype('<i4'))
896
897 def test_sign_bit(self):
898 x = np.array([0, -0.0, 0])
899 assert_equal(str(np.abs(x)), '[0. 0. 0.]')
900
901 def test_flat_index_byteswap(self):
902 for dt in (np.dtype('<i4'), np.dtype('>i4')):
903 x = np.array([-1, 0, 1], dtype=dt)
904 assert_equal(x.flat[0].dtype, x[0].dtype)
905
906 def test_copy_detection_corner_case(self):
907 # Ticket #658
908 np.indices((0, 3, 4)).T.reshape(-1, 3)
909
910 def test_object_array_refcounting(self):
911 # Ticket #633
912 if not hasattr(sys, 'getrefcount'):
913 return
914
915 # NB. this is probably CPython-specific
916
917 cnt = sys.getrefcount
918
919 a = object()
920 b = object()
921 c = object()
922
923 cnt0_a = cnt(a)
924 cnt0_b = cnt(b)
925 cnt0_c = cnt(c)
926
927 # -- 0d -> 1-d broadcast slice assignment
928
929 arr = np.zeros(5, dtype=np.object_)
930
931 arr[:] = a
932 assert_equal(cnt(a), cnt0_a + 5)
933
934 arr[:] = b
935 assert_equal(cnt(a), cnt0_a)
936 assert_equal(cnt(b), cnt0_b + 5)
937
938 arr[:2] = c
939 assert_equal(cnt(b), cnt0_b + 3)
940 assert_equal(cnt(c), cnt0_c + 2)
941
942 del arr
943
944 # -- 1-d -> 2-d broadcast slice assignment
945
946 arr = np.zeros((5, 2), dtype=np.object_)
947 arr0 = np.zeros(2, dtype=np.object_)
948
949 arr0[0] = a
950 assert_(cnt(a) == cnt0_a + 1)
951 arr0[1] = b
952 assert_(cnt(b) == cnt0_b + 1)
953
954 arr[:, :] = arr0
955 assert_(cnt(a) == cnt0_a + 6)
956 assert_(cnt(b) == cnt0_b + 6)
957
958 arr[:, 0] = None
959 assert_(cnt(a) == cnt0_a + 1)
960
961 del arr, arr0
962
963 # -- 2-d copying + flattening
964
965 arr = np.zeros((5, 2), dtype=np.object_)
966
967 arr[:, 0] = a
968 arr[:, 1] = b
969 assert_(cnt(a) == cnt0_a + 5)
970 assert_(cnt(b) == cnt0_b + 5)
971
972 arr2 = arr.copy()
973 assert_(cnt(a) == cnt0_a + 10)
974 assert_(cnt(b) == cnt0_b + 10)
975
976 arr2 = arr[:, 0].copy()
977 assert_(cnt(a) == cnt0_a + 10)
978 assert_(cnt(b) == cnt0_b + 5)
979
980 arr2 = arr.flatten()
981 assert_(cnt(a) == cnt0_a + 10)
982 assert_(cnt(b) == cnt0_b + 10)
983
984 del arr, arr2
985
986 # -- concatenate, repeat, take, choose
987
988 arr1 = np.zeros((5, 1), dtype=np.object_)
989 arr2 = np.zeros((5, 1), dtype=np.object_)
990
991 arr1[...] = a
992 arr2[...] = b
993 assert_(cnt(a) == cnt0_a + 5)
994 assert_(cnt(b) == cnt0_b + 5)
995
996 tmp = np.concatenate((arr1, arr2))
997 assert_(cnt(a) == cnt0_a + 5 + 5)
998 assert_(cnt(b) == cnt0_b + 5 + 5)
999
1000 tmp = arr1.repeat(3, axis=0)
1001 assert_(cnt(a) == cnt0_a + 5 + 3 * 5)
1002
1003 tmp = arr1.take([1, 2, 3], axis=0)
1004 assert_(cnt(a) == cnt0_a + 5 + 3)
1005
1006 x = np.array([[0], [1], [0], [1], [1]], int)
1007 tmp = x.choose(arr1, arr2)
1008 assert_(cnt(a) == cnt0_a + 5 + 2)
1009 assert_(cnt(b) == cnt0_b + 5 + 3)
1010
1011 def test_mem_custom_float_to_array(self):
1012 # Ticket 702
1013 class MyFloat:
1014 def __float__(self):
1015 return 1.0
1016
1017 tmp = np.atleast_1d([MyFloat()])
1018 tmp.astype(float) # Should succeed
1019
1020 def test_object_array_refcount_self_assign(self):
1021 # Ticket #711
1022 class VictimObject:
1023 deleted = False
1024
1025 def __del__(self):
1026 self.deleted = True
1027
1028 d = VictimObject()
1029 arr = np.zeros(5, dtype=np.object_)
1030 arr[:] = d
1031 del d
1032 arr[:] = arr # refcount of 'd' might hit zero here
1033 assert_(not arr[0].deleted)
1034 arr[:] = arr # trying to induce a segfault by doing it again...
1035 assert_(not arr[0].deleted)
1036
1037 def test_mem_fromiter_invalid_dtype_string(self):
1038 x = [1, 2, 3]
1039 assert_raises(ValueError,
1040 np.fromiter, list(x), dtype='S')
1041
1042 def test_reduce_big_object_array(self):
1043 # Ticket #713
1044 oldsize = np.setbufsize(10 * 16)
1045 a = np.array([None] * 161, object)
1046 assert_(not np.any(a))
1047 np.setbufsize(oldsize)
1048
1049 def test_mem_0d_array_index(self):
1050 # Ticket #714
1051 np.zeros(10)[np.array(0)]
1052
1053 def test_nonnative_endian_fill(self):
1054 # Non-native endian arrays were incorrectly filled with scalars
1055 # before r5034.
1056 if sys.byteorder == 'little':
1057 dtype = np.dtype('>i4')
1058 else:
1059 dtype = np.dtype('<i4')
1060 x = np.empty([1], dtype=dtype)
1061 x.fill(1)
1062 assert_equal(x, np.array([1], dtype=dtype))
1063
1064 def test_dot_alignment_sse2(self):
1065 # Test for ticket #551, changeset r5140
1066 x = np.zeros((30, 40))
1067 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
1068 y = pickle.loads(pickle.dumps(x, protocol=proto))
1069 # y is now typically not aligned on a 8-byte boundary
1070 z = np.ones((1, y.shape[0]))
1071 # This shouldn't cause a segmentation fault:
1072 np.dot(z, y)
1073
1074 @pytest.mark.filterwarnings(
1075 "ignore:.*align should be passed:numpy.exceptions.VisibleDeprecationWarning")
1076 def test_astype_copy(self):
1077 # Ticket #788, changeset r5155
1078 # The test data file was generated by scipy.io.savemat.
1079 # The dtype is float64, but the isbuiltin attribute is 0.
1080 data_dir = path.join(path.dirname(__file__), 'data')
1081 filename = path.join(data_dir, "astype_copy.pkl")
1082 with open(filename, 'rb') as f:
1083 xp = pickle.load(f, encoding='latin1')
1084 xpd = xp.astype(np.float64)
1085 assert_(xp.__array_interface__['data'][0] !=
1086 xpd.__array_interface__['data'][0])
1087
1088 def test_compress_small_type(self):
1089 # Ticket #789, changeset 5217.
1090 # compress with out argument segfaulted if cannot cast safely
1091 import numpy as np
1092 a = np.array([[1, 2], [3, 4]])
1093 b = np.zeros((2, 1), dtype=np.single)
1094 try:
1095 a.compress([True, False], axis=1, out=b)
1096 raise AssertionError("compress with an out which cannot be "
1097 "safely casted should not return "
1098 "successfully")
1099 except TypeError:
1100 pass
1101
1102 def test_attributes(self):
1103 # Ticket #791
1104 class TestArray(np.ndarray):
1105 def __new__(cls, data, info):
1106 result = np.array(data)
1107 result = result.view(cls)
1108 result.info = info
1109 return result
1110
1111 def __array_finalize__(self, obj):
1112 self.info = getattr(obj, 'info', '')
1113
1114 dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba')
1115 assert_(dat.info == 'jubba')
1116 dat.resize((4, 2))
1117 assert_(dat.info == 'jubba')
1118 dat.sort()
1119 assert_(dat.info == 'jubba')
1120 dat.fill(2)
1121 assert_(dat.info == 'jubba')
1122 dat.put([2, 3, 4], [6, 3, 4])
1123 assert_(dat.info == 'jubba')
1124 dat.setfield(4, np.int32, 0)
1125 assert_(dat.info == 'jubba')
1126 dat.setflags()
1127 assert_(dat.info == 'jubba')
1128 assert_(dat.all(1).info == 'jubba')
1129 assert_(dat.any(1).info == 'jubba')
1130 assert_(dat.argmax(1).info == 'jubba')
1131 assert_(dat.argmin(1).info == 'jubba')
1132 assert_(dat.argsort(1).info == 'jubba')
1133 assert_(dat.astype(TestArray).info == 'jubba')
1134 assert_(dat.byteswap().info == 'jubba')
1135 assert_(dat.clip(2, 7).info == 'jubba')
1136 assert_(dat.compress([0, 1, 1]).info == 'jubba')
1137 assert_(dat.conj().info == 'jubba')
1138 assert_(dat.conjugate().info == 'jubba')
1139 assert_(dat.copy().info == 'jubba')
1140 dat2 = TestArray([2, 3, 1, 0], 'jubba')
1141 choices = [[0, 1, 2, 3], [10, 11, 12, 13],
1142 [20, 21, 22, 23], [30, 31, 32, 33]]
1143 assert_(dat2.choose(choices).info == 'jubba')
1144 assert_(dat.cumprod(1).info == 'jubba')
1145 assert_(dat.cumsum(1).info == 'jubba')
1146 assert_(dat.diagonal().info == 'jubba')
1147 assert_(dat.flatten().info == 'jubba')
1148 assert_(dat.getfield(np.int32, 0).info == 'jubba')
1149 assert_(dat.imag.info == 'jubba')
1150 assert_(dat.max(1).info == 'jubba')
1151 assert_(dat.mean(1).info == 'jubba')
1152 assert_(dat.min(1).info == 'jubba')
1153 assert_(dat.prod(1).info == 'jubba')
1154 assert_(dat.ravel().info == 'jubba')
1155 assert_(dat.real.info == 'jubba')
1156 assert_(dat.repeat(2).info == 'jubba')
1157 assert_(dat.reshape((2, 4)).info == 'jubba')
1158 assert_(dat.round().info == 'jubba')
1159 assert_(dat.squeeze().info == 'jubba')
1160 assert_(dat.std(1).info == 'jubba')
1161 assert_(dat.sum(1).info == 'jubba')
1162 assert_(dat.swapaxes(0, 1).info == 'jubba')
1163 assert_(dat.take([2, 3, 5]).info == 'jubba')
1164 assert_(dat.transpose().info == 'jubba')
1165 assert_(dat.T.info == 'jubba')
1166 assert_(dat.var(1).info == 'jubba')
1167 assert_(dat.view(TestArray).info == 'jubba')
1168 # These methods do not preserve subclasses
1169 assert_(type(dat.nonzero()[0]) is np.ndarray)
1170 assert_(type(dat.nonzero()[1]) is np.ndarray)
1171
1172 def test_recarray_tolist(self):
1173 # Ticket #793, changeset r5215
1174 # Comparisons fail for NaN, so we can't use random memory
1175 # for the test.
1176 buf = np.zeros(40, dtype=np.int8)
1177 a = np.recarray(2, formats="i4,f8,f8", names="id,x,y", buf=buf)
1178 b = a.tolist()
1179 assert_(a[0].tolist() == b[0])
1180 assert_(a[1].tolist() == b[1])
1181
1182 def test_nonscalar_item_method(self):
1183 # Make sure that .item() fails graciously when it should
1184 a = np.arange(5)
1185 assert_raises(ValueError, a.item)
1186
1187 def test_char_array_creation(self):
1188 a = np.array('123', dtype='c')
1189 b = np.array([b'1', b'2', b'3'])
1190 assert_equal(a, b)
1191
1192 def test_unaligned_unicode_access(self):
1193 # Ticket #825
1194 for i in range(1, 9):
1195 msg = 'unicode offset: %d chars' % i
1196 t = np.dtype([('a', 'S%d' % i), ('b', 'U2')])
1197 x = np.array([(b'a', 'b')], dtype=t)
1198 assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg)
1199
1200 def test_sign_for_complex_nan(self):
