_asarray.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. finalize_array_function_like,
  8. set_module,
  9. )
  10. from .multiarray import array, asanyarray
  11. __all__ = ["require"]
  12. POSSIBLE_FLAGS = {
  13. 'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
  14. 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
  15. 'A': 'A', 'ALIGNED': 'A',
  16. 'W': 'W', 'WRITEABLE': 'W',
  17. 'O': 'O', 'OWNDATA': 'O',
  18. 'E': 'E', 'ENSUREARRAY': 'E'
  19. }
  20. @finalize_array_function_like
  21. @set_module('numpy')
  22. def require(a, dtype=None, requirements=None, *, like=None):
  23. """
  24. Return an ndarray of the provided type that satisfies requirements.
  25. This function is useful to be sure that an array with the correct flags
  26. is returned for passing to compiled code (perhaps through ctypes).
  27. Parameters
  28. ----------
  29. a : array_like
  30. The object to be converted to a type-and-requirement-satisfying array.
  31. dtype : data-type
  32. The required data-type. If None preserve the current dtype. If your
  33. application requires the data to be in native byteorder, include
  34. a byteorder specification as a part of the dtype specification.
  35. requirements : str or sequence of str
  36. The requirements list can be any of the following
  37. * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
  38. * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
  39. * 'ALIGNED' ('A') - ensure a data-type aligned array
  40. * 'WRITEABLE' ('W') - ensure a writable array
  41. * 'OWNDATA' ('O') - ensure an array that owns its own data
  42. * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
  43. ${ARRAY_FUNCTION_LIKE}
  44. .. versionadded:: 1.20.0
  45. Returns
  46. -------
  47. out : ndarray
  48. Array with specified requirements and type if given.
  49. See Also
  50. --------
  51. asarray : Convert input to an ndarray.
  52. asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
  53. ascontiguousarray : Convert input to a contiguous array.
  54. asfortranarray : Convert input to an ndarray with column-major
  55. memory order.
  56. ndarray.flags : Information about the memory layout of the array.
  57. Notes
  58. -----
  59. The returned array will be guaranteed to have the listed requirements
  60. by making a copy if needed.
  61. Examples
  62. --------
  63. >>> import numpy as np
  64. >>> x = np.arange(6).reshape(2,3)
  65. >>> x.flags
  66. C_CONTIGUOUS : True
  67. F_CONTIGUOUS : False
  68. OWNDATA : False
  69. WRITEABLE : True
  70. ALIGNED : True
  71. WRITEBACKIFCOPY : False
  72. >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
  73. >>> y.flags
  74. C_CONTIGUOUS : False
  75. F_CONTIGUOUS : True
  76. OWNDATA : True
  77. WRITEABLE : True
  78. ALIGNED : True
  79. WRITEBACKIFCOPY : False
  80. """
  81. if like is not None:
  82. return _require_with_like(
  83. like,
  84. a,
  85. dtype=dtype,
  86. requirements=requirements,
  87. )
  88. if not requirements:
  89. return asanyarray(a, dtype=dtype)
  90. requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements}
  91. if 'E' in requirements:
  92. requirements.remove('E')
  93. subok = False
  94. else:
  95. subok = True
  96. order = 'A'
  97. if requirements >= {'C', 'F'}:
  98. raise ValueError('Cannot specify both "C" and "F" order')
  99. elif 'F' in requirements:
  100. order = 'F'
  101. requirements.remove('F')
  102. elif 'C' in requirements:
  103. order = 'C'
  104. requirements.remove('C')
  105. arr = array(a, dtype=dtype, order=order, copy=None, subok=subok)
  106. for prop in requirements:
  107. if not arr.flags[prop]:
  108. return arr.copy(order)
  109. return arr
  110. _require_with_like = array_function_dispatch()(require)