Skip to main content

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