Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 57 additions & 10 deletions src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::ptr::null_mut;
use super::error::ArrayCastError;
use super::*;

/// Untyped safe interface for NumPy ndarray.
/// Interface for [NumPy ndarray](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html).
pub struct PyArray<T>(PyObject, PhantomData<T>);

pyobject_native_type_convert!(
Expand Down Expand Up @@ -53,16 +53,18 @@ impl<T> IntoPyObject for PyArray<T> {
}

impl<T> PyArray<T> {
/// Get raw pointer for PyArrayObject
/// Gets a raw `PyArrayObject` pointer.
pub fn as_array_ptr(&self) -> *mut npyffi::PyArrayObject {
self.as_ptr() as _
}

/// Constructs `PyArray` from raw python object without incrementing reference counts.
pub unsafe fn from_owned_ptr(py: Python, ptr: *mut pyo3::ffi::PyObject) -> Self {
let obj = PyObject::from_owned_ptr(py, ptr);
PyArray(obj, PhantomData)
}

/// Constructs PyArray from raw python object and increments reference counts.
pub unsafe fn from_borrowed_ptr(py: Python, ptr: *mut pyo3::ffi::PyObject) -> Self {
let obj = PyObject::from_borrowed_ptr(py, ptr);
PyArray(obj, PhantomData)
Expand Down Expand Up @@ -135,8 +137,6 @@ impl<T> PyArray<T> {
}

/// Same as [shape](./struct.PyArray.html#method.shape)
///
/// Reserved for backward compatibility.
#[inline]
pub fn dims(&self) -> &[usize] {
self.shape()
Expand Down Expand Up @@ -294,6 +294,7 @@ impl<T: TypeNum> PyArray<T> {
IntoPyArray::into_pyarray(arr, py, np)
}

/// Returns the pointer to the first element of the inner array.
unsafe fn data(&self) -> *mut T {
let ptr = self.as_array_ptr();
(*ptr).data as *mut T
Expand All @@ -310,13 +311,14 @@ impl<T: TypeNum> PyArray<T> {
shape.strides(Dim(st))
}

pub fn typenum(&self) -> i32 {
fn typenum(&self) -> i32 {
unsafe {
let descr = (*self.as_array_ptr()).descr;
(*descr).type_num
}
}

/// Returns the scalar type of the array.
pub fn data_type(&self) -> NpyDataType {
NpyDataType::from_i32(self.typenum())
}
Expand Down Expand Up @@ -360,6 +362,9 @@ impl<T: TypeNum> PyArray<T> {
unsafe { Ok(::std::slice::from_raw_parts_mut(self.data(), self.len())) }
}

/// Construct a new PyArray given a raw pointer and dimensions.
///
/// Please use `new` or from methods instead.
pub unsafe fn new_(
py: Python,
np: &PyArrayModule,
Expand All @@ -382,27 +387,69 @@ impl<T: TypeNum> PyArray<T> {
Self::from_owned_ptr(py, ptr)
}

/// a wrapper of [PyArray_SimpleNew](https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_SimpleNew)
/// Creates a new uninitialized array.
///
/// See also [PyArray_SimpleNew](https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_SimpleNew).
///
/// # Example
/// ```
/// # extern crate pyo3; extern crate numpy; #[macro_use] extern crate ndarray; fn main() {
/// use numpy::{PyArray, PyArrayModule};
/// let gil = pyo3::Python::acquire_gil();
/// let np = PyArrayModule::import(gil.python()).unwrap();
/// let pyarray = PyArray::new(gil.python(), &np, &[2, 2]);
/// assert_eq!(pyarray.as_array().unwrap(), array![[0, 0], [0, 0]].into_dyn());
/// # }
/// ```
pub fn new(py: Python, np: &PyArrayModule, dims: &[usize]) -> Self {
unsafe { Self::new_(py, np, dims, null_mut(), null_mut()) }
}

/// a wrapper of [PyArray_ZEROS](https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_ZEROS)
pub fn zeros(py: Python, np: &PyArrayModule, dims: &[usize], order: NPY_ORDER) -> Self {
/// Construct a new nd-dimensional array filled with 0. If `is_fortran` is true, then
/// a fortran order array is created, otherwise a C-order array is created.
///
/// See also [PyArray_Zeros](https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_Zeros)
///
/// # Example
/// ```
/// # extern crate pyo3; extern crate numpy; #[macro_use] extern crate ndarray; fn main() {
/// use numpy::{PyArray, PyArrayModule};
/// let gil = pyo3::Python::acquire_gil();
/// let np = PyArrayModule::import(gil.python()).unwrap();
/// let pyarray = PyArray::zeros(gil.python(), &np, &[2, 2], false);
/// assert_eq!(pyarray.as_array().unwrap(), array![[0, 0], [0, 0]].into_dyn());
/// # }
/// ```
pub fn zeros(py: Python, np: &PyArrayModule, dims: &[usize], is_fortran: bool) -> Self {
let dims: Vec<npy_intp> = dims.iter().map(|d| *d as npy_intp).collect();
unsafe {
let descr = np.PyArray_DescrFromType(T::typenum());
let ptr = np.PyArray_Zeros(
dims.len() as i32,
dims.as_ptr() as *mut npy_intp,
descr,
order as i32,
if is_fortran { -1 } else { 0 },
);
Self::from_owned_ptr(py, ptr)
}
}

/// a wrapper of [PyArray_Arange](https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_Arange)
/// Return evenly spaced values within a given interval.
/// Same as [numpy.arange](https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html).
///
/// See also [PyArray_Arange](https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_Arange).
///
/// # Example
/// ```
/// # extern crate pyo3; extern crate numpy; fn main() {
/// use numpy::{PyArray, PyArrayModule, IntoPyArray};
/// let gil = pyo3::Python::acquire_gil();
/// let np = PyArrayModule::import(gil.python()).unwrap();
/// let pyarray = PyArray::<f64>::arange(gil.python(), &np, 2.0, 4.0, 0.5);
/// assert_eq!(pyarray.as_slice().unwrap(), &[2.0, 2.5, 3.0, 3.5]);
/// let pyarray = PyArray::<i32>::arange(gil.python(), &np, -2.0, 4.0, 3.0);
/// assert_eq!(pyarray.as_slice().unwrap(), &[-2, 1]);
/// # }
pub fn arange(py: Python, np: &PyArrayModule, start: f64, stop: f64, step: f64) -> Self {
unsafe {
let ptr = np.PyArray_Arange(start, stop, step, T::typenum());
Expand Down
12 changes: 12 additions & 0 deletions src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ use std::ptr::null_mut;

use super::*;

/// Covversion trait from rust types to `PyArray`.
///
/// # Example
/// ```
/// # extern crate pyo3; extern crate numpy; fn main() {
/// use numpy::{PyArray, PyArrayModule, IntoPyArray};
/// let gil = pyo3::Python::acquire_gil();
/// let np = PyArrayModule::import(gil.python()).unwrap();
/// let py_array = vec![1, 2, 3].into_pyarray(gil.python(), &np);
/// assert_eq!(py_array.as_slice().unwrap(), &[1, 2, 3]);
/// # }
/// ```
pub trait IntoPyArray {
type Item: TypeNum;
fn into_pyarray(self, Python, &PyArrayModule) -> PyArray<Self::Item>;
Expand Down
6 changes: 4 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,20 @@ impl<T, E: IntoPyErr> IntoPyResult for Result<T, E> {
}
}

/// Error for casting `PyArray` into `ArrayView` or `ArrayViewMut`
/// Represents a casting error between rust types and numpy array.
#[derive(Debug)]
pub enum ArrayCastError {
/// Error for casting `PyArray` into `ArrayView` or `ArrayViewMut`
ToRust {
from: NpyDataType,
to: NpyDataType,
},
/// Error for casting rust's `Vec` into numpy array.
FromVec,
}

impl ArrayCastError {
pub fn to_rust(from: i32, to: i32) -> Self {
pub(crate) fn to_rust(from: i32, to: i32) -> Self {
ArrayCastError::ToRust {
from: NpyDataType::from_i32(from),
to: NpyDataType::from_i32(to),
Expand Down
11 changes: 4 additions & 7 deletions src/npyffi/array.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
//! Low-Level binding for Array API
//!
//! https://docs.scipy.org/doc/numpy/reference/c-api.array.html
//! Low-Level binding for [Array API](https://docs.scipy.org/doc/numpy/reference/c-api.array.html)

use libc::FILE;
use std::ops::Deref;
Expand All @@ -13,10 +11,9 @@ use pyo3::{ObjectProtocol, PyModule, PyResult, Python, ToPyPointer};

use npyffi::*;

/// Low-Level binding for Array API
/// https://docs.scipy.org/doc/numpy/reference/c-api.array.html
/// Low-Level binding for [Array API](https://docs.scipy.org/doc/numpy/reference/c-api.array.html)
///
/// Most of Array API is exposed as the related function of this module object.
/// Most of the Array APIs are exposed as related functions of this module object.
/// Some APIs (including most accessor) in the above URL are not implemented
/// since they are defined as C macro, and cannot be called from rust.
/// Some of these are implemented on the high-level interface as a Rust function.
Expand Down Expand Up @@ -61,7 +58,7 @@ impl<'py> PyArrayModule<'py> {
}

/// Returns internal `PyModule` type, which includes `numpy.core.multiarray`,
/// so that you can use `PyArrayModule` with some pyo3 functions.
/// so that you can use `PyArrayModule` with some functions.
///
/// # Example
///
Expand Down
3 changes: 1 addition & 2 deletions src/npyffi/ufunc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ use pyo3::{ObjectProtocol, PyModule, PyResult, Python, ToPyPointer};
use super::objects::*;
use super::types::*;

/// Low-Level binding for UFunc API
/// https://docs.scipy.org/doc/numpy/reference/c-api.ufunc.html
/// Low-Level binding for [UFunc API](https://docs.scipy.org/doc/numpy/reference/c-api.ufunc.html)
///
/// Most of UFunc API is exposed as the related function of this module object.
pub struct PyUFuncModule<'py> {
Expand Down
6 changes: 3 additions & 3 deletions tests/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ fn zeros() {
let np = PyArrayModule::import(gil.python()).unwrap();
let n = 3;
let m = 5;
let arr = PyArray::<f64>::zeros(gil.python(), &np, &[n, m], NPY_CORDER);
let arr = PyArray::<f64>::zeros(gil.python(), &np, &[n, m], false);
assert!(arr.ndim() == 2);
assert!(arr.dims() == [n, m]);
assert!(arr.strides() == [m as isize * 8, 8]);

let arr = PyArray::<f64>::zeros(gil.python(), &np, &[n, m], NPY_FORTRANORDER);
let arr = PyArray::<f64>::zeros(gil.python(), &np, &[n, m], true);
assert!(arr.ndim() == 2);
assert!(arr.dims() == [n, m]);
assert!(arr.strides() == [8, n as isize * 8]);
Expand All @@ -49,7 +49,7 @@ fn arange() {
fn as_array() {
let gil = pyo3::Python::acquire_gil();
let np = PyArrayModule::import(gil.python()).unwrap();
let arr = PyArray::<f64>::zeros(gil.python(), &np, &[3, 2, 4], NPY_CORDER);
let arr = PyArray::<f64>::zeros(gil.python(), &np, &[3, 2, 4], false);
let a = arr.as_array().unwrap();
assert_eq!(arr.shape(), a.shape());
assert_eq!(
Expand Down