codekingpro/portable-devtools
115k
1import sys
2
3import pytest
4
5import numpy as np
6import numpy._core.umath as ncu
7from numpy._core._rational_tests import rational
8from numpy.lib import stride_tricks
9from numpy.testing import (
10 HAS_REFCOUNT,
11 assert_,
12 assert_array_equal,
13 assert_equal,
14 assert_raises,
15)
16
17
18def test_array_array():
19 tobj = type(object)
20 ones11 = np.ones((1, 1), np.float64)
21 tndarray = type(ones11)
22 # Test is_ndarray
23 assert_equal(np.array(ones11, dtype=np.float64), ones11)
24 if HAS_REFCOUNT:
25 old_refcount = sys.getrefcount(tndarray)
26 np.array(ones11)
27 assert_equal(old_refcount, sys.getrefcount(tndarray))
28
29 # test None
30 assert_equal(np.array(None, dtype=np.float64),
31 np.array(np.nan, dtype=np.float64))
32 if HAS_REFCOUNT:
33 old_refcount = sys.getrefcount(tobj)
34 np.array(None, dtype=np.float64)
35 assert_equal(old_refcount, sys.getrefcount(tobj))
36
37 # test scalar
38 assert_equal(np.array(1.0, dtype=np.float64),
39 np.ones((), dtype=np.float64))
40 if HAS_REFCOUNT:
41 old_refcount = sys.getrefcount(np.float64)
42 np.array(np.array(1.0, dtype=np.float64), dtype=np.float64)
43 assert_equal(old_refcount, sys.getrefcount(np.float64))
44
45 # test string
46 S2 = np.dtype((bytes, 2))
47 S3 = np.dtype((bytes, 3))
48 S5 = np.dtype((bytes, 5))
49 assert_equal(np.array(b"1.0", dtype=np.float64),
50 np.ones((), dtype=np.float64))
51 assert_equal(np.array(b"1.0").dtype, S3)
52 assert_equal(np.array(b"1.0", dtype=bytes).dtype, S3)
53 assert_equal(np.array(b"1.0", dtype=S2), np.array(b"1."))
54 assert_equal(np.array(b"1", dtype=S5), np.ones((), dtype=S5))
55
56 # test string
57 U2 = np.dtype((str, 2))
58 U3 = np.dtype((str, 3))
59 U5 = np.dtype((str, 5))
60 assert_equal(np.array("1.0", dtype=np.float64),
61 np.ones((), dtype=np.float64))
62 assert_equal(np.array("1.0").dtype, U3)
63 assert_equal(np.array("1.0", dtype=str).dtype, U3)
64 assert_equal(np.array("1.0", dtype=U2), np.array("1."))
65 assert_equal(np.array("1", dtype=U5), np.ones((), dtype=U5))
66
67 builtins = getattr(__builtins__, '__dict__', __builtins__)
68 assert_(hasattr(builtins, 'get'))
69
70 # test memoryview
71 dat = np.array(memoryview(b'1.0'), dtype=np.float64)
72 assert_equal(dat, [49.0, 46.0, 48.0])
73 assert_(dat.dtype.type is np.float64)
74
75 dat = np.array(memoryview(b'1.0'))
76 assert_equal(dat, [49, 46, 48])
77 assert_(dat.dtype.type is np.uint8)
78
79 # test array interface
80 a = np.array(100.0, dtype=np.float64)
81 o = type("o", (object,),
82 {"__array_interface__": a.__array_interface__})
83 assert_equal(np.array(o, dtype=np.float64), a)
84
85 # test array_struct interface
86 a = np.array([(1, 4.0, 'Hello'), (2, 6.0, 'World')],
87 dtype=[('f0', int), ('f1', float), ('f2', str)])
88 o = type("o", (object,),
89 {"__array_struct__": a.__array_struct__})
90 # wasn't what I expected... is np.array(o) supposed to equal a ?
91 # instead we get an array([...], dtype=">V18")
92 assert_equal(bytes(np.array(o).data), bytes(a.data))
93
94 # test __array__
95 def custom__array__(self, dtype=None, copy=None):
96 return np.array(100.0, dtype=dtype, copy=copy)
97
98 o = type("o", (object,), {"__array__": custom__array__})()
99 assert_equal(np.array(o, dtype=np.float64), np.array(100.0, np.float64))
100
101 # test recursion
102 nested = 1.5
103 for i in range(ncu.MAXDIMS):
104 nested = [nested]
105
106 # no error
107 np.array(nested)
108
109 # Exceeds recursion limit
110 assert_raises(ValueError, np.array, [nested], dtype=np.float64)
111
112 # Try with lists...
113 # float32
114 assert_equal(np.array([None] * 10, dtype=np.float32),
115 np.full((10,), np.nan, dtype=np.float32))
116 assert_equal(np.array([[None]] * 10, dtype=np.float32),
117 np.full((10, 1), np.nan, dtype=np.float32))
118 assert_equal(np.array([[None] * 10], dtype=np.float32),
119 np.full((1, 10), np.nan, dtype=np.float32))
120 assert_equal(np.array([[None] * 10] * 10, dtype=np.float32),
121 np.full((10, 10), np.nan, dtype=np.float32))
122 # float64
123 assert_equal(np.array([None] * 10, dtype=np.float64),
124 np.full((10,), np.nan, dtype=np.float64))
125 assert_equal(np.array([[None]] * 10, dtype=np.float64),
126 np.full((10, 1), np.nan, dtype=np.float64))
127 assert_equal(np.array([[None] * 10], dtype=np.float64),
128 np.full((1, 10), np.nan, dtype=np.float64))
129 assert_equal(np.array([[None] * 10] * 10, dtype=np.float64),
130 np.full((10, 10), np.nan, dtype=np.float64))
131
132 assert_equal(np.array([1.0] * 10, dtype=np.float64),
133 np.ones((10,), dtype=np.float64))
134 assert_equal(np.array([[1.0]] * 10, dtype=np.float64),
135 np.ones((10, 1), dtype=np.float64))
136 assert_equal(np.array([[1.0] * 10], dtype=np.float64),
137 np.ones((1, 10), dtype=np.float64))
138 assert_equal(np.array([[1.0] * 10] * 10, dtype=np.float64),
139 np.ones((10, 10), dtype=np.float64))
140
141 # Try with tuples
142 assert_equal(np.array((None,) * 10, dtype=np.float64),
143 np.full((10,), np.nan, dtype=np.float64))
144 assert_equal(np.array([(None,)] * 10, dtype=np.float64),
145 np.full((10, 1), np.nan, dtype=np.float64))
146 assert_equal(np.array([(None,) * 10], dtype=np.float64),
147 np.full((1, 10), np.nan, dtype=np.float64))
148 assert_equal(np.array([(None,) * 10] * 10, dtype=np.float64),
149 np.full((10, 10), np.nan, dtype=np.float64))
150
151 assert_equal(np.array((1.0,) * 10, dtype=np.float64),
152 np.ones((10,), dtype=np.float64))
153 assert_equal(np.array([(1.0,)] * 10, dtype=np.float64),
154 np.ones((10, 1), dtype=np.float64))
155 assert_equal(np.array([(1.0,) * 10], dtype=np.float64),
156 np.ones((1, 10), dtype=np.float64))
157 assert_equal(np.array([(1.0,) * 10] * 10, dtype=np.float64),
158 np.ones((10, 10), dtype=np.float64))
159
160
161@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
162def test___array___refcount():
163 class MyArray:
164 def __init__(self, dtype):
165 self.val = np.array(-1, dtype=dtype)
166
167 def __array__(self, dtype=None, copy=None):
168 return self.val.__array__(dtype=dtype, copy=copy)
169
170 # test all possible scenarios:
171 # dtype(none | same | different) x copy(true | false | none)
172 dt = np.dtype(np.int32)
173 old_refcount = sys.getrefcount(dt)
174 np.array(MyArray(dt))
175 assert_equal(old_refcount, sys.getrefcount(dt))
176 np.array(MyArray(dt), dtype=dt)
177 assert_equal(old_refcount, sys.getrefcount(dt))
178 np.array(MyArray(dt), copy=None)
179 assert_equal(old_refcount, sys.getrefcount(dt))
180 np.array(MyArray(dt), dtype=dt, copy=None)
181 assert_equal(old_refcount, sys.getrefcount(dt))
182 dt2 = np.dtype(np.int16)
183 old_refcount2 = sys.getrefcount(dt2)
184 np.array(MyArray(dt), dtype=dt2)
185 assert_equal(old_refcount2, sys.getrefcount(dt2))
186 np.array(MyArray(dt), dtype=dt2, copy=None)
187 assert_equal(old_refcount2, sys.getrefcount(dt2))
188 with pytest.raises(ValueError):
189 np.array(MyArray(dt), dtype=dt2, copy=False)
190 assert_equal(old_refcount2, sys.getrefcount(dt2))
191
192
193@pytest.mark.parametrize("array", [True, False])
194def test_array_impossible_casts(array):
195 # All builtin types can be forcibly cast, at least theoretically,
196 # but user dtypes cannot necessarily.
197 rt = rational(1, 2)
198 if array:
199 rt = np.array(rt)
200 with assert_raises(TypeError):
201 np.array(rt, dtype="M8")
202
203
204def test_array_astype():
205 a = np.arange(6, dtype='f4').reshape(2, 3)
206 # Default behavior: allows unsafe casts, keeps memory layout,
207 # always copies.
208 b = a.astype('i4')
209 assert_equal(a, b)
210 assert_equal(b.dtype, np.dtype('i4'))
211 assert_equal(a.strides, b.strides)
212 b = a.T.astype('i4')
213 assert_equal(a.T, b)
214 assert_equal(b.dtype, np.dtype('i4'))
215 assert_equal(a.T.strides, b.strides)
216 b = a.astype('f4')
217 assert_equal(a, b)
218 assert_(not (a is b))
219
220 # copy=False parameter skips a copy
221 b = a.astype('f4', copy=False)
222 assert_(a is b)
223
224 # order parameter allows overriding of the memory layout,
225 # forcing a copy if the layout is wrong
226 b = a.astype('f4', order='F', copy=False)
227 assert_equal(a, b)
228 assert_(not (a is b))
229 assert_(b.flags.f_contiguous)
230
231 b = a.astype('f4', order='C', copy=False)
232 assert_equal(a, b)
233 assert_(a is b)
234 assert_(b.flags.c_contiguous)
235
236 # casting parameter allows catching bad casts
237 b = a.astype('c8', casting='safe')
238 assert_equal(a, b)
239 assert_equal(b.dtype, np.dtype('c8'))
240
241 assert_raises(TypeError, a.astype, 'i4', casting='safe')
242
243 # subok=False passes through a non-subclassed array
244 b = a.astype('f4', subok=0, copy=False)
245 assert_(a is b)
246
247 class MyNDArray(np.ndarray):
248 pass
249
250 a = np.array([[0, 1, 2], [3, 4, 5]], dtype='f4').view(MyNDArray)
251
252 # subok=True passes through a subclass
253 b = a.astype('f4', subok=True, copy=False)
254 assert_(a is b)
255
256 # subok=True is default, and creates a subtype on a cast
257 b = a.astype('i4', copy=False)
258 assert_equal(a, b)
259 assert_equal(type(b), MyNDArray)
260
261 # subok=False never returns a subclass
262 b = a.astype('f4', subok=False, copy=False)
263 assert_equal(a, b)
264 assert_(not (a is b))
265 assert_(type(b) is not MyNDArray)
266
267 # Make sure converting from string object to fixed length string
268 # does not truncate.
269 a = np.array([b'a' * 100], dtype='O')
270 b = a.astype('S')
271 assert_equal(a, b)
272 assert_equal(b.dtype, np.dtype('S100'))
273 a = np.array(['a' * 100], dtype='O')
274 b = a.astype('U')
275 assert_equal(a, b)
276 assert_equal(b.dtype, np.dtype('U100'))
277
278 # Same test as above but for strings shorter than 64 characters
279 a = np.array([b'a' * 10], dtype='O')
280 b = a.astype('S')
281 assert_equal(a, b)
282 assert_equal(b.dtype, np.dtype('S10'))
283 a = np.array(['a' * 10], dtype='O')
284 b = a.astype('U')
285 assert_equal(a, b)
286 assert_equal(b.dtype, np.dtype('U10'))
287
288 a = np.array(123456789012345678901234567890, dtype='O').astype('S')
289 assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
290 a = np.array(123456789012345678901234567890, dtype='O').astype('U')
291 assert_array_equal(a, np.array('1234567890' * 3, dtype='U30'))
292
293 a = np.array([123456789012345678901234567890], dtype='O').astype('S')
294 assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
295 a = np.array([123456789012345678901234567890], dtype='O').astype('U')
296 assert_array_equal(a, np.array('1234567890' * 3, dtype='U30'))
297
298 a = np.array(123456789012345678901234567890, dtype='S')
299 assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
300 a = np.array(123456789012345678901234567890, dtype='U')
301 assert_array_equal(a, np.array('1234567890' * 3, dtype='U30'))
302
303 a = np.array('a\u0140', dtype='U')
304 b = np.ndarray(buffer=a, dtype='uint32', shape=2)
305 assert_(b.size == 2)
306
307 a = np.array([1000], dtype='i4')
308 assert_raises(TypeError, a.astype, 'S1', casting='safe')
309
310 a = np.array(1000, dtype='i4')
311 assert_raises(TypeError, a.astype, 'U1', casting='safe')
312
313 # gh-24023
314 assert_raises(TypeError, a.astype)
315
316@pytest.mark.parametrize("dt", ["S", "U"])
317def test_array_astype_to_string_discovery_empty(dt):
318 # See also gh-19085
319 arr = np.array([""], dtype=object)
320 # Note, the itemsize is the `0 -> 1` logic, which should change.
321 # The important part the test is rather that it does not error.
322 assert arr.astype(dt).dtype.itemsize == np.dtype(f"{dt}1").itemsize
323
324 # check the same thing for `np.can_cast` (since it accepts arrays)
325 assert np.can_cast(arr, dt, casting="unsafe")
326 assert not np.can_cast(arr, dt, casting="same_kind")
327 # as well as for the object as a descriptor:
328 assert np.can_cast("O", dt, casting="unsafe")
329
330@pytest.mark.parametrize("dt", ["d", "f", "S13", "U32"])
331def test_array_astype_to_void(dt):
332 dt = np.dtype(dt)
333 arr = np.array([], dtype=dt)
334 assert arr.astype("V").dtype.itemsize == dt.itemsize
335
336def test_object_array_astype_to_void():
337 # This is different to `test_array_astype_to_void` as object arrays
338 # are inspected. The default void is "V8" (8 is the length of double)
339 arr = np.array([], dtype="O").astype("V")
340 assert arr.dtype == "V8"
341
342@pytest.mark.parametrize("t",
343 np._core.sctypes['uint'] +
344 np._core.sctypes['int'] +
345 np._core.sctypes['float']
346)
347def test_array_astype_warning(t):
348 # test ComplexWarning when casting from complex to float or int
349 a = np.array(10, dtype=np.complex128)
350 pytest.warns(np.exceptions.ComplexWarning, a.astype, t)
351
352@pytest.mark.parametrize(["dtype", "out_dtype"],
353 [(np.bytes_, np.bool),
354 (np.str_, np.bool),
355 (np.dtype("S10,S9"), np.dtype("?,?")),
356 # The following also checks unaligned unicode access:
357 (np.dtype("S7,U9"), np.dtype("?,?"))])
358def test_string_to_boolean_cast(dtype, out_dtype):
359 # Only the last two (empty) strings are falsy (the `\0` is stripped):
360 arr = np.array(
361 ["10", "10\0\0\0", "0\0\0", "0", "False", " ", "", "\0"],
362 dtype=dtype)
363 expected = np.array(
364 [True, True, True, True, True, True, False, False],
365 dtype=out_dtype)
366 assert_array_equal(arr.astype(out_dtype), expected)
367 # As it's similar, check that nonzero behaves the same (structs are
368 # nonzero if all entries are)
369 assert_array_equal(np.nonzero(arr), np.nonzero(expected))
370
371@pytest.mark.parametrize("str_type", [str, bytes, np.str_])
372@pytest.mark.parametrize("scalar_type",
373 [np.complex64, np.complex128, np.clongdouble])
374def test_string_to_complex_cast(str_type, scalar_type):
375 value = scalar_type(b"1+3j")
376 assert scalar_type(value) == 1 + 3j
377 assert np.array([value], dtype=object).astype(scalar_type)[()] == 1 + 3j
378 assert np.array(value).astype(scalar_type)[()] == 1 + 3j
379 arr = np.zeros(1, dtype=scalar_type)
380 arr[0] = value
381 assert arr[0] == 1 + 3j
382
383@pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
384def test_none_to_nan_cast(dtype):
385 # Note that at the time of writing this test, the scalar constructors
386 # reject None
387 arr = np.zeros(1, dtype=dtype)
388 arr[0] = None
389 assert np.isnan(arr)[0]
390 assert np.isnan(np.array(None, dtype=dtype))[()]
391 assert np.isnan(np.array([None], dtype=dtype))[0]
392 assert np.isnan(np.array(None).astype(dtype))[()]
393
394def test_copyto_fromscalar():
395 a = np.arange(6, dtype='f4').reshape(2, 3)
396
397 # Simple copy
398 np.copyto(a, 1.5)
399 assert_equal(a, 1.5)
400 np.copyto(a.T, 2.5)
401 assert_equal(a, 2.5)
402
403 # Where-masked copy
404 mask = np.array([[0, 1, 0], [0, 0, 1]], dtype='?')
405 np.copyto(a, 3.5, where=mask)
406 assert_equal(a, [[2.5, 3.5, 2.5], [2.5, 2.5, 3.5]])
407 mask = np.array([[0, 1], [1, 1], [1, 0]], dtype='?')
408 np.copyto(a.T, 4.5, where=mask)
409 assert_equal(a, [[2.5, 4.5, 4.5], [4.5, 4.5, 3.5]])
410
411def test_copyto():
412 a = np.arange(6, dtype='i4').reshape(2, 3)
413
414 # Simple copy
415 np.copyto(a, [[3, 1, 5], [6, 2, 1]])
416 assert_equal(a, [[3, 1, 5], [6, 2, 1]])
417
418 # Overlapping copy should work
419 np.copyto(a[:, :2], a[::-1, 1::-1])
420 assert_equal(a, [[2, 6, 5], [1, 3, 1]])
421
422 # Defaults to 'same_kind' casting
423 assert_raises(TypeError, np.copyto, a, 1.5)
424
425 # Force a copy with 'unsafe' casting, truncating 1.5 to 1
426 np.copyto(a, 1.5, casting='unsafe')
427 assert_equal(a, 1)
428
429 # Copying with a mask
430 np.copyto(a, 3, where=[True, False, True])
431 assert_equal(a, [[3, 1, 3], [3, 1, 3]])
432
433 # Casting rule still applies with a mask
434 assert_raises(TypeError, np.copyto, a, 3.5, where=[True, False, True])
435
436 # Lists of integer 0's and 1's is ok too
437 np.copyto(a, 4.0, casting='unsafe', where=[[0, 1, 1], [1, 0, 0]])
438 assert_equal(a, [[3, 4, 4], [4, 1, 3]])
439
440 # Overlapping copy with mask should work
441 np.copyto(a[:, :2], a[::-1, 1::-1], where=[[0, 1], [1, 1]])
442 assert_equal(a, [[3, 4, 4], [4, 3, 3]])
443
444 # 'dst' must be an array
445 assert_raises(TypeError, np.copyto, [1, 2, 3], [2, 3, 4])
446
447
448def test_copyto_cast_safety():
449 with pytest.raises(TypeError):
450 np.copyto(np.arange(3), 3., casting="safe")
451
452 # Can put integer and float scalars safely (and equiv):
453 np.copyto(np.arange(3), 3, casting="equiv")
454 np.copyto(np.arange(3.), 3., casting="equiv")
455 # And also with less precision safely:
456 np.copyto(np.arange(3, dtype="uint8"), 3, casting="safe")
457 np.copyto(np.arange(3., dtype="float32"), 3., casting="safe")
458
459 # But not equiv:
460 with pytest.raises(TypeError):
461 np.copyto(np.arange(3, dtype="uint8"), 3, casting="equiv")
462
463 with pytest.raises(TypeError):
464 np.copyto(np.arange(3., dtype="float32"), 3., casting="equiv")
465
466 # As a special thing, object is equiv currently:
467 np.copyto(np.arange(3, dtype=object), 3, casting="equiv")
468
469 # The following raises an overflow error/gives a warning but not
470 # type error (due to casting), though:
471 with pytest.raises(OverflowError):
472 np.copyto(np.arange(3), 2**80, casting="safe")
473
474 with pytest.warns(RuntimeWarning):
475 np.copyto(np.arange(3, dtype=np.float32), 2e300, casting="safe")
476
477
478def test_copyto_permut():
479 # test explicit overflow case
480 pad = 500
481 l = [True] * pad + [True, True, True, True]
482 r = np.zeros(len(l) - pad)
483 d = np.ones(len(l) - pad)
484 mask = np.array(l)[pad:]
485 np.copyto(r, d, where=mask[::-1])
486
487 # test all permutation of possible masks, 9 should be sufficient for
488 # current 4 byte unrolled code
489 power = 9
490 d = np.ones(power)
491 for i in range(2**power):
492 r = np.zeros(power)
493 l = [(i & x) != 0 for x in range(power)]
494 mask = np.array(l)
495 np.copyto(r, d, where=mask)
496 assert_array_equal(r == 1, l)
497 assert_equal(r.sum(), sum(l))
498
499 r = np.zeros(power)
500 np.copyto(r, d, where=mask[::-1])
501 assert_array_equal(r == 1, l[::-1])
502 assert_equal(r.sum(), sum(l))
503
504 r = np.zeros(power)
505 np.copyto(r[::2], d[::2], where=mask[::2])
506 assert_array_equal(r[::2] == 1, l[::2])
507 assert_equal(r[::2].sum(), sum(l[::2]))
508
509 r = np.zeros(power)
510 np.copyto(r[::2], d[::2], where=mask[::-2])
511 assert_array_equal(r[::2] == 1, l[::-2])
512 assert_equal(r[::2].sum(), sum(l[::-2]))
513
514 for c in [0xFF, 0x7F, 0x02, 0x10]:
515 r = np.zeros(power)
516 mask = np.array(l)
517 imask = np.array(l).view(np.uint8)
518 imask[mask != 0] = c
519 np.copyto(r, d, where=mask)
520 assert_array_equal(r == 1, l)
521 assert_equal(r.sum(), sum(l))
522
523 r = np.zeros(power)
524 np.copyto(r, d, where=True)
525 assert_equal(r.sum(), r.size)
526 r = np.ones(power)
527 d = np.zeros(power)
528 np.copyto(r, d, where=False)
529 assert_equal(r.sum(), r.size)
530
531def test_copy_order():
532 a = np.arange(24).reshape(2, 1, 3, 4)
533 b = a.copy(order='F')
534 c = np.arange(24).reshape(2, 1, 4, 3).swapaxes(2, 3)
535
536 def check_copy_result(x, y, ccontig, fcontig, strides=False):
537 assert_(not (x is y))
538 assert_equal(x, y)
539 assert_equal(res.flags.c_contiguous, ccontig)
540 assert_equal(res.flags.f_contiguous, fcontig)
541
542 # Validate the initial state of a, b, and c
543 assert_(a.flags.c_contiguous)
544 assert_(not a.flags.f_contiguous)
545 assert_(not b.flags.c_contiguous)
546 assert_(b.flags.f_contiguous)
547 assert_(not c.flags.c_contiguous)
548 assert_(not c.flags.f_contiguous)
549
550 # Copy with order='C'
551 res = a.copy(order='C')
552 check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
553 res = b.copy(order='C')
554 check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)
555 res = c.copy(order='C')
556 check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)
557 res = np.copy(a, order='C')
558 check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
559 res = np.copy(b, order='C')
560 check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)
561 res = np.copy(c, order='C')
562 check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)
563
564 # Copy with order='F'
565 res = a.copy(order='F')
566 check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)
567 res = b.copy(order='F')
568 check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
569 res = c.copy(order='F')
570 check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)
571 res = np.copy(a, order='F')
572 check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)
573 res = np.copy(b, order='F')
574 check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
575 res = np.copy(c, order='F')
576 check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)
577
578 # Copy with order='K'
579 res = a.copy(order='K')
580 check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
581 res = b.copy(order='K')
582 check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
583 res = c.copy(order='K')
584 check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)
585 res = np.copy(a, order='K')
586 check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
587 res = np.copy(b, order='K')
588 check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
589 res = np.copy(c, order='K')
590 check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)
591
592def test_contiguous_flags():
593 a = np.ones((4, 4, 1))[::2, :, :]
594 a = stride_tricks.as_strided(a, strides=a.strides[:2] + (-123,))
595 b = np.ones((2, 2, 1, 2, 2)).swapaxes(3, 4)
596
597 def check_contig(a, ccontig, fcontig):
598 assert_(a.flags.c_contiguous == ccontig)
599 assert_(a.flags.f_contiguous == fcontig)
600
601 # Check if new arrays are correct:
602 check_contig(a, False, False)
603 check_contig(b, False, False)
604 check_contig(np.empty((2, 2, 0, 2, 2)), True, True)
605 check_contig(np.array([[[1], [2]]], order='F'), True, True)
606 check_contig(np.empty((2, 2)), True, False)
607 check_contig(np.empty((2, 2), order='F'), False, True)
608
609 # Check that np.array creates correct contiguous flags:
610 check_contig(np.array(a, copy=None), False, False)
611 check_contig(np.array(a, copy=None, order='C'), True, False)
612 check_contig(np.array(a, ndmin=4, copy=None, order='F'), False, True)
613
614 # Check slicing update of flags and :
615 check_contig(a[0], True, True)
616 check_contig(a[None, ::4, ..., None], True, True)
617 check_contig(b[0, 0, ...], False, True)
618 check_contig(b[:, :, 0:0, :, :], True, True)
619
620 # Test ravel and squeeze.
621 check_contig(a.ravel(), True, True)
622 check_contig(np.ones((1, 3, 1)).squeeze(), True, True)
623
624def test_broadcast_arrays():
625 # Test user defined dtypes
626 dtype = 'u4,u4,u4'
627 a = np.array([(1, 2, 3)], dtype=dtype)
628 b = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=dtype)
629 result = np.broadcast_arrays(a, b)
630 assert_equal(result[0], np.array([(1, 2, 3), (1, 2, 3), (1, 2, 3)], dtype=dtype))
631 assert_equal(result[1], np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=dtype))
632
633@pytest.mark.parametrize(["shape", "fill_value", "expected_output"],
634 [((2, 2), [5.0, 6.0], np.array([[5.0, 6.0], [5.0, 6.0]])),
635 ((3, 2), [1.0, 2.0], np.array([[1.0, 2.0], [1.0, 2.0], [1.0, 2.0]]))])
636def test_full_from_list(shape, fill_value, expected_output):
637 output = np.full(shape, fill_value)
638 assert_equal(output, expected_output)
639
640def test_astype_copyflag():
641 # test the various copyflag options
642 arr = np.arange(10, dtype=np.intp)
643
644 res_true = arr.astype(np.intp, copy=True)
645 assert not np.shares_memory(arr, res_true)
646
647 res_false = arr.astype(np.intp, copy=False)
648 assert np.shares_memory(arr, res_false)
649
650 res_false_float = arr.astype(np.float64, copy=False)
651 assert not np.shares_memory(arr, res_false_float)
652
653 # _CopyMode enum isn't allowed
654 assert_raises(ValueError, arr.astype, np.float64,
655 copy=np._CopyMode.NEVER)
656 