MCPcopy Create free account
hub / github.com/apache/arrow / TensorToNdarray

Function TensorToNdarray

python/pyarrow/src/arrow/python/numpy_convert.cc:233–281  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

231}
232
233Status TensorToNdarray(const std::shared_ptr<Tensor>& tensor, PyObject* base,
234 PyObject** out) {
235 int type_num = 0;
236 RETURN_NOT_OK(GetNumPyType(*tensor->type(), &type_num));
237 PyArray_Descr* dtype = PyArray_DescrNewFromType(type_num);
238 RETURN_IF_PYERROR();
239
240 const int ndim = tensor->ndim();
241 std::vector<npy_intp> npy_shape(ndim);
242 std::vector<npy_intp> npy_strides(ndim);
243
244 for (int i = 0; i < ndim; ++i) {
245 npy_shape[i] = tensor->shape()[i];
246 npy_strides[i] = tensor->strides()[i];
247 }
248
249 const void* immutable_data = nullptr;
250 if (tensor->data()) {
251 immutable_data = tensor->data()->data();
252 }
253
254 // Remove const =(
255 void* mutable_data = const_cast<void*>(immutable_data);
256
257 int array_flags = 0;
258 if (tensor->is_row_major()) {
259 array_flags |= NPY_ARRAY_C_CONTIGUOUS;
260 }
261 if (tensor->is_column_major()) {
262 array_flags |= NPY_ARRAY_F_CONTIGUOUS;
263 }
264 if (tensor->is_mutable()) {
265 array_flags |= NPY_ARRAY_WRITEABLE;
266 }
267
268 PyObject* result =
269 PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, npy_shape.data(),
270 npy_strides.data(), mutable_data, array_flags, nullptr);
271 RETURN_IF_PYERROR();
272
273 if (base == Py_None || base == nullptr) {
274 base = py::wrap_tensor(tensor);
275 } else {
276 Py_XINCREF(base);
277 }
278 PyArray_SetBaseObject(reinterpret_cast<PyArrayObject*>(result), base);
279 *out = result;
280 return Status::OK();
281}
282
283// Wrap the dense data of a sparse tensor in a ndarray
284static Status SparseTensorDataToNdarray(const SparseTensor& sparse_tensor,

Callers 3

SparseCOOTensorToNdarrayFunction · 0.85
SparseCSXMatrixToNdarrayFunction · 0.85
SparseCSFTensorToNdarrayFunction · 0.85

Calls 9

GetNumPyTypeFunction · 0.85
ndimMethod · 0.80
is_row_majorMethod · 0.80
is_column_majorMethod · 0.80
OKFunction · 0.50
typeMethod · 0.45
shapeMethod · 0.45
stridesMethod · 0.45
dataMethod · 0.45

Tested by

no test coverage detected