|
16 | 16 | // under the License.
|
17 | 17 |
|
18 | 18 | // helpers.h includes a NumPy header, so we include this first
|
| 19 | +#include "arrow/python/numpy_init.h" |
19 | 20 | #include "arrow/python/numpy_interop.h"
|
20 | 21 |
|
21 | 22 | #include "arrow/python/helpers.h"
|
|
31 | 32 | #include "arrow/type_fwd.h"
|
32 | 33 | #include "arrow/util/checked_cast.h"
|
33 | 34 | #include "arrow/util/config.h"
|
| 35 | +#include "arrow/util/float16.h" |
34 | 36 | #include "arrow/util/logging.h"
|
35 | 37 |
|
36 | 38 | namespace arrow {
|
@@ -73,21 +75,22 @@ std::shared_ptr<DataType> GetPrimitiveType(Type::type type) {
|
73 | 75 | }
|
74 | 76 | }
|
75 | 77 |
|
76 |
| -PyObject* PyHalf_FromHalf(npy_half value) { |
77 |
| - PyObject* result = PyArrayScalar_New(Half); |
78 |
| - if (result != NULL) { |
79 |
| - PyArrayScalar_ASSIGN(result, Half, value); |
80 |
| - } |
81 |
| - return result; |
| 78 | +PyObject* PyFloat_FromHalf(uint16_t value) { |
| 79 | + // Convert the uint16_t Float16 value to a PyFloat object |
| 80 | + arrow::util::Float16 half_val = arrow::util::Float16::FromBits(value); |
| 81 | + return PyFloat_FromDouble(half_val.ToDouble()); |
82 | 82 | }
|
83 | 83 |
|
84 |
| -Status PyFloat_AsHalf(PyObject* obj, npy_half* out) { |
85 |
| - if (PyArray_IsScalar(obj, Half)) { |
86 |
| - *out = PyArrayScalar_VAL(obj, Half); |
87 |
| - return Status::OK(); |
| 84 | +Result<uint16_t> PyFloat_AsHalf(PyObject* obj) { |
| 85 | + if (PyFloat_Check(obj)) { |
| 86 | + arrow::util::Float16 half_val = |
| 87 | + arrow::util::Float16::FromDouble(PyFloat_AsDouble(obj)); |
| 88 | + return half_val.bits(); |
| 89 | + } else if (has_numpy() && PyArray_IsScalar(obj, Half)) { |
| 90 | + return PyArrayScalar_VAL(obj, Half); |
88 | 91 | } else {
|
89 |
| - // XXX: cannot use npy_double_to_half() without linking with Numpy |
90 |
| - return Status::TypeError("Expected np.float16 instance"); |
| 92 | + return Status::TypeError("conversion to float16 expects a `float` or ", |
| 93 | + "`np.float16` object, got ", Py_TYPE(obj)->tp_name); |
91 | 94 | }
|
92 | 95 | }
|
93 | 96 |
|
|
0 commit comments