jorisvandenbossche commented on code in PR #8510:
URL: https://github.com/apache/arrow/pull/8510#discussion_r1091696423


##########
cpp/src/arrow/extension_type_test.cc:
##########
@@ -333,4 +335,82 @@ TEST_F(TestExtensionType, ValidateExtensionArray) {
   ASSERT_OK(ext_arr4->ValidateFull());
 }
 
+TEST_F(TestExtensionType, TensorArrayType) {
+  using TensorArrayType = extension::TensorArrayType;
+
+  auto value_type = int64();
+  std::vector<int64_t> shape = {3, 3, 4};
+  std::vector<int64_t> row_major_strides = {36, 12, 4};
+  std::vector<int64_t> column_major_strides = {4, 12, 36};
+  std::vector<int64_t> values = {0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 
11,
+                                 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 
23,
+                                 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 
35};
+  std::vector<int64_t> values_partial = {0,  1,  2,  3,  4,  5,  6,  7,  8,  
9,  10, 11,
+                                         12, 13, 14, 15, 16, 17, 18, 19, 20, 
21, 22, 23};
+  std::vector<int64_t> shape_partial = {2, 3, 4};
+
+  ASSERT_OK_AND_ASSIGN(auto tensor, Tensor::Make(value_type, 
Buffer::Wrap(values), shape,
+                                                 row_major_strides));
+  ASSERT_OK_AND_ASSIGN(auto tensor_partial,
+                       Tensor::Make(value_type, Buffer::Wrap(values_partial),
+                                    shape_partial, row_major_strides));
+
+  std::shared_ptr<ExtensionType> row_major_ext_type = extension::tensor_array(
+      value_type, shape, /*is_row_major=*/true, "{\"key1\": \"metadata1\"}");
+  std::shared_ptr<ExtensionType> column_major_ext_type =
+      extension::tensor_array(value_type, shape, /*is_row_major=*/false, 
"{\"key2\": 1}");
+  auto exact_ext_type = 
std::dynamic_pointer_cast<TensorArrayType>(row_major_ext_type);
+
+  auto ext_arr = exact_ext_type->MakeArray(tensor);
+  auto ext_arr_partial = exact_ext_type->MakeArray(tensor_partial);
+
+  ASSERT_EQ(row_major_ext_type->Serialize(),
+            "{\"shape\":[3,3,4],\"order\":\"C\",\"metadata\":\"{\\\"key1\\\": "
+            "\\\"metadata1\\\"}\"}");
+  ASSERT_EQ(column_major_ext_type->Serialize(),
+            "{\"shape\":[3,3,4],\"order\":\"F\",\"metadata\":\"{\\\"key2\\\": 
1}\"}");
+  ASSERT_EQ(row_major_ext_type->extension_name(), "arrow.fixed_size_tensor");
+  ASSERT_OK(ext_arr->ValidateFull());
+  ASSERT_OK(ext_arr_partial->ValidateFull());
+
+  AssertArraysEqual(*ext_arr->storage()->Slice(0, 24), 
*ext_arr_partial->storage());
+  auto arr_slice = ext_arr->Slice(0, 24);
+  auto tensor_slice = exact_ext_type->ToTensor(arr_slice);
+  // TODO
+  // ASSERT_TRUE(tensor_partial->Equals(*tensor_slice));
+
+  auto type = std::dynamic_pointer_cast<TensorArrayType>(ext_arr->type());
+  ASSERT_EQ(type->id(), Type::EXTENSION);
+
+  std::string serialized = row_major_ext_type->Serialize();
+  ASSERT_OK_AND_ASSIGN(auto deserialized,
+                       row_major_ext_type->Deserialize(row_major_ext_type, 
serialized));
+  // TODO
+  // ASSERT_TRUE(deserialized->Equals(row_major_ext_type));
+  ASSERT_FALSE(deserialized->Equals(*fixed_size_binary(16)));
+
+  auto batch =
+      RecordBatch::Make(schema({field("f0", type)}), ext_arr->length(), 
{ext_arr});
+
+  std::shared_ptr<RecordBatch> read_batch;
+  RoundtripBatch(batch, &read_batch);
+  // TODO: this should be true?
+  // CompareBatch(*batch, *read_batch, /* compare_metadata */ false);

