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

Function NdarrayToTensor

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

Source from the content-addressed store, hash-verified

194#undef TO_ARROW_TYPE_CASE
195
196Status NdarrayToTensor(MemoryPool* pool, PyObject* ao,
197 const std::vector<std::string>& dim_names,
198 std::shared_ptr<Tensor>* out) {
199 if (!PyArray_Check(ao)) {
200 return Status::TypeError("Did not pass ndarray object");
201 }
202
203 PyArrayObject* ndarray = reinterpret_cast<PyArrayObject*>(ao);
204
205 // TODO(wesm): What do we want to do with non-contiguous memory and negative strides?
206
207 int ndim = PyArray_NDIM(ndarray);
208
209 std::shared_ptr<Buffer> data = std::make_shared<NumPyBuffer>(ao);
210 std::vector<int64_t> shape(ndim);
211 std::vector<int64_t> strides(ndim);
212
213 npy_intp* array_strides = PyArray_STRIDES(ndarray);
214 npy_intp* array_shape = PyArray_SHAPE(ndarray);
215 for (int i = 0; i < ndim; ++i) {
216 if (array_strides[i] < 0) {
217 return Status::Invalid("Negative ndarray strides not supported");
218 }
219 shape[i] = array_shape[i];
220 strides[i] = array_strides[i];
221 }
222
223 ARROW_ASSIGN_OR_RAISE(
224 auto type, GetTensorType(reinterpret_cast<PyObject*>(PyArray_DESCR(ndarray))));
225 *out = std::make_shared<Tensor>(type, data, shape, strides, dim_names);
226 return Status::OK();
227}
228
229Status TensorToNdarray(const std::shared_ptr<Tensor>& tensor, PyObject* base,
230 PyObject** out) {

Callers 3

Calls 3

TypeErrorFunction · 0.50
InvalidFunction · 0.50
OKFunction · 0.50

Tested by

no test coverage detected