From 4cf6d2bee9fa6619045239c2a16e7590b39a624d Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Sat, 1 Apr 2017 18:19:32 -0400 Subject: [PATCH 1/3] Draft tensor conversion to/from numpy Change-Id: Ia9cfb8214689d1c143e843b66daaea30b26e79f4 --- cpp/src/arrow/CMakeLists.txt | 1 + cpp/src/arrow/api.h | 1 + cpp/src/arrow/io/io-hdfs-test.cc | 7 +- cpp/src/arrow/ipc/ipc-read-write-benchmark.cc | 4 +- cpp/src/arrow/python/CMakeLists.txt | 9 + cpp/src/arrow/python/builtin_convert.cc | 5 +- cpp/src/arrow/python/common.h | 17 -- cpp/src/arrow/python/numpy_convert.cc | 266 ++++++++++++++++++ cpp/src/arrow/python/numpy_convert.h | 69 +++++ cpp/src/arrow/python/pandas_convert.cc | 88 +----- cpp/src/arrow/python/pandas_convert.h | 3 - cpp/src/arrow/python/python-test.cc | 2 +- cpp/src/arrow/tensor.cc | 14 +- cpp/src/arrow/tensor.h | 7 + cpp/src/arrow/util/logging.h | 7 +- python/pyarrow/__init__.py | 3 +- python/pyarrow/array.pxd | 13 +- python/pyarrow/array.pyx | 80 +++++- python/pyarrow/includes/libarrow.pxd | 16 ++ python/pyarrow/includes/pyarrow.pxd | 2 +- python/pyarrow/io.pyx | 2 +- python/pyarrow/schema.pyx | 2 +- python/pyarrow/table.pyx | 2 +- python/pyarrow/tests/test_convert_pandas.py | 8 +- 24 files changed, 493 insertions(+), 135 deletions(-) create mode 100644 cpp/src/arrow/python/numpy_convert.cc create mode 100644 cpp/src/arrow/python/numpy_convert.h diff --git a/cpp/src/arrow/CMakeLists.txt b/cpp/src/arrow/CMakeLists.txt index bd33bf5b8296..8eaa76ae9e84 100644 --- a/cpp/src/arrow/CMakeLists.txt +++ b/cpp/src/arrow/CMakeLists.txt @@ -28,6 +28,7 @@ install(FILES pretty_print.h status.h table.h + tensor.h type.h type_fwd.h type_traits.h diff --git a/cpp/src/arrow/api.h b/cpp/src/arrow/api.h index 50a09515297f..aa0da7580244 100644 --- a/cpp/src/arrow/api.h +++ b/cpp/src/arrow/api.h @@ -29,6 +29,7 @@ #include "arrow/pretty_print.h" #include "arrow/status.h" #include "arrow/table.h" +#include "arrow/tensor.h" #include "arrow/type.h" #include "arrow/visitor.h" diff --git a/cpp/src/arrow/io/io-hdfs-test.cc b/cpp/src/arrow/io/io-hdfs-test.cc index f3140be0b2da..af59e96a1448 100644 --- a/cpp/src/arrow/io/io-hdfs-test.cc +++ b/cpp/src/arrow/io/io-hdfs-test.cc @@ -78,9 +78,10 @@ class TestHdfsClient : public ::testing::Test { LibHdfsShim* driver_shim; client_ = nullptr; - scratch_dir_ = boost::filesystem::unique_path( - boost::filesystem::temp_directory_path() / "arrow-hdfs/scratch-%%%%") - .string(); + scratch_dir_ = + boost::filesystem::unique_path( + boost::filesystem::temp_directory_path() / "arrow-hdfs/scratch-%%%%") + .string(); loaded_driver_ = false; diff --git a/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc b/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc index b385929d8b10..1aecdbc63319 100644 --- a/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc +++ b/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc @@ -80,7 +80,7 @@ static void BM_WriteRecordBatch(benchmark::State& state) { // NOLINT non-const int32_t metadata_length; int64_t body_length; if (!ipc::WriteRecordBatch(*record_batch, 0, &stream, &metadata_length, &body_length, - default_memory_pool()) + default_memory_pool()) .ok()) { state.SkipWithError("Failed to write!"); } @@ -101,7 +101,7 @@ static void BM_ReadRecordBatch(benchmark::State& state) { // NOLINT non-const r int32_t metadata_length; int64_t body_length; if (!ipc::WriteRecordBatch(*record_batch, 0, &stream, &metadata_length, &body_length, - default_memory_pool()) + default_memory_pool()) .ok()) { state.SkipWithError("Failed to write!"); } diff --git a/cpp/src/arrow/python/CMakeLists.txt b/cpp/src/arrow/python/CMakeLists.txt index faaad89656f9..66d400509de5 100644 --- a/cpp/src/arrow/python/CMakeLists.txt +++ b/cpp/src/arrow/python/CMakeLists.txt @@ -55,6 +55,7 @@ set(ARROW_PYTHON_SRCS config.cc helpers.cc io.cc + numpy_convert.cc pandas_convert.cc ) @@ -71,6 +72,14 @@ ADD_ARROW_LIB(arrow_python STATIC_LINK_LIBS ${ARROW_IO_SHARED_PRIVATE_LINK_LIBS} ) +if ("${COMPILER_FAMILY}" STREQUAL "clang") + # Clang, be quiet. Python C API has lots of macros + set_property(SOURCE ${ARROW_PYTHON_SRCS} + APPEND_STRING + PROPERTY + COMPILE_FLAGS -Wno-parentheses-equality) +endif() + install(FILES api.h builtin_convert.h diff --git a/cpp/src/arrow/python/builtin_convert.cc b/cpp/src/arrow/python/builtin_convert.cc index 6a13fdccdeaf..86cf3485adb5 100644 --- a/cpp/src/arrow/python/builtin_convert.cc +++ b/cpp/src/arrow/python/builtin_convert.cc @@ -412,8 +412,9 @@ class FixedWidthBytesConverter : public TypedConverter { PyObject* item; PyObject* bytes_obj; OwnedRef tmp; - Py_ssize_t expected_length = std::dynamic_pointer_cast( - typed_builder_->type())->byte_width(); + Py_ssize_t expected_length = + std::dynamic_pointer_cast(typed_builder_->type()) + ->byte_width(); Py_ssize_t size = PySequence_Size(seq); for (int64_t i = 0; i < size; ++i) { item = PySequence_GetItem(seq, i); diff --git a/cpp/src/arrow/python/common.h b/cpp/src/arrow/python/common.h index f1be471cd3a8..32bfa784acbd 100644 --- a/cpp/src/arrow/python/common.h +++ b/cpp/src/arrow/python/common.h @@ -103,23 +103,6 @@ struct PyObjectStringify { ARROW_EXPORT void set_default_memory_pool(MemoryPool* pool); ARROW_EXPORT MemoryPool* get_memory_pool(); -class ARROW_EXPORT NumPyBuffer : public Buffer { - public: - explicit NumPyBuffer(PyArrayObject* arr) : Buffer(nullptr, 0) { - arr_ = arr; - Py_INCREF(arr); - - data_ = reinterpret_cast(PyArray_DATA(arr_)); - size_ = PyArray_SIZE(arr_) * PyArray_DESCR(arr_)->elsize; - capacity_ = size_; - } - - virtual ~NumPyBuffer() { Py_XDECREF(arr_); } - - private: - PyArrayObject* arr_; -}; - class ARROW_EXPORT PyBuffer : public Buffer { public: /// Note that the GIL must be held when calling the PyBuffer constructor. diff --git a/cpp/src/arrow/python/numpy_convert.cc b/cpp/src/arrow/python/numpy_convert.cc new file mode 100644 index 000000000000..d34b06590f17 --- /dev/null +++ b/cpp/src/arrow/python/numpy_convert.cc @@ -0,0 +1,266 @@ +// 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 + +#include "arrow/python/numpy_convert.h" +#include "arrow/python/numpy_interop.h" + +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/tensor.h" +#include "arrow/type.h" + +#include "arrow/python/common.h" +#include "arrow/python/type_traits.h" + +namespace arrow { +namespace py { + +bool is_contiguous(PyObject* array) { + if (PyArray_Check(array)) { + return PyArray_FLAGS(reinterpret_cast(array)) & + (NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); + } else { + return false; + } +} + +int cast_npy_type_compat(int type_num) { +// Both LONGLONG and INT64 can be observed in the wild, which is buggy. We set +// U/LONGLONG to U/INT64 so things work properly. + +#if (NPY_INT64 == NPY_LONGLONG) && (NPY_SIZEOF_LONGLONG == 8) + if (type_num == NPY_LONGLONG) { type_num = NPY_INT64; } + if (type_num == NPY_ULONGLONG) { type_num = NPY_UINT64; } +#endif + + return type_num; +} + +NumPyBuffer::NumPyBuffer(PyObject* ao) : Buffer(nullptr, 0) { + arr_ = ao; + Py_INCREF(ao); + + if (!PyArray_Check(ao)) { + PyArrayObject* ndarray = reinterpret_cast(ao); + data_ = reinterpret_cast(PyArray_DATA(ndarray)); + size_ = PyArray_SIZE(ndarray) * PyArray_DESCR(ndarray)->elsize; + capacity_ = size_; + } +} + +NumPyBuffer::~NumPyBuffer() { + Py_XDECREF(arr_); +} + +#define TO_ARROW_TYPE_CASE(NPY_NAME, FACTORY) \ + case NPY_##NPY_NAME: \ + *out = FACTORY(); \ + break; + +Status GetTensorType(PyObject* dtype, std::shared_ptr* out) { + PyArray_Descr* descr = reinterpret_cast(dtype); + int type_num = cast_npy_type_compat(descr->type_num); + + switch (type_num) { + TO_ARROW_TYPE_CASE(BOOL, uint8); + TO_ARROW_TYPE_CASE(INT8, int8); + TO_ARROW_TYPE_CASE(INT16, int16); + TO_ARROW_TYPE_CASE(INT32, int32); + TO_ARROW_TYPE_CASE(INT64, int64); +#if (NPY_INT64 != NPY_LONGLONG) + TO_ARROW_TYPE_CASE(LONGLONG, int64); +#endif + TO_ARROW_TYPE_CASE(UINT8, uint8); + TO_ARROW_TYPE_CASE(UINT16, uint16); + TO_ARROW_TYPE_CASE(UINT32, uint32); + TO_ARROW_TYPE_CASE(UINT64, uint64); +#if (NPY_UINT64 != NPY_ULONGLONG) + TO_ARROW_CASE(ULONGLONG); +#endif + TO_ARROW_TYPE_CASE(FLOAT32, float32); + TO_ARROW_TYPE_CASE(FLOAT64, float64); + default: { + std::stringstream ss; + ss << "Unsupported numpy type " << descr->type_num << std::endl; + return Status::NotImplemented(ss.str()); + } + } + return Status::OK(); +} + +Status GetNumPyType(const DataType& type, int* type_num) { +#define NUMPY_TYPE_CASE(ARROW_NAME, NPY_NAME) \ + case Type::ARROW_NAME: \ + *type_num = NPY_##NPY_NAME; \ + break; + + switch (type.type) { + NUMPY_TYPE_CASE(UINT8, UINT8); + NUMPY_TYPE_CASE(INT8, INT8); + NUMPY_TYPE_CASE(UINT16, UINT16); + NUMPY_TYPE_CASE(INT16, INT16); + NUMPY_TYPE_CASE(UINT32, UINT32); + NUMPY_TYPE_CASE(INT32, INT32); + NUMPY_TYPE_CASE(UINT64, UINT64); + NUMPY_TYPE_CASE(INT64, INT64); + NUMPY_TYPE_CASE(HALF_FLOAT, FLOAT16); + NUMPY_TYPE_CASE(FLOAT, FLOAT32); + NUMPY_TYPE_CASE(DOUBLE, FLOAT64); + default: { + std::stringstream ss; + ss << "Unsupported tensor type: " << type.ToString() << std::endl; + return Status::NotImplemented(ss.str()); + } + } +#undef NUMPY_TYPE_CASE + + return Status::OK(); +} + +Status NumPyDtypeToArrow(PyObject* dtype, std::shared_ptr* out) { + PyArray_Descr* descr = reinterpret_cast(dtype); + + int type_num = cast_npy_type_compat(descr->type_num); + + switch (type_num) { + TO_ARROW_TYPE_CASE(BOOL, boolean); + TO_ARROW_TYPE_CASE(INT8, int8); + TO_ARROW_TYPE_CASE(INT16, int16); + TO_ARROW_TYPE_CASE(INT32, int32); + TO_ARROW_TYPE_CASE(INT64, int64); +#if (NPY_INT64 != NPY_LONGLONG) + TO_ARROW_TYPE_CASE(LONGLONG, int64); +#endif + TO_ARROW_TYPE_CASE(UINT8, uint8); + TO_ARROW_TYPE_CASE(UINT16, uint16); + TO_ARROW_TYPE_CASE(UINT32, uint32); + TO_ARROW_TYPE_CASE(UINT64, uint64); +#if (NPY_UINT64 != NPY_ULONGLONG) + TO_ARROW_CASE(ULONGLONG); +#endif + TO_ARROW_TYPE_CASE(FLOAT32, float32); + TO_ARROW_TYPE_CASE(FLOAT64, float64); + case NPY_DATETIME: { + auto date_dtype = + reinterpret_cast(descr->c_metadata); + TimeUnit unit; + switch (date_dtype->meta.base) { + case NPY_FR_s: + unit = TimeUnit::SECOND; + break; + case NPY_FR_ms: + unit = TimeUnit::MILLI; + break; + case NPY_FR_us: + unit = TimeUnit::MICRO; + break; + case NPY_FR_ns: + unit = TimeUnit::NANO; + break; + default: + return Status::NotImplemented("Unsupported datetime64 time unit"); + } + *out = timestamp(unit); + } break; + default: { + std::stringstream ss; + ss << "Unsupported numpy type " << descr->type_num << std::endl; + return Status::NotImplemented(ss.str()); + } + } + + return Status::OK(); +} + +#undef TO_ARROW_TYPE_CASE + +Status NdarrayToTensor(MemoryPool* pool, PyObject* ao, std::shared_ptr* out) { + if (!PyArray_Check(ao)) { return Status::TypeError("Did not pass ndarray object"); } + + PyArrayObject* ndarray = reinterpret_cast(ao); + + // TODO(wesm): What do we want to do with non-contiguous memory and negative strides? + + int ndim = PyArray_NDIM(ndarray); + + std::shared_ptr data = std::make_shared(ao); + std::vector shape(ndim); + std::vector strides(ndim); + + npy_intp* array_strides = PyArray_STRIDES(ndarray); + npy_intp* array_shape = PyArray_SHAPE(ndarray); + for (int i = 0; i < ndim; ++i) { + if (array_strides[i] < 0) { + return Status::Invalid("Negative ndarray strides not supported"); + } + shape[i] = array_shape[i]; + strides[i] = array_strides[i]; + } + + std::shared_ptr type; + RETURN_NOT_OK( + GetTensorType(reinterpret_cast(PyArray_DESCR(ndarray)), &type)); + return MakeTensor(type, data, shape, strides, {}, out); +} + +Status TensorToNdarray(const Tensor& tensor, PyObject* base, PyObject** out) { + int type_num; + RETURN_NOT_OK(GetNumPyType(*tensor.type(), &type_num)); + PyArray_Descr* dtype = PyArray_DescrNewFromType(type_num); + RETURN_IF_PYERROR(); + + std::vector npy_shape(tensor.ndim()); + std::vector npy_strides(tensor.ndim()); + + for (int i = 0; i < tensor.ndim(); ++i) { + npy_shape[i] = tensor.shape()[i]; + npy_strides[i] = tensor.strides()[i]; + } + + const void* immutable_data = nullptr; + if (tensor.data()) { immutable_data = tensor.data()->data(); } + + // Remove const =( + void* mutable_data = const_cast(immutable_data); + + int array_flags = 0; + if (tensor.is_row_major()) { array_flags |= NPY_ARRAY_C_CONTIGUOUS; } + + if (tensor.is_column_major()) { array_flags |= NPY_ARRAY_F_CONTIGUOUS; } + + if (tensor.is_mutable()) { array_flags |= NPY_ARRAY_WRITEABLE; } + + PyObject* result = PyArray_NewFromDescr(&PyArray_Type, dtype, tensor.ndim(), + npy_shape.data(), npy_strides.data(), mutable_data, array_flags, nullptr); + RETURN_IF_PYERROR() + + if (base != Py_None) { + PyArray_SetBaseObject(reinterpret_cast(result), base); + } + *out = result; + return Status::OK(); +} + +} // namespace py +} // namespace arrow diff --git a/cpp/src/arrow/python/numpy_convert.h b/cpp/src/arrow/python/numpy_convert.h new file mode 100644 index 000000000000..b4cf1bc26f29 --- /dev/null +++ b/cpp/src/arrow/python/numpy_convert.h @@ -0,0 +1,69 @@ +// 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. + +// Functions for converting between pandas's NumPy-based data representation +// and Arrow data structures + +#ifndef ARROW_PYTHON_NUMPY_CONVERT_H +#define ARROW_PYTHON_NUMPY_CONVERT_H + +#include + +#include +#include + +#include "arrow/buffer.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +struct DataType; +class MemoryPool; +class Status; +class Tensor; + +namespace py { + +class ARROW_EXPORT NumPyBuffer : public Buffer { + public: + explicit NumPyBuffer(PyObject* arr); + virtual ~NumPyBuffer(); + + private: + PyObject* arr_; +}; + +// Handle misbehaved types like LONGLONG and ULONGLONG +int cast_npy_type_compat(int type_num); + +bool is_contiguous(PyObject* array); + +ARROW_EXPORT +Status NumPyDtypeToArray(PyObject* dtype, std::shared_ptr* out); + +Status GetTensorType(PyObject* dtype, std::shared_ptr* out); +Status GetNumPyType(const DataType& type, int* type_num); + +ARROW_EXPORT Status NdarrayToTensor( + MemoryPool* pool, PyObject* ao, std::shared_ptr* out); + +ARROW_EXPORT Status TensorToNdarray(const Tensor& tensor, PyObject* base, PyObject** out); + +} // namespace py +} // namespace arrow + +#endif // ARROW_PYTHON_NUMPY_CONVERT_H diff --git a/cpp/src/arrow/python/pandas_convert.cc b/cpp/src/arrow/python/pandas_convert.cc index ddfec1bf45a2..01019e5669f2 100644 --- a/cpp/src/arrow/python/pandas_convert.cc +++ b/cpp/src/arrow/python/pandas_convert.cc @@ -36,11 +36,6 @@ #include "arrow/array.h" #include "arrow/loader.h" -#include "arrow/python/builtin_convert.h" -#include "arrow/python/common.h" -#include "arrow/python/config.h" -#include "arrow/python/type_traits.h" -#include "arrow/python/util/datetime.h" #include "arrow/status.h" #include "arrow/table.h" #include "arrow/type_fwd.h" @@ -49,24 +44,19 @@ #include "arrow/util/logging.h" #include "arrow/util/macros.h" +#include "arrow/python/builtin_convert.h" +#include "arrow/python/common.h" +#include "arrow/python/config.h" +#include "arrow/python/numpy_convert.h" +#include "arrow/python/type_traits.h" +#include "arrow/python/util/datetime.h" + namespace arrow { namespace py { // ---------------------------------------------------------------------- // Utility code -int cast_npy_type_compat(int type_num) { -// Both LONGLONG and INT64 can be observed in the wild, which is buggy. We set -// U/LONGLONG to U/INT64 so things work properly. - -#if (NPY_INT64 == NPY_LONGLONG) && (NPY_SIZEOF_LONGLONG == 8) - if (type_num == NPY_LONGLONG) { type_num = NPY_INT64; } - if (type_num == NPY_ULONGLONG) { type_num = NPY_UINT64; } -#endif - - return type_num; -} - static inline bool PyObject_is_null(const PyObject* obj) { return obj == Py_None || obj == numpy_nan; } @@ -395,7 +385,7 @@ inline Status PandasConverter::ConvertData(std::shared_ptr* data) { return Status::NotImplemented("NumPy type casts not yet implemented"); } - *data = std::make_shared(arr_); + *data = std::make_shared(reinterpret_cast(arr_)); return Status::OK(); } @@ -730,68 +720,6 @@ Status PandasObjectsToArrow(MemoryPool* pool, PyObject* ao, PyObject* mo, return converter.ConvertObjects(out); } -Status PandasDtypeToArrow(PyObject* dtype, std::shared_ptr* out) { - PyArray_Descr* descr = reinterpret_cast(dtype); - - int type_num = cast_npy_type_compat(descr->type_num); - -#define TO_ARROW_TYPE_CASE(NPY_NAME, FACTORY) \ - case NPY_##NPY_NAME: \ - *out = FACTORY(); \ - break; - - switch (type_num) { - TO_ARROW_TYPE_CASE(BOOL, boolean); - TO_ARROW_TYPE_CASE(INT8, int8); - TO_ARROW_TYPE_CASE(INT16, int16); - TO_ARROW_TYPE_CASE(INT32, int32); - TO_ARROW_TYPE_CASE(INT64, int64); -#if (NPY_INT64 != NPY_LONGLONG) - TO_ARROW_TYPE_CASE(LONGLONG, int64); -#endif - TO_ARROW_TYPE_CASE(UINT8, uint8); - TO_ARROW_TYPE_CASE(UINT16, uint16); - TO_ARROW_TYPE_CASE(UINT32, uint32); - TO_ARROW_TYPE_CASE(UINT64, uint64); -#if (NPY_UINT64 != NPY_ULONGLONG) - TO_ARROW_CASE(ULONGLONG); -#endif - TO_ARROW_TYPE_CASE(FLOAT32, float32); - TO_ARROW_TYPE_CASE(FLOAT64, float64); - case NPY_DATETIME: { - auto date_dtype = - reinterpret_cast(descr->c_metadata); - TimeUnit unit; - switch (date_dtype->meta.base) { - case NPY_FR_s: - unit = TimeUnit::SECOND; - break; - case NPY_FR_ms: - unit = TimeUnit::MILLI; - break; - case NPY_FR_us: - unit = TimeUnit::MICRO; - break; - case NPY_FR_ns: - unit = TimeUnit::NANO; - break; - default: - return Status::NotImplemented("Unsupported datetime64 time unit"); - } - *out = timestamp(unit); - } break; - default: { - std::stringstream ss; - ss << "Unsupported numpy type " << descr->type_num << std::endl; - return Status::NotImplemented(ss.str()); - } - } - -#undef TO_ARROW_TYPE_CASE - - return Status::OK(); -} - // ---------------------------------------------------------------------- // pandas 0.x DataFrame conversion internals diff --git a/cpp/src/arrow/python/pandas_convert.h b/cpp/src/arrow/python/pandas_convert.h index 105c1598d393..8fd31076a994 100644 --- a/cpp/src/arrow/python/pandas_convert.h +++ b/cpp/src/arrow/python/pandas_convert.h @@ -61,9 +61,6 @@ ARROW_EXPORT Status ConvertTableToPandas( const std::shared_ptr& table, int nthreads, PyObject** out); -ARROW_EXPORT -Status PandasDtypeToArrow(PyObject* dtype, std::shared_ptr* out); - ARROW_EXPORT Status PandasToArrow(MemoryPool* pool, PyObject* ao, PyObject* mo, const std::shared_ptr& type, std::shared_ptr* out); diff --git a/cpp/src/arrow/python/python-test.cc b/cpp/src/arrow/python/python-test.cc index 01e30f5a36ce..f269ebfb642c 100644 --- a/cpp/src/arrow/python/python-test.cc +++ b/cpp/src/arrow/python/python-test.cc @@ -26,9 +26,9 @@ #include "arrow/table.h" #include "arrow/test-util.h" +#include "arrow/python/builtin_convert.h" #include "arrow/python/common.h" #include "arrow/python/pandas_convert.h" -#include "arrow/python/builtin_convert.h" namespace arrow { namespace py { diff --git a/cpp/src/arrow/tensor.cc b/cpp/src/arrow/tensor.cc index 9a8de5119ea5..8bbb97b596e1 100644 --- a/cpp/src/arrow/tensor.cc +++ b/cpp/src/arrow/tensor.cc @@ -90,13 +90,21 @@ int64_t Tensor::size() const { } bool Tensor::is_contiguous() const { - std::vector c_strides; - std::vector f_strides; + return is_row_major() || is_column_major(); +} +bool Tensor::is_row_major() const { + std::vector c_strides; const auto& fw_type = static_cast(*type_); ComputeRowMajorStrides(fw_type, shape_, &c_strides); + return strides_ == c_strides; +} + +bool Tensor::is_column_major() const { + std::vector f_strides; + const auto& fw_type = static_cast(*type_); ComputeColumnMajorStrides(fw_type, shape_, &f_strides); - return strides_ == c_strides || strides_ == f_strides; + return strides_ == f_strides; } bool Tensor::Equals(const Tensor& other) const { diff --git a/cpp/src/arrow/tensor.h b/cpp/src/arrow/tensor.h index eeb5c3e8e553..12015f14b1d3 100644 --- a/cpp/src/arrow/tensor.h +++ b/cpp/src/arrow/tensor.h @@ -89,8 +89,15 @@ class ARROW_EXPORT Tensor { /// Return true if the underlying data buffer is mutable bool is_mutable() const { return data_->is_mutable(); } + /// Either row major or column major bool is_contiguous() const; + /// AKA "C order" + bool is_row_major() const; + + /// AKA "Fortran order" + bool is_column_major() const; + Type::type type_enum() const { return type_->type; } bool Equals(const Tensor& other) const; diff --git a/cpp/src/arrow/util/logging.h b/cpp/src/arrow/util/logging.h index 697d47c54100..b22f07dd6345 100644 --- a/cpp/src/arrow/util/logging.h +++ b/cpp/src/arrow/util/logging.h @@ -38,10 +38,9 @@ namespace arrow { #define ARROW_LOG_INTERNAL(level) ::arrow::internal::CerrLog(level) #define ARROW_LOG(level) ARROW_LOG_INTERNAL(ARROW_##level) -#define ARROW_CHECK(condition) \ - (condition) ? 0 \ - : ::arrow::internal::FatalLog(ARROW_FATAL) \ - << __FILE__ << __LINE__ << " Check failed: " #condition " " +#define ARROW_CHECK(condition) \ + (condition) ? 0 : ::arrow::internal::FatalLog(ARROW_FATAL) \ + << __FILE__ << __LINE__ << " Check failed: " #condition " " #ifdef NDEBUG #define ARROW_DFATAL ARROW_WARNING diff --git a/python/pyarrow/__init__.py b/python/pyarrow/__init__.py index 3df2a1d44554..c52b733f9ed6 100644 --- a/python/pyarrow/__init__.py +++ b/python/pyarrow/__init__.py @@ -28,8 +28,7 @@ import pyarrow.config from pyarrow.config import cpu_count, set_cpu_count -from pyarrow.array import (Array, - from_pandas_series, from_pylist, +from pyarrow.array import (Array, from_pylist, NumericArray, IntegerArray, FloatingPointArray, BooleanArray, Int8Array, UInt8Array, diff --git a/python/pyarrow/array.pxd b/python/pyarrow/array.pxd index 0b5f33d0d2db..42675630fd51 100644 --- a/python/pyarrow/array.pxd +++ b/python/pyarrow/array.pxd @@ -16,7 +16,7 @@ # under the License. from pyarrow.includes.common cimport shared_ptr, int64_t -from pyarrow.includes.libarrow cimport CArray +from pyarrow.includes.libarrow cimport CArray, CTensor from pyarrow.scalar import NA @@ -41,6 +41,17 @@ cdef class Array: cdef getitem(self, int64_t i) +cdef class Tensor: + cdef: + shared_ptr[CTensor] sp_tensor + CTensor* tp + + cdef readonly: + DataType type + + cdef init(self, const shared_ptr[CTensor]& sp_tensor) + + cdef object box_array(const shared_ptr[CArray]& sp_array) diff --git a/python/pyarrow/array.pyx b/python/pyarrow/array.pyx index b9799f15bf3e..d89e184c31e2 100644 --- a/python/pyarrow/array.pyx +++ b/python/pyarrow/array.pyx @@ -81,7 +81,7 @@ cdef class Array: self.type = box_data_type(self.sp_array.get().type()) @staticmethod - def from_pandas(obj, mask=None, DataType type=None, + def from_numpy(obj, mask=None, DataType type=None, timestamps_to_ms=False, MemoryPool memory_pool=None): """ @@ -116,7 +116,7 @@ cdef class Array: >>> import pandas as pd >>> import pyarrow as pa - >>> pa.Array.from_pandas(pd.Series([1, 2])) + >>> pa.Array.from_numpy(pd.Series([1, 2])) [ 1, @@ -124,7 +124,7 @@ cdef class Array: ] >>> import numpy as np - >>> pa.Array.from_pandas(pd.Series([1, 2]), np.array([0, 1], + >>> pa.Array.from_numpy(pd.Series([1, 2]), np.array([0, 1], ... dtype=bool)) [ @@ -166,7 +166,7 @@ cdef class Array: values, obj.dtype, type, timestamps_to_ms=timestamps_to_ms) if type is None: - check_status(pyarrow.PandasDtypeToArrow(values.dtype, &c_type)) + check_status(pyarrow.NumPyDtypeToArray(values.dtype, &c_type)) else: c_type = type.sp_type @@ -316,6 +316,69 @@ cdef class Array: return [x.as_py() for x in self] +cdef class Tensor: + + cdef init(self, const shared_ptr[CTensor]& sp_tensor): + self.sp_tensor = sp_tensor + self.tp = sp_tensor.get() + self.type = box_data_type(self.tp.type()) + + def __repr__(self): + return object.__repr__(self) + + @staticmethod + def from_numpy(obj): + pass + + def to_numpy(self): + pass + + property is_mutable: + + def __get__(self): + return self.tp.is_mutable() + + property is_contiguous: + + def __get__(self): + return self.tp.is_contiguous() + + property ndim: + + def __get__(self): + return self.tp.ndim() + + property size: + + def __get__(self): + return self.tp.size() + + property shape: + + def __get__(self): + cdef: + const vector[int64_t]& c_shape = self.tp.shape() + size_t i + + py_shape = [] + for i in range(c_shape.size()): + py_shape.append(c_shape[i]) + return py_shape + + property strides: + + def __get__(self): + cdef: + const vector[int64_t]& c_strides = self.tp.strides() + size_t i + + py_strides = [] + for i in range(c_strides.size()): + py_strides.append(c_strides[i]) + return py_strides + + + cdef wrap_array_output(PyObject* output): cdef object obj = PyObject_to_object(output) @@ -479,10 +542,10 @@ cdef class DictionaryArray(Array): else: mask = mask | (indices == -1) - arrow_indices = Array.from_pandas(indices, mask=mask, - memory_pool=memory_pool) - arrow_dictionary = Array.from_pandas(dictionary, - memory_pool=memory_pool) + arrow_indices = Array.from_numpy(indices, mask=mask, + memory_pool=memory_pool) + arrow_dictionary = Array.from_numpy(dictionary, + memory_pool=memory_pool) if not isinstance(arrow_indices, IntegerArray): raise ValueError('Indices must be integer type') @@ -549,4 +612,3 @@ cdef object get_series_values(object obj): from_pylist = Array.from_list -from_pandas_series = Array.from_pandas diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index f549884d175f..0825750f53f0 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -282,6 +282,22 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: CStatus RemoveColumn(int i, shared_ptr[CTable]* out) + cdef cppclass CTensor" arrow::Tensor": + shared_ptr[CDataType] type() + shared_ptr[CBuffer] data() + + const vector[int64_t]& shape() + const vector[int64_t]& strides() + int64_t size() + + int ndim() + const c_string& dim_name(int i) + + c_bool is_mutable() + c_bool is_contiguous() + Type type_enum() + c_bool Equals(const CTensor& other) + CStatus ConcatenateTables(const vector[shared_ptr[CTable]]& tables, shared_ptr[CTable]* result) diff --git a/python/pyarrow/includes/pyarrow.pxd b/python/pyarrow/includes/pyarrow.pxd index 8142c1c06ff7..86312f319f7d 100644 --- a/python/pyarrow/includes/pyarrow.pxd +++ b/python/pyarrow/includes/pyarrow.pxd @@ -34,7 +34,7 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: shared_ptr[CArray]* out, const shared_ptr[CDataType]& type) - CStatus PandasDtypeToArrow(object dtype, shared_ptr[CDataType]* type) + CStatus NumPyDtypeToArray(object dtype, shared_ptr[CDataType]* type) CStatus PandasToArrow(CMemoryPool* pool, object ao, object mo, const shared_ptr[CDataType]& type, diff --git a/python/pyarrow/io.pyx b/python/pyarrow/io.pyx index 0b27379c273b..608b20d896ae 100644 --- a/python/pyarrow/io.pyx +++ b/python/pyarrow/io.pyx @@ -1095,7 +1095,7 @@ cdef class FeatherWriter: if isinstance(col, Array): arr = col else: - arr = Array.from_pandas(col, mask=mask) + arr = Array.from_numpy(col, mask=mask) cdef c_string c_name = tobytes(name) diff --git a/python/pyarrow/schema.pyx b/python/pyarrow/schema.pyx index 06df64461ae2..1c817afa895d 100644 --- a/python/pyarrow/schema.pyx +++ b/python/pyarrow/schema.pyx @@ -452,6 +452,6 @@ cdef Schema box_schema(const shared_ptr[CSchema]& type): def type_from_numpy_dtype(object dtype): cdef shared_ptr[CDataType] c_type with nogil: - check_status(pyarrow.PandasDtypeToArrow(dtype, &c_type)) + check_status(pyarrow.NumPyDtypeToArray(dtype, &c_type)) return box_data_type(c_type) diff --git a/python/pyarrow/table.pyx b/python/pyarrow/table.pyx index e6fddbd0cfbb..94389a73cc97 100644 --- a/python/pyarrow/table.pyx +++ b/python/pyarrow/table.pyx @@ -309,7 +309,7 @@ cdef _dataframe_to_arrays(df, timestamps_to_ms, Schema schema): if schema is not None: type = schema.field_by_name(name).type - arr = Array.from_pandas(col, type=type, + arr = Array.from_numpy(col, type=type, timestamps_to_ms=timestamps_to_ms) names.append(name) arrays.append(arr) diff --git a/python/pyarrow/tests/test_convert_pandas.py b/python/pyarrow/tests/test_convert_pandas.py index c472ee69034c..abb98a36f63b 100644 --- a/python/pyarrow/tests/test_convert_pandas.py +++ b/python/pyarrow/tests/test_convert_pandas.py @@ -78,7 +78,7 @@ def _check_pandas_roundtrip(self, df, expected=None, nthreads=1, def _check_array_roundtrip(self, values, expected=None, timestamps_to_ms=False, type=None): - arr = A.Array.from_pandas(values, timestamps_to_ms=timestamps_to_ms, + arr = A.Array.from_numpy(values, timestamps_to_ms=timestamps_to_ms, type=type) result = arr.to_pandas() @@ -115,7 +115,7 @@ def test_float_nulls(self): for name, arrow_dtype in dtypes: values = np.random.randn(num_values).astype(name) - arr = A.from_pandas_series(values, null_mask) + arr = A.Array.from_numpy(values, null_mask) arrays.append(arr) fields.append(A.Field.from_py(name, arrow_dtype)) values[null_mask] = np.nan @@ -168,7 +168,7 @@ def test_integer_with_nulls(self): for name in int_dtypes: values = np.random.randint(0, 100, size=num_values) - arr = A.from_pandas_series(values, null_mask) + arr = A.Array.from_numpy(values, null_mask) arrays.append(arr) expected = values.astype('f8') @@ -202,7 +202,7 @@ def test_boolean_nulls(self): mask = np.random.randint(0, 10, size=num_values) < 3 values = np.random.randint(0, 10, size=num_values) < 5 - arr = A.from_pandas_series(values, mask) + arr = A.Array.from_numpy(values, mask) expected = values.astype(object) expected[mask] = None From eb21a17a94e78e35b2585c5a14238dad47f31399 Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Sat, 1 Apr 2017 19:15:23 -0400 Subject: [PATCH 2/3] Finish basic tensor zero-copy roundtrips, simple repr. flake8 fixes Change-Id: Ic8f8f8fd2eae7d53df73eaf51dc6c4e855ad7906 --- cpp/src/arrow/python/CMakeLists.txt | 1 + cpp/src/arrow/python/api.h | 1 + cpp/src/arrow/python/helpers.cc | 1 + cpp/src/arrow/python/numpy_convert.cc | 9 ++-- cpp/src/arrow/python/numpy_convert.h | 2 +- python/pyarrow/__init__.py | 5 +- python/pyarrow/array.pyx | 49 +++++++++++++------- python/pyarrow/includes/libarrow.pxd | 1 + python/pyarrow/includes/pyarrow.pxd | 12 +++-- python/pyarrow/schema.pyx | 14 ++++-- python/pyarrow/tests/pandas_examples.py | 5 +- python/pyarrow/tests/test_convert_builtin.py | 2 +- python/pyarrow/tests/test_convert_pandas.py | 7 ++- python/pyarrow/tests/test_feather.py | 2 - python/pyarrow/tests/test_jemalloc.py | 17 +++++-- 15 files changed, 85 insertions(+), 43 deletions(-) diff --git a/cpp/src/arrow/python/CMakeLists.txt b/cpp/src/arrow/python/CMakeLists.txt index 66d400509de5..a8b4cc7ff1de 100644 --- a/cpp/src/arrow/python/CMakeLists.txt +++ b/cpp/src/arrow/python/CMakeLists.txt @@ -88,6 +88,7 @@ install(FILES do_import_numpy.h helpers.h io.h + numpy_convert.h numpy_interop.h pandas_convert.h type_traits.h diff --git a/cpp/src/arrow/python/api.h b/cpp/src/arrow/python/api.h index f4f1c0cf9a5d..895d1f447ff5 100644 --- a/cpp/src/arrow/python/api.h +++ b/cpp/src/arrow/python/api.h @@ -22,6 +22,7 @@ #include "arrow/python/common.h" #include "arrow/python/helpers.h" #include "arrow/python/io.h" +#include "arrow/python/numpy_convert.h" #include "arrow/python/pandas_convert.h" #endif // ARROW_PYTHON_API_H diff --git a/cpp/src/arrow/python/helpers.cc b/cpp/src/arrow/python/helpers.cc index add2d9a222ad..be5f412fbea1 100644 --- a/cpp/src/arrow/python/helpers.cc +++ b/cpp/src/arrow/python/helpers.cc @@ -42,6 +42,7 @@ std::shared_ptr GetPrimitiveType(Type::type type) { GET_PRIMITIVE_TYPE(DATE32, date32); GET_PRIMITIVE_TYPE(DATE64, date64); GET_PRIMITIVE_TYPE(BOOL, boolean); + GET_PRIMITIVE_TYPE(HALF_FLOAT, float16); GET_PRIMITIVE_TYPE(FLOAT, float32); GET_PRIMITIVE_TYPE(DOUBLE, float64); GET_PRIMITIVE_TYPE(BINARY, binary); diff --git a/cpp/src/arrow/python/numpy_convert.cc b/cpp/src/arrow/python/numpy_convert.cc index d34b06590f17..c0835a7524d3 100644 --- a/cpp/src/arrow/python/numpy_convert.cc +++ b/cpp/src/arrow/python/numpy_convert.cc @@ -61,11 +61,15 @@ NumPyBuffer::NumPyBuffer(PyObject* ao) : Buffer(nullptr, 0) { arr_ = ao; Py_INCREF(ao); - if (!PyArray_Check(ao)) { + if (PyArray_Check(ao)) { PyArrayObject* ndarray = reinterpret_cast(ao); data_ = reinterpret_cast(PyArray_DATA(ndarray)); size_ = PyArray_SIZE(ndarray) * PyArray_DESCR(ndarray)->elsize; capacity_ = size_; + + if (PyArray_FLAGS(ndarray) & NPY_ARRAY_WRITEABLE) { + is_mutable_ = true; + } } } @@ -98,6 +102,7 @@ Status GetTensorType(PyObject* dtype, std::shared_ptr* out) { #if (NPY_UINT64 != NPY_ULONGLONG) TO_ARROW_CASE(ULONGLONG); #endif + TO_ARROW_TYPE_CASE(FLOAT16, float16); TO_ARROW_TYPE_CASE(FLOAT32, float32); TO_ARROW_TYPE_CASE(FLOAT64, float64); default: { @@ -246,9 +251,7 @@ Status TensorToNdarray(const Tensor& tensor, PyObject* base, PyObject** out) { int array_flags = 0; if (tensor.is_row_major()) { array_flags |= NPY_ARRAY_C_CONTIGUOUS; } - if (tensor.is_column_major()) { array_flags |= NPY_ARRAY_F_CONTIGUOUS; } - if (tensor.is_mutable()) { array_flags |= NPY_ARRAY_WRITEABLE; } PyObject* result = PyArray_NewFromDescr(&PyArray_Type, dtype, tensor.ndim(), diff --git a/cpp/src/arrow/python/numpy_convert.h b/cpp/src/arrow/python/numpy_convert.h index b4cf1bc26f29..685a626d4ca2 100644 --- a/cpp/src/arrow/python/numpy_convert.h +++ b/cpp/src/arrow/python/numpy_convert.h @@ -53,7 +53,7 @@ int cast_npy_type_compat(int type_num); bool is_contiguous(PyObject* array); ARROW_EXPORT -Status NumPyDtypeToArray(PyObject* dtype, std::shared_ptr* out); +Status NumPyDtypeToArrow(PyObject* dtype, std::shared_ptr* out); Status GetTensorType(PyObject* dtype, std::shared_ptr* out); Status GetNumPyType(const DataType& type, int* type_num); diff --git a/python/pyarrow/__init__.py b/python/pyarrow/__init__.py index c52b733f9ed6..5215028c90f0 100644 --- a/python/pyarrow/__init__.py +++ b/python/pyarrow/__init__.py @@ -28,7 +28,7 @@ import pyarrow.config from pyarrow.config import cpu_count, set_cpu_count -from pyarrow.array import (Array, from_pylist, +from pyarrow.array import (Array, Tensor, from_pylist, NumericArray, IntegerArray, FloatingPointArray, BooleanArray, Int8Array, UInt8Array, @@ -62,7 +62,8 @@ int8, int16, int32, int64, uint8, uint16, uint32, uint64, timestamp, date32, date64, - float_, double, binary, string, + float16, float32, float64, + binary, string, list_, struct, dictionary, field, DataType, FixedSizeBinaryType, Field, Schema, schema) diff --git a/python/pyarrow/array.pyx b/python/pyarrow/array.pyx index d89e184c31e2..398e4cbffa94 100644 --- a/python/pyarrow/array.pyx +++ b/python/pyarrow/array.pyx @@ -166,7 +166,7 @@ cdef class Array: values, obj.dtype, type, timestamps_to_ms=timestamps_to_ms) if type is None: - check_status(pyarrow.NumPyDtypeToArray(values.dtype, &c_type)) + check_status(pyarrow.NumPyDtypeToArrow(values.dtype, &c_type)) else: c_type = type.sp_type @@ -324,14 +324,28 @@ cdef class Tensor: self.type = box_data_type(self.tp.type()) def __repr__(self): - return object.__repr__(self) + return """ +type: {0} +shape: {1} +strides: {2}""".format(self.type, self.shape, self.strides) @staticmethod def from_numpy(obj): - pass + cdef shared_ptr[CTensor] ctensor + check_status(pyarrow.NdarrayToTensor(default_memory_pool(), + obj, &ctensor)) + return box_tensor(ctensor) def to_numpy(self): - pass + """ + Convert arrow::Tensor to numpy.ndarray with zero copy + """ + cdef: + PyObject* out + + check_status(pyarrow.TensorToNdarray(deref(self.tp), self, + &out)) + return PyObject_to_object(out) property is_mutable: @@ -356,25 +370,19 @@ cdef class Tensor: property shape: def __get__(self): - cdef: - const vector[int64_t]& c_shape = self.tp.shape() - size_t i - + cdef size_t i py_shape = [] - for i in range(c_shape.size()): - py_shape.append(c_shape[i]) + for i in range(self.tp.shape().size()): + py_shape.append(self.tp.shape()[i]) return py_shape property strides: def __get__(self): - cdef: - const vector[int64_t]& c_strides = self.tp.strides() - size_t i - + cdef size_t i py_strides = [] - for i in range(c_strides.size()): - py_strides.append(c_strides[i]) + for i in range(self.tp.strides().size()): + py_strides.append(self.tp.strides()[i]) return py_strides @@ -598,6 +606,15 @@ cdef object box_array(const shared_ptr[CArray]& sp_array): return arr +cdef object box_tensor(const shared_ptr[CTensor]& sp_tensor): + if sp_tensor.get() == NULL: + raise ValueError('Tensor was NULL') + + cdef Tensor tensor = Tensor() + tensor.init(sp_tensor) + return tensor + + cdef object get_series_values(object obj): import pandas as pd diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 0825750f53f0..8da063cbdc36 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -35,6 +35,7 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: Type_UINT64" arrow::Type::UINT64" Type_INT64" arrow::Type::INT64" + Type_HALF_FLOAT" arrow::Type::HALF_FLOAT" Type_FLOAT" arrow::Type::FLOAT" Type_DOUBLE" arrow::Type::DOUBLE" diff --git a/python/pyarrow/includes/pyarrow.pxd b/python/pyarrow/includes/pyarrow.pxd index 86312f319f7d..9b64435e48d7 100644 --- a/python/pyarrow/includes/pyarrow.pxd +++ b/python/pyarrow/includes/pyarrow.pxd @@ -18,8 +18,8 @@ # distutils: language = c++ from pyarrow.includes.common cimport * -from pyarrow.includes.libarrow cimport (CArray, CBuffer, CColumn, - CTable, CDataType, CStatus, Type, +from pyarrow.includes.libarrow cimport (CArray, CBuffer, CColumn, CDataType, + CTable, CTensor, CStatus, Type, CMemoryPool, TimeUnit) cimport pyarrow.includes.libarrow_io as arrow_io @@ -34,7 +34,7 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: shared_ptr[CArray]* out, const shared_ptr[CDataType]& type) - CStatus NumPyDtypeToArray(object dtype, shared_ptr[CDataType]* type) + CStatus NumPyDtypeToArrow(object dtype, shared_ptr[CDataType]* type) CStatus PandasToArrow(CMemoryPool* pool, object ao, object mo, const shared_ptr[CDataType]& type, @@ -44,6 +44,12 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: const shared_ptr[CDataType]& type, shared_ptr[CArray]* out) + CStatus NdarrayToTensor(CMemoryPool* pool, object ao, + shared_ptr[CTensor]* out); + + CStatus TensorToNdarray(const CTensor& tensor, PyObject* base, + PyObject** out) + CStatus ConvertArrayToPandas(const shared_ptr[CArray]& arr, PyObject* py_ref, PyObject** out) diff --git a/python/pyarrow/schema.pyx b/python/pyarrow/schema.pyx index 1c817afa895d..253be4590b51 100644 --- a/python/pyarrow/schema.pyx +++ b/python/pyarrow/schema.pyx @@ -241,7 +241,9 @@ cdef set PRIMITIVE_TYPES = set([ la.Type_UINT32, la.Type_INT32, la.Type_UINT64, la.Type_INT64, la.Type_TIMESTAMP, la.Type_DATE32, - la.Type_DATE64, la.Type_FLOAT, + la.Type_DATE64, + la.Type_HALF_FLOAT, + la.Type_FLOAT, la.Type_DOUBLE]) @@ -340,11 +342,15 @@ def date64(): return primitive_type(la.Type_DATE64) -def float_(): +def float16(): + return primitive_type(la.Type_HALF_FLOAT) + + +def float32(): return primitive_type(la.Type_FLOAT) -def double(): +def float64(): return primitive_type(la.Type_DOUBLE) @@ -452,6 +458,6 @@ cdef Schema box_schema(const shared_ptr[CSchema]& type): def type_from_numpy_dtype(object dtype): cdef shared_ptr[CDataType] c_type with nogil: - check_status(pyarrow.NumPyDtypeToArray(dtype, &c_type)) + check_status(pyarrow.NumPyDtypeToArrow(dtype, &c_type)) return box_data_type(c_type) diff --git a/python/pyarrow/tests/pandas_examples.py b/python/pyarrow/tests/pandas_examples.py index c9343fce233d..e081c3871305 100644 --- a/python/pyarrow/tests/pandas_examples.py +++ b/python/pyarrow/tests/pandas_examples.py @@ -37,7 +37,7 @@ def dataframe_with_arrays(): ('i4', pa.int32()), ('i8', pa.int64()), ('u1', pa.uint8()), ('u2', pa.uint16()), ('u4', pa.uint32()), ('u8', pa.uint64()), - ('f4', pa.float_()), ('f8', pa.double())] + ('f4', pa.float32()), ('f8', pa.float64())] arrays = OrderedDict() fields = [] @@ -77,6 +77,7 @@ def dataframe_with_arrays(): return df, schema + def dataframe_with_lists(): """ Dataframe with list columns of every possible primtive type. @@ -97,7 +98,7 @@ def dataframe_with_lists(): None, [0] ] - fields.append(pa.field('double', pa.list_(pa.double()))) + fields.append(pa.field('double', pa.list_(pa.float64()))) arrays['double'] = [ [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], [0., 1., 2., 3., 4.], diff --git a/python/pyarrow/tests/test_convert_builtin.py b/python/pyarrow/tests/test_convert_builtin.py index bb6d2d17d5f0..15fca560c651 100644 --- a/python/pyarrow/tests/test_convert_builtin.py +++ b/python/pyarrow/tests/test_convert_builtin.py @@ -70,7 +70,7 @@ def test_double(self): arr = pyarrow.from_pylist(data) assert len(arr) == 6 assert arr.null_count == 3 - assert arr.type == pyarrow.double() + assert arr.type == pyarrow.float64() assert arr.to_pylist() == data def test_unicode(self): diff --git a/python/pyarrow/tests/test_convert_pandas.py b/python/pyarrow/tests/test_convert_pandas.py index abb98a36f63b..0b3c02e9945e 100644 --- a/python/pyarrow/tests/test_convert_pandas.py +++ b/python/pyarrow/tests/test_convert_pandas.py @@ -22,7 +22,6 @@ import unittest import numpy as np -import numpy.testing as npt import pandas as pd import pandas.util.testing as tm @@ -79,7 +78,7 @@ def _check_pandas_roundtrip(self, df, expected=None, nthreads=1, def _check_array_roundtrip(self, values, expected=None, timestamps_to_ms=False, type=None): arr = A.Array.from_numpy(values, timestamps_to_ms=timestamps_to_ms, - type=type) + type=type) result = arr.to_pandas() assert arr.null_count == pd.isnull(values).sum() @@ -90,7 +89,7 @@ def _check_array_roundtrip(self, values, expected=None, def test_float_no_nulls(self): data = {} fields = [] - dtypes = [('f4', A.float_()), ('f8', A.double())] + dtypes = [('f4', A.float32()), ('f8', A.float64())] num_values = 100 for numpy_dtype, arrow_dtype in dtypes: @@ -106,7 +105,7 @@ def test_float_nulls(self): num_values = 100 null_mask = np.random.randint(0, 10, size=num_values) < 3 - dtypes = [('f4', A.float_()), ('f8', A.double())] + dtypes = [('f4', A.float32()), ('f8', A.float64())] names = ['f4', 'f8'] expected_cols = [] diff --git a/python/pyarrow/tests/test_feather.py b/python/pyarrow/tests/test_feather.py index dd6888f2d130..525da344c995 100644 --- a/python/pyarrow/tests/test_feather.py +++ b/python/pyarrow/tests/test_feather.py @@ -15,8 +15,6 @@ import os import unittest -import pytest - from numpy.testing import assert_array_equal import numpy as np diff --git a/python/pyarrow/tests/test_jemalloc.py b/python/pyarrow/tests/test_jemalloc.py index 8efd514dd0ca..c6cc2cc34a08 100644 --- a/python/pyarrow/tests/test_jemalloc.py +++ b/python/pyarrow/tests/test_jemalloc.py @@ -33,11 +33,15 @@ def test_different_memory_pool(): gc.collect() bytes_before_default = pyarrow.total_allocated_bytes() bytes_before_jemalloc = pyarrow.jemalloc.default_pool().bytes_allocated() - array = pyarrow.from_pylist([1, None, 3, None], - memory_pool=pyarrow.jemalloc.default_pool()) + + # it works + array = pyarrow.from_pylist([1, None, 3, None], # noqa + memory_pool=pyarrow.jemalloc.default_pool()) gc.collect() assert pyarrow.total_allocated_bytes() == bytes_before_default - assert pyarrow.jemalloc.default_pool().bytes_allocated() > bytes_before_jemalloc + assert (pyarrow.jemalloc.default_pool().bytes_allocated() > + bytes_before_jemalloc) + @jemalloc def test_default_memory_pool(): @@ -47,10 +51,13 @@ def test_default_memory_pool(): old_memory_pool = pyarrow.memory.default_pool() pyarrow.memory.set_default_pool(pyarrow.jemalloc.default_pool()) - array = pyarrow.from_pylist([1, None, 3, None]) + + array = pyarrow.from_pylist([1, None, 3, None]) # noqa + pyarrow.memory.set_default_pool(old_memory_pool) gc.collect() assert pyarrow.total_allocated_bytes() == bytes_before_default - assert pyarrow.jemalloc.default_pool().bytes_allocated() > bytes_before_jemalloc + assert (pyarrow.jemalloc.default_pool().bytes_allocated() > + bytes_before_jemalloc) From 2c234270e66d5e1148b20182e3a1944d8ea3a69a Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Sat, 1 Apr 2017 19:17:28 -0400 Subject: [PATCH 3/3] Restore clang-format-3.9 formatting Change-Id: I0ab2071ebb5ed328f7731a0290cacf7653a4b7f4 --- cpp/src/arrow/io/io-hdfs-test.cc | 7 +++---- cpp/src/arrow/ipc/ipc-read-write-benchmark.cc | 4 ++-- cpp/src/arrow/python/builtin_convert.cc | 5 ++--- cpp/src/arrow/python/numpy_convert.cc | 4 +--- cpp/src/arrow/util/logging.h | 7 ++++--- 5 files changed, 12 insertions(+), 15 deletions(-) diff --git a/cpp/src/arrow/io/io-hdfs-test.cc b/cpp/src/arrow/io/io-hdfs-test.cc index af59e96a1448..f3140be0b2da 100644 --- a/cpp/src/arrow/io/io-hdfs-test.cc +++ b/cpp/src/arrow/io/io-hdfs-test.cc @@ -78,10 +78,9 @@ class TestHdfsClient : public ::testing::Test { LibHdfsShim* driver_shim; client_ = nullptr; - scratch_dir_ = - boost::filesystem::unique_path( - boost::filesystem::temp_directory_path() / "arrow-hdfs/scratch-%%%%") - .string(); + scratch_dir_ = boost::filesystem::unique_path( + boost::filesystem::temp_directory_path() / "arrow-hdfs/scratch-%%%%") + .string(); loaded_driver_ = false; diff --git a/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc b/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc index 1aecdbc63319..b385929d8b10 100644 --- a/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc +++ b/cpp/src/arrow/ipc/ipc-read-write-benchmark.cc @@ -80,7 +80,7 @@ static void BM_WriteRecordBatch(benchmark::State& state) { // NOLINT non-const int32_t metadata_length; int64_t body_length; if (!ipc::WriteRecordBatch(*record_batch, 0, &stream, &metadata_length, &body_length, - default_memory_pool()) + default_memory_pool()) .ok()) { state.SkipWithError("Failed to write!"); } @@ -101,7 +101,7 @@ static void BM_ReadRecordBatch(benchmark::State& state) { // NOLINT non-const r int32_t metadata_length; int64_t body_length; if (!ipc::WriteRecordBatch(*record_batch, 0, &stream, &metadata_length, &body_length, - default_memory_pool()) + default_memory_pool()) .ok()) { state.SkipWithError("Failed to write!"); } diff --git a/cpp/src/arrow/python/builtin_convert.cc b/cpp/src/arrow/python/builtin_convert.cc index 86cf3485adb5..6a13fdccdeaf 100644 --- a/cpp/src/arrow/python/builtin_convert.cc +++ b/cpp/src/arrow/python/builtin_convert.cc @@ -412,9 +412,8 @@ class FixedWidthBytesConverter : public TypedConverter { PyObject* item; PyObject* bytes_obj; OwnedRef tmp; - Py_ssize_t expected_length = - std::dynamic_pointer_cast(typed_builder_->type()) - ->byte_width(); + Py_ssize_t expected_length = std::dynamic_pointer_cast( + typed_builder_->type())->byte_width(); Py_ssize_t size = PySequence_Size(seq); for (int64_t i = 0; i < size; ++i) { item = PySequence_GetItem(seq, i); diff --git a/cpp/src/arrow/python/numpy_convert.cc b/cpp/src/arrow/python/numpy_convert.cc index c0835a7524d3..3697819120db 100644 --- a/cpp/src/arrow/python/numpy_convert.cc +++ b/cpp/src/arrow/python/numpy_convert.cc @@ -67,9 +67,7 @@ NumPyBuffer::NumPyBuffer(PyObject* ao) : Buffer(nullptr, 0) { size_ = PyArray_SIZE(ndarray) * PyArray_DESCR(ndarray)->elsize; capacity_ = size_; - if (PyArray_FLAGS(ndarray) & NPY_ARRAY_WRITEABLE) { - is_mutable_ = true; - } + if (PyArray_FLAGS(ndarray) & NPY_ARRAY_WRITEABLE) { is_mutable_ = true; } } } diff --git a/cpp/src/arrow/util/logging.h b/cpp/src/arrow/util/logging.h index b22f07dd6345..697d47c54100 100644 --- a/cpp/src/arrow/util/logging.h +++ b/cpp/src/arrow/util/logging.h @@ -38,9 +38,10 @@ namespace arrow { #define ARROW_LOG_INTERNAL(level) ::arrow::internal::CerrLog(level) #define ARROW_LOG(level) ARROW_LOG_INTERNAL(ARROW_##level) -#define ARROW_CHECK(condition) \ - (condition) ? 0 : ::arrow::internal::FatalLog(ARROW_FATAL) \ - << __FILE__ << __LINE__ << " Check failed: " #condition " " +#define ARROW_CHECK(condition) \ + (condition) ? 0 \ + : ::arrow::internal::FatalLog(ARROW_FATAL) \ + << __FILE__ << __LINE__ << " Check failed: " #condition " " #ifdef NDEBUG #define ARROW_DFATAL ARROW_WARNING