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