Skip to content

Commit

Permalink
disallow truncation in types.arraydata (#890)
Browse files Browse the repository at this point in the history
If `types.arraydata` is passed a `numpy.array` with dtype `numpy.int64` and the
platform default int type is 32 bit, then `types.arraydata` truncates the array
to `numpy.int32` without warning. This behavior is inherited from
`numpy.astype`. Since this may lead to unexpected behavior, this PR disallows
truncation by checking that the casted array is equal to the original array.
  • Loading branch information
joostvanzwieten committed Nov 21, 2024
2 parents f2a895b + 64625dc commit 3c11e79
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
2 changes: 1 addition & 1 deletion nutils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'Numerical Utilities for Finite Element Analysis'

__version__ = version = '9a39'
__version__ = version = '9a40'
version_name = 'jook-sing'
9 changes: 6 additions & 3 deletions nutils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,9 +387,12 @@ class arraydata(Singleton):
def __new__(cls, arg):
if isinstance(arg, cls):
return arg
array = numpy.asarray(arg)
dtype = dict(b=bool, u=int, i=int, f=float, c=complex)[array.dtype.kind]
return super().__new__(cls, dtype, array.shape, array.astype(dtype, copy=False).tobytes())
orig = numpy.asarray(arg)
dtype = dict(b=bool, u=int, i=int, f=float, c=complex)[orig.dtype.kind]
array = orig.astype(dtype, copy=False)
if array.dtype != orig.dtype and not numpy.equal(array, orig).all():
raise ValueError('cannot cast array with dtype {orig.dtype} to native dtype {array.dtype} without truncation')
return super().__new__(cls, dtype, array.shape, array.tobytes())

def reshape(self, *shape):
if numpy.prod(shape) != numpy.prod(self.shape):
Expand Down

0 comments on commit 3c11e79

Please sign in to comment.