_asarray.py 9.6 KB

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