diff --git a/cpp/src/arrow/extension/fixed_shape_tensor.cc b/cpp/src/arrow/extension/fixed_shape_tensor.cc index 7f55375b8226..a0d772943ec6 100644 --- a/cpp/src/arrow/extension/fixed_shape_tensor.cc +++ b/cpp/src/arrow/extension/fixed_shape_tensor.cc @@ -200,6 +200,8 @@ Result> FixedShapeTensorType::MakeTensor( } std::vector shape = ext_type.shape(); + ARROW_ASSIGN_OR_RAISE( + auto strides, internal::ComputeStrides(ext_type.value_type(), shape, permutation)); internal::Permute(permutation, &shape); std::vector dim_names = ext_type.dim_names(); @@ -207,8 +209,6 @@ Result> FixedShapeTensorType::MakeTensor( internal::Permute(permutation, &dim_names); } - ARROW_ASSIGN_OR_RAISE( - auto strides, internal::ComputeStrides(ext_type.value_type(), shape, permutation)); ARROW_ASSIGN_OR_RAISE(const auto buffer, internal::SliceTensorBuffer( *array, *ext_type.value_type(), shape)); @@ -340,10 +340,9 @@ Result> FixedShapeTensorArray::ToTensorWithNulls() const std::vector shape = ext_type.shape(); ARROW_ASSIGN_OR_RAISE(const int64_t cell_size, internal::ComputeShapeProduct(shape)); shape.insert(shape.begin(), 1, this->length()); - internal::Permute(permutation, &shape); - ARROW_ASSIGN_OR_RAISE(auto tensor_strides, internal::ComputeStrides(value_type, shape, permutation)); + internal::Permute(permutation, &shape); const auto& raw_buffer = this->storage()->data()->child_data[0]->buffers[1]; ARROW_ASSIGN_OR_RAISE( diff --git a/cpp/src/arrow/extension/tensor_extension_array_test.cc b/cpp/src/arrow/extension/tensor_extension_array_test.cc index 29147df6ba6a..cfd16031b7c2 100644 --- a/cpp/src/arrow/extension/tensor_extension_array_test.cc +++ b/cpp/src/arrow/extension/tensor_extension_array_test.cc @@ -605,7 +605,7 @@ TEST_F(TestFixedShapeTensorType, ComputeStrides) { ASSERT_EQ(ext_type_6->Serialize(), R"({"shape":[3,4,7],"permutation":[1,2,0]})"); auto ext_type_7 = internal::checked_pointer_cast( fixed_shape_tensor(int32(), {3, 4, 7}, {2, 0, 1}, {})); - ASSERT_EQ(ext_type_7->strides(), (std::vector{4, 112, 16})); + ASSERT_EQ(ext_type_7->strides(), (std::vector{4, 112, 28})); ASSERT_EQ(ext_type_7->Serialize(), R"({"shape":[3,4,7],"permutation":[2,0,1]})"); } @@ -676,7 +676,7 @@ TEST_F(TestFixedShapeTensorType, GetTensor) { // Get tensor from extension array with non-trivial permutation ASSERT_OK_AND_ASSIGN(auto expected_permuted_tensor, Tensor::Make(value_type_, Buffer::Wrap(element_values[i]), - {4, 3}, {8, 24}, {"y", "x"})); + {4, 3}, {8, 32}, {"y", "x"})); ASSERT_OK_AND_ASSIGN(scalar, permuted_array->GetScalar(i)); ASSERT_OK_AND_ASSIGN(auto actual_permuted_tensor, exact_permuted_ext_type->MakeTensor( @@ -1002,6 +1002,50 @@ TEST_F(TestVariableShapeTensorType, ComputeStrides) { ASSERT_TRUE(tensor->Equals(*t)); } +TEST_F(TestVariableShapeTensorType, ComputeStridesWithNonTrivialPermutation) { + auto permuted_ext_type = internal::checked_pointer_cast( + variable_shape_tensor(value_type_, ndim_, {1, 0, 2}, dim_names_, uniform_shape_)); + + auto shape = ArrayFromJSON(shape_type_, "[[2,3,1]]"); + auto data = ArrayFromJSON(data_type_, "[[1,1,2,3,4,5]]"); + std::vector> fields = {field("data", data_type_), + field("shape", shape_type_)}; + ASSERT_OK_AND_ASSIGN(auto storage_arr, StructArray::Make({data, shape}, fields)); + auto ext_arr = ExtensionType::WrapArray(permuted_ext_type, storage_arr); + auto ext_array = std::static_pointer_cast(ext_arr); + + ASSERT_OK_AND_ASSIGN(auto scalar, ext_array->GetScalar(0)); + ASSERT_OK_AND_ASSIGN(auto tensor, + permuted_ext_type->MakeTensor( + internal::checked_pointer_cast(scalar))); + + ASSERT_EQ(tensor->shape(), (std::vector{3, 2, 1})); + ASSERT_EQ(tensor->strides(), (std::vector{sizeof(int64_t), sizeof(int64_t) * 3, + sizeof(int64_t)})); + ASSERT_EQ(tensor->dim_names(), (std::vector{"y", "x", "z"})); + + // Non-self-inverse 3-cycle permutation with distinct dimension sizes + auto cyclic_ext_type = internal::checked_pointer_cast( + variable_shape_tensor(value_type_, ndim_, {2, 0, 1}, dim_names_, {})); + auto cyclic_shape = ArrayFromJSON(shape_type_, "[[2,3,4]]"); + auto cyclic_data = ArrayFromJSON( + data_type_, "[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]]"); + ASSERT_OK_AND_ASSIGN(auto cyclic_storage, + StructArray::Make({cyclic_data, cyclic_shape}, fields)); + auto cyclic_arr = std::static_pointer_cast( + ExtensionType::WrapArray(cyclic_ext_type, cyclic_storage)); + ASSERT_OK_AND_ASSIGN(auto cyclic_scalar, cyclic_arr->GetScalar(0)); + ASSERT_OK_AND_ASSIGN( + auto cyclic_tensor, + cyclic_ext_type->MakeTensor( + internal::checked_pointer_cast(cyclic_scalar))); + ASSERT_EQ(cyclic_tensor->shape(), (std::vector{4, 2, 3})); + ASSERT_EQ( + cyclic_tensor->strides(), + (std::vector{sizeof(int64_t), sizeof(int64_t) * 12, sizeof(int64_t) * 4})); + ASSERT_EQ(cyclic_tensor->dim_names(), (std::vector{"z", "x", "y"})); +} + TEST_F(TestVariableShapeTensorType, ToString) { auto exact_ext_type = internal::checked_pointer_cast(ext_type_); diff --git a/cpp/src/arrow/extension/tensor_internal.cc b/cpp/src/arrow/extension/tensor_internal.cc index d2965bc578f7..014fc6feabd8 100644 --- a/cpp/src/arrow/extension/tensor_internal.cc +++ b/cpp/src/arrow/extension/tensor_internal.cc @@ -84,12 +84,10 @@ Result> ComputeStrides(const std::shared_ptr& val int64_t remaining = 0; if (!shape.empty() && shape[0] > 0) { remaining = byte_width; - for (auto i : perm) { - if (i > 0) { - if (MultiplyWithOverflow(remaining, shape[i], &remaining)) { - return Status::Invalid( - "Strides computed from shape would not fit in 64-bit integer"); - } + for (size_t i = 1; i < ndim; ++i) { + if (MultiplyWithOverflow(remaining, shape[i], &remaining)) { + return Status::Invalid( + "Strides computed from shape would not fit in 64-bit integer"); } } } @@ -101,11 +99,9 @@ Result> ComputeStrides(const std::shared_ptr& val } strides.push_back(remaining); - for (auto i : perm) { - if (i > 0) { - remaining /= shape[i]; - strides.push_back(remaining); - } + for (size_t i = 1; i < ndim; ++i) { + remaining /= shape[i]; + strides.push_back(remaining); } Permute(perm, &strides); diff --git a/docs/source/python/api/arrays.rst b/docs/source/python/api/arrays.rst index 290ce09befb1..c9dc39f690ae 100644 --- a/docs/source/python/api/arrays.rst +++ b/docs/source/python/api/arrays.rst @@ -101,6 +101,7 @@ may expose data type-specific methods or properties. JsonArray UuidArray Bool8Array + VariableShapeTensorArray .. _api.scalar: @@ -165,6 +166,7 @@ classes may expose data type-specific methods or properties. UnionScalar ExtensionScalar FixedShapeTensorScalar + VariableShapeTensorScalar OpaqueScalar JsonScalar UuidScalar diff --git a/docs/source/python/api/datatypes.rst b/docs/source/python/api/datatypes.rst index ea9e547d32c7..e8bd2b53ea66 100644 --- a/docs/source/python/api/datatypes.rst +++ b/docs/source/python/api/datatypes.rst @@ -68,6 +68,7 @@ These should be used to create Arrow data types and schemas. dictionary run_end_encoded fixed_shape_tensor + variable_shape_tensor union dense_union sparse_union @@ -142,6 +143,7 @@ implemented by PyArrow. :toctree: ../generated/ FixedShapeTensorType + VariableShapeTensorType OpaqueType JsonType UuidType diff --git a/python/pyarrow-stubs/__init__.pyi b/python/pyarrow-stubs/__init__.pyi index 445936bef98c..cf2fab0591a5 100644 --- a/python/pyarrow-stubs/__init__.pyi +++ b/python/pyarrow-stubs/__init__.pyi @@ -136,6 +136,8 @@ from pyarrow.lib import ( UnknownExtensionType as UnknownExtensionType, UuidArray as UuidArray, UuidType as UuidType, + VariableShapeTensorArray as VariableShapeTensorArray, + VariableShapeTensorType as VariableShapeTensorType, VersionInfo as VersionInfo, array as array, binary as binary, @@ -221,6 +223,7 @@ from pyarrow.lib import ( unregister_extension_type as unregister_extension_type, utf8 as utf8, uuid as uuid, + variable_shape_tensor as variable_shape_tensor, ) from pyarrow import types as types diff --git a/python/pyarrow-stubs/__lib/array.pyi b/python/pyarrow-stubs/__lib/array.pyi index d8f97ec67b1b..0e3b52985f95 100644 --- a/python/pyarrow-stubs/__lib/array.pyi +++ b/python/pyarrow-stubs/__lib/array.pyi @@ -608,6 +608,16 @@ class FixedShapeTensorArray(ExtensionArray): @staticmethod def from_tensor(tensor: Tensor) -> FixedShapeTensorArray: ... +class VariableShapeTensorArray(ExtensionArray): + @staticmethod + def from_numpy_ndarray( + obj: Sequence[NDArray[Any]], + dim_names: Sequence[str] | None = None, + permutation: Sequence[int] | None = None, + uniform_shape: Sequence[int | None] | None = None, + ) -> VariableShapeTensorArray: ... + def to_numpy_ndarray_list(self) -> list[NDArray[Any] | None]: ... + class OpaqueArray(ExtensionArray): ... class Bool8Array(ExtensionArray): @@ -684,6 +694,7 @@ __all__ = [ "JsonArray", "OpaqueArray", "FixedShapeTensorArray", + "VariableShapeTensorArray", "concat_arrays", "_empty_array", ] diff --git a/python/pyarrow-stubs/__lib/types.pyi b/python/pyarrow-stubs/__lib/types.pyi index 7810d33b762c..678798a77e4b 100644 --- a/python/pyarrow-stubs/__lib/types.pyi +++ b/python/pyarrow-stubs/__lib/types.pyi @@ -263,6 +263,18 @@ class FixedShapeTensorType(BaseExtensionType): @property def permutation(self) -> list[int] | None: ... +class VariableShapeTensorType(BaseExtensionType): + @property + def value_type(self) -> DataType: ... + @property + def ndim(self) -> int: ... + @property + def dim_names(self) -> list[str] | None: ... + @property + def permutation(self) -> list[int] | None: ... + @property + def uniform_shape(self) -> list[int | None] | None: ... + class Bool8Type(BaseExtensionType): ... class UuidType(BaseExtensionType): ... class JsonType(BaseExtensionType): ... @@ -562,6 +574,13 @@ def fixed_shape_tensor( dim_names: Sequence[str] | None = None, permutation: Sequence[int] | None = None, ) -> FixedShapeTensorType: ... +def variable_shape_tensor( + value_type: DataType, + ndim: int, + dim_names: Sequence[str] | None = None, + permutation: Sequence[int] | None = None, + uniform_shape: Sequence[int | None] | None = None, +) -> VariableShapeTensorType: ... def bool8() -> Bool8Type: ... def opaque(storage_type: DataType, type_name: str, vendor_name: str) -> OpaqueType: ... def type_for_alias(name: str) -> DataType: ... @@ -600,6 +619,7 @@ __all__ = [ "BaseExtensionType", "ExtensionType", "FixedShapeTensorType", + "VariableShapeTensorType", "Bool8Type", "UuidType", "JsonType", @@ -658,6 +678,7 @@ __all__ = [ "json_", "uuid", "fixed_shape_tensor", + "variable_shape_tensor", "bool8", "opaque", "type_for_alias", diff --git a/python/pyarrow/__init__.py b/python/pyarrow/__init__.py index c024cdc69a7d..53ad9c730edd 100644 --- a/python/pyarrow/__init__.py +++ b/python/pyarrow/__init__.py @@ -180,6 +180,7 @@ def print_entry(label, value): dictionary, run_end_encoded, bool8, fixed_shape_tensor, json_, opaque, uuid, + variable_shape_tensor, field, type_for_alias, DataType, DictionaryType, StructType, @@ -193,6 +194,7 @@ def print_entry(label, value): RunEndEncodedType, Bool8Type, FixedShapeTensorType, JsonType, OpaqueType, UuidType, UnknownExtensionType, + VariableShapeTensorType, register_extension_type, unregister_extension_type, DictionaryMemo, KeyValueMetadata, @@ -229,6 +231,7 @@ def print_entry(label, value): StructArray, ExtensionArray, RunEndEncodedArray, Bool8Array, FixedShapeTensorArray, JsonArray, OpaqueArray, UuidArray, + VariableShapeTensorArray, scalar, NA, _NULL as NULL, Scalar, NullScalar, BooleanScalar, Int8Scalar, Int16Scalar, Int32Scalar, Int64Scalar, @@ -246,7 +249,8 @@ def print_entry(label, value): FixedSizeBinaryScalar, DictionaryScalar, MapScalar, StructScalar, UnionScalar, RunEndEncodedScalar, Bool8Scalar, ExtensionScalar, - FixedShapeTensorScalar, JsonScalar, OpaqueScalar, UuidScalar) + FixedShapeTensorScalar, JsonScalar, OpaqueScalar, UuidScalar, + VariableShapeTensorScalar) # Buffers, allocation from pyarrow.lib import (DeviceAllocationType, Device, MemoryManager, diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index d45c3470f8c7..d2a00d38dc77 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -4996,7 +4996,7 @@ cdef class FixedShapeTensorArray(ExtensionArray): and the rest of the dimensions will match the permuted shape of the fixed shape tensor. - The conversion is zero-copy. + The conversion is zero-copy if data is primitive numeric and without nulls. Returns ------- @@ -5081,17 +5081,7 @@ cdef class FixedShapeTensorArray(ExtensionArray): "Cannot convert 1D array or scalar to fixed shape tensor array") if np.prod(obj.shape) == 0: raise ValueError("Expected a non-empty ndarray") - if dim_names is not None: - if not isinstance(dim_names, Sequence): - raise TypeError("dim_names must be a tuple or list") - if len(dim_names) != len(obj.shape[1:]): - raise ValueError( - (f"The length of dim_names ({len(dim_names)}) does not match" - f"the number of tensor dimensions ({len(obj.shape[1:])})." - ) - ) - if not all(isinstance(name, str) for name in dim_names): - raise TypeError("Each element of dim_names must be a string") + _validate_dim_names(dim_names, len(obj.shape[1:])) permutation = (-np.array(obj.strides)).argsort(kind='stable') if permutation[0] != 0: @@ -5100,12 +5090,13 @@ cdef class FixedShapeTensorArray(ExtensionArray): arrow_type = from_numpy_dtype(obj.dtype) shape = np.take(obj.shape, permutation) + permutation = _invert_permutation(permutation[1:] - 1) values = np.ravel(obj, order="K") return ExtensionArray.from_storage( fixed_shape_tensor(arrow_type, shape[1:], dim_names=dim_names, - permutation=permutation[1:] - 1), + permutation=permutation), FixedSizeListArray.from_arrays(values, shape[1:].prod()) ) @@ -5299,6 +5290,296 @@ cdef class Bool8Array(ExtensionArray): return Bool8Array.from_storage(storage_arr) +def _check_sequence_param(value, ndim, name): + if value is None: + return False + if not isinstance(value, Sequence) or isinstance(value, (str, bytes)): + raise TypeError(f"{name} must be a tuple or list") + if len(value) != ndim: + raise ValueError( + (f"The length of {name} ({len(value)}) does not match" + f" the number of tensor dimensions ({ndim}).")) + return True + + +def _validate_dim_names(dim_names, ndim): + if not _check_sequence_param(dim_names, ndim, "dim_names"): + return + if not all(isinstance(name, str) for name in dim_names): + raise TypeError("Each element of dim_names must be a string") + + +def _validate_permutation(permutation, ndim): + if not _check_sequence_param(permutation, ndim, "permutation"): + return None + int_types = (int, np.integer) if np is not None else (int,) + for x in permutation: + if isinstance(x, bool) or not isinstance(x, int_types): + raise TypeError("Each element of permutation must be an integer") + normalized = [int(x) for x in permutation] + if sorted(normalized) != list(range(ndim)): + raise ValueError( + "permutation must contain each dimension index exactly once") + return normalized + + +def _validate_uniform_shape(uniform_shape, ndim): + if not _check_sequence_param(uniform_shape, ndim, "uniform_shape"): + return + int_types = (int, np.integer) if np is not None else (int,) + for value in uniform_shape: + if value is None: + continue + if isinstance(value, bool) or not isinstance(value, int_types): + raise TypeError( + "Each non-None element of uniform_shape must be an integer") + if value < 0: + raise ValueError( + "uniform_shape must contain non-negative values") + + +def _infer_uniform_shape(shape_rows, ndim): + if len(shape_rows) == 0: + return None + inferred = [] + for i in range(ndim): + axis_size = shape_rows[0][i] + if all(shape[i] == axis_size for shape in shape_rows): + inferred.append(axis_size) + else: + inferred.append(None) + if all(x is None for x in inferred): + return None + return inferred + + +def _invert_permutation(permutation): + return [int(x) for x in + np.argsort(np.array(permutation, dtype=np.int64), kind="stable")] + + +def _permutation_from_strides(arr): + """Infer the logical-to-physical permutation from array strides. + + Note: for arrays with size-1 dimensions, the inferred permutation + may be unreliable since size-1 strides are unconstrained. Callers + should skip permutation validation for such arrays. + """ + return _invert_permutation( + (-np.array(arr.strides, dtype=np.int64)).argsort(kind="stable")) + + +cdef class VariableShapeTensorArray(ExtensionArray): + """ + Concrete class for variable shape tensor extension arrays. + + Examples + -------- + Define the extension type for tensor array + + >>> import pyarrow as pa + >>> tensor_type = pa.variable_shape_tensor(pa.float64(), 2) + + Create an extension array + + >>> shapes = pa.array([[2, 3], [1, 2]], pa.list_(pa.int32(), 2)) + >>> values = pa.array([[1, 2, 3, 4, 5, 6], [7, 8]], pa.list_(pa.float64())) + >>> arr = pa.StructArray.from_arrays([values, shapes], names=["data", "shape"]) + >>> pa.ExtensionArray.from_storage(tensor_type, arr) + + -- is_valid: all not null + -- child 0 type: list + [ + [ + 1, + 2, + 3, + 4, + 5, + 6 + ], + [ + 7, + 8 + ] + ] + -- child 1 type: fixed_size_list[2] + [ + [ + 2, + 3 + ], + [ + 1, + 2 + ] + ] + """ + + @staticmethod + def from_numpy_ndarray(obj, dim_names=None, permutation=None, uniform_shape=None): + """ + Convert a sequence of numpy.ndarrays to a variable shape tensor extension array. + The length of the input sequence becomes the length of the output array. + + Parameters + ---------- + obj : Sequence[numpy.ndarray] + Non-empty sequence of ndarrays with matching dtype, ndim, and + memory permutation. + dim_names : tuple or list of strings, default None + Explicit names to tensor dimensions in physical order. + permutation : tuple or list of integers, default None + Logical-to-physical permutation for all input arrays. If None, + inferred from strides. + uniform_shape : tuple or list of integers or None, default None + Optional known uniform dimensions in physical order. If None, inferred. + + Returns + ------- + VariableShapeTensorArray + + Examples + -------- + >>> import pyarrow as pa + >>> import numpy as np + >>> arrays = [np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32), + ... np.array([[7, 8]], dtype=np.int32)] + >>> pa.VariableShapeTensorArray.from_numpy_ndarray(arrays) + + ... + """ + cdef: + list arrays + list shape_rows + int ndim + int i + object base_dtype + DataType arrow_type + list normalized_permutation + list permutation_metadata + Array values + Array shapes + StructArray struct_arr + VariableShapeTensorType ext_type + + if np is None: + raise ImportError( + "Cannot convert numpy.ndarray if NumPy is not present") + + if not isinstance(obj, Sequence) or isinstance(obj, (str, bytes)): + raise TypeError("obj must be a sequence of numpy arrays") + arrays = list(obj) + + if len(arrays) == 0: + raise ValueError("Expected a non-empty sequence of ndarrays") + + for i, arr in enumerate(arrays): + if not isinstance(arr, np.ndarray): + raise TypeError(f"obj[{i}] must be a numpy.ndarray") + if arr.ndim == 0: + raise ValueError("Cannot convert scalar to variable shape tensor array") + if arr.size > 0: + for axis, (size, stride) in enumerate(zip(arr.shape, arr.strides)): + if size > 1 and stride <= 0: + raise ValueError( + f"obj[{i}] has non-positive stride {stride} along " + f"axis {axis}. Consider making the array contiguous " + f"first with np.ascontiguousarray().") + + base_dtype = arrays[0].dtype + ndim = arrays[0].ndim + arrow_type = from_numpy_dtype(base_dtype) + + for i, arr in enumerate(arrays[1:], start=1): + if arr.dtype != base_dtype: + raise TypeError( + f"obj[{i}] has dtype {arr.dtype}; expected {base_dtype}") + if arr.ndim != ndim: + raise ValueError(f"obj[{i}] has ndim {arr.ndim}; expected {ndim}") + + _validate_dim_names(dim_names, ndim) + normalized_permutation = _validate_permutation(permutation, ndim) + + # Infer permutation if not provided by the user. Prefer arrays + # without size-1 dimensions since their strides are unambiguous. + if normalized_permutation is None: + for arr in arrays: + if all(s > 1 for s in arr.shape): + normalized_permutation = _permutation_from_strides(arr) + break + else: + # All arrays have size-1 dims; use first array's strides + normalized_permutation = _permutation_from_strides(arrays[0]) + + physical_to_logical = _invert_permutation(normalized_permutation) + + # Validate that every non-empty array's strides along non-trivial + # dimensions (size > 1) are consistent with physical_to_logical order. + for i, arr in enumerate(arrays): + if arr.size == 0: + continue + prev_stride = None + for axis in physical_to_logical: + if arr.shape[axis] <= 1: + continue + stride = arr.strides[axis] + if prev_stride is not None and stride > prev_stride: + ndarray_permutation_list = _permutation_from_strides(arr) + raise ValueError( + (f"obj[{i}] has permutation {ndarray_permutation_list}; " + f"expected {list(normalized_permutation)}")) + prev_stride = stride + + shape_rows = [ + [int(x) for x in np.take(arr.shape, physical_to_logical)] + for arr in arrays + ] + + if uniform_shape is not None: + _validate_uniform_shape(uniform_shape, ndim) + for i, value in enumerate(uniform_shape): + if value is not None: + if any(shape[i] != value for shape in shape_rows): + raise ValueError( + (f"uniform_shape[{i}]={value} does not match input shape " + f"dimension values")) + else: + uniform_shape = _infer_uniform_shape(shape_rows, ndim) + + values = array( + [np.transpose(arr, physical_to_logical).ravel(order="C") + for arr in arrays], + list_(arrow_type)) + shapes = array(shape_rows, list_(int32(), list_size=ndim)) + struct_arr = StructArray.from_arrays([values, shapes], names=["data", "shape"]) + + if np.array_equal(normalized_permutation, np.arange(ndim)): + permutation_metadata = None + else: + permutation_metadata = normalized_permutation + + ext_type = variable_shape_tensor( + arrow_type, + ndim, + dim_names=dim_names, + permutation=permutation_metadata, + uniform_shape=uniform_shape, + ) + return ExtensionArray.from_storage(ext_type, struct_arr) + + def to_numpy_ndarray_list(self): + """ + Convert variable shape tensor extension array to a list of numpy.ndarrays. + + Returns + ------- + list + List containing one ndarray per valid element and None for null elements. + """ + return [x.to_numpy() if x.is_valid else None for x in self] + + cdef dict _array_classes = { _Type_NA: NullArray, _Type_BOOL: BooleanArray, diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 25a9aa8da6f5..90bcc2c27500 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -3044,6 +3044,27 @@ cdef extern from "arrow/extension/fixed_shape_tensor.h" namespace "arrow::extens const shared_ptr[CTensor]& tensor) +cdef extern from "arrow/extension/variable_shape_tensor.h" namespace "arrow::extension" nogil: + cdef cppclass CVariableShapeTensorType \ + " arrow::extension::VariableShapeTensorType"(CExtensionType): + + @staticmethod + CResult[shared_ptr[CTensor]] MakeTensor(const shared_ptr[CExtensionScalar]& scalar) + + @staticmethod + CResult[shared_ptr[CDataType]] Make(const shared_ptr[CDataType]& value_type, + const int32_t ndim, + const vector[int64_t] permutation, + const vector[c_string] dim_names, + const vector[optional[int64_t]] uniform_shape) + + const shared_ptr[CDataType] value_type() + const int32_t ndim() + const vector[int64_t] permutation() + const vector[c_string] dim_names() + const vector[optional[int64_t]] uniform_shape() + + cdef extern from "arrow/extension/opaque.h" namespace "arrow::extension" nogil: cdef cppclass COpaqueType \ " arrow::extension::OpaqueType"(CExtensionType): diff --git a/python/pyarrow/lib.pxd b/python/pyarrow/lib.pxd index 38f1ac69a807..20077a4fb0aa 100644 --- a/python/pyarrow/lib.pxd +++ b/python/pyarrow/lib.pxd @@ -195,6 +195,11 @@ cdef class ExtensionType(BaseExtensionType): const CPyExtensionType* cpy_ext_type +cdef class VariableShapeTensorType(BaseExtensionType): + cdef: + const CVariableShapeTensorType* tensor_ext_type + + cdef class FixedShapeTensorType(BaseExtensionType): cdef: const CFixedShapeTensorType* tensor_ext_type diff --git a/python/pyarrow/public-api.pxi b/python/pyarrow/public-api.pxi index d1fa1192debc..b0035ce79cb3 100644 --- a/python/pyarrow/public-api.pxi +++ b/python/pyarrow/public-api.pxi @@ -131,6 +131,8 @@ cdef api object pyarrow_wrap_data_type( out = Bool8Type.__new__(Bool8Type) elif extension_name == b"arrow.fixed_shape_tensor": out = FixedShapeTensorType.__new__(FixedShapeTensorType) + elif extension_name == b"arrow.variable_shape_tensor": + out = VariableShapeTensorType.__new__(VariableShapeTensorType) elif extension_name == b"arrow.opaque": out = OpaqueType.__new__(OpaqueType) elif extension_name == b"arrow.uuid": diff --git a/python/pyarrow/scalar.pxi b/python/pyarrow/scalar.pxi index 8c9adf9b522c..1f825c0c5fc3 100644 --- a/python/pyarrow/scalar.pxi +++ b/python/pyarrow/scalar.pxi @@ -1562,6 +1562,8 @@ cdef class FixedShapeTensorScalar(ExtensionScalar): ------- numpy.ndarray """ + if not self.is_valid: + raise ValueError("Cannot convert null scalar to numpy array") return self.to_tensor().to_numpy() def to_tensor(self): @@ -1576,6 +1578,8 @@ cdef class FixedShapeTensorScalar(ExtensionScalar): pyarrow.Tensor Tensor represented stored in FixedShapeTensorScalar. """ + if not self.is_valid: + raise ValueError("Cannot convert null scalar to Tensor") cdef: CFixedShapeTensorType* c_type = static_pointer_cast[CFixedShapeTensorType, CDataType]( self.wrapped.get().type).get() @@ -1640,6 +1644,47 @@ cdef class Bool8Scalar(ExtensionScalar): py_val = super().as_py() return None if py_val is None else py_val != 0 + +cdef class VariableShapeTensorScalar(ExtensionScalar): + """ + Concrete class for variable shape tensor extension scalar. + """ + + def to_numpy(self): + """ + Convert variable shape tensor extension scalar to a numpy.ndarray. + + The conversion is zero-copy. + + Returns + ------- + numpy.ndarray + """ + if not self.is_valid: + raise ValueError("Cannot convert null scalar to numpy array") + return self.to_tensor().to_numpy() + + def to_tensor(self): + """ + Convert variable shape tensor extension scalar to a pyarrow.Tensor. + + The conversion is zero-copy. + + Returns + ------- + tensor : pyarrow.Tensor + """ + if not self.is_valid: + raise ValueError("Cannot convert null scalar to Tensor") + cdef: + shared_ptr[CExtensionScalar] scalar = static_pointer_cast[CExtensionScalar, CScalar](self.wrapped) + shared_ptr[CTensor] ctensor + + with nogil: + ctensor = GetResultValue(CVariableShapeTensorType.MakeTensor(scalar)) + return pyarrow_wrap_tensor(ctensor) + + cdef dict _scalar_classes = { _Type_BOOL: BooleanScalar, _Type_UINT8: UInt8Scalar, diff --git a/python/pyarrow/tests/test_extension_type.py b/python/pyarrow/tests/test_extension_type.py index a9d15cfec10a..3a5183a2f87b 100644 --- a/python/pyarrow/tests/test_extension_type.py +++ b/python/pyarrow/tests/test_extension_type.py @@ -1613,7 +1613,7 @@ def test_array_from_extension_scalars(): assert result.equals(pa.array([u1, u2], type=pa.uuid())) -def test_tensor_type(): +def test_fixed_shape_tensor_type(): tensor_type = pa.fixed_shape_tensor(pa.int8(), [2, 3]) assert tensor_type.extension_name == "arrow.fixed_shape_tensor" assert tensor_type.storage_type == pa.list_(pa.int8(), 6) @@ -1638,6 +1638,56 @@ def test_tensor_type(): assert tensor_type.permutation is None +def test_variable_shape_tensor_type(): + tensor_type = pa.variable_shape_tensor(pa.int8(), 2) + expected_storage_type = pa.struct([ + pa.field("data", pa.list_(pa.int8())), + pa.field("shape", pa.list_(pa.int32(), 2)) + ]) + assert tensor_type.extension_name == "arrow.variable_shape_tensor" + assert tensor_type.storage_type == expected_storage_type + assert tensor_type.ndim == 2 + assert tensor_type.dim_names is None + assert tensor_type.permutation is None + assert tensor_type.uniform_shape is None + + tensor_type = pa.variable_shape_tensor(pa.int64(), 3, dim_names=['C', 'H', 'W']) + expected_storage_type = pa.struct([ + pa.field("data", pa.list_(pa.int64())), + pa.field("shape", pa.list_(pa.int32(), 3)) + ]) + assert tensor_type.extension_name == "arrow.variable_shape_tensor" + assert tensor_type.storage_type == expected_storage_type + assert tensor_type.ndim == 3 + assert tensor_type.dim_names == ['C', 'H', 'W'] + assert tensor_type.permutation is None + assert tensor_type.uniform_shape is None + + tensor_type = pa.variable_shape_tensor(pa.bool_(), 2, permutation=[1, 0]) + expected_storage_type = pa.struct([ + pa.field("data", pa.list_(pa.bool_())), + pa.field("shape", pa.list_(pa.int32(), 2)) + ]) + assert tensor_type.extension_name == "arrow.variable_shape_tensor" + assert tensor_type.storage_type == expected_storage_type + assert tensor_type.ndim == 2 + assert tensor_type.dim_names is None + assert tensor_type.permutation == [1, 0] + assert tensor_type.uniform_shape is None + + tensor_type = pa.variable_shape_tensor(pa.float64(), 2, uniform_shape=[1, None]) + expected_storage_type = pa.struct([ + pa.field("data", pa.list_(pa.float64())), + pa.field("shape", pa.list_(pa.int32(), 2)) + ]) + assert tensor_type.extension_name == "arrow.variable_shape_tensor" + assert tensor_type.storage_type == expected_storage_type + assert tensor_type.ndim == 2 + assert tensor_type.dim_names is None + assert tensor_type.permutation is None + assert tensor_type.uniform_shape == [1, None] + + @pytest.mark.numpy @pytest.mark.parametrize("np_type_str", ("int8", "int64", "float32")) def test_tensor_class_methods(np_type_str): @@ -1688,13 +1738,13 @@ def test_tensor_class_methods(np_type_str): tensor_type = pa.fixed_shape_tensor(arrow_type, [2, 2, 3], permutation=[2, 0, 1]) result = pa.ExtensionArray.from_storage(tensor_type, storage) expected = as_strided(flat_arr, shape=(1, 3, 2, 2), - strides=(bw * 12, bw, bw * 6, bw * 2)) + strides=(bw * 12, bw, bw * 6, bw * 3)) np.testing.assert_array_equal(result.to_numpy_ndarray(), expected) assert result.type.permutation == [2, 0, 1] assert result.type.shape == [2, 2, 3] assert result.to_tensor().shape == (1, 3, 2, 2) - assert result.to_tensor().strides == (12 * bw, 1 * bw, 6 * bw, 2 * bw) + assert result.to_tensor().strides == (12 * bw, 1 * bw, 6 * bw, 3 * bw) tensor_type = pa.fixed_shape_tensor(arrow_type, [2, 2, 3], permutation=[2, 1, 0]) result = pa.ExtensionArray.from_storage(tensor_type, storage) @@ -1777,6 +1827,14 @@ def test_tensor_array_from_numpy(np_type_str): assert tensor_array_from_numpy.type.dim_names is None assert tensor_array_from_numpy.to_tensor() == pa.Tensor.from_numpy(arr) + arr = np.arange(48, dtype=np.dtype(np_type_str)).reshape((2, 2, 3, 4)) + arr = np.transpose(arr, (0, 2, 3, 1)) + tensor_array_from_numpy = pa.FixedShapeTensorArray.from_numpy_ndarray(arr) + assert tensor_array_from_numpy.type.shape == [2, 3, 4] + assert tensor_array_from_numpy.type.permutation == [1, 2, 0] + assert tensor_array_from_numpy.type.dim_names is None + assert tensor_array_from_numpy.to_tensor() == pa.Tensor.from_numpy(arr) + arr = flat_arr.reshape(1, 2, 3, 2) result = pa.FixedShapeTensorArray.from_numpy_ndarray(arr) expected = np.array( @@ -1900,6 +1958,273 @@ def test_tensor_array_from_list_of_0d_arrays(): @pytest.mark.numpy +@pytest.mark.parametrize("value_type", ( + "int8", "int32", "int64", "float64")) +def test_variable_shape_tensor_class_methods(value_type): + value_type = getattr(np, value_type) + ndim = 2 + shape_type = pa.list_(pa.int32(), ndim) + arrow_type = pa.from_numpy_dtype(value_type) + tensor_type = pa.variable_shape_tensor( + arrow_type, + ndim, + dim_names=["H", "W"], + permutation=[0, 1], + uniform_shape=[None, None], + ) + fields = [pa.field("data", pa.list_(arrow_type)), pa.field("shape", shape_type)] + + shapes = pa.array([[2, 3], [2, 1]], shape_type) + values = pa.array([[1, 2, 3, 4, 5, 6], [7, 8]], pa.list_(arrow_type)) + struct_arr = pa.StructArray.from_arrays([values, shapes], fields=fields) + arr = pa.ExtensionArray.from_storage(tensor_type, struct_arr) + basic_arr = pa.ExtensionArray.from_storage( + pa.variable_shape_tensor(arrow_type, ndim, uniform_shape=[2, None]), struct_arr + ) + + storage = pa.array( + [([1, 2, 3, 4, 5, 6], [2, 3]), ([7, 8], [2, 1])], type=pa.struct(fields) + ) + assert pa.ExtensionArray.from_storage(tensor_type, storage).equals(arr) + + assert arr.type == tensor_type + + ndarray_list = [ + np.array([[1, 2, 3], [4, 5, 6]], dtype=value_type), + np.array([[7], [8]], dtype=value_type), + ] + for x, y in zip(arr, ndarray_list): + np.testing.assert_array_equal(x.to_numpy(), y) + + from_numpy = pa.VariableShapeTensorArray.from_numpy_ndarray(ndarray_list) + assert from_numpy.equals(basic_arr) + assert from_numpy.type.uniform_shape == [2, None] + + assert arr.to_pylist() == [ + {"data": [1, 2, 3, 4, 5, 6], "shape": [2, 3]}, + {"data": [7, 8], "shape": [2, 1]}, + ] + + expected_0 = np.array([[1, 2, 3], [4, 5, 6]], dtype=value_type) + expected_1 = np.array([[7], [8]], dtype=value_type) + + np.testing.assert_array_equal(arr[0].to_tensor().to_numpy(), expected_0) + np.testing.assert_array_equal(arr[1].to_tensor().to_numpy(), expected_1) + + np.testing.assert_array_equal(arr[0].to_numpy(), expected_0) + np.testing.assert_array_equal(arr[1].to_numpy(), expected_1) + + assert arr[0].to_tensor().equals( + pa.Tensor.from_numpy(expected_0, dim_names=["H", "W"])) + + assert arr[1].to_tensor().equals( + pa.Tensor.from_numpy(expected_1, dim_names=["H", "W"])) + + shapes = pa.array([[2, 3], [0, 0]], shape_type) + values = pa.array([[1, 2, 3, 4, 5, 6], []], pa.list_(arrow_type)) + struct_arr = pa.StructArray.from_arrays([values, shapes], fields=fields) + arr = pa.ExtensionArray.from_storage(tensor_type, struct_arr) + np.testing.assert_array_equal(arr[1].to_tensor().to_numpy(), np.array( + [], dtype=value_type).reshape(shapes[1].as_py())) + + +@pytest.mark.numpy +@pytest.mark.parametrize("value_type", ("int8", "int64", "float32")) +def test_variable_shape_tensor_array_from_numpy(value_type): + value_type = np.dtype(value_type).type() + arrow_type = pa.from_numpy_dtype(value_type) + + arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], + dtype=value_type, order="C") + tensor_array_from_numpy = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert isinstance(tensor_array_from_numpy.type, pa.VariableShapeTensorType) + assert tensor_array_from_numpy.type.value_type == arrow_type + assert tensor_array_from_numpy.type.ndim == 3 + assert tensor_array_from_numpy.type.permutation is None + assert tensor_array_from_numpy.type.uniform_shape == [2, 2, 3] + + f_arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], + dtype=value_type, order="F") + with pytest.raises(ValueError, match=r"obj\[1\] has permutation"): + pa.VariableShapeTensorArray.from_numpy_ndarray([f_arr, arr]) + with pytest.raises(ValueError, match=r"obj\[1\] has ndim"): + pa.VariableShapeTensorArray.from_numpy_ndarray([arr.reshape((12, 1)), arr]) + with pytest.raises(TypeError, match=r"obj\[1\] has dtype"): + pa.VariableShapeTensorArray.from_numpy_ndarray([arr.astype(np.int32()), arr]) + + from numpy.lib.stride_tricks import as_strided + + flat_arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=value_type) + bw = value_type.itemsize + + arr = flat_arr.reshape(1, 3, 4) + tensor_array_from_numpy = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert tensor_array_from_numpy.type.ndim == 3 + assert tensor_array_from_numpy.type.permutation is None + assert tensor_array_from_numpy.type.uniform_shape == [1, 3, 4] + + arr = as_strided(flat_arr, shape=(1, 2, 3, 2), + strides=(bw * 12, bw * 6, bw, bw * 3)) + tensor_array_from_numpy = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert tensor_array_from_numpy.type.ndim == 4 + assert tensor_array_from_numpy.type.permutation == [0, 1, 3, 2] + assert tensor_array_from_numpy[0].to_tensor() == pa.Tensor.from_numpy(arr) + assert tensor_array_from_numpy.type.uniform_shape == [1, 2, 2, 3] + + arr = flat_arr.reshape(1, 2, 3, 2) + result = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + expected = np.array( + [[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]], dtype=value_type) + np.testing.assert_array_equal(result[0].to_numpy(), expected) + + arr = np.arange(24, dtype=value_type).reshape((2, 3, 4)) + arr = np.transpose(arr, (2, 0, 1)) + result = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert result.type.permutation == [2, 0, 1] + assert result[0].to_tensor() == pa.Tensor.from_numpy(arr) + np.testing.assert_array_equal(result[0].to_numpy(), arr) + + arr = np.array([1, 2, 3, 4], dtype=value_type) + result = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert result.type.ndim == 1 + assert result.type.uniform_shape == [4] + np.testing.assert_array_equal(result[0].to_numpy(), arr) + + arr = np.array(1, dtype=value_type) + with pytest.raises(ValueError, match="Cannot convert scalar"): + pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + + arr = np.array([], dtype=value_type).reshape((0)) + result = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert result.type.ndim == 1 + np.testing.assert_array_equal(result[0].to_numpy(), arr) + + arr = np.array([], dtype=value_type).reshape((0, 3, 2)) + result = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert result.type.ndim == 3 + np.testing.assert_array_equal(result[0].to_numpy(), arr) + + arr = np.array([], dtype=value_type).reshape((3, 0, 2)) + result = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert result.type.ndim == 3 + np.testing.assert_array_equal(result[0].to_numpy(), arr) + + +@pytest.mark.numpy +@pytest.mark.parametrize("dtype", ( + "int8", "int16", "int32", "int64", "float32", "float64")) +def test_variable_shape_tensor_roundtrip_2d(dtype): + """Roundtrip C-contiguous 2D arrays through variable shape tensor.""" + dtype = np.dtype(dtype) + arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=dtype) + + result = pa.VariableShapeTensorArray.from_numpy_ndarray([arr]) + assert result.type.permutation is None + assert result.type.ndim == 2 + + tensor = result[0].to_tensor() + assert tensor == pa.Tensor.from_numpy(arr) + assert list(tensor.shape) == list(arr.shape) + assert list(tensor.strides) == list(arr.strides) + np.testing.assert_array_equal(result[0].to_numpy(), arr) + + stored_shape = result.storage.field("shape")[0].as_py() + assert stored_shape == list(arr.shape) + + # from_storage constructor path + arrow_type = pa.from_numpy_dtype(dtype) + tensor_type = pa.variable_shape_tensor(arrow_type, 2) + fields = [ + pa.field("data", pa.list_(arrow_type)), + pa.field("shape", pa.list_(pa.int32(), 2)), + ] + values = pa.array([[1, 2, 3, 4, 5, 6], [7, 8]], + pa.list_(arrow_type)) + shapes = pa.array([[2, 3], [2, 1]], pa.list_(pa.int32(), 2)) + storage = pa.StructArray.from_arrays([values, shapes], fields=fields) + ext_arr = pa.ExtensionArray.from_storage(tensor_type, storage) + + assert isinstance(ext_arr, pa.VariableShapeTensorArray) + assert ext_arr.type == tensor_type + expected_0 = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype) + expected_1 = np.array([[7], [8]], dtype=dtype) + np.testing.assert_array_equal(ext_arr[0].to_numpy(), expected_0) + np.testing.assert_array_equal(ext_arr[1].to_numpy(), expected_1) + + +@pytest.mark.numpy +def test_variable_shape_tensor_from_numpy_empty_input_rejected(): + with pytest.raises(ValueError, match="non-empty sequence of ndarrays"): + pa.VariableShapeTensorArray.from_numpy_ndarray([]) + + +@pytest.mark.numpy +def test_variable_shape_tensor_from_numpy_validation(): + arr = np.array([[1, 2], [3, 4]], dtype=np.int32) + result = pa.VariableShapeTensorArray.from_numpy_ndarray((arr,)) + assert result.type.ndim == 2 + + with pytest.raises(TypeError, match="obj must be a sequence of numpy arrays"): + pa.VariableShapeTensorArray.from_numpy_ndarray(arr) + + with pytest.raises(TypeError, match=r"obj\[1\] must be a numpy.ndarray"): + pa.VariableShapeTensorArray.from_numpy_ndarray([arr, [1, 2]]) + + with pytest.raises(ValueError, match="permutation must contain each dimension"): + pa.VariableShapeTensorArray.from_numpy_ndarray([arr], permutation=[0, 0]) + + with pytest.raises(ValueError, match=r"obj\[0\] has permutation"): + pa.VariableShapeTensorArray.from_numpy_ndarray([arr], permutation=[1, 0]) + + with pytest.raises(ValueError, match=r"uniform_shape\[0\]=3"): + pa.VariableShapeTensorArray.from_numpy_ndarray([arr], uniform_shape=[3, None]) + + +@pytest.mark.numpy +def test_variable_shape_tensor_to_numpy_ndarray_list_with_nulls(): + tensor_type = pa.variable_shape_tensor(pa.int32(), 2) + + data = pa.array([[1, 2, 3, 4, 5, 6], [10, 20], [7, 8]], pa.list_(pa.int32())) + shapes = pa.array([[2, 3], [1, 2], [2, 1]], + pa.list_(pa.int32(), 2)) + mask = pa.array([False, True, False]) + + storage = pa.StructArray.from_arrays( + [data, shapes], names=["data", "shape"], mask=mask) + arr = pa.ExtensionArray.from_storage(tensor_type, storage) + + result = arr.to_numpy_ndarray_list() + assert len(result) == 3 + np.testing.assert_array_equal( + result[0], np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)) + assert result[1] is None + np.testing.assert_array_equal( + result[2], np.array([[7], [8]], dtype=np.int32)) + + +@pytest.mark.numpy +def test_variable_shape_tensor_metadata_roundtrip_from_numpy(): + ndarray_list = [ + np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32), + np.array([[7], [8]], dtype=np.int32), + ] + arr = pa.VariableShapeTensorArray.from_numpy_ndarray( + ndarray_list, dim_names=["H", "W"]) + batch = pa.RecordBatch.from_arrays([arr], ["ext"]) + + buf = ipc_write_batch(batch) + batch = ipc_read_batch(buf) + result = batch.column(0) + + assert isinstance(result, pa.VariableShapeTensorArray) + assert result.type.dim_names == ["H", "W"] + assert result.type.permutation is None + assert result.type.uniform_shape == [2, None] + out_list = result.to_numpy_ndarray_list() + np.testing.assert_array_equal(out_list[0], ndarray_list[0]) + np.testing.assert_array_equal(out_list[1], ndarray_list[1]) + + @pytest.mark.parametrize("tensor_type", ( pa.fixed_shape_tensor(pa.int8(), [2, 2, 3]), pa.fixed_shape_tensor(pa.int8(), [2, 2, 3], permutation=[0, 2, 1]), @@ -1930,6 +2255,48 @@ def test_tensor_type_ipc(tensor_type): assert result.type.shape == [2, 2, 3] +@pytest.mark.parametrize("tensor_type", ( + pa.variable_shape_tensor(pa.int8(), 2), + pa.variable_shape_tensor(pa.int8(), 2, permutation=[1, 0]), + pa.variable_shape_tensor(pa.int8(), 2, dim_names=['H', 'W']), + pa.variable_shape_tensor(pa.int8(), 2, uniform_shape=[None, None]), +)) +def test_variable_shape_tensor_type_ipc(tensor_type): + values_type = tensor_type.storage_type.field(0).type + shape_type = tensor_type.storage_type.field(1).type + values = pa.array([[1, 2, 3, 4, 5, 6], [7, 8]], values_type) + shapes = pa.array([[2, 3], [1, 2]], shape_type) + + struct_arr = pa.StructArray.from_arrays([values, shapes], names=["data", "shape"]) + arr = pa.ExtensionArray.from_storage(tensor_type, struct_arr) + batch = pa.RecordBatch.from_arrays([arr], ["ext"]) + + # check the built array has exactly the expected clss + tensor_class = tensor_type.__arrow_ext_class__() + assert isinstance(arr, tensor_class) + + buf = ipc_write_batch(batch) + del batch + batch = ipc_read_batch(buf) + + result = batch.column(0) + # check the deserialized array class is the expected one + assert isinstance(result, tensor_class) + assert result.type.extension_name == "arrow.variable_shape_tensor" + assert result.storage.to_pylist() == [ + {"data": [1, 2, 3, 4, 5, 6], "shape": [2, 3]}, + {"data": [7, 8], "shape": [1, 2]}, + ] + + # we get back an actual TensorType + assert isinstance(result.type, pa.VariableShapeTensorType) + assert result.type.value_type == pa.int8() + assert result.type.ndim == 2 + assert result.type.permutation == tensor_type.permutation + assert result.type.dim_names == tensor_type.dim_names + assert result.type.uniform_shape == tensor_type.uniform_shape + + def test_tensor_type_equality(): tensor_type = pa.fixed_shape_tensor(pa.int8(), [2, 2, 3]) assert tensor_type.extension_name == "arrow.fixed_shape_tensor" @@ -1939,6 +2306,14 @@ def test_tensor_type_equality(): assert tensor_type == tensor_type2 assert not tensor_type == tensor_type3 + tensor_type = pa.variable_shape_tensor(pa.int8(), 2) + assert tensor_type.extension_name == "arrow.variable_shape_tensor" + + tensor_type2 = pa.variable_shape_tensor(pa.int8(), 2) + tensor_type3 = pa.variable_shape_tensor(pa.uint8(), 2) + assert tensor_type == tensor_type2 + assert not tensor_type == tensor_type3 + def test_tensor_type_cast(): tensor_type = pa.fixed_shape_tensor(pa.int8(), [2, 3]) @@ -2000,7 +2375,7 @@ def test_extension_to_pandas_storage_type(registered_period_type): assert isinstance(result["ext"].dtype, pd.ArrowDtype) -def test_tensor_type_is_picklable(pickle_module): +def test_fixed_shape_tensor_type_is_picklable(pickle_module): # GH-35599 expected_type = pa.fixed_shape_tensor(pa.int32(), (2, 2)) @@ -2016,6 +2391,308 @@ def test_tensor_type_is_picklable(pickle_module): assert result == expected_arr +def test_variable_shape_tensor_type_is_picklable(pickle_module): + expected_type = pa.variable_shape_tensor(pa.int32(), 2) + result = pickle_module.loads(pickle_module.dumps(expected_type)) + + assert result == expected_type + + shapes = pa.array([[2, 3], [1, 2]], pa.list_(pa.int32(), 2)) + values = pa.array([[1, 2, 3, 4, 5, 6], [7, 8]], pa.list_(pa.int32())) + arr = pa.StructArray.from_arrays([values, shapes], names=["data", "shape"]) + expected_arr = pa.ExtensionArray.from_storage(expected_type, arr) + + result = pickle_module.loads(pickle_module.dumps(expected_arr)) + + assert result == expected_arr + + # Pickle with all optional params populated + expected_type = pa.variable_shape_tensor( + pa.float32(), 3, + dim_names=['C', 'H', 'W'], + permutation=[0, 2, 1], + uniform_shape=[3, None, None]) + result = pickle_module.loads(pickle_module.dumps(expected_type)) + assert result == expected_type + assert result.dim_names == ['C', 'H', 'W'] + assert result.permutation == [0, 2, 1] + assert result.uniform_shape == [3, None, None] + + +@pytest.mark.numpy +def test_variable_shape_tensor_scalar(): + tensor_type = pa.variable_shape_tensor(pa.int32(), 2) + values = pa.array([[1, 2, 3, 4, 5, 6], [7, 8]], pa.list_(pa.int32())) + shapes = pa.array([[2, 3], [2, 1]], pa.list_(pa.int32(), 2)) + storage = pa.StructArray.from_arrays( + [values, shapes], names=["data", "shape"]) + arr = pa.ExtensionArray.from_storage(tensor_type, storage) + + scalar = arr[0] + assert isinstance(scalar, pa.VariableShapeTensorScalar) + np.testing.assert_array_equal( + scalar.to_numpy(), + np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)) + + tensor = scalar.to_tensor() + assert isinstance(tensor, pa.Tensor) + np.testing.assert_array_equal( + tensor.to_numpy(), + np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)) + + # null scalar + mask = pa.array([True, False]) + storage_with_null = pa.StructArray.from_arrays( + [values, shapes], names=["data", "shape"], mask=mask) + arr_with_null = pa.ExtensionArray.from_storage(tensor_type, storage_with_null) + null_scalar = arr_with_null[0] + + assert not null_scalar.is_valid + with pytest.raises(ValueError, match="Cannot convert null scalar to numpy array"): + null_scalar.to_numpy() + with pytest.raises(ValueError, match="Cannot convert null scalar to Tensor"): + null_scalar.to_tensor() + + +@pytest.mark.numpy +def test_fixed_shape_tensor_scalar_null(): + tensor_type = pa.fixed_shape_tensor(pa.int32(), [2, 3]) + storage = pa.array([[1, 2, 3, 4, 5, 6], None], + pa.list_(pa.int32(), 6)) + arr = pa.ExtensionArray.from_storage(tensor_type, storage) + null_scalar = arr[1] + + assert not null_scalar.is_valid + with pytest.raises(ValueError, match="Cannot convert null scalar to numpy array"): + null_scalar.to_numpy() + with pytest.raises(ValueError, match="Cannot convert null scalar to Tensor"): + null_scalar.to_tensor() + + +def test_variable_shape_tensor_type_cast(): + tensor_type = pa.variable_shape_tensor(pa.int32(), 2) + values = pa.array([[1, 2, 3, 4, 5, 6], [7, 8]], pa.list_(pa.int32())) + shapes = pa.array([[2, 3], [2, 1]], pa.list_(pa.int32(), 2)) + storage = pa.StructArray.from_arrays( + [values, shapes], names=["data", "shape"]) + + # cast storage -> extension type + result = storage.cast(tensor_type) + expected = pa.ExtensionArray.from_storage(tensor_type, storage) + assert result.equals(expected) + + # cast extension type -> storage type + storage_result = result.cast(storage.type) + assert storage_result.equals(storage) + + +@pytest.mark.parametrize(("tensor_type", "text"), [ + ( + pa.variable_shape_tensor(pa.int8(), 2), + 'variable_shape_tensor[value_type=int8, ndim=2]' + ), + ( + pa.variable_shape_tensor(pa.int32(), 3, permutation=[0, 2, 1]), + 'variable_shape_tensor[value_type=int32, ndim=3, permutation=[0,2,1]]' + ), + ( + pa.variable_shape_tensor(pa.int64(), 3, dim_names=['C', 'H', 'W']), + 'variable_shape_tensor[value_type=int64, ndim=3, dim_names=[C,H,W]]' + ), + ( + pa.variable_shape_tensor(pa.int32(), 2, uniform_shape=[2, None]), + 'variable_shape_tensor[value_type=int32, ndim=2, uniform_shape=[2,null]]' + ), +]) +def test_variable_shape_tensor_type_str(tensor_type, text): + tensor_type_str = tensor_type.__str__() + assert text in tensor_type_str + + +@pytest.mark.numpy +def test_variable_shape_tensor_from_numpy_dim_names_validation(): + arrays = [np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)] + + # Wrong-length dim_names + with pytest.raises(ValueError, match="length of dim_names"): + pa.VariableShapeTensorArray.from_numpy_ndarray( + arrays, dim_names=["only_one"]) + + # Non-string dim_names + with pytest.raises(TypeError, match="Each element of dim_names must be a string"): + pa.VariableShapeTensorArray.from_numpy_ndarray( + arrays, dim_names=[1, 2]) + + # String passed as dim_names/permutation/uniform_shape must be rejected + with pytest.raises(TypeError, match="dim_names must be a tuple or list"): + pa.VariableShapeTensorArray.from_numpy_ndarray(arrays, dim_names="HW") + with pytest.raises(TypeError, match="permutation must be a tuple or list"): + pa.VariableShapeTensorArray.from_numpy_ndarray(arrays, permutation="01") + with pytest.raises(TypeError, match="uniform_shape must be a tuple or list"): + pa.VariableShapeTensorArray.from_numpy_ndarray(arrays, uniform_shape="23") + + # Bool / float rejected in permutation and uniform_shape + with pytest.raises(TypeError, match="Each element of permutation must be an integer"): + pa.VariableShapeTensorArray.from_numpy_ndarray( + arrays, permutation=[False, True]) + with pytest.raises(TypeError, match="Each element of permutation must be an integer"): + pa.VariableShapeTensorArray.from_numpy_ndarray(arrays, permutation=[0.0, 1.0]) + with pytest.raises(TypeError, match="Each non-None element of uniform_shape must be an integer"): + pa.VariableShapeTensorArray.from_numpy_ndarray( + arrays, uniform_shape=[True, None]) + + +def test_variable_shape_tensor_type_validation_and_equality(): + with pytest.raises(TypeError, match="value_type must not be None"): + pa.variable_shape_tensor(None, 2) + with pytest.raises(TypeError, match="ndim must not be None"): + pa.variable_shape_tensor(pa.int32(), None) + with pytest.raises(pa.ArrowInvalid, match="ndim must be non-negative"): + pa.variable_shape_tensor(pa.int32(), -1) + with pytest.raises(pa.ArrowInvalid, match="non-fixed-width"): + pa.variable_shape_tensor(pa.string(), 2) + with pytest.raises(pa.ArrowInvalid, match="dim_names size must match ndim"): + pa.variable_shape_tensor(pa.int32(), 2, dim_names=["H"]) + with pytest.raises(pa.ArrowInvalid, match="permutation size must match ndim"): + pa.variable_shape_tensor(pa.int32(), 2, permutation=[0]) + with pytest.raises(pa.ArrowInvalid, match="uniform_shape size must match ndim"): + pa.variable_shape_tensor(pa.int32(), 2, uniform_shape=[2]) + with pytest.raises(pa.ArrowInvalid, match="uniform_shape must have non-negative"): + pa.variable_shape_tensor(pa.int32(), 2, uniform_shape=[-1, None]) + + # Trivial permutation equals omitted permutation + t_none = pa.variable_shape_tensor(pa.int32(), 2) + t_trivial = pa.variable_shape_tensor(pa.int32(), 2, permutation=[0, 1]) + t_perm = pa.variable_shape_tensor(pa.int32(), 2, permutation=[1, 0]) + assert t_none == t_trivial + assert t_none != t_perm + + # dim_names and uniform_shape affect equality + assert t_none != pa.variable_shape_tensor(pa.int32(), 2, dim_names=["H", "W"]) + assert t_none != pa.variable_shape_tensor(pa.int32(), 2, uniform_shape=[None, None]) + assert ( + pa.variable_shape_tensor(pa.int32(), 2, uniform_shape=[2, None]) + != pa.variable_shape_tensor(pa.int32(), 2, uniform_shape=[3, None]) + ) + + +@pytest.mark.numpy +def test_variable_shape_tensor_from_numpy_edge_cases(): + # NaN values must round-trip cleanly + nan_arr = np.array([[1.0, np.nan, 3.0], [4.0, 5.0, np.nan]], dtype=np.float64) + res_nan = pa.VariableShapeTensorArray.from_numpy_ndarray([nan_arr]) + np.testing.assert_array_equal(res_nan[0].to_numpy(), nan_arr) + + # Non-contiguous strided slice must round-trip cleanly + base = np.arange(24, dtype=np.int32).reshape(4, 6) + sliced = base[:, ::2] + res_sliced = pa.VariableShapeTensorArray.from_numpy_ndarray([sliced]) + np.testing.assert_array_equal(res_sliced[0].to_numpy(), sliced) + + # Negative strides must be rejected (including when not the first element) + valid = np.array([[1, 2], [3, 4]], dtype=np.int32) + neg_stride = valid[::-1] + with pytest.raises(ValueError, match="non-positive stride"): + pa.VariableShapeTensorArray.from_numpy_ndarray([neg_stride]) + with pytest.raises(ValueError, match="non-positive stride"): + pa.VariableShapeTensorArray.from_numpy_ndarray([valid, neg_stride]) + + # Zero (broadcast) strides must be rejected + broadcast = np.broadcast_to(np.array([1, 2], dtype=np.int32), (3, 2)) + with pytest.raises(ValueError, match="non-positive stride"): + pa.VariableShapeTensorArray.from_numpy_ndarray([broadcast]) + + # Mixed size-1 C-order and F-order arrays must be rejected rather than corrupted + c_with_one = np.arange(6, dtype=np.int32).reshape(1, 2, 3) + f_arr = np.asfortranarray(np.arange(24, dtype=np.int32).reshape(2, 3, 4)) + with pytest.raises(ValueError, match=r"obj\[0\] has permutation"): + pa.VariableShapeTensorArray.from_numpy_ndarray([c_with_one, f_arr]) + + # Explicit F-order permutation with matching arrays + f_arr_1 = np.asfortranarray(np.arange(6, dtype=np.int32).reshape(2, 3)) + f_arr_2 = np.asfortranarray(np.arange(8, dtype=np.int32).reshape(4, 2)) + res_f = pa.VariableShapeTensorArray.from_numpy_ndarray( + [f_arr_1, f_arr_2], permutation=[1, 0]) + assert res_f.type.permutation == [1, 0] + np.testing.assert_array_equal(res_f[0].to_numpy(), f_arr_1) + np.testing.assert_array_equal(res_f[1].to_numpy(), f_arr_2) + + +@pytest.mark.numpy +def test_variable_shape_tensor_slice_and_inner_nulls(): + arrays = [ + np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32), + np.array([[7, 8]], dtype=np.int32), + np.array([[9], [10], [11]], dtype=np.int32), + ] + arr = pa.VariableShapeTensorArray.from_numpy_ndarray(arrays) + sliced = arr.slice(1, 2) + assert len(sliced) == 2 + np.testing.assert_array_equal(sliced[0].to_numpy(), arrays[1]) + np.testing.assert_array_equal(sliced[1].to_numpy(), arrays[2]) + + # Inner data list containing nulls cannot be converted to Tensor + tensor_type = pa.variable_shape_tensor(pa.int32(), 2) + values = pa.array([[1, None, 3, 4]], pa.list_(pa.int32())) + shapes = pa.array([[2, 2]], pa.list_(pa.int32(), 2)) + storage = pa.StructArray.from_arrays([values, shapes], names=["data", "shape"]) + arr_inner_null = pa.ExtensionArray.from_storage(tensor_type, storage) + with pytest.raises(pa.ArrowInvalid, match="Cannot convert data with nulls"): + arr_inner_null[0].to_tensor() + + +_TENSOR_PERMUTATION_CASES = [ + ((3, 5), (0, 1)), + ((3, 5), (1, 0)), + ((2, 3, 5), (0, 2, 1)), + ((2, 3, 5), (1, 2, 0)), + ((2, 3, 5), (2, 0, 1)), + ((2, 3, 5), (2, 1, 0)), + ((2, 3, 5, 7), (3, 0, 1, 2)), + ((2, 3, 5, 7), (1, 3, 0, 2)), +] + + +@pytest.mark.numpy +@pytest.mark.parametrize(("physical_shape", "perm"), _TENSOR_PERMUTATION_CASES) +def test_fixed_shape_tensor_permutation_matches_numpy_strides(physical_shape, perm): + base = np.arange(int(np.prod(physical_shape)), dtype=np.int32).reshape( + physical_shape) + batched = np.stack([base, base + base.size]).transpose( + (0,) + tuple(p + 1 for p in perm)) + + arr = pa.FixedShapeTensorArray.from_numpy_ndarray(batched) + assert arr.type.shape == list(physical_shape) + assert arr.type.permutation == list(perm) + + out = arr.to_numpy_ndarray() + assert out.shape == batched.shape + assert out.strides == batched.strides + np.testing.assert_array_equal(out, batched) + + +@pytest.mark.numpy +@pytest.mark.parametrize( + ("physical_shape", "perm"), + _TENSOR_PERMUTATION_CASES + [((2, 1, 3), (2, 0, 1))], +) +def test_variable_shape_tensor_permutation_matches_numpy_strides(physical_shape, perm): + base = np.arange(int(np.prod(physical_shape)), dtype=np.int32).reshape( + physical_shape) + expected = np.transpose(base, perm) + explicit_perm = perm if 1 in physical_shape else None + + arr = pa.VariableShapeTensorArray.from_numpy_ndarray( + [expected], permutation=explicit_perm) + expected_perm = None if perm == tuple(range(len(perm))) else list(perm) + assert arr.type.permutation == expected_perm + + out = arr[0].to_numpy() + assert out.shape == expected.shape + assert out.strides == expected.strides + np.testing.assert_array_equal(out, expected) + + @pytest.mark.parametrize(("tensor_type", "text"), [ ( pa.fixed_shape_tensor(pa.int8(), [2, 2, 3]), diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi index b6d647ce3db7..9ad562eddc04 100644 --- a/python/pyarrow/types.pxi +++ b/python/pyarrow/types.pxi @@ -1990,6 +1990,105 @@ cdef class UuidType(BaseExtensionType): return UuidScalar +cdef class VariableShapeTensorType(BaseExtensionType): + """ + Concrete class for variable shape tensor extension type. + + Examples + -------- + Create an instance of variable shape tensor extension type: + + >>> import pyarrow as pa + >>> pa.variable_shape_tensor(pa.int32(), 2) + VariableShapeTensorType(extension) + + Create an instance of variable shape tensor extension type with + permutation: + + >>> tensor_type = pa.variable_shape_tensor(pa.int8(), 3, + ... permutation=[0, 2, 1]) + >>> tensor_type.permutation + [0, 2, 1] + """ + + cdef void init(self, const shared_ptr[CDataType]& type) except *: + BaseExtensionType.init(self, type) + self.tensor_ext_type = type.get() + + @property + def value_type(self): + """ + Data type of an individual tensor. + """ + return pyarrow_wrap_data_type(self.tensor_ext_type.value_type()) + + @property + def ndim(self): + """ + Number of dimensions of the tensors. + """ + return self.tensor_ext_type.ndim() + + @property + def dim_names(self): + """ + Explicit names of the dimensions. + """ + list_of_bytes = self.tensor_ext_type.dim_names() + if len(list_of_bytes) != 0: + return [frombytes(x) for x in list_of_bytes] + else: + return None + + @property + def permutation(self): + """ + Indices of the dimensions ordering. + """ + indices = self.tensor_ext_type.permutation() + if len(indices) != 0: + return indices + else: + return None + + @property + def uniform_shape(self): + """ + Shape over dimensions that are guaranteed to be constant. + + Returns None if no uniform shape metadata is present on the type. + When present, returns a list of length ``ndim`` where integer values + indicate uniform (fixed) dimensions and None values indicate + variable dimensions. Note that ``[None, None]`` (metadata present, + all dimensions variable) is distinct from ``None`` (no metadata). + """ + cdef: + vector[optional[int64_t]] c_uniform_shape = self.tensor_ext_type.uniform_shape() + length = c_uniform_shape.size() + + if length == 0: + return None + + uniform_shape = [] + for i in range(length): + if c_uniform_shape[i].has_value(): + uniform_shape.append(c_uniform_shape[i].value()) + else: + uniform_shape.append(None) + + return uniform_shape + + def __arrow_ext_class__(self): + return VariableShapeTensorArray + + def __reduce__(self): + return variable_shape_tensor, (self.value_type, self.ndim, + self.dim_names, self.permutation, self.uniform_shape) + + def __arrow_ext_scalar_class__(self): + return VariableShapeTensorScalar + + cdef class FixedShapeTensorType(BaseExtensionType): """ Concrete class for fixed shape tensor extension type. @@ -5536,7 +5635,7 @@ def fixed_shape_tensor(DataType value_type, shape, dim_names=None, permutation=N The physical shape of the contained tensors. dim_names : tuple or list of strings, default None Explicit names to tensor dimensions. - permutation : tuple or list integers, default None + permutation : tuple or list of integers, default None Indices of the desired ordering of the original dimensions. The indices contain a permutation of the values ``[0, 1, .., N-1]`` where N is the number of dimensions. The permutation indicates which dimension @@ -5724,6 +5823,123 @@ def opaque(DataType storage_type, str type_name not None, str vendor_name not No return out +def variable_shape_tensor(DataType value_type, ndim, dim_names=None, permutation=None, + uniform_shape=None): + """ + Create instance of variable shape tensor extension type with number of + dimensions and optional names of tensor dimensions and indices of the + desired logical ordering of dimensions. + + Parameters + ---------- + value_type : DataType + Data type of individual tensor elements. + ndim : integer + The number of dimensions of the contained tensors. + dim_names : tuple or list of strings, default None + Explicit names to tensor dimensions. + permutation : tuple or list of integers, default None + Indices of the desired ordering of the original dimensions. + The indices contain a permutation of the values ``[0, 1, .., N-1]`` where + N is the number of dimensions. The permutation indicates which dimension + of the logical layout corresponds to which dimension of the physical tensor. + For more information on this parameter see + :ref:`variable_shape_tensor_extension`. + uniform_shape : tuple or list of integers or None, default None + Shape of dimensions that are guaranteed to stay constant over all tensors + in the array if all their non-uniform sizes were replaced by None. + + Examples + -------- + Create an instance of variable shape tensor extension type: + + >>> import pyarrow as pa + >>> tensor_type = pa.variable_shape_tensor(pa.int32(), 2) + >>> tensor_type + VariableShapeTensorType(extension) + + Inspect the data type: + + >>> tensor_type.value_type + DataType(int32) + >>> tensor_type.ndim + 2 + + Create a table with variable shape tensor extension array: + + >>> fields = [pa.field("data", pa.list_(pa.int32())), pa.field("shape", pa.list_(pa.int32(), 2))] + >>> storage = pa.array([([1, 2, 3, 4, 5, 6], [2, 3]), ([7, 8], [1, 2])], type=pa.struct(fields)) + >>> tensor = pa.ExtensionArray.from_storage(tensor_type, storage) + >>> pa.table([tensor], names=["tensor_array"]) + pyarrow.Table + tensor_array: extension + ---- + tensor_array: [ -- is_valid: all not null + -- child 0 type: list + [[1,2,3,4,5,6],[7,8]] + -- child 1 type: fixed_size_list[2] + [[2,3],[1,2]]] + + Create an instance of variable shape tensor extension type with names + of tensor dimensions: + + >>> tensor_type = pa.variable_shape_tensor(pa.int8(), 3, + ... dim_names=['C', 'H', 'W']) + >>> tensor_type.dim_names + ['C', 'H', 'W'] + + Create an instance of variable shape tensor extension type with + permutation: + + >>> tensor_type = pa.variable_shape_tensor(pa.int8(), 3, + ... permutation=[0, 2, 1]) + >>> tensor_type.permutation + [0, 2, 1] + + Returns + ------- + type : VariableShapeTensorType + """ + + cdef: + int32_t c_ndim + vector[int64_t] c_permutation + vector[c_string] c_dim_names + vector[optional[int64_t]] c_uniform_shape + shared_ptr[CDataType] c_tensor_ext_type + + if value_type is None: + raise TypeError('value_type must not be None') + if ndim is None: + raise TypeError('ndim must not be None') + + c_ndim = ndim + + if permutation is not None: + for i in permutation: + c_permutation.push_back(i) + + if dim_names is not None: + for x in dim_names: + c_dim_names.push_back(tobytes(x)) + + if uniform_shape is not None: + for x in uniform_shape: + if x is None: + c_uniform_shape.push_back(nullopt) + else: + c_uniform_shape.push_back((x)) + + cdef VariableShapeTensorType out = VariableShapeTensorType.__new__(VariableShapeTensorType) + + with nogil: + c_tensor_ext_type = GetResultValue(CVariableShapeTensorType.Make( + value_type.sp_type, c_ndim, c_permutation, c_dim_names, c_uniform_shape)) + + out.init(c_tensor_ext_type) + return out + + cdef dict _type_aliases = { 'null': null, 'bool': bool_,