diff --git a/src/ansys/dpf/core/scoping.py b/src/ansys/dpf/core/scoping.py index 14bd2fafd91..72aa98c1a32 100644 --- a/src/ansys/dpf/core/scoping.py +++ b/src/ansys/dpf/core/scoping.py @@ -50,10 +50,12 @@ if TYPE_CHECKING: # pragma: nocover from ctypes import c_void_p as ScopingPointer + from numpy import typing as np_typing + from ansys.dpf.core.server_types import AnyServerType import ansys.grpc.dpf.scoping_pb2.Scoping as ScopingMessage - IdVectorType = Union[list[int], range] + IdVectorType = Union[list[int], range, np_typing.NDArray[np.int32]] class Scoping: @@ -184,6 +186,9 @@ def _set_location(self, loc=locations.nodal): def _set_ids(self, ids: IdVectorType): """Set the ids. + Scoping IDs are stored as int32. + Converts automatically int64 Numpy arrays to int32. + Parameters ---------- ids: @@ -192,6 +197,14 @@ def _set_ids(self, ids: IdVectorType): """ if isinstance(ids, range): ids = list(ids) + if isinstance(ids, np.ndarray): + if ids.dtype == np.int64: + ids = ids.astype(np.int32) + if ids.dtype != np.int32: + raise ValueError( + f"Accepted dtypes for NumPy arrays when setting scoping IDs are " + f"'np.int32' and np.int64' (provided is '{ids.dtype}')." + ) if isinstance(self._server, server_types.InProcessServer): self._api.scoping_resize(self, len(ids)) ids_ptr = self._api.scoping_get_ids(self, len(ids)) diff --git a/tests/test_scoping.py b/tests/test_scoping.py index 8822f36a6cb..5903fb7abc3 100644 --- a/tests/test_scoping.py +++ b/tests/test_scoping.py @@ -64,6 +64,24 @@ def test_set_get_ids_scoping(server_type): assert np.allclose(scop.ids, ids) +def test_set_get_ids_scoping_int64_array(server_type): + # Numpy 2 switches default int precision from 32 to 64 on Windows + # This tests verifies we convert any array of int64 to int32. + scop = Scoping(server=server_type) + ids_list = [1, 2, 3, 4] + ids = np.array(ids_list, dtype=np.int64) + scop.ids = ids + assert np.allclose(scop.ids, ids_list) + + +def test_set_get_ids_scoping_raise_dtype_array(server_type): + scop = Scoping(server=server_type) + ids_list = [1.0, 2.0, 3.0, 4.0] + ids = np.array(ids_list) + with pytest.raises(ValueError, match="Accepted dtypes"): + scop.ids = ids + + def test_set_get_ids_scoping_range(server_type): range_ids = range(1, 10) scop = Scoping(