Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy patharray_type_caster.cc
More file actions
418 lines (391 loc) · 14.9 KB
/
Copy patharray_type_caster.cc
File metadata and controls
418 lines (391 loc) · 14.9 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright 2020 The TensorStore Authors
//
// Licensed 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 "python/tensorstore/numpy.h"
// numpy.h must be included first
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
// Other headers must be included after pybind11 to ensure header-order
// inclusion constraints are satisfied.
#include "python/tensorstore/array_type_caster.h"
// Other headers
#include <stddef.h>
#include <algorithm>
#include <cassert>
#include <exception>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include "absl/strings/str_format.h"
#include "python/tensorstore/data_type.h"
#include "python/tensorstore/json_type_caster.h"
#include "tensorstore/array.h"
#include "tensorstore/contiguous_layout.h"
#include "tensorstore/data_type.h"
#include "tensorstore/index.h"
#include "tensorstore/internal/elementwise_function.h"
#include "tensorstore/rank.h"
#include "tensorstore/strided_layout.h"
#include "tensorstore/util/generic_stringify.h"
#include "tensorstore/util/iterate.h"
#include "tensorstore/util/span.h"
namespace tensorstore {
namespace internal_python {
namespace py = pybind11;
namespace {
/// Converts string and json types to Python objects.
struct ConvertToObject {
py::object operator()(
const ::tensorstore::dtypes::string_t* x) const noexcept {
return py::reinterpret_steal<py::object>(
PyBytes_FromStringAndSize(x->data(), x->size()));
}
py::object operator()(
const ::tensorstore::dtypes::ustring_t* x) const noexcept {
return py::reinterpret_steal<py::object>(
PyUnicode_FromStringAndSize(x->utf8.data(), x->utf8.size()));
}
py::object operator()(const ::tensorstore::dtypes::json_t* x) const noexcept {
return JsonToPyObject(*x);
}
};
template <typename T>
constexpr const internal::ElementwiseFunction<2, void*>*
GetConvertToNumpyObjectArrayFunction() {
if constexpr (std::is_invocable_v<const ConvertToObject&, const T*>) {
const auto func = [](const T* from, PyObject** to, void* arg) {
if (auto obj = ConvertToObject()(from)) {
Py_XDECREF(std::exchange(*to, obj.release().ptr()));
return true;
}
return false;
};
return internal::SimpleElementwiseFunction<decltype(func)(T, PyObject*),
void*>();
}
return nullptr;
}
constexpr const internal::ElementwiseFunction<2, void*>*
kConvertDataTypeToNumpyObjectArray[kNumDataTypeIds] = {
#define TENSORSTORE_INTERNAL_DO_CONVERT(T, ...) \
GetConvertToNumpyObjectArrayFunction<::tensorstore::dtypes::T>(),
TENSORSTORE_FOR_EACH_DATA_TYPE(TENSORSTORE_INTERNAL_DO_CONVERT)
#undef TENSORSTORE_INTERNAL_DO_CONVERT
};
/// Converts Python objects to string and json types.
///
/// On success, sets `*to` to the converted value and returns `true`.
///
/// If an error occurs, sets `ex` to an exception and returns `false`.
struct ConvertFromObject {
std::exception_ptr ex;
bool operator()(PyObject** from, ::tensorstore::dtypes::string_t* to,
void*) noexcept {
char* buffer;
Py_ssize_t length;
if (::PyBytes_AsStringAndSize(*from, &buffer, &length) == -1) {
ex = std::make_exception_ptr(py::error_already_set());
return false;
}
to->assign(buffer, length);
return true;
}
bool operator()(PyObject** from, ::tensorstore::dtypes::ustring_t* to,
void*) noexcept {
Py_ssize_t length;
const char* buffer = ::PyUnicode_AsUTF8AndSize(*from, &length);
if (!buffer) {
ex = std::make_exception_ptr(py::error_already_set());
return false;
}
to->utf8.assign(buffer, length);
return true;
}
bool operator()(PyObject** from, ::tensorstore::dtypes::json_t* to,
void*) noexcept {
try {
*to = PyObjectToJson(*from);
return true;
} catch (...) {
ex = std::current_exception();
return false;
}
}
};
template <typename T>
constexpr const internal::ElementwiseFunction<2, void*>*
GetConvertFromNumpyObjectArrayFunction() {
if constexpr (std::is_invocable_v<ConvertFromObject&, PyObject**, T*,
void*>) {
return internal::SimpleElementwiseFunction<ConvertFromObject(PyObject*, T),
void*>();
}
return nullptr;
}
constexpr const internal::ElementwiseFunction<2, void*>*
kConvertDataTypeFromNumpyObjectArray[kNumDataTypeIds] = {
#define TENSORSTORE_INTERNAL_DO_CONVERT(T, ...) \
GetConvertFromNumpyObjectArrayFunction<::tensorstore::dtypes::T>(),
TENSORSTORE_FOR_EACH_DATA_TYPE(TENSORSTORE_INTERNAL_DO_CONVERT)
#undef TENSORSTORE_INTERNAL_DO_CONVERT
};
pybind11::object GetNumpyObjectArrayImpl(SharedArrayView<const void> source,
bool is_const) {
Py_ssize_t target_shape_ssize_t[NPY_MAXDIMS];
std::copy(source.shape().begin(), source.shape().end(), target_shape_ssize_t);
auto array_obj = py::reinterpret_steal<py::array>(PyArray_NewFromDescr(
&PyArray_Type, PyArray_DescrFromType(NPY_OBJECT),
static_cast<int>(source.rank()), target_shape_ssize_t,
/*strides=*/nullptr,
/*data=*/nullptr,
/*flags=*/NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_WRITEABLE,
/*obj=*/nullptr));
if (!array_obj) throw py::error_already_set();
Index target_strides[NPY_MAXDIMS];
std::copy_n(array_obj.strides(), source.rank(), target_strides);
if (!internal::IterateOverStridedLayouts<2>(
/*closure=*/{kConvertDataTypeToNumpyObjectArray[static_cast<size_t>(
source.dtype().id())],
nullptr},
/*arg=*/nullptr,
/*shape=*/source.shape(),
{{const_cast<void*>(source.data()),
static_cast<void*>(
py::detail::array_proxy(array_obj.ptr())->data)}},
{{source.byte_strides().data(), target_strides}},
/*constraints=*/skip_repeated_elements,
{{source.dtype().size(), sizeof(PyObject*)}})) {
throw py::error_already_set();
}
if (is_const) {
PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(array_obj.ptr()),
NPY_ARRAY_WRITEABLE);
}
return std::move(array_obj);
}
/// Creates an array by copying from a NumPy object array.
///
/// \param array_obj The NumPy object array, must have a data type number of
/// `NPY_OBJECT`.
/// \param dtype The TensorStore data type of the returned array. If the
/// invalid `DataType()` is specified, uses json.
/// \returns The new array.
/// \throws If the conversion fails.
SharedArray<void, dynamic_rank> ArrayFromNumpyObjectArray(
pybind11::array array_obj, DataType dtype) {
if (!dtype.valid()) {
dtype = dtype_v<::tensorstore::dtypes::json_t>;
}
const DimensionIndex rank = array_obj.ndim();
if (rank > kMaxRank) {
throw pybind11::value_error(absl::StrFormat(
"Array of rank %d is not supported by tensorstore", rank));
}
StridedLayout<dynamic_rank(kMaxRank)> array_obj_layout;
array_obj_layout.set_rank(rank);
AssignArrayLayout(array_obj, rank, array_obj_layout.shape().data(),
array_obj_layout.byte_strides().data());
auto array = tensorstore::AllocateArrayLike<void>(
array_obj_layout, skip_repeated_elements, default_init, dtype);
ConvertFromObject converter;
if (!internal::IterateOverStridedLayouts<2>(
/*closure=*/{kConvertDataTypeFromNumpyObjectArray[static_cast<size_t>(
dtype.id())],
&converter},
/*arg=*/nullptr,
/*shape=*/array.shape(),
{{static_cast<void*>(py::detail::array_proxy(array_obj.ptr())->data),
const_cast<void*>(array.data())}},
{{array_obj_layout.byte_strides().data(),
array.byte_strides().data()}},
/*constraints=*/skip_repeated_elements,
{{sizeof(PyObject*), dtype.size()}})) {
std::rethrow_exception(std::move(converter.ex));
}
return array;
}
} // namespace
void AssignArrayLayout(pybind11::array array_obj, DimensionIndex rank,
Index* shape, Index* byte_strides) {
[[maybe_unused]] const int flags =
py::detail::array_proxy(array_obj.ptr())->flags;
assert(array_obj.ndim() == rank);
assert(flags & NPY_ARRAY_ALIGNED);
std::copy_n(array_obj.shape(), rank, shape);
for (DimensionIndex i = 0; i < rank; ++i) {
if (shape[i] < 0 || shape[i] > kMaxFiniteIndex) {
throw std::out_of_range(
absl::StrFormat("Array shape[%d]=%d is not valid", i, shape[i]));
}
}
std::copy_n(array_obj.strides(), rank, byte_strides);
}
pybind11::object GetNumpyArrayImpl(SharedArrayView<const void> value,
bool is_const) {
if (value.rank() > NPY_MAXDIMS) {
throw std::out_of_range(
absl::StrFormat("Array of rank %d (which is greater than %d) cannot be "
"converted to NumPy array",
value.rank(), NPY_MAXDIMS));
}
if (const DataTypeId id = value.dtype().id();
id != DataTypeId::custom &&
kConvertDataTypeToNumpyObjectArray[static_cast<size_t>(id)]) {
return GetNumpyObjectArrayImpl(value, is_const);
}
Py_ssize_t shape[NPY_MAXDIMS];
Py_ssize_t strides[NPY_MAXDIMS];
std::copy_n(value.shape().data(), value.rank(), shape);
std::copy_n(value.byte_strides().data(), value.rank(), strides);
int flags = 0;
if (!is_const) {
flags |= NPY_ARRAY_WRITEABLE;
}
auto py_dtype = GetNumpyDtypeOrThrow(value.dtype());
auto obj = py::reinterpret_steal<py::array>(PyArray_NewFromDescr(
/*subtype=*/&PyArray_Type,
/*descr=*/reinterpret_cast<PyArray_Descr*>(py_dtype.release().ptr()),
/*nd=*/static_cast<int>(value.rank()),
/*dims=*/shape,
/*strides=*/strides,
/*data=*/const_cast<void*>(value.data()), flags, nullptr));
if (!obj) throw py::error_already_set();
using Pointer = std::shared_ptr<const void>;
PyArray_SetBaseObject(
reinterpret_cast<PyArrayObject*>(obj.ptr()),
py::capsule(new Pointer(std::move(value.pointer())),
[](void* p) { delete static_cast<Pointer*>(p); })
.release()
.ptr());
return std::move(obj);
}
void CopyFromNumpyArray(pybind11::handle src, ArrayView<void> out) {
// TODO(jbms): Avoid an extra copy
SharedArray<const void> temp_src;
ConvertToArray(src, &temp_src, /*data_type_constraint=*/out.dtype(),
/*min_rank=*/out.rank(), /*max_rank=*/out.rank());
if (!internal::RangesEqual(temp_src.shape(), out.shape())) {
throw py::value_error(absl::StrFormat(
"Cannot copy source array of shape %v"
" to target array of shape %v",
GenericStringify(temp_src.shape()), GenericStringify(out.shape())));
}
CopyArray(temp_src, out);
}
ContiguousLayoutOrder GetContiguousLayoutOrderOrThrow(pybind11::handle obj) {
Py_UCS4 c;
if (PyUnicode_Check(obj.ptr())) {
if (PyUnicode_READY(obj.ptr()) != 0) throw py::error_already_set();
if (PyUnicode_GET_LENGTH(obj.ptr()) != 1) goto invalid;
void* data = PyUnicode_DATA(obj.ptr());
int kind = PyUnicode_KIND(obj.ptr());
c = PyUnicode_READ(kind, data, 0);
} else if (PyBytes_Check(obj.ptr())) {
if (PyBytes_GET_SIZE(obj.ptr()) != 1) goto invalid;
c = PyBytes_AS_STRING(obj.ptr())[0];
} else {
goto invalid;
}
switch (c) {
case 'C':
return ContiguousLayoutOrder::c;
case 'F':
return ContiguousLayoutOrder::fortran;
default:
break;
}
invalid:
throw py::type_error("`order` must be specified as 'C' or 'F'");
}
bool ConvertToArrayImpl(pybind11::handle src,
SharedArray<void, dynamic_rank>& out,
bool& out_array_is_writable,
DataType data_type_constraint, DimensionIndex min_rank,
DimensionIndex max_rank, bool writable, bool no_throw,
std::optional<bool> copy) {
// Determine the NumPy data type corresponding to `data_type_constraint`.
pybind11::dtype dtype_handle =
data_type_constraint.valid()
? GetNumpyDtypeOrThrow(data_type_constraint)
: pybind11::reinterpret_steal<pybind11::dtype>(pybind11::handle());
int flags = NPY_ARRAY_ALIGNED;
if (writable) {
flags |= NPY_ARRAY_WRITEABLE;
}
if (copy == true) {
flags |= NPY_ARRAY_ENSURECOPY;
} else if (copy == false) {
flags |= NPY_ARRAY_ENSURENOCOPY;
}
// Convert `src` to a NumPy array.
auto obj = pybind11::reinterpret_steal<pybind11::array>(PyArray_FromAny(
src.ptr(), reinterpret_cast<PyArray_Descr*>(dtype_handle.release().ptr()),
min_rank == dynamic_rank ? 0 : min_rank,
max_rank == dynamic_rank ? 0 : max_rank, flags, nullptr));
const auto try_convert = [&] {
if (!obj) {
if (no_throw) {
PyErr_Clear();
return false;
}
throw pybind11::error_already_set();
}
const int type_num =
pybind11::detail::array_descriptor_proxy(obj.dtype().ptr())->type_num;
if (copy == false && type_num == NPY_OBJECT) {
if (no_throw) return false;
throw pybind11::value_error(
"NumPy object arrays cannot be converted without copying");
}
// PyArray_FromAny does not handle rank constraints of 0, so we need to
// check them separately.
if (max_rank == 0 && obj.ndim() != 0) {
if (data_type_constraint != dtype_v<::tensorstore::dtypes::json_t>) {
if (no_throw) return false;
throw pybind11::value_error(absl::StrFormat(
"Expected array of rank 0, but received array of rank %d",
obj.ndim()));
}
// For json data type, the user may have specified a Python value like
// `[1, 2, 3]` which is intended to be interpreted as a single JSON value
// (i.e. rank-0 array). Attempt a conversion directly from the
// user-specified value.
out = MakeScalarArray(PyObjectToJson(src));
out_array_is_writable = true;
return true;
}
if (type_num == NPY_OBJECT) {
// Arrays of Python objects require copying.
out = ArrayFromNumpyObjectArray(std::move(obj), data_type_constraint);
out_array_is_writable = true;
return true;
}
out_array_is_writable = static_cast<bool>(
PyArray_FLAGS(reinterpret_cast<PyArrayObject*>(obj.ptr())) &
NPY_ARRAY_WRITEABLE);
out = UncheckedArrayFromNumpy<void>(std::move(obj));
return true;
};
if (no_throw) {
try {
return try_convert();
} catch (...) {
return false;
}
}
return try_convert();
}
} // namespace internal_python
} // namespace tensorstore
You can’t perform that action at this time.
