Skip to content

Commit 8b2a7af

Browse files
committed
fix numpy int64/uint64 conversion
1 parent 9059f83 commit 8b2a7af

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

dash_vtk/utils/vtk.py

+29-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import dash_vtk
22
import base64
3+
import numpy as np
34

45
try:
56
# v9 and above
@@ -29,6 +30,9 @@
2930
def b64_encode_numpy(obj):
3031
# Convert 1D numpy arrays with numeric types to memoryviews with
3132
# datatype and shape metadata.
33+
if len(obj) == 0:
34+
return obj.tolist()
35+
3236
dtype = obj.dtype
3337
if (
3438
dtype.kind in ["u", "i", "f"]
@@ -40,8 +44,31 @@ def b64_encode_numpy(obj):
4044
buffer = base64.b64encode(memoryview(obj.ravel(order="C"))).decode("utf-8")
4145
return {"bvals": buffer, "dtype": str(dtype), "shape": obj.shape}
4246
else:
43-
# Convert all other numpy arrays to lists
44-
return obj.tolist()
47+
buffer = None
48+
dtype_str = None
49+
# Try to see if we can downsize the array
50+
max_value = np.amax(obj)
51+
min_value = np.amin(obj)
52+
signed = min_value < 0
53+
test_value = max(max_value, -min_value)
54+
if test_value < np.iinfo(np.int16).max and signed:
55+
dtype_str = 'int16'
56+
buffer = base64.b64encode(memoryview(obj.astype(np.int16).ravel(order="C"))).decode("utf-8")
57+
elif test_value < np.iinfo(np.int32).max and signed:
58+
dtype_str = 'int32'
59+
buffer = base64.b64encode(memoryview(obj.astype(np.int32).ravel(order="C"))).decode("utf-8")
60+
elif test_value < np.iinfo(np.uint16).max and not signed:
61+
dtype_str = 'uint16'
62+
buffer = base64.b64encode(memoryview(obj.astype(np.uint16).ravel(order="C"))).decode("utf-8")
63+
elif test_value < np.iinfo(np.uint32).max and not signed:
64+
dtype_str = 'uint32'
65+
buffer = base64.b64encode(memoryview(obj.astype(np.uint32).ravel(order="C"))).decode("utf-8")
66+
67+
if dtype:
68+
return {"bvals": buffer, "dtype": dtype_str, "shape": obj.shape}
69+
70+
# Convert all other numpy arrays to lists
71+
return obj.tolist()
4572

4673

4774
def to_mesh_state(dataset, field_to_keep=None, point_arrays=None, cell_arrays=None):

0 commit comments

Comments
 (0)