Skip to content

Commit 086a68e

Browse files
authored
Fix Scoping.ids setter for int64 arrays (#2040)
* Scoping.ids converts int64 arrays to int32 arrays * Add testing * Update src/ansys/dpf/core/scoping.py * Raise on non-int arrays * Fix style check * Fix Style check * Update src/ansys/dpf/core/scoping.py
1 parent 17bc61f commit 086a68e

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/ansys/dpf/core/scoping.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,12 @@
5050
if TYPE_CHECKING: # pragma: nocover
5151
from ctypes import c_void_p as ScopingPointer
5252

53+
from numpy import typing as np_typing
54+
5355
from ansys.dpf.core.server_types import AnyServerType
5456
import ansys.grpc.dpf.scoping_pb2.Scoping as ScopingMessage
5557

56-
IdVectorType = Union[list[int], range]
58+
IdVectorType = Union[list[int], range, np_typing.NDArray[np.int32]]
5759

5860

5961
class Scoping:
@@ -184,6 +186,9 @@ def _set_location(self, loc=locations.nodal):
184186
def _set_ids(self, ids: IdVectorType):
185187
"""Set the ids.
186188
189+
Scoping IDs are stored as int32.
190+
Converts automatically int64 Numpy arrays to int32.
191+
187192
Parameters
188193
----------
189194
ids:
@@ -192,6 +197,14 @@ def _set_ids(self, ids: IdVectorType):
192197
"""
193198
if isinstance(ids, range):
194199
ids = list(ids)
200+
if isinstance(ids, np.ndarray):
201+
if ids.dtype == np.int64:
202+
ids = ids.astype(np.int32)
203+
if ids.dtype != np.int32:
204+
raise ValueError(
205+
f"Accepted dtypes for NumPy arrays when setting scoping IDs are "
206+
f"'np.int32' and np.int64' (provided is '{ids.dtype}')."
207+
)
195208
if isinstance(self._server, server_types.InProcessServer):
196209
self._api.scoping_resize(self, len(ids))
197210
ids_ptr = self._api.scoping_get_ids(self, len(ids))

tests/test_scoping.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,24 @@ def test_set_get_ids_scoping(server_type):
6464
assert np.allclose(scop.ids, ids)
6565

6666

67+
def test_set_get_ids_scoping_int64_array(server_type):
68+
# Numpy 2 switches default int precision from 32 to 64 on Windows
69+
# This tests verifies we convert any array of int64 to int32.
70+
scop = Scoping(server=server_type)
71+
ids_list = [1, 2, 3, 4]
72+
ids = np.array(ids_list, dtype=np.int64)
73+
scop.ids = ids
74+
assert np.allclose(scop.ids, ids_list)
75+
76+
77+
def test_set_get_ids_scoping_raise_dtype_array(server_type):
78+
scop = Scoping(server=server_type)
79+
ids_list = [1.0, 2.0, 3.0, 4.0]
80+
ids = np.array(ids_list)
81+
with pytest.raises(ValueError, match="Accepted dtypes"):
82+
scop.ids = ids
83+
84+
6785
def test_set_get_ids_scoping_range(server_type):
6886
range_ids = range(1, 10)
6987
scop = Scoping(

0 commit comments

Comments
 (0)