_asarray.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. """
  2. Functions in the ``as*array`` family that promote array-likes into arrays.
  3. `require` fits this category despite its name not matching this pattern.
  4. """
  5. from .overrides import (
  6. array_function_dispatch,
  7. set_array_function_like_doc,
  8. set_module,
  9. )
  10. from .multiarray import array
  11. __all__ = [
  12. "asarray", "asanyarray", "ascontiguousarray", "asfortranarray", "require",
  13. ]
  14. def _asarray_dispatcher(a, dtype=None, order=None, *, like=None):
  15. return (like,)
  16. @set_array_function_like_doc
  17. @set_module('numpy')
  18. def asarray(a, dtype=None, order=None, *, like=None):
  19. """Convert the input to an array.
  20. Parameters
  21. ----------
  22. a : array_like
  23. Input data, in any form that can be converted to an array. This
  24. includes lists, lists of tuples, tuples, tuples of tuples, tuples
  25. of lists and ndarrays.
  26. dtype : data-type, optional
  27. By default, the data-type is inferred from the input data.
  28. order : {'C', 'F', 'A', 'K'}, optional
  29. Memory layout. 'A' and 'K' depend on the order of input array a.
  30. 'C' row-major (C-style),
  31. 'F' column-major (Fortran-style) memory representation.
  32. 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
  33. 'K' (keep) preserve input order
  34. Defaults to 'C'.
  35. ${ARRAY_FUNCTION_LIKE}
  36. .. versionadded:: 1.20.0
  37. Returns
  38. -------
  39. out : ndarray
  40. Array interpretation of `a`. No copy is performed if the input
  41. is already an ndarray with matching dtype and order. If `a` is a
  42. subclass of ndarray, a base class ndarray is returned.
  43. See Also
  44. --------
  45. asanyarray : Similar function which passes through subclasses.
  46. ascontiguousarray : Convert input to a contiguous array.
  47. asfarray : Convert input to a floating point ndarray.
  48. asfortranarray : Convert input to an ndarray with column-major
  49. memory order.
  50. asarray_chkfinite : Similar function which checks input for NaNs and Infs.
  51. fromiter : Create an array from an iterator.
  52. fromfunction : Construct an array by executing a function on grid
  53. positions.
  54. Examples
  55. --------
  56. Convert a list into an array:
  57. >>> a = [1, 2]
  58. >>> np.asarray(a)
  59. array([1, 2])
  60. Existing arrays are not copied:
  61. >>> a = np.array([1, 2])
  62. >>> np.asarray(a) is a
  63. True
  64. If `dtype` is set, array is copied only if dtype does not match:
  65. >>> a = np.array([1, 2], dtype=np.float32)
  66. >>> np.asarray(a, dtype=np.float32) is a
  67. True
  68. >>> np.asarray(a, dtype=np.float64) is a
  69. False
  70. Contrary to `asanyarray`, ndarray subclasses are not passed through:
  71. >>> issubclass(np.recarray, np.ndarray)
  72. True
  73. >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
  74. >>> np.asarray(a) is a
  75. False
  76. >>> np.asanyarray(a) is a
  77. True
  78. """
  79. if like is not None:
  80. return _asarray_with_like(a, dtype=dtype, order=order, like=like)
  81. return array(a, dtype, copy=False, order=order)
  82. _asarray_with_like = array_function_dispatch(
  83. _asarray_dispatcher
  84. )(asarray)
  85. @set_array_function_like_doc
  86. @set_module('numpy')
  87. def asanyarray(a, dtype=None, order=None, *, like=None):
  88. """Convert the input to an ndarray, but pass ndarray subclasses through.
  89. Parameters
  90. ----------
  91. a : array_like
  92. Input data, in any form that can be converted to an array. This
  93. includes scalars, lists, lists of tuples, tuples, tuples of tuples,
  94. tuples of lists, and ndarrays.
  95. dtype : data-type, optional
  96. By default, the data-type is inferred from the input data.
  97. order : {'C', 'F', 'A', 'K'}, optional
  98. Memory layout. 'A' and 'K' depend on the order of input array a.
  99. 'C' row-major (C-style),
  100. 'F' column-major (Fortran-style) memory representation.
  101. 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
  102. 'K' (keep) preserve input order
  103. Defaults to 'C'.
  104. ${ARRAY_FUNCTION_LIKE}
  105. .. versionadded:: 1.20.0
  106. Returns
  107. -------
  108. out : ndarray or an ndarray subclass
  109. Array interpretation of `a`. If `a` is an ndarray or a subclass
  110. of ndarray, it is returned as-is and no copy is performed.
  111. See Also
  112. --------
  113. asarray : Similar function which always returns ndarrays.
  114. ascontiguousarray : Convert input to a contiguous array.
  115. asfarray : Convert input to a floating point ndarray.
  116. asfortranarray : Convert input to an ndarray with column-major
  117. memory order.
  118. asarray_chkfinite : Similar function which checks input for NaNs and
  119. Infs.
  120. fromiter : Create an array from an iterator.
  121. fromfunction : Construct an array by executing a function on grid
  122. positions.
  123. Examples
  124. --------
  125. Convert a list into an array:
  126. >>> a = [1, 2]
  127. >>> np.asanyarray(a)
  128. array([1, 2])
  129. Instances of `ndarray` subclasses are passed through as-is:
  130. >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
  131. >>> np.asanyarray(a) is a
  132. True
  133. """
  134. if like is not None:
  135. return _asanyarray_with_like(a, dtype=dtype, order=order, like=like)
  136. return array(a, dtype, copy=False, order=order, subok=True)
  137. _asanyarray_with_like = array_function_dispatch(
  138. _asarray_dispatcher
  139. )(asanyarray)
  140. def _asarray_contiguous_fortran_dispatcher(a, dtype=None, *, like=None):
  141. return (like,)
  142. @set_array_function_like_doc
  143. @set_module('numpy')
  144. def ascontiguousarray(a, dtype=None, *, like=None):
  145. """
  146. Return a contiguous array (ndim >= 1) in memory (C order).
  147. Parameters
  148. ----------
  149. a : array_like
  150. Input array.
  151. dtype : str or dtype object, optional
  152. Data-type of returned array.
  153. ${ARRAY_FUNCTION_LIKE}
  154. .. versionadded:: 1.20.0
  155. Returns
  156. -------
  157. out : ndarray
  158. Contiguous array of same shape and content as `a`, with type `dtype`
  159. if specified.
  160. See Also
  161. --------
  162. asfortranarray : Convert input to an ndarray with column-major
  163. memory order.
  164. require : Return an ndarray that satisfies requirements.
  165. ndarray.flags : Information about the memory layout of the array.
  166. Examples
  167. --------
  168. >>> x = np.arange(6).reshape(2,3)
  169. >>> np.ascontiguousarray(x, dtype=np.float32)
  170. array([[0., 1., 2.],
  171. [3., 4., 5.]], dtype=float32)
  172. >>> x.flags['C_CONTIGUOUS']
  173. True
  174. Note: This function returns an array with at least one-dimension (1-d)
  175. so it will not preserve 0-d arrays.
  176. """
  177. if like is not None:
  178. return _ascontiguousarray_with_like(a, dtype=dtype, like=like)
  179. return array(a, dtype, copy=False, order='C', ndmin=1)
  180. _ascontiguousarray_with_like = array_function_dispatch(
  181. _asarray_contiguous_fortran_dispatcher
  182. )(ascontiguousarray)
  183. @set_array_function_like_doc
  184. @set_module('numpy')
  185. def asfortranarray(a, dtype=None, *, like=None):
  186. """
  187. Return an array (ndim >= 1) laid out in Fortran order in memory.
  188. Parameters
  189. ----------
  190. a : array_like
  191. Input array.
  192. dtype : str or dtype object, optional
  193. By default, the data-type is inferred from the input data.
  194. ${ARRAY_FUNCTION_LIKE}
  195. .. versionadded:: 1.20.0
  196. Returns
  197. -------
  198. out : ndarray
  199. The input `a` in Fortran, or column-major, order.
  200. See Also
  201. --------
  202. ascontiguousarray : Convert input to a contiguous (C order) array.
  203. asanyarray : Convert input to an ndarray with either row or
  204. column-major memory order.
  205. require : Return an ndarray that satisfies requirements.
  206. ndarray.flags : Information about the memory layout of the array.
  207. Examples
  208. --------
  209. >>> x = np.arange(6).reshape(2,3)
  210. >>> y = np.asfortranarray(x)
  211. >>> x.flags['F_CONTIGUOUS']
  212. False
  213. >>> y.flags['F_CONTIGUOUS']
  214. True
  215. Note: This function returns an array with at least one-dimension (1-d)
  216. so it will not preserve 0-d arrays.
  217. """
  218. if like is not None:
  219. return _asfortranarray_with_like(a, dtype=dtype, like=like)
  220. return array(a, dtype, copy=False, order='F', ndmin=1)
  221. _asfortranarray_with_like = array_function_dispatch(
  222. _asarray_contiguous_fortran_dispatcher
  223. )(asfortranarray)
  224. def _require_dispatcher(a, dtype=None, requirements=None, *, like=None):
  225. return (like,)
  226. @set_array_function_like_doc
  227. @set_module('numpy')
  228. def require(a, dtype=None, requirements=None, *, like=None):
  229. """
  230. Return an ndarray of the provided type that satisfies requirements.
  231. This function is useful to be sure that an array with the correct flags
  232. is returned for passing to compiled code (perhaps through ctypes).
  233. Parameters
  234. ----------
  235. a : array_like
  236. The object to be converted to a type-and-requirement-satisfying array.
  237. dtype : data-type
  238. The required data-type. If None preserve the current dtype. If your
  239. application requires the data to be in native byteorder, include
  240. a byteorder specification as a part of the dtype specification.
  241. requirements : str or list of str
  242. The requirements list can be any of the following
  243. * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
  244. * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
  245. * 'ALIGNED' ('A') - ensure a data-type aligned array
  246. * 'WRITEABLE' ('W') - ensure a writable array
  247. * 'OWNDATA' ('O') - ensure an array that owns its own data
  248. * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
  249. ${ARRAY_FUNCTION_LIKE}
  250. .. versionadded:: 1.20.0
  251. Returns
  252. -------
  253. out : ndarray
  254. Array with specified requirements and type if given.
  255. See Also
  256. --------
  257. asarray : Convert input to an ndarray.
  258. asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
  259. ascontiguousarray : Convert input to a contiguous array.
  260. asfortranarray : Convert input to an ndarray with column-major
  261. memory order.
  262. ndarray.flags : Information about the memory layout of the array.
  263. Notes
  264. -----
  265. The returned array will be guaranteed to have the listed requirements
  266. by making a copy if needed.
  267. Examples
  268. --------
  269. >>> x = np.arange(6).reshape(2,3)
  270. >>> x.flags
  271. C_CONTIGUOUS : True
  272. F_CONTIGUOUS : False
  273. OWNDATA : False
  274. WRITEABLE : True
  275. ALIGNED : True
  276. WRITEBACKIFCOPY : False
  277. UPDATEIFCOPY : False
  278. >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
  279. >>> y.flags
  280. C_CONTIGUOUS : False
  281. F_CONTIGUOUS : True
  282. OWNDATA : True
  283. WRITEABLE : True
  284. ALIGNED : True
  285. WRITEBACKIFCOPY : False
  286. UPDATEIFCOPY : False
  287. """
  288. if like is not None:
  289. return _require_with_like(
  290. a,
  291. dtype=dtype,
  292. requirements=requirements,
  293. like=like,
  294. )
  295. possible_flags = {'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
  296. 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
  297. 'A': 'A', 'ALIGNED': 'A',
  298. 'W': 'W', 'WRITEABLE': 'W',
  299. 'O': 'O', 'OWNDATA': 'O',
  300. 'E': 'E', 'ENSUREARRAY': 'E'}
  301. if not requirements:
  302. return asanyarray(a, dtype=dtype)
  303. else:
  304. requirements = {possible_flags[x.upper()] for x in requirements}
  305. if 'E' in requirements:
  306. requirements.remove('E')
  307. subok = False
  308. else:
  309. subok = True
  310. order = 'A'
  311. if requirements >= {'C', 'F'}:
  312. raise ValueError('Cannot specify both "C" and "F" order')
  313. elif 'F' in requirements:
  314. order = 'F'
  315. requirements.remove('F')
  316. elif 'C' in requirements:
  317. order = 'C'
  318. requirements.remove('C')
  319. arr = array(a, dtype=dtype, order=order, copy=False, subok=subok)
  320. for prop in requirements:
  321. if not arr.flags[prop]:
  322. arr = arr.copy(order)
  323. break
  324. return arr
  325. _require_with_like = array_function_dispatch(
  326. _require_dispatcher
  327. )(require)