Skip to content

Commit

Permalink
Closes Bears-R-Us#3699 zeros, ones, full to return Array
Browse files Browse the repository at this point in the history
  • Loading branch information
ajpotts committed Aug 28, 2024
1 parent efebabf commit d4a6d48
Show file tree
Hide file tree
Showing 6 changed files with 233 additions and 115 deletions.
1 change: 1 addition & 0 deletions arkouda/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
del get_versions

from arkouda.numpy import *
from arkouda.array_api import *
from arkouda.array_view import *
from arkouda.client import *
from arkouda.client_dtypes import *
Expand Down
61 changes: 24 additions & 37 deletions arkouda/array_api/array_object.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# type: ignore
"""
Wrapper class around the ndarray object for the array API standard.
Expand All @@ -15,30 +16,26 @@

from __future__ import annotations

import types
from enum import IntEnum
from ._dtypes import (
# _all_dtypes,
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union

from ._dtypes import ( # _all_dtypes,; _integer_or_boolean_dtypes,; _numeric_dtypes,
_boolean_dtypes,
_integer_dtypes,
# _integer_or_boolean_dtypes,
_floating_dtypes,
_complex_floating_dtypes,
# _numeric_dtypes,
_result_type,
_dtype_categories,
_floating_dtypes,
_integer_dtypes,
_result_type,
)
from .creation_functions import asarray

from typing import TYPE_CHECKING, Optional, Tuple, Union, Any, Dict, Callable, List
import types

if TYPE_CHECKING:
from ._typing import Device, Dtype

import arkouda as ak
import numpy as np

from arkouda.pdarraycreation import scalar_array
import arkouda as ak
from arkouda import array_api

HANDLED_FUNCTIONS: Dict[str, Callable] = {}
Expand Down Expand Up @@ -122,9 +119,7 @@ def item(self):
if self._has_single_elem():
return self._array[0]
else:
raise ValueError(
"Can only convert an array with one element to a Python scalar"
)
raise ValueError("Can only convert an array with one element to a Python scalar")

def transpose(self, axes: Optional[Tuple[int, ...]] = None):
"""
Expand Down Expand Up @@ -188,9 +183,7 @@ def chunk_info(self: Array, /) -> List[List[int]]:
"""
import json

return json.loads(
ak.generic_msg(cmd=f"chunkInfo{self.ndim}D", args={"array": self._array})
)
return json.loads(ak.generic_msg(cmd=f"chunkInfo{self.ndim}D", args={"array": self._array}))

def __array__(self, dtype: None | np.dtype[Any] = None):
"""
Expand Down Expand Up @@ -244,9 +237,7 @@ def _check_allowed_dtypes(

# The spec explicitly disallows this.
if res_dtype != self.dtype:
raise TypeError(
f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}"
)
raise TypeError(f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}")

return other

