Copilot commented on code in PR #40354:
URL: https://github.com/apache/arrow/pull/40354#discussion_r4762630140
##########
cpp/src/arrow/extension/fixed_shape_tensor.cc:
##########
@@ -200,15 +200,15 @@ Result<std::shared_ptr<Tensor>>
FixedShapeTensorType::MakeTensor(
}
std::vector<int64_t> shape = ext_type.shape();
+ ARROW_ASSIGN_OR_RAISE(
+ auto strides, internal::ComputeStrides(ext_type.value_type(), shape,
permutation));
Review Comment:
The corrected strides conflict with unchanged test expectations, causing the
C++ and Python tensor tests to fail. Update
`cpp/src/arrow/extension/tensor_extension_array_test.cc:679` from `{8, 24}` to
`{8, 32}`, and change the final stride from `2*bw` to `3*bw` in both
expectations at `python/pyarrow/tests/test_extension_type.py:1741,1747`. Keep
the corrected stride calculations here and in `ToTensorWithNulls`.
##########
python/pyarrow/array.pxi:
##########
@@ -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)
+ <pyarrow.lib.VariableShapeTensorArray object at ...>
+ -- is_valid: all not null
+ -- child 0 type: list<item: double>
+ [
+ [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ],
+ [
+ 7,
+ 8
+ ]
+ ]
+ -- child 1 type: fixed_size_list<item: int32>[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)
+ <pyarrow.lib.VariableShapeTensorArray object at ...>
+ ...
+ """
+ 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])
Review Comment:
When every input has a singleton axis, taking the first array's stride order
can reject compatible arrays. For example, `np.empty((2, 1, 3), order='F')` and
`np.empty((1, 2, 3), order='F')` are both Fortran-contiguous, but this infers
`[2, 0, 1]` and subsequently rejects `obj[1]`; `[2, 1, 0]` works for both.
Infer a common order from all inputs' non-singleton-axis constraints instead of
fixing arbitrary singleton-axis positions from the first input.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]