Skip to content

Commit 9282a91

Browse files
committed
Added astype function
1 parent 44dac9e commit 9282a91

2 files changed

Lines changed: 29 additions & 18 deletions

File tree

src/blosc2/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@ def __array_namespace_info__() -> Info:
311311
linspace,
312312
eye,
313313
asarray,
314+
astype,
314315
indices,
315316
sort,
316317
reshape,
@@ -480,7 +481,7 @@ def __array_namespace_info__() -> Info:
480481
"are_partitions_aligned",
481482
"are_partitions_behaved",
482483
"asarray",
483-
"clib_info",
484+
"astypeclib_info",
484485
"compress",
485486
"compress2",
486487
"compressor_list",

src/blosc2/ndarray.py

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4071,7 +4071,7 @@ def save(array: NDArray, urlpath: str, contiguous=True, **kwargs: Any) -> None:
40714071
array.save(urlpath, contiguous, **kwargs)
40724072

40734073

4074-
def asarray(array: Sequence | np.ndarray | blosc2.C2Array, copy=True, **kwargs: Any) -> NDArray: # noqa: C901
4074+
def asarray(array: Sequence | np.ndarray | blosc2.C2Array | NDArray, copy=True, **kwargs: Any) -> NDArray: # noqa: C901
40754075
"""Convert the `array` to an `NDArray`.
40764076
40774077
Parameters
@@ -4109,14 +4109,12 @@ def asarray(array: Sequence | np.ndarray | blosc2.C2Array, copy=True, **kwargs:
41094109
if not copy:
41104110
raise ValueError("asarray which avoids copy not implemented yet.")
41114111
# Convert scalars to numpy array
4112-
dtype = kwargs.pop("dtype", None) # check if dtype provided
4112+
casting = kwargs.pop("casting", "unsafe")
4113+
if casting != "unsafe":
4114+
raise ValueError("Only unsafe casting is supported at the moment.")
41134115
if not hasattr(array, "shape"):
4114-
array = np.array(array, dtype=dtype) # defaults if dtype=None
4115-
if dtype is not None and array.dtype != dtype:
4116-
try:
4117-
array = array.astype(dtype)
4118-
except Exception as e:
4119-
raise ValueError("Cannot provide dtype argument for C2Arrays.") from e
4116+
array = np.asarray(array) # defaults if dtype=None
4117+
dtype = kwargs.pop("dtype", array.dtype) # check if dtype provided
41204118
kwargs = _check_ndarray_kwargs(**kwargs)
41214119
chunks = kwargs.pop("chunks", None)
41224120
blocks = kwargs.pop("blocks", None)
@@ -4132,13 +4130,15 @@ def asarray(array: Sequence | np.ndarray | blosc2.C2Array, copy=True, **kwargs:
41324130
small_size = 2**24 # 16 MB
41334131
array_nbytes = math.prod(shape) * array.dtype.itemsize
41344132
if array_nbytes < small_size:
4135-
if not isinstance(array, np.ndarray):
4136-
if hasattr(array, "chunks"):
4137-
# A getitem operation should be enough to get a numpy array
4138-
array = array[()]
4139-
else:
4140-
if not array.flags.contiguous:
4141-
array = np.ascontiguousarray(array)
4133+
if not isinstance(array, np.ndarray) and hasattr(array, "chunks"):
4134+
# A getitem operation should be enough to get a numpy array
4135+
array = array[()]
4136+
4137+
if dtype != array.dtype:
4138+
array = array.astype(dtype=dtype, casting=casting)
4139+
if not array.flags.contiguous:
4140+
array = np.ascontiguousarray(array)
4141+
41424142
return blosc2_ext.asarray(array, chunks, blocks, **kwargs)
41434143

41444144
# Create the empty array
@@ -4156,8 +4156,8 @@ def asarray(array: Sequence | np.ndarray | blosc2.C2Array, copy=True, **kwargs:
41564156
slice(c * s, builtins.min((c + 1) * s, shape[i]))
41574157
for i, (c, s) in enumerate(zip(coords, chunks, strict=True))
41584158
)
4159-
# Ensure the array slice is contiguous
4160-
array_slice = np.ascontiguousarray(array[slice_])
4159+
# Ensure the array slice is contiguous and of correct dtype
4160+
array_slice = np.ascontiguousarray(array[slice_], dtype=dtype)
41614161
if behaved:
41624162
# The whole chunk is to be updated, so this fastpath is safe
41634163
ndarr.schunk.update_data(nchunk, array_slice, copy=False)
@@ -4167,6 +4167,16 @@ def asarray(array: Sequence | np.ndarray | blosc2.C2Array, copy=True, **kwargs:
41674167
return ndarr
41684168

41694169

4170+
def astype(
4171+
array: Sequence | np.ndarray | NDArray | blosc2.C2Array,
4172+
dtype,
4173+
casting: str = "unsafe",
4174+
copy: bool = True,
4175+
**kwargs: Any,
4176+
) -> NDArray:
4177+
return asarray(array, dtype=dtype, casting=casting, copy=copy, **kwargs)
4178+
4179+
41704180
def _check_ndarray_kwargs(**kwargs): # noqa: C901
41714181
storage = kwargs.get("storage")
41724182
if storage is not None:

0 commit comments

Comments
 (0)