Skip to content
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

Add __array__ method to pyopencl.Array #301

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions pyopencl/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ class Array:
.. automethod :: get
.. automethod :: get_async
.. automethod :: copy
.. automethod :: __array__

.. automethod :: __str__
.. automethod :: __repr__
Expand Down Expand Up @@ -806,6 +807,21 @@ def copy(self, queue=_copy_queue):

return result

def __array__(self, dtype=None):
"""Return a numpy array copy of the array.

Equivalent to :meth:`get` with no arguments. If `dtype` is given, two
copies of the input array will be made: one for the conversion, and
another for the cast.

:arg dtype: a valid NumPy dtype, such as ``np.float64`` or
``'float32'``.

.. versionadded:: ...
"""
out = self.get().astype(dtype)
return out

def __str__(self):
if self.queue is None:
return (f"<cl.Array {self.shape} of {self.dtype} "
Expand Down
7 changes: 7 additions & 0 deletions test/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,13 @@ def test_random_int_in_range(ctx_factory, rng_class, dtype, plot_hist=False):

# {{{ misc

def test_array_method(ctx_factory):
ctx = ctx_factory()
queue = cl.CommandQueue(ctx)
arr = make_random_array(queue, np.float32, 1024)
np.testing.assert_array_equal(arr, arr.get())


def test_numpy_integer_shape(ctx_factory):
try:
list(np.int32(17))
Expand Down