@@ -28,22 +28,19 @@ def normalize_to_array(x):
2828 return x
2929
3030
31- def normalize_meta (x , ndim , dtype = None ):
32- if ndim > x .ndim :
33- meta = x [(Ellipsis , ) + tuple (None for _ in range (ndim - x .ndim ))]
34- meta = meta [tuple (slice (0 , 0 , None ) for _ in range (meta .ndim ))]
35- elif ndim < x .ndim :
36- meta = np .sum (x , axis = tuple (d for d in range ((x .ndim - ndim ))))
37- else :
38- meta = x
39-
40- if dtype :
41- meta = meta .astype (dtype )
42-
43- return meta
44-
45-
46- def meta_from_array (x , ndim , dtype = None ):
31+ def meta_from_array (x , ndim = None , dtype = None ):
32+ """ Normalize an array to appropriate meta object
33+
34+ Parameters
35+ ----------
36+ x: array-like
37+ ndim: int
38+ dtype: dtype
39+
40+ Returns
41+ -------
42+ array-like
43+ """
4744 if isinstance (x , list ) or isinstance (x , tuple ):
4845 ndims = [0 if isinstance (a , numbers .Number )
4946 else a .ndim if hasattr (a , 'ndim' ) else len (a ) for a in x ]
@@ -53,11 +50,28 @@ def meta_from_array(x, ndim, dtype=None):
5350 # x._meta must be a Dask Array, some libraries (e.g. zarr) implement a
5451 # _meta attribute that are incompatible with Dask Array._meta
5552 if hasattr (x , '_meta' ) and isinstance (x , Array ):
56- meta = x ._meta
57- else :
53+ x = x ._meta
54+
55+ if ndim is None :
56+ ndim = x .ndim
57+
58+ try :
5859 meta = x [tuple (slice (0 , 0 , None ) for _ in range (x .ndim ))]
60+ if meta .ndim != ndim :
61+ if ndim > x .ndim :
62+ meta = meta [(Ellipsis , ) + tuple (None for _ in range (ndim - meta .ndim ))]
63+ meta = meta [tuple (slice (0 , 0 , None ) for _ in range (meta .ndim ))]
64+ elif ndim == 0 :
65+ meta = meta .sum ()
66+ else :
67+ meta = meta .reshape ((0 ,) * ndim )
68+ except Exception :
69+ meta = np .empty ((0 ,) * ndim , dtype = dtype or x .dtype )
70+
71+ if dtype and meta .dtype != dtype :
72+ meta = meta .astype (dtype )
5973
60- return normalize_meta ( meta , ndim , dtype )
74+ return meta
6175
6276
6377def allclose (a , b , equal_nan = False , ** kwargs ):
0 commit comments