Normalize an array to appropriate meta object Parameters ---------- x: array-like, callable Either an object that looks sufficiently like a Numpy array, or a callable that accepts shape and dtype keywords ndim: int Number of dimensions of the array dtype:
(x, ndim=None, dtype=None)
| 25 | |
| 26 | |
| 27 | def meta_from_array(x, ndim=None, dtype=None): |
| 28 | """Normalize an array to appropriate meta object |
| 29 | |
| 30 | Parameters |
| 31 | ---------- |
| 32 | x: array-like, callable |
| 33 | Either an object that looks sufficiently like a Numpy array, |
| 34 | or a callable that accepts shape and dtype keywords |
| 35 | ndim: int |
| 36 | Number of dimensions of the array |
| 37 | dtype: Numpy dtype |
| 38 | A valid input for ``np.dtype`` |
| 39 | |
| 40 | Returns |
| 41 | ------- |
| 42 | array-like with zero elements of the correct dtype |
| 43 | """ |
| 44 | # If using x._meta, x must be a Dask Array, some libraries (e.g. zarr) |
| 45 | # implement a _meta attribute that are incompatible with Dask Array._meta |
| 46 | if hasattr(x, "_meta") and is_dask_collection(x) and is_arraylike(x): |
| 47 | x = x._meta |
| 48 | |
| 49 | if dtype is None and x is None: |
| 50 | raise ValueError("You must specify the meta or dtype of the array") |
| 51 | |
| 52 | if np.isscalar(x): |
| 53 | x = np.array(x) |
| 54 | |
| 55 | if x is None: |
| 56 | x = np.ndarray |
| 57 | elif dtype is None and hasattr(x, "dtype"): |
| 58 | dtype = x.dtype |
| 59 | |
| 60 | if isinstance(x, type): |
| 61 | x = x(shape=(0,) * (ndim or 0), dtype=dtype) |
| 62 | |
| 63 | if isinstance(x, (list, tuple)): |
| 64 | ndims = [ |
| 65 | ( |
| 66 | 0 |
| 67 | if isinstance(a, numbers.Number) |
| 68 | else a.ndim if hasattr(a, "ndim") else len(a) |
| 69 | ) |
| 70 | for a in x |
| 71 | ] |
| 72 | a = [a if nd == 0 else meta_from_array(a, nd) for a, nd in zip(x, ndims)] |
| 73 | return a if isinstance(x, list) else tuple(x) |
| 74 | |
| 75 | if ( |
| 76 | not hasattr(x, "shape") |
| 77 | or not hasattr(x, "dtype") |
| 78 | or not isinstance(x.shape, tuple) |
| 79 | ): |
| 80 | return x |
| 81 | |
| 82 | if ndim is None: |
| 83 | ndim = x.ndim |
| 84 |
searching dependent graphs…