diff --git a/src/datajoint/blob.py b/src/datajoint/blob.py index d8bf7a416..6206430d1 100644 --- a/src/datajoint/blob.py +++ b/src/datajoint/blob.py @@ -342,7 +342,7 @@ def pack_array(self, array: np.ndarray) -> bytes: blob += b"".join(len_u64(it) + it for it in (self.pack_blob(e) for e in array.flatten(order="F"))) self.set_dj0() # not supported by original mym elif serialize_lookup[array.dtype]["scalar_type"] == "CHAR": - blob += array.view(np.uint8).astype(np.uint16).tobytes() # convert to 16-bit chars for MATLAB + blob += array.view(np.uint8).astype(np.uint16).tobytes(order="F") # MATLAB column-major order else: # numeric arrays if array.ndim == 0: # not supported by original mym self.set_dj0() diff --git a/tests/unit/test_blob_character_arrays.py b/tests/unit/test_blob_character_arrays.py new file mode 100644 index 000000000..9dec44d61 --- /dev/null +++ b/tests/unit/test_blob_character_arrays.py @@ -0,0 +1,40 @@ +"""Regression tests for MATLAB-compatible character-array blob serialization.""" + +import numpy as np +import pytest + +from datajoint.blob import pack, unpack + + +@pytest.mark.parametrize( + "characters", + [ + [[b"a", b"b", b"c"], [b"d", b"e", b"f"]], + [[b"a", b"b"], [b"c", b"d"], [b"e", b"f"]], + [[b"a", b"b"], [b"c", b"d"]], + ], + ids=["two-by-three", "three-by-two", "two-by-two"], +) +def test_char_matrix_round_trip(characters): + matrix = np.asarray(characters, dtype="S1") + actual = unpack(pack(matrix, compress=False)) + np.testing.assert_array_equal(actual, matrix.astype("U1")) + + +def test_char_matrix_uses_matlab_column_major_bytes(): + matrix = np.array([[b"a", b"b", b"c"], [b"d", b"e", b"f"]], dtype="S1") + encoded = pack(matrix, compress=False) + expected_data = matrix.view(np.uint8).astype(np.uint16).tobytes(order="F") + + assert encoded.startswith(b"mYm\0") + assert encoded.endswith(expected_data) + np.testing.assert_array_equal(unpack(encoded), matrix.astype("U1")) + + +def test_compressed_char_matrix_round_trip(): + small = np.array([[b"a", b"b", b"c"], [b"d", b"e", b"f"]], dtype="S1") + matrix = np.tile(small, (50, 30)) + encoded = pack(matrix) + + assert encoded.startswith(b"ZL123\0") + np.testing.assert_array_equal(unpack(encoded), matrix.astype("U1"))