|
| 1 | +use std::marker::PhantomData; |
| 2 | +use std::ops::Deref; |
| 3 | + |
| 4 | +use ndarray::{Array1, Dimension, Ix0, Ix1, Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn}; |
| 5 | +use pyo3::{intern, sync::GILOnceCell, types::PyDict, FromPyObject, Py, PyAny, PyResult}; |
| 6 | + |
| 7 | +use crate::sealed::Sealed; |
| 8 | +use crate::{get_array_module, Element, IntoPyArray, PyArray, PyReadonlyArray}; |
| 9 | + |
| 10 | +pub trait Coerce: Sealed { |
| 11 | + const VAL: bool; |
| 12 | +} |
| 13 | + |
| 14 | +/// Marker type to indicate that the element type received via [`PyArrayLike`] must match the specified type exactly. |
| 15 | +#[derive(Debug)] |
| 16 | +pub struct TypeMustMatch; |
| 17 | + |
| 18 | +impl Sealed for TypeMustMatch {} |
| 19 | + |
| 20 | +impl Coerce for TypeMustMatch { |
| 21 | + const VAL: bool = false; |
| 22 | +} |
| 23 | + |
| 24 | +/// Marker type to indicate that the element type received via [`PyArrayLike`] can be cast to the specified type by NumPy's [`asarray`](https://numpy.org/doc/stable/reference/generated/numpy.asarray.html). |
| 25 | +#[derive(Debug)] |
| 26 | +pub struct AllowTypeChange; |
| 27 | + |
| 28 | +impl Sealed for AllowTypeChange {} |
| 29 | + |
| 30 | +impl Coerce for AllowTypeChange { |
| 31 | + const VAL: bool = true; |
| 32 | +} |
| 33 | + |
| 34 | +/// Receiver for arrays or array-like types. |
| 35 | +/// |
| 36 | +/// When building API using NumPy in Python, it is common for functions to additionally accept any array-like type such as `list[float]` as arguments. |
| 37 | +/// `PyArrayLike` enables the same pattern in Rust extensions, i.e. by taking this type as the argument of a `#[pyfunction]`, |
| 38 | +/// one will always get access to a [`PyReadonlyArray`] that will either reference to the NumPy array originally passed into the function |
| 39 | +/// or a temporary one created by converting the input type into a NumPy array. |
| 40 | +/// |
| 41 | +/// Depending on whether [`TypeMustMatch`] or [`AllowTypeChange`] is used for the `C` type parameter, |
| 42 | +/// the element type must either match the specific type `T` exactly or will be cast to it by NumPy's [`asarray`](https://numpy.org/doc/stable/reference/generated/numpy.asarray.html). |
| 43 | +/// |
| 44 | +/// # Example |
| 45 | +/// |
| 46 | +/// `PyArrayLike1<'py, T, TypeMustMatch>` will enable you to receive both NumPy arrays and sequences |
| 47 | +/// |
| 48 | +/// ```rust |
| 49 | +/// # use pyo3::prelude::*; |
| 50 | +/// use pyo3::py_run; |
| 51 | +/// use numpy::{get_array_module, PyArrayLike1, TypeMustMatch}; |
| 52 | +/// |
| 53 | +/// #[pyfunction] |
| 54 | +/// fn sum_up<'py>(py: Python<'py>, array: PyArrayLike1<'py, f64, TypeMustMatch>) -> f64 { |
| 55 | +/// array.as_array().sum() |
| 56 | +/// } |
| 57 | +/// |
| 58 | +/// Python::with_gil(|py| { |
| 59 | +/// let np = get_array_module(py).unwrap(); |
| 60 | +/// let sum_up = wrap_pyfunction!(sum_up)(py).unwrap(); |
| 61 | +/// |
| 62 | +/// py_run!(py, np sum_up, r"assert sum_up(np.array([1., 2., 3.])) == 6."); |
| 63 | +/// py_run!(py, np sum_up, r"assert sum_up((1., 2., 3.)) == 6."); |
| 64 | +/// }); |
| 65 | +/// ``` |
| 66 | +/// |
| 67 | +/// but it will not cast the element type if that is required |
| 68 | +/// |
| 69 | +/// ```rust,should_panic |
| 70 | +/// use pyo3::prelude::*; |
| 71 | +/// use pyo3::py_run; |
| 72 | +/// use numpy::{get_array_module, PyArrayLike1, TypeMustMatch}; |
| 73 | +/// |
| 74 | +/// #[pyfunction] |
| 75 | +/// fn sum_up<'py>(py: Python<'py>, array: PyArrayLike1<'py, i32, TypeMustMatch>) -> i32 { |
| 76 | +/// array.as_array().sum() |
| 77 | +/// } |
| 78 | +/// |
| 79 | +/// Python::with_gil(|py| { |
| 80 | +/// let np = get_array_module(py).unwrap(); |
| 81 | +/// let sum_up = wrap_pyfunction!(sum_up)(py).unwrap(); |
| 82 | +/// |
| 83 | +/// py_run!(py, np sum_up, r"assert sum_up((1., 2., 3.)) == 6"); |
| 84 | +/// }); |
| 85 | +/// ``` |
| 86 | +/// |
| 87 | +/// whereas `PyArrayLike1<'py, T, AllowTypeChange>` will do even at the cost loosing precision |
| 88 | +/// |
| 89 | +/// ```rust |
| 90 | +/// use pyo3::prelude::*; |
| 91 | +/// use pyo3::py_run; |
| 92 | +/// use numpy::{get_array_module, AllowTypeChange, PyArrayLike1}; |
| 93 | +/// |
| 94 | +/// #[pyfunction] |
| 95 | +/// fn sum_up<'py>(py: Python<'py>, array: PyArrayLike1<'py, i32, AllowTypeChange>) -> i32 { |
| 96 | +/// array.as_array().sum() |
| 97 | +/// } |
| 98 | +/// |
| 99 | +/// Python::with_gil(|py| { |
| 100 | +/// let np = get_array_module(py).unwrap(); |
| 101 | +/// let sum_up = wrap_pyfunction!(sum_up)(py).unwrap(); |
| 102 | +/// |
| 103 | +/// py_run!(py, np sum_up, r"assert sum_up((1.5, 2.5)) == 3"); |
| 104 | +/// }); |
| 105 | +/// ``` |
| 106 | +#[derive(Debug)] |
| 107 | +#[repr(transparent)] |
| 108 | +pub struct PyArrayLike<'py, T, D, C = TypeMustMatch>(PyReadonlyArray<'py, T, D>, PhantomData<C>) |
| 109 | +where |
| 110 | + T: Element, |
| 111 | + D: Dimension, |
| 112 | + C: Coerce; |
| 113 | + |
| 114 | +impl<'py, T, D, C> Deref for PyArrayLike<'py, T, D, C> |
| 115 | +where |
| 116 | + T: Element, |
| 117 | + D: Dimension, |
| 118 | + C: Coerce, |
| 119 | +{ |
| 120 | + type Target = PyReadonlyArray<'py, T, D>; |
| 121 | + |
| 122 | + fn deref(&self) -> &Self::Target { |
| 123 | + &self.0 |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl<'py, T, D, C> FromPyObject<'py> for PyArrayLike<'py, T, D, C> |
| 128 | +where |
| 129 | + T: Element, |
| 130 | + D: Dimension, |
| 131 | + C: Coerce, |
| 132 | + Vec<T>: FromPyObject<'py>, |
| 133 | +{ |
| 134 | + fn extract(ob: &'py PyAny) -> PyResult<Self> { |
| 135 | + if let Ok(array) = ob.downcast::<PyArray<T, D>>() { |
| 136 | + return Ok(Self(array.readonly(), PhantomData)); |
| 137 | + } |
| 138 | + |
| 139 | + let py = ob.py(); |
| 140 | + |
| 141 | + if matches!(D::NDIM, None | Some(1)) { |
| 142 | + if let Ok(vec) = ob.extract::<Vec<T>>() { |
| 143 | + let array = Array1::from(vec) |
| 144 | + .into_dimensionality() |
| 145 | + .expect("D being compatible to Ix1") |
| 146 | + .into_pyarray(py) |
| 147 | + .readonly(); |
| 148 | + return Ok(Self(array, PhantomData)); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + static AS_ARRAY: GILOnceCell<Py<PyAny>> = GILOnceCell::new(); |
| 153 | + |
| 154 | + let as_array = AS_ARRAY |
| 155 | + .get_or_try_init(py, || { |
| 156 | + get_array_module(py)?.getattr("asarray").map(Into::into) |
| 157 | + })? |
| 158 | + .as_ref(py); |
| 159 | + |
| 160 | + let kwargs = if C::VAL { |
| 161 | + let kwargs = PyDict::new(py); |
| 162 | + kwargs.set_item(intern!(py, "dtype"), T::get_dtype(py))?; |
| 163 | + Some(kwargs) |
| 164 | + } else { |
| 165 | + None |
| 166 | + }; |
| 167 | + |
| 168 | + let array = as_array.call((ob,), kwargs)?.extract()?; |
| 169 | + Ok(Self(array, PhantomData)) |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +/// Receiver for zero-dimensional arrays or array-like types. |
| 174 | +pub type PyArrayLike0<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, Ix0, C>; |
| 175 | + |
| 176 | +/// Receiver for one-dimensional arrays or array-like types. |
| 177 | +pub type PyArrayLike1<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, Ix1, C>; |
| 178 | + |
| 179 | +/// Receiver for two-dimensional arrays or array-like types. |
| 180 | +pub type PyArrayLike2<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, Ix2, C>; |
| 181 | + |
| 182 | +/// Receiver for three-dimensional arrays or array-like types. |
| 183 | +pub type PyArrayLike3<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, Ix3, C>; |
| 184 | + |
| 185 | +/// Receiver for four-dimensional arrays or array-like types. |
| 186 | +pub type PyArrayLike4<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, Ix4, C>; |
| 187 | + |
| 188 | +/// Receiver for five-dimensional arrays or array-like types. |
| 189 | +pub type PyArrayLike5<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, Ix5, C>; |
| 190 | + |
| 191 | +/// Receiver for six-dimensional arrays or array-like types. |
| 192 | +pub type PyArrayLike6<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, Ix6, C>; |
| 193 | + |
| 194 | +/// Receiver for arrays or array-like types whose dimensionality is determined at runtime. |
| 195 | +pub type PyArrayLikeDyn<'py, T, C = TypeMustMatch> = PyArrayLike<'py, T, IxDyn, C>; |
0 commit comments