Review Comment:
   Yes, this should. But for roundtripping through IPC, you need to register 
the type. See for example for one of the other tested types:
   
   
https://github.com/apache/arrow/blob/dd80f857913a0a81de65179e228fe60b00af4313/cpp/src/arrow/extension_type_test.cc#L289-L299



##########
cpp/src/arrow/extension/tensor_array.cc:
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "arrow/extension/tensor_array.h"
+#include "arrow/extension_type.h"
+
+#include "arrow/json/rapidjson_defs.h"  // IWYU pragma: keep
+#include "arrow/tensor.h"
+#include "arrow/util/logging.h"
+
+#include <rapidjson/rapidjson.h>
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+
+namespace rj = arrow::rapidjson;
+
+namespace arrow {
+namespace extension {
+
+std::string TensorArrayType::extension_name() const { return 
"arrow.fixed_size_tensor"; }
+
+size_t TensorArrayType::ndim() const { return shape_.size(); }
+
+std::vector<int64_t> TensorArrayType::shape() const { return shape_; }
+
+std::vector<int64_t> TensorArrayType::strides() const {
+  std::vector<int64_t> strides;
+  const auto& element_type =
+      internal::checked_cast<const FixedWidthType&>(*storage_type());
+
+  if (is_row_major_) {
+    DCHECK_OK(internal::ComputeRowMajorStrides(element_type, shape_, 
&strides));
+  } else {
+    DCHECK_OK(internal::ComputeColumnMajorStrides(element_type, shape_, 
&strides));
+  }
+
+  return strides;
+}
+
+std::shared_ptr<DataType> TensorArrayType::storage_type() const { return 
storage_type_; }
+
+std::string TensorArrayType::order() const { return is_row_major_ ? "C" : "F"; 
}
+
+bool TensorArrayType::ExtensionEquals(const ExtensionType& other) const {
+  if (extension_name() != other.extension_name()) {
+    return false;
+  }
+
+  const auto& other_ext = static_cast<const TensorArrayType&>(other);
+  bool equals = storage_type()->Equals(other_ext.storage_type());
+  equals &= shape() == other_ext.shape();
+  equals &= strides() == other_ext.strides();

Review Comment:
   Check the order/is_row_major instead of the strides? (I know it's 
equivalent, but since it's the order that is part of the official metadata, it 
seems more logical to check that)



##########
cpp/src/arrow/extension/tensor_array.cc:
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "arrow/extension/tensor_array.h"
+#include "arrow/extension_type.h"
+
+#include "arrow/json/rapidjson_defs.h"  // IWYU pragma: keep
+#include "arrow/tensor.h"
+#include "arrow/util/logging.h"
+
+#include <rapidjson/rapidjson.h>
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+
+namespace rj = arrow::rapidjson;
+
+namespace arrow {
+namespace extension {
+
+std::string TensorArrayType::extension_name() const { return 
"arrow.fixed_size_tensor"; }
+
+size_t TensorArrayType::ndim() const { return shape_.size(); }
+
+std::vector<int64_t> TensorArrayType::shape() const { return shape_; }
+
+std::vector<int64_t> TensorArrayType::strides() const {
+  std::vector<int64_t> strides;
+  const auto& element_type =
+      internal::checked_cast<const FixedWidthType&>(*storage_type());
+
+  if (is_row_major_) {
+    DCHECK_OK(internal::ComputeRowMajorStrides(element_type, shape_, 
&strides));
+  } else {
+    DCHECK_OK(internal::ComputeColumnMajorStrides(element_type, shape_, 
&strides));
+  }
+
+  return strides;
+}
+
+std::shared_ptr<DataType> TensorArrayType::storage_type() const { return 
storage_type_; }
+
+std::string TensorArrayType::order() const { return is_row_major_ ? "C" : "F"; 
}
+
+bool TensorArrayType::ExtensionEquals(const ExtensionType& other) const {
+  if (extension_name() != other.extension_name()) {
+    return false;
+  }
+
+  const auto& other_ext = static_cast<const TensorArrayType&>(other);
+  bool equals = storage_type()->Equals(other_ext.storage_type());
+  equals &= shape() == other_ext.shape();
+  equals &= strides() == other_ext.strides();
+  return equals;
+}
+
+std::string TensorArrayType::Serialize() const {
+  rj::Document document;
+  document.SetObject();
+  rj::Document::AllocatorType& allocator = document.GetAllocator();
+
+  rj::Value shape(rj::kArrayType);
+  for (auto v : shape_) {
+    shape.PushBack(v, allocator);
+  }
+  document.AddMember(rj::Value("shape", allocator), shape, allocator);
+  document.AddMember(rj::Value("order", allocator),
+                     rj::Value(is_row_major_ ? "C" : "F", allocator), 
allocator);
+  if (!document.HasMember("metadata")) {
+    document.AddMember(rj::Value("metadata", allocator), rj::Value(metadata_, 
allocator),
+                       allocator);
+  }
+
+  rj::StringBuffer buffer;
+  rj::Writer<rj::StringBuffer> writer(buffer);
+  document.Accept(writer);
+  return buffer.GetString();
+}
+
+Result<std::shared_ptr<DataType>> TensorArrayType::Deserialize(
+    std::shared_ptr<DataType> storage_type, const std::string& 
serialized_data) const {
+  rj::Document document;
+  document.Parse(serialized_data);
+  if (!document.HasMember("shape") || !document.HasMember("order") ||
+      !document["shape"].IsArray()) {
+    return Status::Invalid("Invalid serialized data: ", serialized_data);
+  }
+
+  std::vector<int64_t> shape;
+  for (auto& v : document["shape"].GetArray()) {
+    shape.emplace_back(v.GetInt64());
+  }
+
+  bool is_row_major = document["order"].GetString() == std::string("C");
+
+  document.RemoveMember("shape");
+  document.RemoveMember("order");
+
+  rj::StringBuffer buffer;
+  rj::Writer<rj::StringBuffer> writer(buffer);
+  document.Accept(writer);
+  const std::string remaining_metadata = buffer.GetString();
+
+  return std::make_shared<TensorArrayType>(storage_type, shape, is_row_major,
+                                           remaining_metadata);
+}
+
+std::shared_ptr<Array> TensorArrayType::MakeArray(std::shared_ptr<ArrayData> 
data) const {
+  return std::make_shared<ExtensionArray>(data);
+}
+
+std::shared_ptr<TensorArray> TensorArrayType::MakeArray(
+    std::shared_ptr<Tensor> tensor) const {
+  ARROW_PREDICT_TRUE(tensor->is_row_major());
+
+  auto ext_type = tensor_array(tensor->type(), tensor->shape(), 
tensor->is_row_major());
+
+  auto data = ArrayData::Make(ext_type, tensor->size(), {nullptr, 
tensor->data()});
+  data->type = ext_type;
+  return std::make_shared<TensorArray>(data);
+}
+
+std::shared_ptr<Tensor> TensorArrayType::ToTensor(std::shared_ptr<Array> arr) 
const {
+  ARROW_DCHECK_EQ(arr->null_count(), 0) << "Null values not supported in 
tensors.";
+  std::vector<int64_t> shape = shape_;
+  shape.insert(shape.begin(), 1, arr->length());
+  return std::make_shared<Tensor>(storage_type(), arr->data()->buffers[1], 
shape,
+                                  strides());
+}
+
+std::shared_ptr<ExtensionType> tensor_array(const std::shared_ptr<DataType>& 
storage_type,
+                                            const std::vector<int64_t>& shape,
+                                            const bool& is_row_major,
+                                            const std::string& metadata) {
+  // TODO: Should we register the extension type here?

Review Comment:
   I don't think it should be registered here (that would give unpredictable 
behaviour, as it would only get registered if you use this function, and eg not 
when reading IPC with such an extension type)



##########
cpp/src/arrow/extension_type_test.cc:
##########
@@ -333,4 +335,82 @@ TEST_F(TestExtensionType, ValidateExtensionArray) {
   ASSERT_OK(ext_arr4->ValidateFull());
 }
 
+TEST_F(TestExtensionType, TensorArrayType) {
+  using TensorArrayType = extension::TensorArrayType;
+
+  auto value_type = int64();
+  std::vector<int64_t> shape = {3, 3, 4};
+  std::vector<int64_t> row_major_strides = {36, 12, 4};
+  std::vector<int64_t> column_major_strides = {4, 12, 36};
+  std::vector<int64_t> values = {0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 
11,
+                                 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 
23,
+                                 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 
35};
+  std::vector<int64_t> values_partial = {0,  1,  2,  3,  4,  5,  6,  7,  8,  
9,  10, 11,
+                                         12, 13, 14, 15, 16, 17, 18, 19, 20, 
21, 22, 23};
+  std::vector<int64_t> shape_partial = {2, 3, 4};
+
+  ASSERT_OK_AND_ASSIGN(auto tensor, Tensor::Make(value_type, 
Buffer::Wrap(values), shape,
+                                                 row_major_strides));
+  ASSERT_OK_AND_ASSIGN(auto tensor_partial,
+                       Tensor::Make(value_type, Buffer::Wrap(values_partial),
+                                    shape_partial, row_major_strides));
+
+  std::shared_ptr<ExtensionType> row_major_ext_type = extension::tensor_array(
+      value_type, shape, /*is_row_major=*/true, "{\"key1\": \"metadata1\"}");
+  std::shared_ptr<ExtensionType> column_major_ext_type =
+      extension::tensor_array(value_type, shape, /*is_row_major=*/false, 
"{\"key2\": 1}");
+  auto exact_ext_type = 
std::dynamic_pointer_cast<TensorArrayType>(row_major_ext_type);
+
+  auto ext_arr = exact_ext_type->MakeArray(tensor);
+  auto ext_arr_partial = exact_ext_type->MakeArray(tensor_partial);
+
+  ASSERT_EQ(row_major_ext_type->Serialize(),
+            "{\"shape\":[3,3,4],\"order\":\"C\",\"metadata\":\"{\\\"key1\\\": "
+            "\\\"metadata1\\\"}\"}");
+  ASSERT_EQ(column_major_ext_type->Serialize(),
+            "{\"shape\":[3,3,4],\"order\":\"F\",\"metadata\":\"{\\\"key2\\\": 
1}\"}");
+  ASSERT_EQ(row_major_ext_type->extension_name(), "arrow.fixed_size_tensor");
+  ASSERT_OK(ext_arr->ValidateFull());
+  ASSERT_OK(ext_arr_partial->ValidateFull());
+
+  AssertArraysEqual(*ext_arr->storage()->Slice(0, 24), 
*ext_arr_partial->storage());
+  auto arr_slice = ext_arr->Slice(0, 24);
+  auto tensor_slice = exact_ext_type->ToTensor(arr_slice);
+  // TODO
+  // ASSERT_TRUE(tensor_partial->Equals(*tensor_slice));
+
+  auto type = std::dynamic_pointer_cast<TensorArrayType>(ext_arr->type());
+  ASSERT_EQ(type->id(), Type::EXTENSION);
+
+  std::string serialized = row_major_ext_type->Serialize();
+  ASSERT_OK_AND_ASSIGN(auto deserialized,
+                       row_major_ext_type->Deserialize(row_major_ext_type, 
serialized));
+  // TODO
+  // ASSERT_TRUE(deserialized->Equals(row_major_ext_type));

Review Comment:
   This doesn't work yet?



##########
cpp/src/arrow/extension_type_test.cc:
##########
@@ -333,4 +335,82 @@ TEST_F(TestExtensionType, ValidateExtensionArray) {
   ASSERT_OK(ext_arr4->ValidateFull());
 }
 
+TEST_F(TestExtensionType, TensorArrayType) {
+  using TensorArrayType = extension::TensorArrayType;
+
+  auto value_type = int64();
+  std::vector<int64_t> shape = {3, 3, 4};
+  std::vector<int64_t> row_major_strides = {36, 12, 4};
+  std::vector<int64_t> column_major_strides = {4, 12, 36};
+  std::vector<int64_t> values = {0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 
11,
+                                 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 
23,
+                                 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 
35};
+  std::vector<int64_t> values_partial = {0,  1,  2,  3,  4,  5,  6,  7,  8,  
9,  10, 11,
+                                         12, 13, 14, 15, 16, 17, 18, 19, 20, 
21, 22, 23};
+  std::vector<int64_t> shape_partial = {2, 3, 4};
+
+  ASSERT_OK_AND_ASSIGN(auto tensor, Tensor::Make(value_type, 
Buffer::Wrap(values), shape,
+                                                 row_major_strides));
+  ASSERT_OK_AND_ASSIGN(auto tensor_partial,
+                       Tensor::Make(value_type, Buffer::Wrap(values_partial),
+                                    shape_partial, row_major_strides));
+
+  std::shared_ptr<ExtensionType> row_major_ext_type = extension::tensor_array(
+      value_type, shape, /*is_row_major=*/true, "{\"key1\": \"metadata1\"}");
+  std::shared_ptr<ExtensionType> column_major_ext_type =
+      extension::tensor_array(value_type, shape, /*is_row_major=*/false, 
"{\"key2\": 1}");
+  auto exact_ext_type = 
std::dynamic_pointer_cast<TensorArrayType>(row_major_ext_type);
+
+  auto ext_arr = exact_ext_type->MakeArray(tensor);
+  auto ext_arr_partial = exact_ext_type->MakeArray(tensor_partial);
+
+  ASSERT_EQ(row_major_ext_type->Serialize(),
+            "{\"shape\":[3,3,4],\"order\":\"C\",\"metadata\":\"{\\\"key1\\\": "
+            "\\\"metadata1\\\"}\"}");
+  ASSERT_EQ(column_major_ext_type->Serialize(),
+            "{\"shape\":[3,3,4],\"order\":\"F\",\"metadata\":\"{\\\"key2\\\": 
1}\"}");
+  ASSERT_EQ(row_major_ext_type->extension_name(), "arrow.fixed_size_tensor");
+  ASSERT_OK(ext_arr->ValidateFull());
+  ASSERT_OK(ext_arr_partial->ValidateFull());
+
+  AssertArraysEqual(*ext_arr->storage()->Slice(0, 24), 
*ext_arr_partial->storage());
+  auto arr_slice = ext_arr->Slice(0, 24);
+  auto tensor_slice = exact_ext_type->ToTensor(arr_slice);
+  // TODO
+  // ASSERT_TRUE(tensor_partial->Equals(*tensor_slice));
+
+  auto type = std::dynamic_pointer_cast<TensorArrayType>(ext_arr->type());
+  ASSERT_EQ(type->id(), Type::EXTENSION);
+
+  std::string serialized = row_major_ext_type->Serialize();
+  ASSERT_OK_AND_ASSIGN(auto deserialized,
+                       row_major_ext_type->Deserialize(row_major_ext_type, 
serialized));
+  // TODO
+  // ASSERT_TRUE(deserialized->Equals(row_major_ext_type));
+  ASSERT_FALSE(deserialized->Equals(*fixed_size_binary(16)));
+
+  auto batch =
+      RecordBatch::Make(schema({field("f0", type)}), ext_arr->length(), 
{ext_arr});
+
+  std::shared_ptr<RecordBatch> read_batch;
+  RoundtripBatch(batch, &read_batch);
+  // TODO: this should be true?
+  // CompareBatch(*batch, *read_batch, /* compare_metadata */ false);

Review Comment:
   For a canonical extension type, though, I assume that we will want to always 
register it when loading the arrow library, and then you don't need to register 
it just in the test.



-- 
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]

Reply via email to