test_api.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import sys
  2. import numpy as np
  3. from numpy.core._rational_tests import rational
  4. import pytest
  5. from numpy.testing import (
  6. assert_, assert_equal, assert_array_equal, assert_raises, assert_warns,
  7. HAS_REFCOUNT
  8. )
  9. def test_array_array():
  10. tobj = type(object)
  11. ones11 = np.ones((1, 1), np.float64)
  12. tndarray = type(ones11)
  13. # Test is_ndarray
  14. assert_equal(np.array(ones11, dtype=np.float64), ones11)
  15. if HAS_REFCOUNT:
  16. old_refcount = sys.getrefcount(tndarray)
  17. np.array(ones11)
  18. assert_equal(old_refcount, sys.getrefcount(tndarray))
  19. # test None
  20. assert_equal(np.array(None, dtype=np.float64),
  21. np.array(np.nan, dtype=np.float64))
  22. if HAS_REFCOUNT:
  23. old_refcount = sys.getrefcount(tobj)
  24. np.array(None, dtype=np.float64)
  25. assert_equal(old_refcount, sys.getrefcount(tobj))
  26. # test scalar
  27. assert_equal(np.array(1.0, dtype=np.float64),
  28. np.ones((), dtype=np.float64))
  29. if HAS_REFCOUNT:
  30. old_refcount = sys.getrefcount(np.float64)
  31. np.array(np.array(1.0, dtype=np.float64), dtype=np.float64)
  32. assert_equal(old_refcount, sys.getrefcount(np.float64))
  33. # test string
  34. S2 = np.dtype((bytes, 2))
  35. S3 = np.dtype((bytes, 3))
  36. S5 = np.dtype((bytes, 5))
  37. assert_equal(np.array(b"1.0", dtype=np.float64),
  38. np.ones((), dtype=np.float64))
  39. assert_equal(np.array(b"1.0").dtype, S3)
  40. assert_equal(np.array(b"1.0", dtype=bytes).dtype, S3)
  41. assert_equal(np.array(b"1.0", dtype=S2), np.array(b"1."))
  42. assert_equal(np.array(b"1", dtype=S5), np.ones((), dtype=S5))
  43. # test string
  44. U2 = np.dtype((str, 2))
  45. U3 = np.dtype((str, 3))
  46. U5 = np.dtype((str, 5))
  47. assert_equal(np.array("1.0", dtype=np.float64),
  48. np.ones((), dtype=np.float64))
  49. assert_equal(np.array("1.0").dtype, U3)
  50. assert_equal(np.array("1.0", dtype=str).dtype, U3)
  51. assert_equal(np.array("1.0", dtype=U2), np.array(str("1.")))
  52. assert_equal(np.array("1", dtype=U5), np.ones((), dtype=U5))
  53. builtins = getattr(__builtins__, '__dict__', __builtins__)
  54. assert_(hasattr(builtins, 'get'))
  55. # test memoryview
  56. dat = np.array(memoryview(b'1.0'), dtype=np.float64)
  57. assert_equal(dat, [49.0, 46.0, 48.0])
  58. assert_(dat.dtype.type is np.float64)
  59. dat = np.array(memoryview(b'1.0'))
  60. assert_equal(dat, [49, 46, 48])
  61. assert_(dat.dtype.type is np.uint8)
  62. # test array interface
  63. a = np.array(100.0, dtype=np.float64)
  64. o = type("o", (object,),
  65. dict(__array_interface__=a.__array_interface__))
  66. assert_equal(np.array(o, dtype=np.float64), a)
  67. # test array_struct interface
  68. a = np.array([(1, 4.0, 'Hello'), (2, 6.0, 'World')],
  69. dtype=[('f0', int), ('f1', float), ('f2', str)])
  70. o = type("o", (object,),
  71. dict(__array_struct__=a.__array_struct__))
  72. ## wasn't what I expected... is np.array(o) supposed to equal a ?
  73. ## instead we get a array([...], dtype=">V18")
  74. assert_equal(bytes(np.array(o).data), bytes(a.data))
  75. # test array
  76. o = type("o", (object,),
  77. dict(__array__=lambda *x: np.array(100.0, dtype=np.float64)))()
  78. assert_equal(np.array(o, dtype=np.float64), np.array(100.0, np.float64))
  79. # test recursion
  80. nested = 1.5
  81. for i in range(np.MAXDIMS):
  82. nested = [nested]
  83. # no error
  84. np.array(nested)
  85. # Exceeds recursion limit
  86. assert_raises(ValueError, np.array, [nested], dtype=np.float64)
  87. # Try with lists...
  88. assert_equal(np.array([None] * 10, dtype=np.float64),
  89. np.full((10,), np.nan, dtype=np.float64))
  90. assert_equal(np.array([[None]] * 10, dtype=np.float64),
  91. np.full((10, 1), np.nan, dtype=np.float64))
  92. assert_equal(np.array([[None] * 10], dtype=np.float64),
  93. np.full((1, 10), np.nan, dtype=np.float64))
  94. assert_equal(np.array([[None] * 10] * 10, dtype=np.float64),
  95. np.full((10, 10), np.nan, dtype=np.float64))
  96. assert_equal(np.array([1.0] * 10, dtype=np.float64),
  97. np.ones((10,), dtype=np.float64))
  98. assert_equal(np.array([[1.0]] * 10, dtype=np.float64),
  99. np.ones((10, 1), dtype=np.float64))
  100. assert_equal(np.array([[1.0] * 10], dtype=np.float64),
  101. np.ones((1, 10), dtype=np.float64))
  102. assert_equal(np.array([[1.0] * 10] * 10, dtype=np.float64),
  103. np.ones((10, 10), dtype=np.float64))
  104. # Try with tuples
  105. assert_equal(np.array((None,) * 10, dtype=np.float64),
  106. np.full((10,), np.nan, dtype=np.float64))
  107. assert_equal(np.array([(None,)] * 10, dtype=np.float64),
  108. np.full((10, 1), np.nan, dtype=np.float64))
  109. assert_equal(np.array([(None,) * 10], dtype=np.float64),
  110. np.full((1, 10), np.nan, dtype=np.float64))
  111. assert_equal(np.array([(None,) * 10] * 10, dtype=np.float64),
  112. np.full((10, 10), np.nan, dtype=np.float64))
  113. assert_equal(np.array((1.0,) * 10, dtype=np.float64),
  114. np.ones((10,), dtype=np.float64))
  115. assert_equal(np.array([(1.0,)] * 10, dtype=np.float64),
  116. np.ones((10, 1), dtype=np.float64))
  117. assert_equal(np.array([(1.0,) * 10], dtype=np.float64),
  118. np.ones((1, 10), dtype=np.float64))
  119. assert_equal(np.array([(1.0,) * 10] * 10, dtype=np.float64),
  120. np.ones((10, 10), dtype=np.float64))
  121. @pytest.mark.parametrize("array", [True, False])
  122. def test_array_impossible_casts(array):
  123. # All builtin types can be forcibly cast, at least theoretically,
  124. # but user dtypes cannot necessarily.
  125. rt = rational(1, 2)
  126. if array:
  127. rt = np.array(rt)
  128. with assert_raises(TypeError):
  129. np.array(rt, dtype="M8")
  130. # TODO: remove when fastCopyAndTranspose deprecation expires
  131. @pytest.mark.parametrize("a",
  132. (
  133. np.array(2), # 0D array
  134. np.array([3, 2, 7, 0]), # 1D array
  135. np.arange(6).reshape(2, 3) # 2D array
  136. ),
  137. )
  138. def test_fastCopyAndTranspose(a):
  139. with pytest.deprecated_call():
  140. b = np.fastCopyAndTranspose(a)
  141. assert_equal(b, a.T)
  142. assert b.flags.owndata
  143. def test_array_astype():
  144. a = np.arange(6, dtype='f4').reshape(2, 3)
  145. # Default behavior: allows unsafe casts, keeps memory layout,
  146. # always copies.
  147. b = a.astype('i4')
  148. assert_equal(a, b)
  149. assert_equal(b.dtype, np.dtype('i4'))
  150. assert_equal(a.strides, b.strides)
  151. b = a.T.astype('i4')
  152. assert_equal(a.T, b)
  153. assert_equal(b.dtype, np.dtype('i4'))
  154. assert_equal(a.T.strides, b.strides)
  155. b = a.astype('f4')
  156. assert_equal(a, b)
  157. assert_(not (a is b))
  158. # copy=False parameter can sometimes skip a copy
  159. b = a.astype('f4', copy=False)
  160. assert_(a is b)
  161. # order parameter allows overriding of the memory layout,
  162. # forcing a copy if the layout is wrong
  163. b = a.astype('f4', order='F', copy=False)
  164. assert_equal(a, b)
  165. assert_(not (a is b))
  166. assert_(b.flags.f_contiguous)
  167. b = a.astype('f4', order='C', copy=False)
  168. assert_equal(a, b)
  169. assert_(a is b)
  170. assert_(b.flags.c_contiguous)
  171. # casting parameter allows catching bad casts
  172. b = a.astype('c8', casting='safe')
  173. assert_equal(a, b)
  174. assert_equal(b.dtype, np.dtype('c8'))
  175. assert_raises(TypeError, a.astype, 'i4', casting='safe')
  176. # subok=False passes through a non-subclassed array
  177. b = a.astype('f4', subok=0, copy=False)
  178. assert_(a is b)
  179. class MyNDArray(np.ndarray):
  180. pass
  181. a = np.array([[0, 1, 2], [3, 4, 5]], dtype='f4').view(MyNDArray)
  182. # subok=True passes through a subclass
  183. b = a.astype('f4', subok=True, copy=False)
  184. assert_(a is b)
  185. # subok=True is default, and creates a subtype on a cast
  186. b = a.astype('i4', copy=False)
  187. assert_equal(a, b)
  188. assert_equal(type(b), MyNDArray)
  189. # subok=False never returns a subclass
  190. b = a.astype('f4', subok=False, copy=False)
  191. assert_equal(a, b)
  192. assert_(not (a is b))
  193. assert_(type(b) is not MyNDArray)
  194. # Make sure converting from string object to fixed length string
  195. # does not truncate.
  196. a = np.array([b'a'*100], dtype='O')
  197. b = a.astype('S')
  198. assert_equal(a, b)
  199. assert_equal(b.dtype, np.dtype('S100'))
  200. a = np.array(['a'*100], dtype='O')
  201. b = a.astype('U')
  202. assert_equal(a, b)
  203. assert_equal(b.dtype, np.dtype('U100'))
  204. # Same test as above but for strings shorter than 64 characters
  205. a = np.array([b'a'*10], dtype='O')
  206. b = a.astype('S')
  207. assert_equal(a, b)
  208. assert_equal(b.dtype, np.dtype('S10'))
  209. a = np.array(['a'*10], dtype='O')
  210. b = a.astype('U')
  211. assert_equal(a, b)
  212. assert_equal(b.dtype, np.dtype('U10'))
  213. a = np.array(123456789012345678901234567890, dtype='O').astype('S')
  214. assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
  215. a = np.array(123456789012345678901234567890, dtype='O').astype('U')
  216. assert_array_equal(a, np.array('1234567890' * 3, dtype='U30'))
  217. a = np.array([123456789012345678901234567890], dtype='O').astype('S')
  218. assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
  219. a = np.array([123456789012345678901234567890], dtype='O').astype('U')
  220. assert_array_equal(a, np.array('1234567890' * 3, dtype='U30'))
  221. a = np.array(123456789012345678901234567890, dtype='S')
  222. assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
  223. a = np.array(123456789012345678901234567890, dtype='U')
  224. assert_array_equal(a, np.array('1234567890' * 3, dtype='U30'))
  225. a = np.array('a\u0140', dtype='U')
  226. b = np.ndarray(buffer=a, dtype='uint32', shape=2)
  227. assert_(b.size == 2)
  228. a = np.array([1000], dtype='i4')
  229. assert_raises(TypeError, a.astype, 'S1', casting='safe')
  230. a = np.array(1000, dtype='i4')
  231. assert_raises(TypeError, a.astype, 'U1', casting='safe')
  232. @pytest.mark.parametrize("dt", ["S", "U"])
  233. def test_array_astype_to_string_discovery_empty(dt):
  234. # See also gh-19085
  235. arr = np.array([""], dtype=object)
  236. # Note, the itemsize is the `0 -> 1` logic, which should change.
  237. # The important part the test is rather that it does not error.
  238. assert arr.astype(dt).dtype.itemsize == np.dtype(f"{dt}1").itemsize
  239. # check the same thing for `np.can_cast` (since it accepts arrays)
  240. assert np.can_cast(arr, dt, casting="unsafe")
  241. assert not np.can_cast(arr, dt, casting="same_kind")
  242. # as well as for the object as a descriptor:
  243. assert np.can_cast("O", dt, casting="unsafe")
  244. @pytest.mark.parametrize("dt", ["d", "f", "S13", "U32"])
  245. def test_array_astype_to_void(dt):
  246. dt = np.dtype(dt)
  247. arr = np.array([], dtype=dt)
  248. assert arr.astype("V").dtype.itemsize == dt.itemsize
  249. def test_object_array_astype_to_void():
  250. # This is different to `test_array_astype_to_void` as object arrays
  251. # are inspected. The default void is "V8" (8 is the length of double)
  252. arr = np.array([], dtype="O").astype("V")
  253. assert arr.dtype == "V8"
  254. @pytest.mark.parametrize("t",
  255. np.sctypes['uint'] + np.sctypes['int'] + np.sctypes['float']
  256. )
  257. def test_array_astype_warning(t):
  258. # test ComplexWarning when casting from complex to float or int
  259. a = np.array(10, dtype=np.complex_)
  260. assert_warns(np.ComplexWarning, a.astype, t)
  261. @pytest.mark.parametrize(["dtype", "out_dtype"],
  262. [(np.bytes_, np.bool_),
  263. (np.unicode_, np.bool_),
  264. (np.dtype("S10,S9"), np.dtype("?,?"))])
  265. def test_string_to_boolean_cast(dtype, out_dtype):
  266. """
  267. Currently, for `astype` strings are cast to booleans effectively by
  268. calling `bool(int(string)`. This is not consistent (see gh-9875) and
  269. will eventually be deprecated.
  270. """
  271. arr = np.array(["10", "10\0\0\0", "0\0\0", "0"], dtype=dtype)
  272. expected = np.array([True, True, False, False], dtype=out_dtype)
  273. assert_array_equal(arr.astype(out_dtype), expected)
  274. @pytest.mark.parametrize(["dtype", "out_dtype"],
  275. [(np.bytes_, np.bool_),
  276. (np.unicode_, np.bool_),
  277. (np.dtype("S10,S9"), np.dtype("?,?"))])
  278. def test_string_to_boolean_cast_errors(dtype, out_dtype):
  279. """
  280. These currently error out, since cast to integers fails, but should not
  281. error out in the future.
  282. """
  283. for invalid in ["False", "True", "", "\0", "non-empty"]:
  284. arr = np.array([invalid], dtype=dtype)
  285. with assert_raises(ValueError):
  286. arr.astype(out_dtype)
  287. @pytest.mark.parametrize("str_type", [str, bytes, np.str_, np.unicode_])
  288. @pytest.mark.parametrize("scalar_type",
  289. [np.complex64, np.complex128, np.clongdouble])
  290. def test_string_to_complex_cast(str_type, scalar_type):
  291. value = scalar_type(b"1+3j")
  292. assert scalar_type(value) == 1+3j
  293. assert np.array([value], dtype=object).astype(scalar_type)[()] == 1+3j
  294. assert np.array(value).astype(scalar_type)[()] == 1+3j
  295. arr = np.zeros(1, dtype=scalar_type)
  296. arr[0] = value
  297. assert arr[0] == 1+3j
  298. @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
  299. def test_none_to_nan_cast(dtype):
  300. # Note that at the time of writing this test, the scalar constructors
  301. # reject None
  302. arr = np.zeros(1, dtype=dtype)
  303. arr[0] = None
  304. assert np.isnan(arr)[0]
  305. assert np.isnan(np.array(None, dtype=dtype))[()]
  306. assert np.isnan(np.array([None], dtype=dtype))[0]
  307. assert np.isnan(np.array(None).astype(dtype))[()]
  308. def test_copyto_fromscalar():
  309. a = np.arange(6, dtype='f4').reshape(2, 3)
  310. # Simple copy
  311. np.copyto(a, 1.5)
  312. assert_equal(a, 1.5)
  313. np.copyto(a.T, 2.5)
  314. assert_equal(a, 2.5)
  315. # Where-masked copy
  316. mask = np.array([[0, 1, 0], [0, 0, 1]], dtype='?')
  317. np.copyto(a, 3.5, where=mask)
  318. assert_equal(a, [[2.5, 3.5, 2.5], [2.5, 2.5, 3.5]])
  319. mask = np.array([[0, 1], [1, 1], [1, 0]], dtype='?')
  320. np.copyto(a.T, 4.5, where=mask)
  321. assert_equal(a, [[2.5, 4.5, 4.5], [4.5, 4.5, 3.5]])
  322. def test_copyto():
  323. a = np.arange(6, dtype='i4').reshape(2, 3)
  324. # Simple copy
  325. np.copyto(a, [[3, 1, 5], [6, 2, 1]])
  326. assert_equal(a, [[3, 1, 5], [6, 2, 1]])
  327. # Overlapping copy should work
  328. np.copyto(a[:, :2], a[::-1, 1::-1])
  329. assert_equal(a, [[2, 6, 5], [1, 3, 1]])
  330. # Defaults to 'same_kind' casting
  331. assert_raises(TypeError, np.copyto, a, 1.5)
  332. # Force a copy with 'unsafe' casting, truncating 1.5 to 1
  333. np.copyto(a, 1.5, casting='unsafe')
  334. assert_equal(a, 1)
  335. # Copying with a mask
  336. np.copyto(a, 3, where=[True, False, True])
  337. assert_equal(a, [[3, 1, 3], [3, 1, 3]])
  338. # Casting rule still applies with a mask
  339. assert_raises(TypeError, np.copyto, a, 3.5, where=[True, False, True])
  340. # Lists of integer 0's and 1's is ok too
  341. np.copyto(a, 4.0, casting='unsafe', where=[[0, 1, 1], [1, 0, 0]])
  342. assert_equal(a, [[3, 4, 4], [4, 1, 3]])
  343. # Overlapping copy with mask should work
  344. np.copyto(a[:, :2], a[::-1, 1::-1], where=[[0, 1], [1, 1]])
  345. assert_equal(a, [[3, 4, 4], [4, 3, 3]])
  346. # 'dst' must be an array
  347. assert_raises(TypeError, np.copyto, [1, 2, 3], [2, 3, 4])
  348. def test_copyto_permut():
  349. # test explicit overflow case
  350. pad = 500
  351. l = [True] * pad + [True, True, True, True]
  352. r = np.zeros(len(l)-pad)
  353. d = np.ones(len(l)-pad)
  354. mask = np.array(l)[pad:]
  355. np.copyto(r, d, where=mask[::-1])
  356. # test all permutation of possible masks, 9 should be sufficient for
  357. # current 4 byte unrolled code
  358. power = 9
  359. d = np.ones(power)
  360. for i in range(2**power):
  361. r = np.zeros(power)
  362. l = [(i & x) != 0 for x in range(power)]
  363. mask = np.array(l)
  364. np.copyto(r, d, where=mask)
  365. assert_array_equal(r == 1, l)
  366. assert_equal(r.sum(), sum(l))
  367. r = np.zeros(power)
  368. np.copyto(r, d, where=mask[::-1])
  369. assert_array_equal(r == 1, l[::-1])
  370. assert_equal(r.sum(), sum(l))
  371. r = np.zeros(power)
  372. np.copyto(r[::2], d[::2], where=mask[::2])
  373. assert_array_equal(r[::2] == 1, l[::2])
  374. assert_equal(r[::2].sum(), sum(l[::2]))
  375. r = np.zeros(power)
  376. np.copyto(r[::2], d[::2], where=mask[::-2])
  377. assert_array_equal(r[::2] == 1, l[::-2])
  378. assert_equal(r[::2].sum(), sum(l[::-2]))
  379. for c in [0xFF, 0x7F, 0x02, 0x10]:
  380. r = np.zeros(power)
  381. mask = np.array(l)
  382. imask = np.array(l).view(np.uint8)
  383. imask[mask != 0] = c
  384. np.copyto(r, d, where=mask)
  385. assert_array_equal(r == 1, l)
  386. assert_equal(r.sum(), sum(l))
  387. r = np.zeros(power)
  388. np.copyto(r, d, where=True)
  389. assert_equal(r.sum(), r.size)
  390. r = np.ones(power)
  391. d = np.zeros(power)
  392. np.copyto(r, d, where=False)
  393. assert_equal(r.sum(), r.size)
  394. def test_copy_order():
  395. a = np.arange(24).reshape(2, 1, 3, 4)
  396. b = a.copy(order='F')
  397. c = np.arange(24).reshape(2, 1, 4, 3).swapaxes(2, 3)
  398. def check_copy_result(x, y, ccontig, fcontig, strides=False):
  399. assert_(not (x is y))
  400. assert_equal(x, y)
  401. assert_equal(res.flags.c_contiguous, ccontig)
  402. assert_equal(res.flags.f_contiguous, fcontig)
  403. # Validate the initial state of a, b, and c
  404. assert_(a.flags.c_contiguous)
  405. assert_(not a.flags.f_contiguous)
  406. assert_(not b.flags.c_contiguous)
  407. assert_(b.flags.f_contiguous)
  408. assert_(not c.flags.c_contiguous)
  409. assert_(not c.flags.f_contiguous)
  410. # Copy with order='C'
  411. res = a.copy(order='C')
  412. check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
  413. res = b.copy(order='C')
  414. check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)
  415. res = c.copy(order='C')
  416. check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)
  417. res = np.copy(a, order='C')
  418. check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
  419. res = np.copy(b, order='C')
  420. check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)
  421. res = np.copy(c, order='C')
  422. check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)
  423. # Copy with order='F'
  424. res = a.copy(order='F')
  425. check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)
  426. res = b.copy(order='F')
  427. check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
  428. res = c.copy(order='F')
  429. check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)
  430. res = np.copy(a, order='F')
  431. check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)
  432. res = np.copy(b, order='F')
  433. check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
  434. res = np.copy(c, order='F')
  435. check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)
  436. # Copy with order='K'
  437. res = a.copy(order='K')
  438. check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
  439. res = b.copy(order='K')
  440. check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
  441. res = c.copy(order='K')
  442. check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)
  443. res = np.copy(a, order='K')
  444. check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
  445. res = np.copy(b, order='K')
  446. check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
  447. res = np.copy(c, order='K')
  448. check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)
  449. def test_contiguous_flags():
  450. a = np.ones((4, 4, 1))[::2,:,:]
  451. a.strides = a.strides[:2] + (-123,)
  452. b = np.ones((2, 2, 1, 2, 2)).swapaxes(3, 4)
  453. def check_contig(a, ccontig, fcontig):
  454. assert_(a.flags.c_contiguous == ccontig)
  455. assert_(a.flags.f_contiguous == fcontig)
  456. # Check if new arrays are correct:
  457. check_contig(a, False, False)
  458. check_contig(b, False, False)
  459. check_contig(np.empty((2, 2, 0, 2, 2)), True, True)
  460. check_contig(np.array([[[1], [2]]], order='F'), True, True)
  461. check_contig(np.empty((2, 2)), True, False)
  462. check_contig(np.empty((2, 2), order='F'), False, True)
  463. # Check that np.array creates correct contiguous flags:
  464. check_contig(np.array(a, copy=False), False, False)
  465. check_contig(np.array(a, copy=False, order='C'), True, False)
  466. check_contig(np.array(a, ndmin=4, copy=False, order='F'), False, True)
  467. # Check slicing update of flags and :
  468. check_contig(a[0], True, True)
  469. check_contig(a[None, ::4, ..., None], True, True)
  470. check_contig(b[0, 0, ...], False, True)
  471. check_contig(b[:, :, 0:0, :, :], True, True)
  472. # Test ravel and squeeze.
  473. check_contig(a.ravel(), True, True)
  474. check_contig(np.ones((1, 3, 1)).squeeze(), True, True)
  475. def test_broadcast_arrays():
  476. # Test user defined dtypes
  477. a = np.array([(1, 2, 3)], dtype='u4,u4,u4')
  478. b = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4')
  479. result = np.broadcast_arrays(a, b)
  480. assert_equal(result[0], np.array([(1, 2, 3), (1, 2, 3), (1, 2, 3)], dtype='u4,u4,u4'))
  481. assert_equal(result[1], np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4'))
  482. @pytest.mark.parametrize(["shape", "fill_value", "expected_output"],
  483. [((2, 2), [5.0, 6.0], np.array([[5.0, 6.0], [5.0, 6.0]])),
  484. ((3, 2), [1.0, 2.0], np.array([[1.0, 2.0], [1.0, 2.0], [1.0, 2.0]]))])
  485. def test_full_from_list(shape, fill_value, expected_output):
  486. output = np.full(shape, fill_value)
  487. assert_equal(output, expected_output)
  488. def test_astype_copyflag():
  489. # test the various copyflag options
  490. arr = np.arange(10, dtype=np.intp)
  491. res_true = arr.astype(np.intp, copy=True)
  492. assert not np.may_share_memory(arr, res_true)
  493. res_always = arr.astype(np.intp, copy=np._CopyMode.ALWAYS)
  494. assert not np.may_share_memory(arr, res_always)
  495. res_false = arr.astype(np.intp, copy=False)
  496. # `res_false is arr` currently, but check `may_share_memory`.
  497. assert np.may_share_memory(arr, res_false)
  498. res_if_needed = arr.astype(np.intp, copy=np._CopyMode.IF_NEEDED)
  499. # `res_if_needed is arr` currently, but check `may_share_memory`.
  500. assert np.may_share_memory(arr, res_if_needed)
  501. res_never = arr.astype(np.intp, copy=np._CopyMode.NEVER)
  502. assert np.may_share_memory(arr, res_never)
  503. # Simple tests for when a copy is necessary:
  504. res_false = arr.astype(np.float64, copy=False)
  505. assert_array_equal(res_false, arr)
  506. res_if_needed = arr.astype(np.float64,
  507. copy=np._CopyMode.IF_NEEDED)
  508. assert_array_equal(res_if_needed, arr)
  509. assert_raises(ValueError, arr.astype, np.float64,
  510. copy=np._CopyMode.NEVER)