Skip to content

add several ndarray method/properties #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion torch_np/_ndarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from . import _binary_ufuncs, _dtypes, _funcs, _helpers, _unary_ufuncs
from ._detail import _dtypes_impl, _util
from ._normalizations import ArrayLike, normalizer

newaxis = None

Expand Down Expand Up @@ -117,6 +118,14 @@ def flags(self):
}
)

@property
def data(self):
return self.tensor.data_ptr()

@property
def nbytes(self):
return self.tensor.storage().nbytes()

@property
def T(self):
return self.transpose()
Expand Down Expand Up @@ -157,7 +166,10 @@ def view(self, dtype):
tview = self.tensor.view(torch_dtype)
return ndarray(tview)

def fill(self, value):
@normalizer
def fill(self, value: ArrayLike):
# Both Pytorch and NumPy accept 0D arrays/tensors and scalars, and
# error out on D > 0 arrays
self.tensor.fill_(value)

def tolist(self):
Expand Down Expand Up @@ -395,6 +407,18 @@ def sort(self, axis=-1, kind=None, order=None):
cumprod = _funcs.cumprod

### indexing ###
def item(self, *args):
# Mimic NumPy's implementation with three special cases (no arguments,
# a flat index and a multi-index):
# https://github.com/numpy/numpy/blob/main/numpy/core/src/multiarray/methods.c#L702
if args == ():
return self.tensor.item()
elif len(args) == 1:
# int argument
return self.ravel()[args[0]]
else:
return self.__getitem__(args)

@staticmethod
def _upcast_int_indices(index):
if isinstance(index, torch.Tensor):
Expand Down