Expand All @@ -264,14 +255,10 @@ def _promote_scalar(self, scalar) -> Array:
# allowed.
if isinstance(scalar, bool):
if self.dtype not in _boolean_dtypes:
raise TypeError(
"Python bool scalars can only be promoted with bool arrays"
)
raise TypeError("Python bool scalars can only be promoted with bool arrays")
elif isinstance(scalar, int):
if self.dtype in _boolean_dtypes:
raise TypeError(
"Python int scalars cannot be promoted with bool arrays"
)
raise TypeError("Python int scalars cannot be promoted with bool arrays")
if self.dtype in _integer_dtypes:
info = np.iinfo(int)
if not (info.min <= scalar <= info.max):
Expand All @@ -281,9 +268,7 @@ def _promote_scalar(self, scalar) -> Array:
# int + array(floating) is allowed
elif isinstance(scalar, float):
if self.dtype not in _floating_dtypes:
raise TypeError(
"Python float scalars can only be promoted with floating-point arrays."
)
raise TypeError("Python float scalars can only be promoted with floating-point arrays.")
elif isinstance(scalar, complex):
if self.dtype not in _complex_floating_dtypes:
raise TypeError(
Expand Down Expand Up @@ -365,9 +350,7 @@ def __and__(self: Array, other: Union[int, bool, Array], /) -> Array:
else:
return Array._new(self._array and other._array)

def __array_namespace__(
self: Array, /, *, api_version: Optional[str] = None
) -> types.ModuleType:
def __array_namespace__(self: Array, /, *, api_version: Optional[str] = None) -> types.ModuleType:
"""
Get the array API namespace from an `Array` instance.
"""
Expand Down Expand Up @@ -409,6 +392,8 @@ def __eq__(self: Array, other: object, /) -> bool:
"""
Check if this array is equal to another array or scalar.
"""
from arkouda.pdarraycreation import scalar_array

if isinstance(other, (int, bool, float)):
return self._array == scalar_array(other)
elif isinstance(other, Array):
Expand Down Expand Up @@ -451,6 +436,8 @@ def __getitem__(
key: Union[int, slice, Tuple[Union[int, slice], ...], Array],
/,
) -> Array:
from arkouda.pdarraycreation import scalar_array

if isinstance(key, Array):
if key.size == 1 or key.shape == ():
k = key._array[0]
Expand Down Expand Up @@ -509,9 +496,7 @@ def __index__(self: Array, /) -> int:
if isinstance(s, int):
return s
else:
raise TypeError(
"Only integer arrays can be converted to a Python integer"
)
raise TypeError("Only integer arrays can be converted to a Python integer")
else:
raise ValueError("cannot convert non-scalar array to int")

Expand Down Expand Up @@ -581,6 +566,8 @@ def __ne__(self: Array, other: object, /) -> bool:
"""
Check if this array is not equal to another array or scalar.
"""
from arkouda.pdarraycreation import scalar_array

if isinstance(other, (int, bool, float)):
return self._array != scalar_array(other)
elif isinstance(other, Array):
Expand Down Expand Up @@ -942,7 +929,7 @@ def _has_single_elem(self: Array, /) -> bool:
def _single_elem(self: Array) -> Optional[Union[int, float, complex, bool]]:
if self._has_single_elem():
if self.ndim > 0:
return self._array[(0,)*self.ndim]
return self._array[(0,) * self.ndim]
else:
return self._array[0]
else:
Expand Down
27 changes: 12 additions & 15 deletions arkouda/array_api/creation_functions.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# type: ignore
from __future__ import annotations

from typing import TYPE_CHECKING, List, Optional, Tuple, Union, cast

from arkouda.client import generic_msg
import numpy as np
from arkouda.pdarrayclass import create_pdarray, pdarray, _to_pdarray
from arkouda.pdarraycreation import scalar_array

from arkouda.client import generic_msg
from arkouda.numpy.dtypes import dtype as akdtype
from arkouda.numpy.dtypes import resolve_scalar_dtype
from arkouda.pdarrayclass import _to_pdarray, create_pdarray, pdarray

if TYPE_CHECKING:
from ._typing import (
Expand All @@ -17,6 +18,8 @@
NestedSequence,
SupportsBufferProtocol,
)


import arkouda as ak


Expand Down Expand Up @@ -83,9 +86,7 @@ def asarray(
elif isinstance(obj, np.ndarray):
return Array._new(_to_pdarray(obj, dt=dtype))
else:
raise ValueError(
"asarray not implemented for 'NestedSequence' or 'SupportsBufferProtocol'"
)
raise ValueError("asarray not implemented for 'NestedSequence' or 'SupportsBufferProtocol'")


def arange(
Expand Down Expand Up @@ -155,9 +156,7 @@ def empty(
)


def empty_like(
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
) -> Array:
def empty_like(x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None) -> Array:
"""
Return a new array whose shape and dtype match the input array, without initializing entries.
"""
Expand Down Expand Up @@ -312,9 +311,7 @@ def ones(
return a


def ones_like(
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
) -> Array:
def ones_like(x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None) -> Array:
"""
Return a new array whose shape and dtype match the input array, filled with ones.
"""
Expand Down Expand Up @@ -367,6 +364,8 @@ def zeros(
"""
Return a new array with the specified shape and type, filled with zeros.
"""
from arkouda.pdarraycreation import scalar_array

from .array_object import Array

if device not in ["cpu", None]:
Expand Down Expand Up @@ -394,9 +393,7 @@ def zeros(
return Array._new(create_pdarray(repMsg))


def zeros_like(
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
) -> Array:
def zeros_like(x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None) -> Array:
"""
Return a new array whose shape and dtype match the input array, filled with zeros.
"""
Expand Down
Loading

0 comments on commit d4a6d48

Please sign in to comment.