test_array_from_pyobj.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. import os
  2. import sys
  3. import copy
  4. import pytest
  5. import numpy as np
  6. from numpy.testing import assert_, assert_equal
  7. from numpy.core.multiarray import typeinfo
  8. from . import util
  9. wrap = None
  10. def setup_module():
  11. """
  12. Build the required testing extension module
  13. """
  14. global wrap
  15. # Check compiler availability first
  16. if not util.has_c_compiler():
  17. pytest.skip("No C compiler available")
  18. if wrap is None:
  19. config_code = """
  20. config.add_extension('test_array_from_pyobj_ext',
  21. sources=['wrapmodule.c', 'fortranobject.c'],
  22. define_macros=[])
  23. """
  24. d = os.path.dirname(__file__)
  25. src = [os.path.join(d, 'src', 'array_from_pyobj', 'wrapmodule.c'),
  26. os.path.join(d, '..', 'src', 'fortranobject.c'),
  27. os.path.join(d, '..', 'src', 'fortranobject.h')]
  28. wrap = util.build_module_distutils(src, config_code,
  29. 'test_array_from_pyobj_ext')
  30. def flags_info(arr):
  31. flags = wrap.array_attrs(arr)[6]
  32. return flags2names(flags)
  33. def flags2names(flags):
  34. info = []
  35. for flagname in ['CONTIGUOUS', 'FORTRAN', 'OWNDATA', 'ENSURECOPY',
  36. 'ENSUREARRAY', 'ALIGNED', 'NOTSWAPPED', 'WRITEABLE',
  37. 'WRITEBACKIFCOPY', 'UPDATEIFCOPY', 'BEHAVED', 'BEHAVED_RO',
  38. 'CARRAY', 'FARRAY'
  39. ]:
  40. if abs(flags) & getattr(wrap, flagname, 0):
  41. info.append(flagname)
  42. return info
  43. class Intent:
  44. def __init__(self, intent_list=[]):
  45. self.intent_list = intent_list[:]
  46. flags = 0
  47. for i in intent_list:
  48. if i == 'optional':
  49. flags |= wrap.F2PY_OPTIONAL
  50. else:
  51. flags |= getattr(wrap, 'F2PY_INTENT_' + i.upper())
  52. self.flags = flags
  53. def __getattr__(self, name):
  54. name = name.lower()
  55. if name == 'in_':
  56. name = 'in'
  57. return self.__class__(self.intent_list + [name])
  58. def __str__(self):
  59. return 'intent(%s)' % (','.join(self.intent_list))
  60. def __repr__(self):
  61. return 'Intent(%r)' % (self.intent_list)
  62. def is_intent(self, *names):
  63. for name in names:
  64. if name not in self.intent_list:
  65. return False
  66. return True
  67. def is_intent_exact(self, *names):
  68. return len(self.intent_list) == len(names) and self.is_intent(*names)
  69. intent = Intent()
  70. _type_names = ['BOOL', 'BYTE', 'UBYTE', 'SHORT', 'USHORT', 'INT', 'UINT',
  71. 'LONG', 'ULONG', 'LONGLONG', 'ULONGLONG',
  72. 'FLOAT', 'DOUBLE', 'CFLOAT']
  73. _cast_dict = {'BOOL': ['BOOL']}
  74. _cast_dict['BYTE'] = _cast_dict['BOOL'] + ['BYTE']
  75. _cast_dict['UBYTE'] = _cast_dict['BOOL'] + ['UBYTE']
  76. _cast_dict['BYTE'] = ['BYTE']
  77. _cast_dict['UBYTE'] = ['UBYTE']
  78. _cast_dict['SHORT'] = _cast_dict['BYTE'] + ['UBYTE', 'SHORT']
  79. _cast_dict['USHORT'] = _cast_dict['UBYTE'] + ['BYTE', 'USHORT']
  80. _cast_dict['INT'] = _cast_dict['SHORT'] + ['USHORT', 'INT']
  81. _cast_dict['UINT'] = _cast_dict['USHORT'] + ['SHORT', 'UINT']
  82. _cast_dict['LONG'] = _cast_dict['INT'] + ['LONG']
  83. _cast_dict['ULONG'] = _cast_dict['UINT'] + ['ULONG']
  84. _cast_dict['LONGLONG'] = _cast_dict['LONG'] + ['LONGLONG']
  85. _cast_dict['ULONGLONG'] = _cast_dict['ULONG'] + ['ULONGLONG']
  86. _cast_dict['FLOAT'] = _cast_dict['SHORT'] + ['USHORT', 'FLOAT']
  87. _cast_dict['DOUBLE'] = _cast_dict['INT'] + ['UINT', 'FLOAT', 'DOUBLE']
  88. _cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT']
  89. # 32 bit system malloc typically does not provide the alignment required by
  90. # 16 byte long double types this means the inout intent cannot be satisfied
  91. # and several tests fail as the alignment flag can be randomly true or fals
  92. # when numpy gains an aligned allocator the tests could be enabled again
  93. if ((np.intp().dtype.itemsize != 4 or np.clongdouble().dtype.alignment <= 8) and
  94. sys.platform != 'win32'):
  95. _type_names.extend(['LONGDOUBLE', 'CDOUBLE', 'CLONGDOUBLE'])
  96. _cast_dict['LONGDOUBLE'] = _cast_dict['LONG'] + \
  97. ['ULONG', 'FLOAT', 'DOUBLE', 'LONGDOUBLE']
  98. _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + \
  99. ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE']
  100. _cast_dict['CDOUBLE'] = _cast_dict['DOUBLE'] + ['CFLOAT', 'CDOUBLE']
  101. class Type:
  102. _type_cache = {}
  103. def __new__(cls, name):
  104. if isinstance(name, np.dtype):
  105. dtype0 = name
  106. name = None
  107. for n, i in typeinfo.items():
  108. if not isinstance(i, type) and dtype0.type is i.type:
  109. name = n
  110. break
  111. obj = cls._type_cache.get(name.upper(), None)
  112. if obj is not None:
  113. return obj
  114. obj = object.__new__(cls)
  115. obj._init(name)
  116. cls._type_cache[name.upper()] = obj
  117. return obj
  118. def _init(self, name):
  119. self.NAME = name.upper()
  120. info = typeinfo[self.NAME]
  121. self.type_num = getattr(wrap, 'NPY_' + self.NAME)
  122. assert_equal(self.type_num, info.num)
  123. self.dtype = np.dtype(info.type)
  124. self.type = info.type
  125. self.elsize = info.bits / 8
  126. self.dtypechar = info.char
  127. def cast_types(self):
  128. return [self.__class__(_m) for _m in _cast_dict[self.NAME]]
  129. def all_types(self):
  130. return [self.__class__(_m) for _m in _type_names]
  131. def smaller_types(self):
  132. bits = typeinfo[self.NAME].alignment
  133. types = []
  134. for name in _type_names:
  135. if typeinfo[name].alignment < bits:
  136. types.append(Type(name))
  137. return types
  138. def equal_types(self):
  139. bits = typeinfo[self.NAME].alignment
  140. types = []
  141. for name in _type_names:
  142. if name == self.NAME:
  143. continue
  144. if typeinfo[name].alignment == bits:
  145. types.append(Type(name))
  146. return types
  147. def larger_types(self):
  148. bits = typeinfo[self.NAME].alignment
  149. types = []
  150. for name in _type_names:
  151. if typeinfo[name].alignment > bits:
  152. types.append(Type(name))
  153. return types
  154. class Array:
  155. def __init__(self, typ, dims, intent, obj):
  156. self.type = typ
  157. self.dims = dims
  158. self.intent = intent
  159. self.obj_copy = copy.deepcopy(obj)
  160. self.obj = obj
  161. # arr.dtypechar may be different from typ.dtypechar
  162. self.arr = wrap.call(typ.type_num, dims, intent.flags, obj)
  163. assert_(isinstance(self.arr, np.ndarray), repr(type(self.arr)))
  164. self.arr_attr = wrap.array_attrs(self.arr)
  165. if len(dims) > 1:
  166. if self.intent.is_intent('c'):
  167. assert_(intent.flags & wrap.F2PY_INTENT_C)
  168. assert_(not self.arr.flags['FORTRAN'],
  169. repr((self.arr.flags, getattr(obj, 'flags', None))))
  170. assert_(self.arr.flags['CONTIGUOUS'])
  171. assert_(not self.arr_attr[6] & wrap.FORTRAN)
  172. else:
  173. assert_(not intent.flags & wrap.F2PY_INTENT_C)
  174. assert_(self.arr.flags['FORTRAN'])
  175. assert_(not self.arr.flags['CONTIGUOUS'])
  176. assert_(self.arr_attr[6] & wrap.FORTRAN)
  177. if obj is None:
  178. self.pyarr = None
  179. self.pyarr_attr = None
  180. return
  181. if intent.is_intent('cache'):
  182. assert_(isinstance(obj, np.ndarray), repr(type(obj)))
  183. self.pyarr = np.array(obj).reshape(*dims).copy()
  184. else:
  185. self.pyarr = np.array(
  186. np.array(obj, dtype=typ.dtypechar).reshape(*dims),
  187. order=self.intent.is_intent('c') and 'C' or 'F')
  188. assert_(self.pyarr.dtype == typ,
  189. repr((self.pyarr.dtype, typ)))
  190. self.pyarr.setflags(write=self.arr.flags['WRITEABLE'])
  191. assert_(self.pyarr.flags['OWNDATA'], (obj, intent))
  192. self.pyarr_attr = wrap.array_attrs(self.pyarr)
  193. if len(dims) > 1:
  194. if self.intent.is_intent('c'):
  195. assert_(not self.pyarr.flags['FORTRAN'])
  196. assert_(self.pyarr.flags['CONTIGUOUS'])
  197. assert_(not self.pyarr_attr[6] & wrap.FORTRAN)
  198. else:
  199. assert_(self.pyarr.flags['FORTRAN'])
  200. assert_(not self.pyarr.flags['CONTIGUOUS'])
  201. assert_(self.pyarr_attr[6] & wrap.FORTRAN)
  202. assert_(self.arr_attr[1] == self.pyarr_attr[1]) # nd
  203. assert_(self.arr_attr[2] == self.pyarr_attr[2]) # dimensions
  204. if self.arr_attr[1] <= 1:
  205. assert_(self.arr_attr[3] == self.pyarr_attr[3],
  206. repr((self.arr_attr[3], self.pyarr_attr[3],
  207. self.arr.tobytes(), self.pyarr.tobytes()))) # strides
  208. assert_(self.arr_attr[5][-2:] == self.pyarr_attr[5][-2:],
  209. repr((self.arr_attr[5], self.pyarr_attr[5]))) # descr
  210. assert_(self.arr_attr[6] == self.pyarr_attr[6],
  211. repr((self.arr_attr[6], self.pyarr_attr[6],
  212. flags2names(0 * self.arr_attr[6] - self.pyarr_attr[6]),
  213. flags2names(self.arr_attr[6]), intent))) # flags
  214. if intent.is_intent('cache'):
  215. assert_(self.arr_attr[5][3] >= self.type.elsize,
  216. repr((self.arr_attr[5][3], self.type.elsize)))
  217. else:
  218. assert_(self.arr_attr[5][3] == self.type.elsize,
  219. repr((self.arr_attr[5][3], self.type.elsize)))
  220. assert_(self.arr_equal(self.pyarr, self.arr))
  221. if isinstance(self.obj, np.ndarray):
  222. if typ.elsize == Type(obj.dtype).elsize:
  223. if not intent.is_intent('copy') and self.arr_attr[1] <= 1:
  224. assert_(self.has_shared_memory())
  225. def arr_equal(self, arr1, arr2):
  226. if arr1.shape != arr2.shape:
  227. return False
  228. return (arr1 == arr2).all()
  229. def __str__(self):
  230. return str(self.arr)
  231. def has_shared_memory(self):
  232. """Check that created array shares data with input array.
  233. """
  234. if self.obj is self.arr:
  235. return True
  236. if not isinstance(self.obj, np.ndarray):
  237. return False
  238. obj_attr = wrap.array_attrs(self.obj)
  239. return obj_attr[0] == self.arr_attr[0]
  240. class TestIntent:
  241. def test_in_out(self):
  242. assert_equal(str(intent.in_.out), 'intent(in,out)')
  243. assert_(intent.in_.c.is_intent('c'))
  244. assert_(not intent.in_.c.is_intent_exact('c'))
  245. assert_(intent.in_.c.is_intent_exact('c', 'in'))
  246. assert_(intent.in_.c.is_intent_exact('in', 'c'))
  247. assert_(not intent.in_.is_intent('c'))
  248. class TestSharedMemory:
  249. num2seq = [1, 2]
  250. num23seq = [[1, 2, 3], [4, 5, 6]]
  251. @pytest.fixture(autouse=True, scope='class', params=_type_names)
  252. def setup_type(self, request):
  253. request.cls.type = Type(request.param)
  254. request.cls.array = lambda self, dims, intent, obj: \
  255. Array(Type(request.param), dims, intent, obj)
  256. def test_in_from_2seq(self):
  257. a = self.array([2], intent.in_, self.num2seq)
  258. assert_(not a.has_shared_memory())
  259. def test_in_from_2casttype(self):
  260. for t in self.type.cast_types():
  261. obj = np.array(self.num2seq, dtype=t.dtype)
  262. a = self.array([len(self.num2seq)], intent.in_, obj)
  263. if t.elsize == self.type.elsize:
  264. assert_(
  265. a.has_shared_memory(), repr((self.type.dtype, t.dtype)))
  266. else:
  267. assert_(not a.has_shared_memory(), repr(t.dtype))
  268. @pytest.mark.parametrize('write', ['w', 'ro'])
  269. @pytest.mark.parametrize('order', ['C', 'F'])
  270. @pytest.mark.parametrize('inp', ['2seq', '23seq'])
  271. def test_in_nocopy(self, write, order, inp):
  272. """Test if intent(in) array can be passed without copies
  273. """
  274. seq = getattr(self, 'num' + inp)
  275. obj = np.array(seq, dtype=self.type.dtype, order=order)
  276. obj.setflags(write=(write == 'w'))
  277. a = self.array(obj.shape, ((order=='C' and intent.in_.c) or intent.in_), obj)
  278. assert a.has_shared_memory()
  279. def test_inout_2seq(self):
  280. obj = np.array(self.num2seq, dtype=self.type.dtype)
  281. a = self.array([len(self.num2seq)], intent.inout, obj)
  282. assert_(a.has_shared_memory())
  283. try:
  284. a = self.array([2], intent.in_.inout, self.num2seq)
  285. except TypeError as msg:
  286. if not str(msg).startswith('failed to initialize intent'
  287. '(inout|inplace|cache) array'):
  288. raise
  289. else:
  290. raise SystemError('intent(inout) should have failed on sequence')
  291. def test_f_inout_23seq(self):
  292. obj = np.array(self.num23seq, dtype=self.type.dtype, order='F')
  293. shape = (len(self.num23seq), len(self.num23seq[0]))
  294. a = self.array(shape, intent.in_.inout, obj)
  295. assert_(a.has_shared_memory())
  296. obj = np.array(self.num23seq, dtype=self.type.dtype, order='C')
  297. shape = (len(self.num23seq), len(self.num23seq[0]))
  298. try:
  299. a = self.array(shape, intent.in_.inout, obj)
  300. except ValueError as msg:
  301. if not str(msg).startswith('failed to initialize intent'
  302. '(inout) array'):
  303. raise
  304. else:
  305. raise SystemError(
  306. 'intent(inout) should have failed on improper array')
  307. def test_c_inout_23seq(self):
  308. obj = np.array(self.num23seq, dtype=self.type.dtype)
  309. shape = (len(self.num23seq), len(self.num23seq[0]))
  310. a = self.array(shape, intent.in_.c.inout, obj)
  311. assert_(a.has_shared_memory())
  312. def test_in_copy_from_2casttype(self):
  313. for t in self.type.cast_types():
  314. obj = np.array(self.num2seq, dtype=t.dtype)
  315. a = self.array([len(self.num2seq)], intent.in_.copy, obj)
  316. assert_(not a.has_shared_memory(), repr(t.dtype))
  317. def test_c_in_from_23seq(self):
  318. a = self.array([len(self.num23seq), len(self.num23seq[0])],
  319. intent.in_, self.num23seq)
  320. assert_(not a.has_shared_memory())
  321. def test_in_from_23casttype(self):
  322. for t in self.type.cast_types():
  323. obj = np.array(self.num23seq, dtype=t.dtype)
  324. a = self.array([len(self.num23seq), len(self.num23seq[0])],
  325. intent.in_, obj)
  326. assert_(not a.has_shared_memory(), repr(t.dtype))
  327. def test_f_in_from_23casttype(self):
  328. for t in self.type.cast_types():
  329. obj = np.array(self.num23seq, dtype=t.dtype, order='F')
  330. a = self.array([len(self.num23seq), len(self.num23seq[0])],
  331. intent.in_, obj)
  332. if t.elsize == self.type.elsize:
  333. assert_(a.has_shared_memory(), repr(t.dtype))
  334. else:
  335. assert_(not a.has_shared_memory(), repr(t.dtype))
  336. def test_c_in_from_23casttype(self):
  337. for t in self.type.cast_types():
  338. obj = np.array(self.num23seq, dtype=t.dtype)
  339. a = self.array([len(self.num23seq), len(self.num23seq[0])],
  340. intent.in_.c, obj)
  341. if t.elsize == self.type.elsize:
  342. assert_(a.has_shared_memory(), repr(t.dtype))
  343. else:
  344. assert_(not a.has_shared_memory(), repr(t.dtype))
  345. def test_f_copy_in_from_23casttype(self):
  346. for t in self.type.cast_types():
  347. obj = np.array(self.num23seq, dtype=t.dtype, order='F')
  348. a = self.array([len(self.num23seq), len(self.num23seq[0])],
  349. intent.in_.copy, obj)
  350. assert_(not a.has_shared_memory(), repr(t.dtype))
  351. def test_c_copy_in_from_23casttype(self):
  352. for t in self.type.cast_types():
  353. obj = np.array(self.num23seq, dtype=t.dtype)
  354. a = self.array([len(self.num23seq), len(self.num23seq[0])],
  355. intent.in_.c.copy, obj)
  356. assert_(not a.has_shared_memory(), repr(t.dtype))
  357. def test_in_cache_from_2casttype(self):
  358. for t in self.type.all_types():
  359. if t.elsize != self.type.elsize:
  360. continue
  361. obj = np.array(self.num2seq, dtype=t.dtype)
  362. shape = (len(self.num2seq),)
  363. a = self.array(shape, intent.in_.c.cache, obj)
  364. assert_(a.has_shared_memory(), repr(t.dtype))
  365. a = self.array(shape, intent.in_.cache, obj)
  366. assert_(a.has_shared_memory(), repr(t.dtype))
  367. obj = np.array(self.num2seq, dtype=t.dtype, order='F')
  368. a = self.array(shape, intent.in_.c.cache, obj)
  369. assert_(a.has_shared_memory(), repr(t.dtype))
  370. a = self.array(shape, intent.in_.cache, obj)
  371. assert_(a.has_shared_memory(), repr(t.dtype))
  372. try:
  373. a = self.array(shape, intent.in_.cache, obj[::-1])
  374. except ValueError as msg:
  375. if not str(msg).startswith('failed to initialize'
  376. ' intent(cache) array'):
  377. raise
  378. else:
  379. raise SystemError(
  380. 'intent(cache) should have failed on multisegmented array')
  381. def test_in_cache_from_2casttype_failure(self):
  382. for t in self.type.all_types():
  383. if t.elsize >= self.type.elsize:
  384. continue
  385. obj = np.array(self.num2seq, dtype=t.dtype)
  386. shape = (len(self.num2seq),)
  387. try:
  388. self.array(shape, intent.in_.cache, obj) # Should succeed
  389. except ValueError as msg:
  390. if not str(msg).startswith('failed to initialize'
  391. ' intent(cache) array'):
  392. raise
  393. else:
  394. raise SystemError(
  395. 'intent(cache) should have failed on smaller array')
  396. def test_cache_hidden(self):
  397. shape = (2,)
  398. a = self.array(shape, intent.cache.hide, None)
  399. assert_(a.arr.shape == shape)
  400. shape = (2, 3)
  401. a = self.array(shape, intent.cache.hide, None)
  402. assert_(a.arr.shape == shape)
  403. shape = (-1, 3)
  404. try:
  405. a = self.array(shape, intent.cache.hide, None)
  406. except ValueError as msg:
  407. if not str(msg).startswith('failed to create intent'
  408. '(cache|hide)|optional array'):
  409. raise
  410. else:
  411. raise SystemError(
  412. 'intent(cache) should have failed on undefined dimensions')
  413. def test_hidden(self):
  414. shape = (2,)
  415. a = self.array(shape, intent.hide, None)
  416. assert_(a.arr.shape == shape)
  417. assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
  418. shape = (2, 3)
  419. a = self.array(shape, intent.hide, None)
  420. assert_(a.arr.shape == shape)
  421. assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
  422. assert_(a.arr.flags['FORTRAN'] and not a.arr.flags['CONTIGUOUS'])
  423. shape = (2, 3)
  424. a = self.array(shape, intent.c.hide, None)
  425. assert_(a.arr.shape == shape)
  426. assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
  427. assert_(not a.arr.flags['FORTRAN'] and a.arr.flags['CONTIGUOUS'])
  428. shape = (-1, 3)
  429. try:
  430. a = self.array(shape, intent.hide, None)
  431. except ValueError as msg:
  432. if not str(msg).startswith('failed to create intent'
  433. '(cache|hide)|optional array'):
  434. raise
  435. else:
  436. raise SystemError('intent(hide) should have failed'
  437. ' on undefined dimensions')
  438. def test_optional_none(self):
  439. shape = (2,)
  440. a = self.array(shape, intent.optional, None)
  441. assert_(a.arr.shape == shape)
  442. assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
  443. shape = (2, 3)
  444. a = self.array(shape, intent.optional, None)
  445. assert_(a.arr.shape == shape)
  446. assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
  447. assert_(a.arr.flags['FORTRAN'] and not a.arr.flags['CONTIGUOUS'])
  448. shape = (2, 3)
  449. a = self.array(shape, intent.c.optional, None)
  450. assert_(a.arr.shape == shape)
  451. assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
  452. assert_(not a.arr.flags['FORTRAN'] and a.arr.flags['CONTIGUOUS'])
  453. def test_optional_from_2seq(self):
  454. obj = self.num2seq
  455. shape = (len(obj),)
  456. a = self.array(shape, intent.optional, obj)
  457. assert_(a.arr.shape == shape)
  458. assert_(not a.has_shared_memory())
  459. def test_optional_from_23seq(self):
  460. obj = self.num23seq
  461. shape = (len(obj), len(obj[0]))
  462. a = self.array(shape, intent.optional, obj)
  463. assert_(a.arr.shape == shape)
  464. assert_(not a.has_shared_memory())
  465. a = self.array(shape, intent.optional.c, obj)
  466. assert_(a.arr.shape == shape)
  467. assert_(not a.has_shared_memory())
  468. def test_inplace(self):
  469. obj = np.array(self.num23seq, dtype=self.type.dtype)
  470. assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS'])
  471. shape = obj.shape
  472. a = self.array(shape, intent.inplace, obj)
  473. assert_(obj[1][2] == a.arr[1][2], repr((obj, a.arr)))
  474. a.arr[1][2] = 54
  475. assert_(obj[1][2] == a.arr[1][2] ==
  476. np.array(54, dtype=self.type.dtype), repr((obj, a.arr)))
  477. assert_(a.arr is obj)
  478. assert_(obj.flags['FORTRAN']) # obj attributes are changed inplace!
  479. assert_(not obj.flags['CONTIGUOUS'])
  480. def test_inplace_from_casttype(self):
  481. for t in self.type.cast_types():
  482. if t is self.type:
  483. continue
  484. obj = np.array(self.num23seq, dtype=t.dtype)
  485. assert_(obj.dtype.type == t.type)
  486. assert_(obj.dtype.type is not self.type.type)
  487. assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS'])
  488. shape = obj.shape
  489. a = self.array(shape, intent.inplace, obj)
  490. assert_(obj[1][2] == a.arr[1][2], repr((obj, a.arr)))
  491. a.arr[1][2] = 54
  492. assert_(obj[1][2] == a.arr[1][2] ==
  493. np.array(54, dtype=self.type.dtype), repr((obj, a.arr)))
  494. assert_(a.arr is obj)
  495. assert_(obj.flags['FORTRAN']) # obj attributes changed inplace!
  496. assert_(not obj.flags['CONTIGUOUS'])
  497. assert_(obj.dtype.type is self.type.type) # obj changed inplace!