numpy/array.rs
1//! Safe interface for NumPy's [N-dimensional arrays][ndarray]
2//!
3//! [ndarray]: https://numpy.org/doc/stable/reference/arrays.ndarray.html
4
5use std::{
6 marker::PhantomData,
7 mem,
8 os::raw::{c_int, c_void},
9 ptr, slice,
10};
11
12use ndarray::{
13 Array, ArrayBase, ArrayView, ArrayViewMut, Axis, Data, Dim, Dimension, IntoDimension, Ix0, Ix1,
14 Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn, RawArrayView, RawArrayViewMut, RawData, ShapeBuilder,
15 StrideShape,
16};
17use num_traits::AsPrimitive;
18use pyo3::{
19 ffi,
20 types::{DerefToPyAny, PyAnyMethods, PyModule},
21 Bound, DowncastError, Py, PyAny, PyErr, PyObject, PyResult, PyTypeInfo, Python,
22};
23
24use crate::borrow::{PyReadonlyArray, PyReadwriteArray};
25use crate::cold;
26use crate::convert::{ArrayExt, IntoPyArray, NpyIndex, ToNpyDims, ToPyArray};
27use crate::dtype::{Element, PyArrayDescrMethods};
28use crate::error::{
29 BorrowError, DimensionalityError, FromVecError, IgnoreError, NotContiguousError, TypeError,
30 DIMENSIONALITY_MISMATCH_ERR, MAX_DIMENSIONALITY_ERR,
31};
32use crate::npyffi::{self, npy_intp, NPY_ORDER, PY_ARRAY_API};
33use crate::slice_container::PySliceContainer;
34use crate::untyped_array::{PyUntypedArray, PyUntypedArrayMethods};
35
36/// A safe, statically-typed wrapper for NumPy's [`ndarray`][ndarray] class.
37///
38/// # Memory location
39///
40/// - Allocated by Rust: Constructed via [`IntoPyArray`] or
41/// [`from_vec`][Self::from_vec] or [`from_owned_array`][Self::from_owned_array].
42///
43/// These methods transfers ownership of the Rust allocation into a suitable Python object
44/// and uses the memory as the internal buffer backing the NumPy array.
45///
46/// Please note that some destructive methods like [`resize`][Self::resize] will fail
47/// when used with this kind of array as NumPy cannot reallocate the internal buffer.
48///
49/// - Allocated by NumPy: Constructed via other methods, like [`ToPyArray`] or
50/// [`from_slice`][Self::from_slice] or [`from_array`][Self::from_array].
51///
52/// These methods allocate memory in Python's private heap via NumPy's API.
53///
54/// In both cases, `PyArray` is managed by Python so it can neither be moved from
55/// nor deallocated manually.
56///
57/// # References
58///
59/// Like [`new`][Self::new], all constructor methods of `PyArray` return a shared reference `&PyArray`
60/// instead of an owned value. This design follows [PyO3's ownership concept][pyo3-memory],
61/// i.e. the return value is GIL-bound owning reference into Python's heap.
62///
63/// # Element type and dimensionality
64///
65/// `PyArray` has two type parametes `T` and `D`.
66/// `T` represents the type of its elements, e.g. [`f32`] or [`PyObject`].
67/// `D` represents its dimensionality, e.g [`Ix2`][type@Ix2] or [`IxDyn`][type@IxDyn].
68///
69/// Element types are Rust types which implement the [`Element`] trait.
70/// Dimensions are represented by the [`ndarray::Dimension`] trait.
71///
72/// Typically, `Ix1, Ix2, ...` are used for fixed dimensionality arrays,
73/// and `IxDyn` is used for dynamic dimensionality arrays. Type aliases
74/// for combining `PyArray` with these types are provided, e.g. [`PyArray1`] or [`PyArrayDyn`].
75///
76/// To specify concrete dimension like `3×4×5`, types which implement the [`ndarray::IntoDimension`]
77/// trait are used. Typically, this means arrays like `[3, 4, 5]` or tuples like `(3, 4, 5)`.
78///
79/// # Example
80///
81/// ```
82/// use numpy::{PyArray, PyArrayMethods};
83/// use ndarray::{array, Array};
84/// use pyo3::Python;
85///
86/// Python::with_gil(|py| {
87/// let pyarray = PyArray::arange(py, 0., 4., 1.).reshape([2, 2]).unwrap();
88/// let array = array![[3., 4.], [5., 6.]];
89///
90/// assert_eq!(
91/// array.dot(&pyarray.readonly().as_array()),
92/// array![[8., 15.], [12., 23.]]
93/// );
94/// });
95/// ```
96///
97/// [ndarray]: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html
98/// [pyo3-memory]: https://pyo3.rs/main/memory.html
99#[repr(transparent)]
100pub struct PyArray<T, D>(PyAny, PhantomData<T>, PhantomData<D>);
101
102/// Zero-dimensional array.
103pub type PyArray0<T> = PyArray<T, Ix0>;
104/// One-dimensional array.
105pub type PyArray1<T> = PyArray<T, Ix1>;
106/// Two-dimensional array.
107pub type PyArray2<T> = PyArray<T, Ix2>;
108/// Three-dimensional array.
109pub type PyArray3<T> = PyArray<T, Ix3>;
110/// Four-dimensional array.
111pub type PyArray4<T> = PyArray<T, Ix4>;
112/// Five-dimensional array.
113pub type PyArray5<T> = PyArray<T, Ix5>;
114/// Six-dimensional array.
115pub type PyArray6<T> = PyArray<T, Ix6>;
116/// Dynamic-dimensional array.
117pub type PyArrayDyn<T> = PyArray<T, IxDyn>;
118
119/// Returns a handle to NumPy's multiarray module.
120pub fn get_array_module<'py>(py: Python<'py>) -> PyResult<Bound<'py, PyModule>> {
121 PyModule::import(py, npyffi::array::mod_name(py)?)
122}
123
124impl<T, D> DerefToPyAny for PyArray<T, D> {}
125
126unsafe impl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D> {
127 const NAME: &'static str = "PyArray<T, D>";
128 const MODULE: Option<&'static str> = Some("numpy");
129
130 fn type_object_raw<'py>(py: Python<'py>) -> *mut ffi::PyTypeObject {
131 unsafe { npyffi::PY_ARRAY_API.get_type_object(py, npyffi::NpyTypes::PyArray_Type) }
132 }
133
134 fn is_type_of(ob: &Bound<'_, PyAny>) -> bool {
135 Self::extract::<IgnoreError>(ob).is_ok()
136 }
137}
138
139impl<T: Element, D: Dimension> PyArray<T, D> {
140 fn extract<'a, 'py, E>(ob: &'a Bound<'py, PyAny>) -> Result<&'a Bound<'py, Self>, E>
141 where
142 E: From<DowncastError<'a, 'py>> + From<DimensionalityError> + From<TypeError<'py>>,
143 {
144 // Check if the object is an array.
145 let array = unsafe {
146 if npyffi::PyArray_Check(ob.py(), ob.as_ptr()) == 0 {
147 return Err(DowncastError::new(ob, <Self as PyTypeInfo>::NAME).into());
148 }
149 ob.downcast_unchecked::<Self>()
150 };
151
152 // Check if the dimensionality matches `D`.
153 let src_ndim = array.ndim();
154 if let Some(dst_ndim) = D::NDIM {
155 if src_ndim != dst_ndim {
156 return Err(DimensionalityError::new(src_ndim, dst_ndim).into());
157 }
158 }
159
160 // Check if the element type matches `T`.
161 let src_dtype = array.dtype();
162 let dst_dtype = T::get_dtype(ob.py());
163 if !src_dtype.is_equiv_to(&dst_dtype) {
164 return Err(TypeError::new(src_dtype, dst_dtype).into());
165 }
166
167 Ok(array)
168 }
169
170 /// Creates a new uninitialized NumPy array.
171 ///
172 /// If `is_fortran` is true, then it has Fortran/column-major order,
173 /// otherwise it has C/row-major order.
174 ///
175 /// # Safety
176 ///
177 /// The returned array will always be safe to be dropped as the elements must either
178 /// be trivially copyable (as indicated by `<T as Element>::IS_COPY`) or be pointers
179 /// into Python's heap, which NumPy will automatically zero-initialize.
180 ///
181 /// However, the elements themselves will not be valid and should be initialized manually
182 /// using raw pointers obtained via [`uget_raw`][Self::uget_raw]. Before that, all methods
183 /// which produce references to the elements invoke undefined behaviour. In particular,
184 /// zero-initialized pointers are _not_ valid instances of `PyObject`.
185 ///
186 /// # Example
187 ///
188 /// ```
189 /// use numpy::prelude::*;
190 /// use numpy::PyArray3;
191 /// use pyo3::Python;
192 ///
193 /// Python::with_gil(|py| {
194 /// let arr = unsafe {
195 /// let arr = PyArray3::<i32>::new(py, [4, 5, 6], false);
196 ///
197 /// for i in 0..4 {
198 /// for j in 0..5 {
199 /// for k in 0..6 {
200 /// arr.uget_raw([i, j, k]).write((i * j * k) as i32);
201 /// }
202 /// }
203 /// }
204 ///
205 /// arr
206 /// };
207 ///
208 /// assert_eq!(arr.shape(), &[4, 5, 6]);
209 /// });
210 /// ```
211 pub unsafe fn new<'py, ID>(py: Python<'py>, dims: ID, is_fortran: bool) -> Bound<'py, Self>
212 where
213 ID: IntoDimension<Dim = D>,
214 {
215 let flags = c_int::from(is_fortran);
216 Self::new_uninit(py, dims, ptr::null_mut(), flags)
217 }
218
219 pub(crate) unsafe fn new_uninit<'py, ID>(
220 py: Python<'py>,
221 dims: ID,
222 strides: *const npy_intp,
223 flag: c_int,
224 ) -> Bound<'py, Self>
225 where
226 ID: IntoDimension<Dim = D>,
227 {
228 let mut dims = dims.into_dimension();
229 let ptr = PY_ARRAY_API.PyArray_NewFromDescr(
230 py,
231 PY_ARRAY_API.get_type_object(py, npyffi::NpyTypes::PyArray_Type),
232 T::get_dtype(py).into_dtype_ptr(),
233 dims.ndim_cint(),
234 dims.as_dims_ptr(),
235 strides as *mut npy_intp, // strides
236 ptr::null_mut(), // data
237 flag, // flag
238 ptr::null_mut(), // obj
239 );
240
241 Bound::from_owned_ptr(py, ptr).downcast_into_unchecked()
242 }
243
244 unsafe fn new_with_data<'py, ID>(
245 py: Python<'py>,
246 dims: ID,
247 strides: *const npy_intp,
248 data_ptr: *const T,
249 container: *mut PyAny,
250 ) -> Bound<'py, Self>
251 where
252 ID: IntoDimension<Dim = D>,
253 {
254 let mut dims = dims.into_dimension();
255 let ptr = PY_ARRAY_API.PyArray_NewFromDescr(
256 py,
257 PY_ARRAY_API.get_type_object(py, npyffi::NpyTypes::PyArray_Type),
258 T::get_dtype(py).into_dtype_ptr(),
259 dims.ndim_cint(),
260 dims.as_dims_ptr(),
261 strides as *mut npy_intp, // strides
262 data_ptr as *mut c_void, // data
263 npyffi::NPY_ARRAY_WRITEABLE, // flag
264 ptr::null_mut(), // obj
265 );
266
267 PY_ARRAY_API.PyArray_SetBaseObject(
268 py,
269 ptr as *mut npyffi::PyArrayObject,
270 container as *mut ffi::PyObject,
271 );
272
273 Bound::from_owned_ptr(py, ptr).downcast_into_unchecked()
274 }
275
276 pub(crate) unsafe fn from_raw_parts<'py>(
277 py: Python<'py>,
278 dims: D,
279 strides: *const npy_intp,
280 data_ptr: *const T,
281 container: PySliceContainer,
282 ) -> Bound<'py, Self> {
283 let container = Bound::new(py, container)
284 .expect("Failed to create slice container")
285 .into_ptr();
286
287 Self::new_with_data(py, dims, strides, data_ptr, container.cast())
288 }
289
290 /// Creates a NumPy array backed by `array` and ties its ownership to the Python object `container`.
291 ///
292 /// The resulting NumPy array will be writeable from Python space. If this is undesireable, use
293 /// [PyReadwriteArray::make_nonwriteable].
294 ///
295 /// # Safety
296 ///
297 /// `container` is set as a base object of the returned array which must not be dropped until `container` is dropped.
298 /// Furthermore, `array` must not be reallocated from the time this method is called and until `container` is dropped.
299 ///
300 /// # Example
301 ///
302 /// ```rust
303 /// # use pyo3::prelude::*;
304 /// # use numpy::{ndarray::Array1, PyArray1};
305 /// #
306 /// #[pyclass]
307 /// struct Owner {
308 /// array: Array1<f64>,
309 /// }
310 ///
311 /// #[pymethods]
312 /// impl Owner {
313 /// #[getter]
314 /// fn array<'py>(this: Bound<'py, Self>) -> Bound<'py, PyArray1<f64>> {
315 /// let array = &this.borrow().array;
316 ///
317 /// // SAFETY: The memory backing `array` will stay valid as long as this object is alive
318 /// // as we do not modify `array` in any way which would cause it to be reallocated.
319 /// unsafe { PyArray1::borrow_from_array(array, this.into_any()) }
320 /// }
321 /// }
322 /// ```
323 pub unsafe fn borrow_from_array<'py, S>(
324 array: &ArrayBase<S, D>,
325 container: Bound<'py, PyAny>,
326 ) -> Bound<'py, Self>
327 where
328 S: Data<Elem = T>,
329 {
330 let (strides, dims) = (array.npy_strides(), array.raw_dim());
331 let data_ptr = array.as_ptr();
332
333 let py = container.py();
334
335 Self::new_with_data(
336 py,
337 dims,
338 strides.as_ptr(),
339 data_ptr,
340 container.into_ptr().cast(),
341 )
342 }
343
344 /// Construct a new NumPy array filled with zeros.
345 ///
346 /// If `is_fortran` is true, then it has Fortran/column-major order,
347 /// otherwise it has C/row-major order.
348 ///
349 /// For arrays of Python objects, this will fill the array
350 /// with valid pointers to zero-valued Python integer objects.
351 ///
352 /// See also [`numpy.zeros`][numpy-zeros] and [`PyArray_Zeros`][PyArray_Zeros].
353 ///
354 /// # Example
355 ///
356 /// ```
357 /// use numpy::{PyArray2, PyArrayMethods};
358 /// use pyo3::Python;
359 ///
360 /// Python::with_gil(|py| {
361 /// let pyarray = PyArray2::<usize>::zeros(py, [2, 2], true);
362 ///
363 /// assert_eq!(pyarray.readonly().as_slice().unwrap(), [0; 4]);
364 /// });
365 /// ```
366 ///
367 /// [numpy-zeros]: https://numpy.org/doc/stable/reference/generated/numpy.zeros.html
368 /// [PyArray_Zeros]: https://numpy.org/doc/stable/reference/c-api/array.html#c.PyArray_Zeros
369 pub fn zeros<ID>(py: Python<'_>, dims: ID, is_fortran: bool) -> Bound<'_, Self>
370 where
371 ID: IntoDimension<Dim = D>,
372 {
373 let mut dims = dims.into_dimension();
374 unsafe {
375 let ptr = PY_ARRAY_API.PyArray_Zeros(
376 py,
377 dims.ndim_cint(),
378 dims.as_dims_ptr(),
379 T::get_dtype(py).into_dtype_ptr(),
380 if is_fortran { -1 } else { 0 },
381 );
382 Bound::from_owned_ptr(py, ptr).downcast_into_unchecked()
383 }
384 }
385
386 /// Constructs a NumPy from an [`ndarray::Array`]
387 ///
388 /// This method uses the internal [`Vec`] of the [`ndarray::Array`] as the base object of the NumPy array.
389 ///
390 /// # Example
391 ///
392 /// ```
393 /// use numpy::{PyArray, PyArrayMethods};
394 /// use ndarray::array;
395 /// use pyo3::Python;
396 ///
397 /// Python::with_gil(|py| {
398 /// let pyarray = PyArray::from_owned_array(py, array![[1, 2], [3, 4]]);
399 ///
400 /// assert_eq!(pyarray.readonly().as_array(), array![[1, 2], [3, 4]]);
401 /// });
402 /// ```
403 pub fn from_owned_array(py: Python<'_>, mut arr: Array<T, D>) -> Bound<'_, Self> {
404 let (strides, dims) = (arr.npy_strides(), arr.raw_dim());
405 let data_ptr = arr.as_mut_ptr();
406 unsafe {
407 Self::from_raw_parts(
408 py,
409 dims,
410 strides.as_ptr(),
411 data_ptr,
412 PySliceContainer::from(arr),
413 )
414 }
415 }
416
417 /// Construct a NumPy array from a [`ndarray::ArrayBase`].
418 ///
419 /// This method allocates memory in Python's heap via the NumPy API,
420 /// and then copies all elements of the array there.
421 ///
422 /// # Example
423 ///
424 /// ```
425 /// use numpy::{PyArray, PyArrayMethods};
426 /// use ndarray::array;
427 /// use pyo3::Python;
428 ///
429 /// Python::with_gil(|py| {
430 /// let pyarray = PyArray::from_array(py, &array![[1, 2], [3, 4]]);
431 ///
432 /// assert_eq!(pyarray.readonly().as_array(), array![[1, 2], [3, 4]]);
433 /// });
434 /// ```
435 pub fn from_array<'py, S>(py: Python<'py>, arr: &ArrayBase<S, D>) -> Bound<'py, Self>
436 where
437 S: Data<Elem = T>,
438 {
439 ToPyArray::to_pyarray(arr, py)
440 }
441}
442
443impl<D: Dimension> PyArray<PyObject, D> {
444 /// Construct a NumPy array containing objects stored in a [`ndarray::Array`]
445 ///
446 /// This method uses the internal [`Vec`] of the [`ndarray::Array`] as the base object of the NumPy array.
447 ///
448 /// # Example
449 ///
450 /// ```
451 /// use ndarray::array;
452 /// use pyo3::{pyclass, Py, Python, types::PyAnyMethods};
453 /// use numpy::{PyArray, PyArrayMethods};
454 ///
455 /// #[pyclass]
456 /// # #[allow(dead_code)]
457 /// struct CustomElement {
458 /// foo: i32,
459 /// bar: f64,
460 /// }
461 ///
462 /// Python::with_gil(|py| {
463 /// let array = array![
464 /// Py::new(py, CustomElement {
465 /// foo: 1,
466 /// bar: 2.0,
467 /// }).unwrap(),
468 /// Py::new(py, CustomElement {
469 /// foo: 3,
470 /// bar: 4.0,
471 /// }).unwrap(),
472 /// ];
473 ///
474 /// let pyarray = PyArray::from_owned_object_array(py, array);
475 ///
476 /// assert!(pyarray.readonly().as_array().get(0).unwrap().bind(py).is_instance_of::<CustomElement>());
477 /// });
478 /// ```
479 pub fn from_owned_object_array<T>(py: Python<'_>, mut arr: Array<Py<T>, D>) -> Bound<'_, Self> {
480 let (strides, dims) = (arr.npy_strides(), arr.raw_dim());
481 let data_ptr = arr.as_mut_ptr() as *const PyObject;
482 unsafe {
483 Self::from_raw_parts(
484 py,
485 dims,
486 strides.as_ptr(),
487 data_ptr,
488 PySliceContainer::from(arr),
489 )
490 }
491 }
492}
493
494impl<T: Element> PyArray<T, Ix1> {
495 /// Construct a one-dimensional array from a [mod@slice].
496 ///
497 /// # Example
498 ///
499 /// ```
500 /// use numpy::{PyArray, PyArrayMethods};
501 /// use pyo3::Python;
502 ///
503 /// Python::with_gil(|py| {
504 /// let slice = &[1, 2, 3, 4, 5];
505 /// let pyarray = PyArray::from_slice(py, slice);
506 /// assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]);
507 /// });
508 /// ```
509 pub fn from_slice<'py>(py: Python<'py>, slice: &[T]) -> Bound<'py, Self> {
510 unsafe {
511 let array = PyArray::new(py, [slice.len()], false);
512 let mut data_ptr = array.data();
513 clone_elements(py, slice, &mut data_ptr);
514 array
515 }
516 }
517
518 /// Construct a one-dimensional array from a [`Vec<T>`][Vec].
519 ///
520 /// # Example
521 ///
522 /// ```
523 /// use numpy::{PyArray, PyArrayMethods};
524 /// use pyo3::Python;
525 ///
526 /// Python::with_gil(|py| {
527 /// let vec = vec![1, 2, 3, 4, 5];
528 /// let pyarray = PyArray::from_vec(py, vec);
529 /// assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]);
530 /// });
531 /// ```
532 #[inline(always)]
533 pub fn from_vec<'py>(py: Python<'py>, vec: Vec<T>) -> Bound<'py, Self> {
534 vec.into_pyarray(py)
535 }
536
537 /// Construct a one-dimensional array from an [`Iterator`].
538 ///
539 /// If no reliable [`size_hint`][Iterator::size_hint] is available,
540 /// this method can allocate memory multiple times, which can hurt performance.
541 ///
542 /// # Example
543 ///
544 /// ```
545 /// use numpy::{PyArray, PyArrayMethods};
546 /// use pyo3::Python;
547 ///
548 /// Python::with_gil(|py| {
549 /// let pyarray = PyArray::from_iter(py, "abcde".chars().map(u32::from));
550 /// assert_eq!(pyarray.readonly().as_slice().unwrap(), &[97, 98, 99, 100, 101]);
551 /// });
552 /// ```
553 pub fn from_iter<I>(py: Python<'_>, iter: I) -> Bound<'_, Self>
554 where
555 I: IntoIterator<Item = T>,
556 {
557 let data = iter.into_iter().collect::<Vec<_>>();
558 data.into_pyarray(py)
559 }
560}
561
562impl<T: Element> PyArray<T, Ix2> {
563 /// Construct a two-dimension array from a [`Vec<Vec<T>>`][Vec].
564 ///
565 /// This function checks all dimensions of the inner vectors and returns
566 /// an error if they are not all equal.
567 ///
568 /// # Example
569 ///
570 /// ```
571 /// use numpy::{PyArray, PyArrayMethods};
572 /// use pyo3::Python;
573 /// use ndarray::array;
574 ///
575 /// Python::with_gil(|py| {
576 /// let vec2 = vec![vec![11, 12], vec![21, 22]];
577 /// let pyarray = PyArray::from_vec2(py, &vec2).unwrap();
578 /// assert_eq!(pyarray.readonly().as_array(), array![[11, 12], [21, 22]]);
579 ///
580 /// let ragged_vec2 = vec![vec![11, 12], vec![21]];
581 /// assert!(PyArray::from_vec2(py, &ragged_vec2).is_err());
582 /// });
583 /// ```
584 pub fn from_vec2<'py>(py: Python<'py>, v: &[Vec<T>]) -> Result<Bound<'py, Self>, FromVecError> {
585 let len2 = v.first().map_or(0, |v| v.len());
586 let dims = [v.len(), len2];
587 // SAFETY: The result of `Self::new` is always safe to drop.
588 unsafe {
589 let array = Self::new(py, dims, false);
590 let mut data_ptr = array.data();
591 for v in v {
592 if v.len() != len2 {
593 cold();
594 return Err(FromVecError::new(v.len(), len2));
595 }
596 clone_elements(py, v, &mut data_ptr);
597 }
598 Ok(array)
599 }
600 }
601}
602
603impl<T: Element> PyArray<T, Ix3> {
604 /// Construct a three-dimensional array from a [`Vec<Vec<Vec<T>>>`][Vec].
605 ///
606 /// This function checks all dimensions of the inner vectors and returns
607 /// an error if they are not all equal.
608 ///
609 /// # Example
610 ///
611 /// ```
612 /// use numpy::{PyArray, PyArrayMethods};
613 /// use pyo3::Python;
614 /// use ndarray::array;
615 ///
616 /// Python::with_gil(|py| {
617 /// let vec3 = vec![
618 /// vec![vec![111, 112], vec![121, 122]],
619 /// vec![vec![211, 212], vec![221, 222]],
620 /// ];
621 /// let pyarray = PyArray::from_vec3(py, &vec3).unwrap();
622 /// assert_eq!(
623 /// pyarray.readonly().as_array(),
624 /// array![[[111, 112], [121, 122]], [[211, 212], [221, 222]]]
625 /// );
626 ///
627 /// let ragged_vec3 = vec![
628 /// vec![vec![111, 112], vec![121, 122]],
629 /// vec![vec![211], vec![221, 222]],
630 /// ];
631 /// assert!(PyArray::from_vec3(py, &ragged_vec3).is_err());
632 /// });
633 /// ```
634 pub fn from_vec3<'py>(
635 py: Python<'py>,
636 v: &[Vec<Vec<T>>],
637 ) -> Result<Bound<'py, Self>, FromVecError> {
638 let len2 = v.first().map_or(0, |v| v.len());
639 let len3 = v.first().map_or(0, |v| v.first().map_or(0, |v| v.len()));
640 let dims = [v.len(), len2, len3];
641 // SAFETY: The result of `Self::new` is always safe to drop.
642 unsafe {
643 let array = Self::new(py, dims, false);
644 let mut data_ptr = array.data();
645 for v in v {
646 if v.len() != len2 {
647 cold();
648 return Err(FromVecError::new(v.len(), len2));
649 }
650 for v in v {
651 if v.len() != len3 {
652 cold();
653 return Err(FromVecError::new(v.len(), len3));
654 }
655 clone_elements(py, v, &mut data_ptr);
656 }
657 }
658 Ok(array)
659 }
660 }
661}
662
663impl<T: Element + AsPrimitive<f64>> PyArray<T, Ix1> {
664 /// Return evenly spaced values within a given interval.
665 ///
666 /// See [numpy.arange][numpy.arange] for the Python API and [PyArray_Arange][PyArray_Arange] for the C API.
667 ///
668 /// # Example
669 ///
670 /// ```
671 /// use numpy::{PyArray, PyArrayMethods};
672 /// use pyo3::Python;
673 ///
674 /// Python::with_gil(|py| {
675 /// let pyarray = PyArray::arange(py, 2.0, 4.0, 0.5);
676 /// assert_eq!(pyarray.readonly().as_slice().unwrap(), &[2.0, 2.5, 3.0, 3.5]);
677 ///
678 /// let pyarray = PyArray::arange(py, -2, 4, 3);
679 /// assert_eq!(pyarray.readonly().as_slice().unwrap(), &[-2, 1]);
680 /// });
681 /// ```
682 ///
683 /// [numpy.arange]: https://numpy.org/doc/stable/reference/generated/numpy.arange.html
684 /// [PyArray_Arange]: https://numpy.org/doc/stable/reference/c-api/array.html#c.PyArray_Arange
685 pub fn arange<'py>(py: Python<'py>, start: T, stop: T, step: T) -> Bound<'py, Self> {
686 unsafe {
687 let ptr = PY_ARRAY_API.PyArray_Arange(
688 py,
689 start.as_(),
690 stop.as_(),
691 step.as_(),
692 T::get_dtype(py).num(),
693 );
694 Bound::from_owned_ptr(py, ptr).downcast_into_unchecked()
695 }
696 }
697}
698
699unsafe fn clone_elements<T: Element>(py: Python<'_>, elems: &[T], data_ptr: &mut *mut T) {
700 if T::IS_COPY {
701 ptr::copy_nonoverlapping(elems.as_ptr(), *data_ptr, elems.len());
702 *data_ptr = data_ptr.add(elems.len());
703 } else {
704 for elem in elems {
705 data_ptr.write(elem.clone_ref(py));
706 *data_ptr = data_ptr.add(1);
707 }
708 }
709}
710
711/// Implementation of functionality for [`PyArray<T, D>`].
712#[doc(alias = "PyArray")]
713pub trait PyArrayMethods<'py, T, D>: PyUntypedArrayMethods<'py> {
714 /// Access an untyped representation of this array.
715 fn as_untyped(&self) -> &Bound<'py, PyUntypedArray>;
716
717 /// Returns a pointer to the first element of the array.
718 fn data(&self) -> *mut T;
719
720 /// Same as [`shape`][PyUntypedArray::shape], but returns `D` instead of `&[usize]`.
721 #[inline(always)]
722 fn dims(&self) -> D
723 where
724 D: Dimension,
725 {
726 D::from_dimension(&Dim(self.shape())).expect(DIMENSIONALITY_MISMATCH_ERR)
727 }
728
729 /// Returns an immutable view of the internal data as a slice.
730 ///
731 /// # Safety
732 ///
733 /// Calling this method is undefined behaviour if the underlying array
734 /// is aliased mutably by other instances of `PyArray`
735 /// or concurrently modified by Python or other native code.
736 ///
737 /// Please consider the safe alternative [`PyReadonlyArray::as_slice`].
738 unsafe fn as_slice(&self) -> Result<&[T], NotContiguousError>
739 where
740 T: Element,
741 D: Dimension,
742 {
743 if self.is_contiguous() {
744 Ok(slice::from_raw_parts(self.data(), self.len()))
745 } else {
746 Err(NotContiguousError)
747 }
748 }
749
750 /// Returns a mutable view of the internal data as a slice.
751 ///
752 /// # Safety
753 ///
754 /// Calling this method is undefined behaviour if the underlying array
755 /// is aliased immutably or mutably by other instances of [`PyArray`]
756 /// or concurrently modified by Python or other native code.
757 ///
758 /// Please consider the safe alternative [`PyReadwriteArray::as_slice_mut`].
759 unsafe fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError>
760 where
761 T: Element,
762 D: Dimension,
763 {
764 if self.is_contiguous() {
765 Ok(slice::from_raw_parts_mut(self.data(), self.len()))
766 } else {
767 Err(NotContiguousError)
768 }
769 }
770
771 /// Get a reference of the specified element if the given index is valid.
772 ///
773 /// # Safety
774 ///
775 /// Calling this method is undefined behaviour if the underlying array
776 /// is aliased mutably by other instances of `PyArray`
777 /// or concurrently modified by Python or other native code.
778 ///
779 /// Consider using safe alternatives like [`PyReadonlyArray::get`].
780 ///
781 /// # Example
782 ///
783 /// ```
784 /// use numpy::{PyArray, PyArrayMethods};
785 /// use pyo3::Python;
786 ///
787 /// Python::with_gil(|py| {
788 /// let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
789 ///
790 /// assert_eq!(unsafe { *pyarray.get([1, 0, 3]).unwrap() }, 11);
791 /// });
792 /// ```
793 unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>
794 where
795 T: Element,
796 D: Dimension;
797
798 /// Same as [`get`][Self::get], but returns `Option<&mut T>`.
799 ///
800 /// # Safety
801 ///
802 /// Calling this method is undefined behaviour if the underlying array
803 /// is aliased immutably or mutably by other instances of [`PyArray`]
804 /// or concurrently modified by Python or other native code.
805 ///
806 /// Consider using safe alternatives like [`PyReadwriteArray::get_mut`].
807 ///
808 /// # Example
809 ///
810 /// ```
811 /// use numpy::{PyArray, PyArrayMethods};
812 /// use pyo3::Python;
813 ///
814 /// Python::with_gil(|py| {
815 /// let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
816 ///
817 /// unsafe {
818 /// *pyarray.get_mut([1, 0, 3]).unwrap() = 42;
819 /// }
820 ///
821 /// assert_eq!(unsafe { *pyarray.get([1, 0, 3]).unwrap() }, 42);
822 /// });
823 /// ```
824 unsafe fn get_mut(&self, index: impl NpyIndex<Dim = D>) -> Option<&mut T>
825 where
826 T: Element,
827 D: Dimension;
828
829 /// Get an immutable reference of the specified element,
830 /// without checking the given index.
831 ///
832 /// See [`NpyIndex`] for what types can be used as the index.
833 ///
834 /// # Safety
835 ///
836 /// Passing an invalid index is undefined behavior.
837 /// The element must also have been initialized and
838 /// all other references to it is must also be shared.
839 ///
840 /// See [`PyReadonlyArray::get`] for a safe alternative.
841 ///
842 /// # Example
843 ///
844 /// ```
845 /// use numpy::{PyArray, PyArrayMethods};
846 /// use pyo3::Python;
847 ///
848 /// Python::with_gil(|py| {
849 /// let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
850 ///
851 /// assert_eq!(unsafe { *pyarray.uget([1, 0, 3]) }, 11);
852 /// });
853 /// ```
854 #[inline(always)]
855 unsafe fn uget<Idx>(&self, index: Idx) -> &T
856 where
857 T: Element,
858 D: Dimension,
859 Idx: NpyIndex<Dim = D>,
860 {
861 &*self.uget_raw(index)
862 }
863
864 /// Same as [`uget`](Self::uget), but returns `&mut T`.
865 ///
866 /// # Safety
867 ///
868 /// Passing an invalid index is undefined behavior.
869 /// The element must also have been initialized and
870 /// other references to it must not exist.
871 ///
872 /// See [`PyReadwriteArray::get_mut`] for a safe alternative.
873 #[inline(always)]
874 #[allow(clippy::mut_from_ref)]
875 unsafe fn uget_mut<Idx>(&self, index: Idx) -> &mut T
876 where
877 T: Element,
878 D: Dimension,
879 Idx: NpyIndex<Dim = D>,
880 {
881 &mut *self.uget_raw(index)
882 }
883
884 /// Same as [`uget`][Self::uget], but returns `*mut T`.
885 ///
886 /// # Safety
887 ///
888 /// Passing an invalid index is undefined behavior.
889 #[inline(always)]
890 unsafe fn uget_raw<Idx>(&self, index: Idx) -> *mut T
891 where
892 T: Element,
893 D: Dimension,
894 Idx: NpyIndex<Dim = D>,
895 {
896 let offset = index.get_unchecked::<T>(self.strides());
897 self.data().offset(offset) as *mut _
898 }
899
900 /// Get a copy of the specified element in the array.
901 ///
902 /// See [`NpyIndex`] for what types can be used as the index.
903 ///
904 /// # Example
905 /// ```
906 /// use numpy::{PyArray, PyArrayMethods};
907 /// use pyo3::Python;
908 ///
909 /// Python::with_gil(|py| {
910 /// let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
911 ///
912 /// assert_eq!(pyarray.get_owned([1, 0, 3]), Some(11));
913 /// });
914 /// ```
915 fn get_owned<Idx>(&self, index: Idx) -> Option<T>
916 where
917 T: Element,
918 D: Dimension,
919 Idx: NpyIndex<Dim = D>;
920
921 /// Turn an array with fixed dimensionality into one with dynamic dimensionality.
922 fn to_dyn(&self) -> &Bound<'py, PyArray<T, IxDyn>>
923 where
924 T: Element,
925 D: Dimension;
926
927 /// Returns a copy of the internal data of the array as a [`Vec`].
928 ///
929 /// Fails if the internal array is not contiguous. See also [`as_slice`][Self::as_slice].
930 ///
931 /// # Example
932 ///
933 /// ```
934 /// use numpy::{PyArray2, PyArrayMethods};
935 /// use pyo3::{Python, types::PyAnyMethods, ffi::c_str};
936 ///
937 /// # fn main() -> pyo3::PyResult<()> {
938 /// Python::with_gil(|py| {
939 /// let pyarray= py
940 /// .eval(c_str!("__import__('numpy').array([[0, 1], [2, 3]], dtype='int64')"), None, None)?
941 /// .downcast_into::<PyArray2<i64>>()?;
942 ///
943 /// assert_eq!(pyarray.to_vec()?, vec![0, 1, 2, 3]);
944 /// # Ok(())
945 /// })
946 /// # }
947 /// ```
948 fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
949 where
950 T: Element,
951 D: Dimension;
952
953 /// Get an immutable borrow of the NumPy array
954 fn try_readonly(&self) -> Result<PyReadonlyArray<'py, T, D>, BorrowError>
955 where
956 T: Element,
957 D: Dimension;
958
959 /// Get an immutable borrow of the NumPy array
960 ///
961 /// # Panics
962 ///
963 /// Panics if the allocation backing the array is currently mutably borrowed.
964 ///
965 /// For a non-panicking variant, use [`try_readonly`][Self::try_readonly].
966 fn readonly(&self) -> PyReadonlyArray<'py, T, D>
967 where
968 T: Element,
969 D: Dimension,
970 {
971 self.try_readonly().unwrap()
972 }
973
974 /// Get a mutable borrow of the NumPy array
975 fn try_readwrite(&self) -> Result<PyReadwriteArray<'py, T, D>, BorrowError>
976 where
977 T: Element,
978 D: Dimension;
979
980 /// Get a mutable borrow of the NumPy array
981 ///
982 /// # Panics
983 ///
984 /// Panics if the allocation backing the array is currently borrowed or
985 /// if the array is [flagged as][flags] not writeable.
986 ///
987 /// For a non-panicking variant, use [`try_readwrite`][Self::try_readwrite].
988 ///
989 /// [flags]: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flags.html
990 fn readwrite(&self) -> PyReadwriteArray<'py, T, D>
991 where
992 T: Element,
993 D: Dimension,
994 {
995 self.try_readwrite().unwrap()
996 }
997
998 /// Returns an [`ArrayView`] of the internal array.
999 ///
1000 /// See also [`PyReadonlyArray::as_array`].
1001 ///
1002 /// # Safety
1003 ///
1004 /// Calling this method invalidates all exclusive references to the internal data, e.g. `&mut [T]` or `ArrayViewMut`.
1005 unsafe fn as_array(&self) -> ArrayView<'_, T, D>
1006 where
1007 T: Element,
1008 D: Dimension;
1009
1010 /// Returns an [`ArrayViewMut`] of the internal array.
1011 ///
1012 /// See also [`PyReadwriteArray::as_array_mut`].
1013 ///
1014 /// # Safety
1015 ///
1016 /// Calling this method invalidates all other references to the internal data, e.g. `ArrayView` or `ArrayViewMut`.
1017 unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>
1018 where
1019 T: Element,
1020 D: Dimension;
1021
1022 /// Returns the internal array as [`RawArrayView`] enabling element access via raw pointers
1023 fn as_raw_array(&self) -> RawArrayView<T, D>
1024 where
1025 T: Element,
1026 D: Dimension;
1027
1028 /// Returns the internal array as [`RawArrayViewMut`] enabling element access via raw pointers
1029 fn as_raw_array_mut(&self) -> RawArrayViewMut<T, D>
1030 where
1031 T: Element,
1032 D: Dimension;
1033
1034 /// Get a copy of the array as an [`ndarray::Array`].
1035 ///
1036 /// # Example
1037 ///
1038 /// ```
1039 /// use numpy::{PyArray, PyArrayMethods};
1040 /// use ndarray::array;
1041 /// use pyo3::Python;
1042 ///
1043 /// Python::with_gil(|py| {
1044 /// let pyarray = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap();
1045 ///
1046 /// assert_eq!(
1047 /// pyarray.to_owned_array(),
1048 /// array![[0, 1], [2, 3]]
1049 /// )
1050 /// });
1051 /// ```
1052 fn to_owned_array(&self) -> Array<T, D>
1053 where
1054 T: Element,
1055 D: Dimension;
1056
1057 /// Copies `self` into `other`, performing a data type conversion if necessary.
1058 ///
1059 /// See also [`PyArray_CopyInto`][PyArray_CopyInto].
1060 ///
1061 /// # Example
1062 ///
1063 /// ```
1064 /// use numpy::{PyArray, PyArrayMethods};
1065 /// use pyo3::Python;
1066 ///
1067 /// Python::with_gil(|py| {
1068 /// let pyarray_f = PyArray::arange(py, 2.0, 5.0, 1.0);
1069 /// let pyarray_i = unsafe { PyArray::<i64, _>::new(py, [3], false) };
1070 ///
1071 /// assert!(pyarray_f.copy_to(&pyarray_i).is_ok());
1072 ///
1073 /// assert_eq!(pyarray_i.readonly().as_slice().unwrap(), &[2, 3, 4]);
1074 /// });
1075 /// ```
1076 ///
1077 /// [PyArray_CopyInto]: https://numpy.org/doc/stable/reference/c-api/array.html#c.PyArray_CopyInto
1078 fn copy_to<U: Element>(&self, other: &Bound<'py, PyArray<U, D>>) -> PyResult<()>
1079 where
1080 T: Element;
1081
1082 /// Cast the `PyArray<T>` to `PyArray<U>`, by allocating a new array.
1083 ///
1084 /// See also [`PyArray_CastToType`][PyArray_CastToType].
1085 ///
1086 /// # Example
1087 ///
1088 /// ```
1089 /// use numpy::{PyArray, PyArrayMethods};
1090 /// use pyo3::Python;
1091 ///
1092 /// Python::with_gil(|py| {
1093 /// let pyarray_f = PyArray::arange(py, 2.0, 5.0, 1.0);
1094 ///
1095 /// let pyarray_i = pyarray_f.cast::<i32>(false).unwrap();
1096 ///
1097 /// assert_eq!(pyarray_i.readonly().as_slice().unwrap(), &[2, 3, 4]);
1098 /// });
1099 /// ```
1100 ///
1101 /// [PyArray_CastToType]: https://numpy.org/doc/stable/reference/c-api/array.html#c.PyArray_CastToType
1102 fn cast<U: Element>(&self, is_fortran: bool) -> PyResult<Bound<'py, PyArray<U, D>>>
1103 where
1104 T: Element;
1105
1106 /// A view of `self` with a different order of axes determined by `axes`.
1107 ///
1108 /// If `axes` is `None`, the order of axes is reversed which corresponds to the standard matrix transpose.
1109 ///
1110 /// See also [`numpy.transpose`][numpy-transpose] and [`PyArray_Transpose`][PyArray_Transpose].
1111 ///
1112 /// # Example
1113 ///
1114 /// ```
1115 /// use numpy::prelude::*;
1116 /// use numpy::PyArray;
1117 /// use pyo3::Python;
1118 /// use ndarray::array;
1119 ///
1120 /// Python::with_gil(|py| {
1121 /// let array = array![[0, 1, 2], [3, 4, 5]].into_pyarray(py);
1122 ///
1123 /// let array = array.permute(Some([1, 0])).unwrap();
1124 ///
1125 /// assert_eq!(array.readonly().as_array(), array![[0, 3], [1, 4], [2, 5]]);
1126 /// });
1127 /// ```
1128 ///
1129 /// [numpy-transpose]: https://numpy.org/doc/stable/reference/generated/numpy.transpose.html
1130 /// [PyArray_Transpose]: https://numpy.org/doc/stable/reference/c-api/array.html#c.PyArray_Transpose
1131 fn permute<ID: IntoDimension>(&self, axes: Option<ID>) -> PyResult<Bound<'py, PyArray<T, D>>>
1132 where
1133 T: Element;
1134
1135 /// Special case of [`permute`][Self::permute] which reverses the order the axes.
1136 fn transpose(&self) -> PyResult<Bound<'py, PyArray<T, D>>>
1137 where
1138 T: Element,
1139 {
1140 self.permute::<()>(None)
1141 }
1142
1143 /// Construct a new array which has same values as `self`,
1144 /// but has different dimensions specified by `shape`
1145 /// and a possibly different memory order specified by `order`.
1146 ///
1147 /// See also [`numpy.reshape`][numpy-reshape] and [`PyArray_Newshape`][PyArray_Newshape].
1148 ///
1149 /// # Example
1150 ///
1151 /// ```
1152 /// use numpy::prelude::*;
1153 /// use numpy::{npyffi::NPY_ORDER, PyArray};
1154 /// use pyo3::Python;
1155 /// use ndarray::array;
1156 ///
1157 /// Python::with_gil(|py| {
1158 /// let array =
1159 /// PyArray::from_iter(py, 0..9).reshape_with_order([3, 3], NPY_ORDER::NPY_FORTRANORDER).unwrap();
1160 ///
1161 /// assert_eq!(array.readonly().as_array(), array![[0, 3, 6], [1, 4, 7], [2, 5, 8]]);
1162 /// assert!(array.is_fortran_contiguous());
1163 ///
1164 /// assert!(array.reshape([5]).is_err());
1165 /// });
1166 /// ```
1167 ///
1168 /// [numpy-reshape]: https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
1169 /// [PyArray_Newshape]: https://numpy.org/doc/stable/reference/c-api/array.html#c.PyArray_Newshape
1170 fn reshape_with_order<ID: IntoDimension>(
1171 &self,
1172 shape: ID,
1173 order: NPY_ORDER,
1174 ) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>
1175 where
1176 T: Element;
1177
1178 /// Special case of [`reshape_with_order`][Self::reshape_with_order] which keeps the memory order the same.
1179 #[inline(always)]
1180 fn reshape<ID: IntoDimension>(&self, shape: ID) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>
1181 where
1182 T: Element,
1183 {
1184 self.reshape_with_order(shape, NPY_ORDER::NPY_ANYORDER)
1185 }
1186
1187 /// Extends or truncates the dimensions of an array.
1188 ///
1189 /// This method works only on [contiguous][PyUntypedArrayMethods::is_contiguous] arrays.
1190 /// Missing elements will be initialized as if calling [`zeros`][PyArray::zeros].
1191 ///
1192 /// See also [`ndarray.resize`][ndarray-resize] and [`PyArray_Resize`][PyArray_Resize].
1193 ///
1194 /// # Safety
1195 ///
1196 /// There should be no outstanding references (shared or exclusive) into the array
1197 /// as this method might re-allocate it and thereby invalidate all pointers into it.
1198 ///
1199 /// # Example
1200 ///
1201 /// ```
1202 /// use numpy::prelude::*;
1203 /// use numpy::PyArray;
1204 /// use pyo3::Python;
1205 ///
1206 /// Python::with_gil(|py| {
1207 /// let pyarray = PyArray::<f64, _>::zeros(py, (10, 10), false);
1208 /// assert_eq!(pyarray.shape(), [10, 10]);
1209 ///
1210 /// unsafe {
1211 /// pyarray.resize((100, 100)).unwrap();
1212 /// }
1213 /// assert_eq!(pyarray.shape(), [100, 100]);
1214 /// });
1215 /// ```
1216 ///
1217 /// [ndarray-resize]: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.resize.html
1218 /// [PyArray_Resize]: https://numpy.org/doc/stable/reference/c-api/array.html#c.PyArray_Resize
1219 unsafe fn resize<ID: IntoDimension>(&self, newshape: ID) -> PyResult<()>
1220 where
1221 T: Element;
1222
1223 /// Try to convert this array into a [`nalgebra::MatrixView`] using the given shape and strides.
1224 ///
1225 /// # Safety
1226 ///
1227 /// Calling this method invalidates all exclusive references to the internal data, e.g. `ArrayViewMut` or `MatrixSliceMut`.
1228 #[doc(alias = "nalgebra")]
1229 #[cfg(feature = "nalgebra")]
1230 unsafe fn try_as_matrix<R, C, RStride, CStride>(
1231 &self,
1232 ) -> Option<nalgebra::MatrixView<'_, T, R, C, RStride, CStride>>
1233 where
1234 T: nalgebra::Scalar + Element,
1235 D: Dimension,
1236 R: nalgebra::Dim,
1237 C: nalgebra::Dim,
1238 RStride: nalgebra::Dim,
1239 CStride: nalgebra::Dim;
1240
1241 /// Try to convert this array into a [`nalgebra::MatrixViewMut`] using the given shape and strides.
1242 ///
1243 /// # Safety
1244 ///
1245 /// Calling this method invalidates all other references to the internal data, e.g. `ArrayView`, `MatrixSlice`, `ArrayViewMut` or `MatrixSliceMut`.
1246 #[doc(alias = "nalgebra")]
1247 #[cfg(feature = "nalgebra")]
1248 unsafe fn try_as_matrix_mut<R, C, RStride, CStride>(
1249 &self,
1250 ) -> Option<nalgebra::MatrixViewMut<'_, T, R, C, RStride, CStride>>
1251 where
1252 T: nalgebra::Scalar + Element,
1253 D: Dimension,
1254 R: nalgebra::Dim,
1255 C: nalgebra::Dim,
1256 RStride: nalgebra::Dim,
1257 CStride: nalgebra::Dim;
1258}
1259
1260/// Implementation of functionality for [`PyArray0<T>`].
1261#[doc(alias = "PyArray", alias = "PyArray0")]
1262pub trait PyArray0Methods<'py, T>: PyArrayMethods<'py, T, Ix0> {
1263 /// Get the single element of a zero-dimensional array.
1264 ///
1265 /// See [`inner`][crate::inner] for an example.
1266 fn item(&self) -> T
1267 where
1268 T: Element + Copy,
1269 {
1270 unsafe { *self.data() }
1271 }
1272}
1273
1274#[inline(always)]
1275fn get_raw<T, D, Idx>(slf: &Bound<'_, PyArray<T, D>>, index: Idx) -> Option<*mut T>
1276where
1277 T: Element,
1278 D: Dimension,
1279 Idx: NpyIndex<Dim = D>,
1280{
1281 let offset = index.get_checked::<T>(slf.shape(), slf.strides())?;
1282 Some(unsafe { slf.data().offset(offset) })
1283}
1284
1285fn as_view<T, D, S, F>(slf: &Bound<'_, PyArray<T, D>>, from_shape_ptr: F) -> ArrayBase<S, D>
1286where
1287 T: Element,
1288 D: Dimension,
1289 S: RawData,
1290 F: FnOnce(StrideShape<D>, *mut T) -> ArrayBase<S, D>,
1291{
1292 fn inner<D: Dimension>(
1293 shape: &[usize],
1294 strides: &[isize],
1295 itemsize: usize,
1296 mut data_ptr: *mut u8,
1297 ) -> (StrideShape<D>, u32, *mut u8) {
1298 let shape = D::from_dimension(&Dim(shape)).expect(DIMENSIONALITY_MISMATCH_ERR);
1299
1300 assert!(strides.len() <= 32, "{}", MAX_DIMENSIONALITY_ERR);
1301
1302 let mut new_strides = D::zeros(strides.len());
1303 let mut inverted_axes = 0_u32;
1304
1305 for i in 0..strides.len() {
1306 // FIXME(kngwyu): Replace this hacky negative strides support with
1307 // a proper constructor, when it's implemented.
1308 // See https://github.com/rust-ndarray/ndarray/issues/842 for more.
1309 if strides[i] >= 0 {
1310 new_strides[i] = strides[i] as usize / itemsize;
1311 } else {
1312 // Move the pointer to the start position.
1313 data_ptr = unsafe { data_ptr.offset(strides[i] * (shape[i] as isize - 1)) };
1314
1315 new_strides[i] = (-strides[i]) as usize / itemsize;
1316 inverted_axes |= 1 << i;
1317 }
1318 }
1319
1320 (shape.strides(new_strides), inverted_axes, data_ptr)
1321 }
1322
1323 let (shape, mut inverted_axes, data_ptr) = inner(
1324 slf.shape(),
1325 slf.strides(),
1326 mem::size_of::<T>(),
1327 slf.data() as _,
1328 );
1329
1330 let mut array = from_shape_ptr(shape, data_ptr as _);
1331
1332 while inverted_axes != 0 {
1333 let axis = inverted_axes.trailing_zeros() as usize;
1334 inverted_axes &= !(1 << axis);
1335
1336 array.invert_axis(Axis(axis));
1337 }
1338
1339 array
1340}
1341
1342#[cfg(feature = "nalgebra")]
1343fn try_as_matrix_shape_strides<N, D, R, C, RStride, CStride>(
1344 slf: &Bound<'_, PyArray<N, D>>,
1345) -> Option<((R, C), (RStride, CStride))>
1346where
1347 N: nalgebra::Scalar + Element,
1348 D: Dimension,
1349 R: nalgebra::Dim,
1350 C: nalgebra::Dim,
1351 RStride: nalgebra::Dim,
1352 CStride: nalgebra::Dim,
1353{
1354 let ndim = slf.ndim();
1355 let shape = slf.shape();
1356 let strides = slf.strides();
1357
1358 if ndim != 1 && ndim != 2 {
1359 return None;
1360 }
1361
1362 if strides.iter().any(|strides| *strides < 0) {
1363 return None;
1364 }
1365
1366 let rows = shape[0];
1367 let cols = *shape.get(1).unwrap_or(&1);
1368
1369 if R::try_to_usize().map(|expected| rows == expected) == Some(false) {
1370 return None;
1371 }
1372
1373 if C::try_to_usize().map(|expected| cols == expected) == Some(false) {
1374 return None;
1375 }
1376
1377 let row_stride = strides[0] as usize / mem::size_of::<N>();
1378 let col_stride = strides
1379 .get(1)
1380 .map_or(rows, |stride| *stride as usize / mem::size_of::<N>());
1381
1382 if RStride::try_to_usize().map(|expected| row_stride == expected) == Some(false) {
1383 return None;
1384 }
1385
1386 if CStride::try_to_usize().map(|expected| col_stride == expected) == Some(false) {
1387 return None;
1388 }
1389
1390 let shape = (R::from_usize(rows), C::from_usize(cols));
1391
1392 let strides = (
1393 RStride::from_usize(row_stride),
1394 CStride::from_usize(col_stride),
1395 );
1396
1397 Some((shape, strides))
1398}
1399
1400impl<'py, T, D> PyArrayMethods<'py, T, D> for Bound<'py, PyArray<T, D>> {
1401 #[inline(always)]
1402 fn as_untyped(&self) -> &Bound<'py, PyUntypedArray> {
1403 unsafe { self.downcast_unchecked() }
1404 }
1405
1406 #[inline(always)]
1407 fn data(&self) -> *mut T {
1408 unsafe { (*self.as_array_ptr()).data.cast() }
1409 }
1410
1411 #[inline(always)]
1412 unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>
1413 where
1414 T: Element,
1415 D: Dimension,
1416 {
1417 let ptr = get_raw(self, index)?;
1418 Some(&*ptr)
1419 }
1420
1421 #[inline(always)]
1422 unsafe fn get_mut(&self, index: impl NpyIndex<Dim = D>) -> Option<&mut T>
1423 where
1424 T: Element,
1425 D: Dimension,
1426 {
1427 let ptr = get_raw(self, index)?;
1428 Some(&mut *ptr)
1429 }
1430
1431 fn get_owned<Idx>(&self, index: Idx) -> Option<T>
1432 where
1433 T: Element,
1434 D: Dimension,
1435 Idx: NpyIndex<Dim = D>,
1436 {
1437 let element = unsafe { self.get(index) };
1438 element.map(|elem| elem.clone_ref(self.py()))
1439 }
1440
1441 fn to_dyn(&self) -> &Bound<'py, PyArray<T, IxDyn>> {
1442 unsafe { self.downcast_unchecked() }
1443 }
1444
1445 fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
1446 where
1447 T: Element,
1448 D: Dimension,
1449 {
1450 let slice = unsafe { self.as_slice() };
1451 slice.map(|slc| T::vec_from_slice(self.py(), slc))
1452 }
1453
1454 fn try_readonly(&self) -> Result<PyReadonlyArray<'py, T, D>, BorrowError>
1455 where
1456 T: Element,
1457 D: Dimension,
1458 {
1459 PyReadonlyArray::try_new(self.clone())
1460 }
1461
1462 fn try_readwrite(&self) -> Result<PyReadwriteArray<'py, T, D>, BorrowError>
1463 where
1464 T: Element,
1465 D: Dimension,
1466 {
1467 PyReadwriteArray::try_new(self.clone())
1468 }
1469
1470 unsafe fn as_array(&self) -> ArrayView<'_, T, D>
1471 where
1472 T: Element,
1473 D: Dimension,
1474 {
1475 as_view(self, |shape, ptr| ArrayView::from_shape_ptr(shape, ptr))
1476 }
1477
1478 unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>
1479 where
1480 T: Element,
1481 D: Dimension,
1482 {
1483 as_view(self, |shape, ptr| ArrayViewMut::from_shape_ptr(shape, ptr))
1484 }
1485
1486 fn as_raw_array(&self) -> RawArrayView<T, D>
1487 where
1488 T: Element,
1489 D: Dimension,
1490 {
1491 as_view(self, |shape, ptr| unsafe {
1492 RawArrayView::from_shape_ptr(shape, ptr)
1493 })
1494 }
1495
1496 fn as_raw_array_mut(&self) -> RawArrayViewMut<T, D>
1497 where
1498 T: Element,
1499 D: Dimension,
1500 {
1501 as_view(self, |shape, ptr| unsafe {
1502 RawArrayViewMut::from_shape_ptr(shape, ptr)
1503 })
1504 }
1505
1506 fn to_owned_array(&self) -> Array<T, D>
1507 where
1508 T: Element,
1509 D: Dimension,
1510 {
1511 let view = unsafe { self.as_array() };
1512 T::array_from_view(self.py(), view)
1513 }
1514
1515 fn copy_to<U: Element>(&self, other: &Bound<'py, PyArray<U, D>>) -> PyResult<()>
1516 where
1517 T: Element,
1518 {
1519 let self_ptr = self.as_array_ptr();
1520 let other_ptr = other.as_array_ptr();
1521 let result = unsafe { PY_ARRAY_API.PyArray_CopyInto(self.py(), other_ptr, self_ptr) };
1522 if result != -1 {
1523 Ok(())
1524 } else {
1525 Err(PyErr::fetch(self.py()))
1526 }
1527 }
1528
1529 fn cast<U: Element>(&self, is_fortran: bool) -> PyResult<Bound<'py, PyArray<U, D>>>
1530 where
1531 T: Element,
1532 {
1533 let ptr = unsafe {
1534 PY_ARRAY_API.PyArray_CastToType(
1535 self.py(),
1536 self.as_array_ptr(),
1537 U::get_dtype(self.py()).into_dtype_ptr(),
1538 if is_fortran { -1 } else { 0 },
1539 )
1540 };
1541 unsafe {
1542 Bound::from_owned_ptr_or_err(self.py(), ptr).map(|ob| ob.downcast_into_unchecked())
1543 }
1544 }
1545
1546 fn permute<ID: IntoDimension>(&self, axes: Option<ID>) -> PyResult<Bound<'py, PyArray<T, D>>> {
1547 let mut axes = axes.map(|axes| axes.into_dimension());
1548 let mut axes = axes.as_mut().map(|axes| axes.to_npy_dims());
1549 let axes = axes
1550 .as_mut()
1551 .map_or_else(ptr::null_mut, |axes| axes as *mut npyffi::PyArray_Dims);
1552
1553 let py = self.py();
1554 let ptr = unsafe { PY_ARRAY_API.PyArray_Transpose(py, self.as_array_ptr(), axes) };
1555 unsafe { Bound::from_owned_ptr_or_err(py, ptr).map(|ob| ob.downcast_into_unchecked()) }
1556 }
1557
1558 fn reshape_with_order<ID: IntoDimension>(
1559 &self,
1560 shape: ID,
1561 order: NPY_ORDER,
1562 ) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>
1563 where
1564 T: Element,
1565 {
1566 let mut shape = shape.into_dimension();
1567 let mut shape = shape.to_npy_dims();
1568
1569 let py = self.py();
1570 let ptr = unsafe {
1571 PY_ARRAY_API.PyArray_Newshape(
1572 py,
1573 self.as_array_ptr(),
1574 &mut shape as *mut npyffi::PyArray_Dims,
1575 order,
1576 )
1577 };
1578 unsafe { Bound::from_owned_ptr_or_err(py, ptr).map(|ob| ob.downcast_into_unchecked()) }
1579 }
1580
1581 unsafe fn resize<ID: IntoDimension>(&self, newshape: ID) -> PyResult<()>
1582 where
1583 T: Element,
1584 {
1585 let mut newshape = newshape.into_dimension();
1586 let mut newshape = newshape.to_npy_dims();
1587
1588 let py = self.py();
1589 let res = PY_ARRAY_API.PyArray_Resize(
1590 py,
1591 self.as_array_ptr(),
1592 &mut newshape as *mut npyffi::PyArray_Dims,
1593 1,
1594 NPY_ORDER::NPY_ANYORDER,
1595 );
1596
1597 if !res.is_null() {
1598 Ok(())
1599 } else {
1600 Err(PyErr::fetch(py))
1601 }
1602 }
1603
1604 #[cfg(feature = "nalgebra")]
1605 unsafe fn try_as_matrix<R, C, RStride, CStride>(
1606 &self,
1607 ) -> Option<nalgebra::MatrixView<'_, T, R, C, RStride, CStride>>
1608 where
1609 T: nalgebra::Scalar + Element,
1610 D: Dimension,
1611 R: nalgebra::Dim,
1612 C: nalgebra::Dim,
1613 RStride: nalgebra::Dim,
1614 CStride: nalgebra::Dim,
1615 {
1616 let (shape, strides) = try_as_matrix_shape_strides(self)?;
1617
1618 let storage = nalgebra::ViewStorage::from_raw_parts(self.data(), shape, strides);
1619
1620 Some(nalgebra::Matrix::from_data(storage))
1621 }
1622
1623 #[cfg(feature = "nalgebra")]
1624 unsafe fn try_as_matrix_mut<R, C, RStride, CStride>(
1625 &self,
1626 ) -> Option<nalgebra::MatrixViewMut<'_, T, R, C, RStride, CStride>>
1627 where
1628 T: nalgebra::Scalar + Element,
1629 D: Dimension,
1630 R: nalgebra::Dim,
1631 C: nalgebra::Dim,
1632 RStride: nalgebra::Dim,
1633 CStride: nalgebra::Dim,
1634 {
1635 let (shape, strides) = try_as_matrix_shape_strides(self)?;
1636
1637 let storage = nalgebra::ViewStorageMut::from_raw_parts(self.data(), shape, strides);
1638
1639 Some(nalgebra::Matrix::from_data(storage))
1640 }
1641}
1642
1643impl<'py, T> PyArray0Methods<'py, T> for Bound<'py, PyArray0<T>> {}
1644
1645#[cfg(test)]
1646mod tests {
1647 use super::*;
1648
1649 use ndarray::array;
1650 use pyo3::{py_run, types::PyList};
1651
1652 #[test]
1653 fn test_dyn_to_owned_array() {
1654 Python::with_gil(|py| {
1655 let array = PyArray::from_vec2(py, &[vec![1, 2], vec![3, 4]])
1656 .unwrap()
1657 .to_dyn()
1658 .to_owned_array();
1659
1660 assert_eq!(array, array![[1, 2], [3, 4]].into_dyn());
1661 });
1662 }
1663
1664 #[test]
1665 fn test_hasobject_flag() {
1666 Python::with_gil(|py| {
1667 let array: Bound<'_, PyArray<PyObject, _>> =
1668 PyArray1::from_slice(py, &[PyList::empty(py).into()]);
1669
1670 py_run!(py, array, "assert array.dtype.hasobject");
1671 });
1672 }
1673}