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

ENH: add copy parameter for api.reshape function #23789

Merged
merged 8 commits into from
Jun 14, 2023
Merged
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
Empty file.
18 changes: 16 additions & 2 deletions numpy/array_api/_manipulation_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,27 @@ def permute_dims(x: Array, /, axes: Tuple[int, ...]) -> Array:


# Note: the optional argument is called 'shape', not 'newshape'
def reshape(x: Array, /, shape: Tuple[int, ...]) -> Array:
def reshape(x: Array,
/,
shape: Tuple[int, ...],
*,
copy: Optional[Bool] = None) -> Array:
"""
Array API compatible wrapper for :py:func:`np.reshape <numpy.reshape>`.

See its docstring for more information.
"""
return Array._new(np.reshape(x._array, shape))

data = x._array
if copy:
data = np.copy(data)

reshaped = np.reshape(data, shape)

if copy is False and not np.shares_memory(data, reshaped):
raise AttributeError("Incompatible shape for in-place modification.")

return Array._new(reshaped)


def roll(
Expand Down
37 changes: 37 additions & 0 deletions numpy/array_api/tests/test_manipulation_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from numpy.testing import assert_raises
import numpy as np

from .. import all
from .._creation_functions import asarray
from .._dtypes import float64, int8
from .._manipulation_functions import (
concat,
reshape,
stack
)


def test_concat_errors():
assert_raises(TypeError, lambda: concat((1, 1), axis=None))
assert_raises(TypeError, lambda: concat([asarray([1], dtype=int8),
asarray([1], dtype=float64)]))


def test_stack_errors():
assert_raises(TypeError, lambda: stack([asarray([1, 1], dtype=int8),
asarray([2, 2], dtype=float64)]))


def test_reshape_copy():
a = asarray(np.ones((2, 3)))
b = reshape(a, (3, 2), copy=True)
assert not np.shares_memory(a._array, b._array)

a = asarray(np.ones((2, 3)))
b = reshape(a, (3, 2), copy=False)
assert np.shares_memory(a._array, b._array)

a = asarray(np.ones((2, 3)).T)
b = reshape(a, (3, 2), copy=True)
assert_raises(AttributeError, lambda: reshape(a, (2, 3), copy=False))