test_api.py 21 KB

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