_asarray.py 3.9 KB

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