Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
_asarray.py131 linesDownload Raw Back to _core
1"""
2Functions in the ``as*array`` family that promote array-likes into arrays.
3
4`require` fits this category despite its name not matching this pattern.
5"""
6from .multiarray import array, asanyarray
7from .overrides import array_function_dispatch, finalize_array_function_like, set_module
8
9__all__ = ["require"]
10
11
12POSSIBLE_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
21
22@finalize_array_function_like
23@set_module('numpy')
24def require(a, dtype=None, requirements=None, *, like=None):
25    """
26    Return an ndarray of the provided type that satisfies requirements.
27
28    This function is useful to be sure that an array with the correct flags
29    is returned for passing to compiled code (perhaps through ctypes).
30
31    Parameters
32    ----------
33    a : array_like
34       The object to be converted to a type-and-requirement-satisfying array.
35    dtype : data-type
36       The required data-type. If None preserve the current dtype. If your
37       application requires the data to be in native byteorder, include
38       a byteorder specification as a part of the dtype specification.
39    requirements : str or sequence of str
40       The requirements list can be any of the following
41
42       * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
43       * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
44       * 'ALIGNED' ('A')      - ensure a data-type aligned array
45       * 'WRITEABLE' ('W')    - ensure a writable array
46       * 'OWNDATA' ('O')      - ensure an array that owns its own data
47       * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
48    ${ARRAY_FUNCTION_LIKE}
49
50        .. versionadded:: 1.20.0
51
52    Returns
53    -------
54    out : ndarray
55        Array with specified requirements and type if given.
56
57    See Also
58    --------
59    asarray : Convert input to an ndarray.
60    asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
61    ascontiguousarray : Convert input to a contiguous array.
62    asfortranarray : Convert input to an ndarray with column-major
63                     memory order.
64    ndarray.flags : Information about the memory layout of the array.
65
66    Notes
67    -----
68    The returned array will be guaranteed to have the listed requirements
69    by making a copy if needed.
70
71    Examples
72    --------
73    >>> import numpy as np
74    >>> x = np.arange(6).reshape(2,3)
75    >>> x.flags
76      C_CONTIGUOUS : True
77      F_CONTIGUOUS : False
78      OWNDATA : False
79      WRITEABLE : True
80      ALIGNED : True
81      WRITEBACKIFCOPY : False
82
83    >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
84    >>> y.flags
85      C_CONTIGUOUS : False
86      F_CONTIGUOUS : True
87      OWNDATA : True
88      WRITEABLE : True
89      ALIGNED : True
90      WRITEBACKIFCOPY : False
91
92    """
93    if like is not None:
94        return _require_with_like(
95            like,
96            a,
97            dtype=dtype,
98            requirements=requirements,
99        )
100
101    if not requirements:
102        return asanyarray(a, dtype=dtype)
103
104    requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements}
105
106    if 'E' in requirements:
107        requirements.remove('E')
108        subok = False
109    else:
110        subok = True
111
112    order = 'A'
113    if requirements >= {'C', 'F'}:
114        raise ValueError('Cannot specify both "C" and "F" order')
115    elif 'F' in requirements:
116        order = 'F'
117        requirements.remove('F')
118    elif 'C' in requirements:
119        order = 'C'
120        requirements.remove('C')
121
122    arr = array(a, dtype=dtype, order=order, copy=None, subok=subok)
123
124    for prop in requirements:
125        if not arr.flags[prop]:
126            return arr.copy(order)
127    return arr
128
129
130_require_with_like = array_function_dispatch()(require)
131 
codekingpro/portable-devtools · Team Ai