numpy/
lib.rs

1//! This crate provides Rust interfaces for [NumPy C APIs][c-api],
2//! especially for the [ndarray][ndarray] class.
3//!
4//! It uses [`pyo3`] for Rust bindings to CPython, and uses
5//! [`ndarray`] as the Rust matrix library.
6//!
7//! To resolve its dependency on NumPy, it calls `import numpy.core` internally.
8//! This means that this crate should work if you can use NumPy in your Python environment,
9//! e.g. after installing it by `pip install numpy`. It does not matter whether you use
10//! the system environment or a dedicated virtual environment.
11//!
12//! Loading NumPy is done automatically and on demand. So if it is not installed, the functions
13//! provided by this crate will panic instead of returning a result.
14//!
15#![cfg_attr(
16    feature = "nalgebra",
17    doc = "Integration with [`nalgebra`] is provided via an implementation of [`ToPyArray`] for [`nalgebra::Matrix`] to convert nalgebra matrices into NumPy arrays
18as well as the [`PyReadonlyArray::try_as_matrix`] and [`PyReadwriteArray::try_as_matrix_mut`] methods to treat NumPy array as nalgebra matrix slices.
19"
20)]
21//! # Example
22//!
23//! ```
24//! use numpy::pyo3::Python;
25//! use numpy::ndarray::array;
26//! use numpy::{ToPyArray, PyArray, PyArrayMethods};
27//!
28//! Python::with_gil(|py| {
29//!     let py_array = array![[1i64, 2], [3, 4]].to_pyarray(py);
30//!
31//!     assert_eq!(
32//!         py_array.readonly().as_array(),
33//!         array![[1i64, 2], [3, 4]]
34//!     );
35//! });
36//! ```
37//!
38#![cfg_attr(feature = "nalgebra", doc = "```")]
39#![cfg_attr(not(feature = "nalgebra"), doc = "```rust,ignore")]
40//! use numpy::pyo3::Python;
41//! use numpy::nalgebra::Matrix3;
42//! use numpy::{pyarray, ToPyArray, PyArrayMethods};
43//!
44//! Python::with_gil(|py| {
45//!     let py_array = pyarray![py, [0, 1, 2], [3, 4, 5], [6, 7, 8]];
46//!
47//!     let py_array_square;
48//!
49//!     {
50//!         let py_array = py_array.readwrite();
51//!         let mut na_matrix = py_array.as_matrix_mut();
52//!
53//!         na_matrix.add_scalar_mut(1);
54//!
55//!         py_array_square = na_matrix.pow(2).to_pyarray(py);
56//!     }
57//!
58//!     assert_eq!(
59//!         py_array.readonly().as_matrix(),
60//!         Matrix3::new(1, 2, 3, 4, 5, 6, 7, 8, 9)
61//!     );
62//!
63//!     assert_eq!(
64//!         py_array_square.readonly().as_matrix(),
65//!         Matrix3::new(30, 36, 42, 66, 81, 96, 102, 126, 150)
66//!     );
67//! });
68#![doc = "```"]
69//!
70//! [c-api]: https://numpy.org/doc/stable/reference/c-api
71//! [ndarray]: https://numpy.org/doc/stable/reference/arrays.ndarray.html
72#![deny(missing_docs)]
73
74pub mod array;
75mod array_like;
76pub mod borrow;
77pub mod convert;
78pub mod datetime;
79mod dtype;
80mod error;
81pub mod npyffi;
82mod slice_container;
83mod strings;
84mod sum_products;
85mod untyped_array;
86
87pub use ndarray;
88pub use pyo3;
89
90#[cfg(feature = "nalgebra")]
91pub use nalgebra;
92
93pub use crate::array::{
94    get_array_module, PyArray, PyArray0, PyArray0Methods, PyArray1, PyArray2, PyArray3, PyArray4,
95    PyArray5, PyArray6, PyArrayDyn, PyArrayMethods,
96};
97pub use crate::array_like::{
98    AllowTypeChange, PyArrayLike, PyArrayLike0, PyArrayLike1, PyArrayLike2, PyArrayLike3,
99    PyArrayLike4, PyArrayLike5, PyArrayLike6, PyArrayLikeDyn, TypeMustMatch,
100};
101pub use crate::borrow::{
102    PyReadonlyArray, PyReadonlyArray0, PyReadonlyArray1, PyReadonlyArray2, PyReadonlyArray3,
103    PyReadonlyArray4, PyReadonlyArray5, PyReadonlyArray6, PyReadonlyArrayDyn, PyReadwriteArray,
104    PyReadwriteArray0, PyReadwriteArray1, PyReadwriteArray2, PyReadwriteArray3, PyReadwriteArray4,
105    PyReadwriteArray5, PyReadwriteArray6, PyReadwriteArrayDyn,
106};
107pub use crate::convert::{IntoPyArray, NpyIndex, ToNpyDims, ToPyArray};
108#[allow(deprecated)]
109pub use crate::dtype::dtype_bound;
110pub use crate::dtype::{dtype, Complex32, Complex64, Element, PyArrayDescr, PyArrayDescrMethods};
111pub use crate::error::{BorrowError, FromVecError, NotContiguousError};
112pub use crate::npyffi::{PY_ARRAY_API, PY_UFUNC_API};
113pub use crate::strings::{PyFixedString, PyFixedUnicode};
114pub use crate::sum_products::{dot, einsum, inner};
115#[allow(deprecated)]
116pub use crate::sum_products::{dot_bound, einsum_bound, inner_bound};
117pub use crate::untyped_array::{PyUntypedArray, PyUntypedArrayMethods};
118
119pub use ndarray::{array, Ix1, Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn};
120
121/// A prelude
122///
123/// The purpose of this module is to avoid direct imports of
124/// the method traits defined by this crate via a glob import:
125///
126/// ```
127/// # #![allow(unused_imports)]
128/// use numpy::prelude::*;
129/// ```
130pub mod prelude {
131    pub use crate::array::{PyArray0Methods, PyArrayMethods};
132    pub use crate::convert::{IntoPyArray, ToPyArray};
133    pub use crate::dtype::PyArrayDescrMethods;
134    pub use crate::untyped_array::PyUntypedArrayMethods;
135}
136
137#[cfg(doctest)]
138mod doctest {
139    macro_rules! doc_comment {
140        ($doc_string:expr, $mod_name:ident) => {
141            #[doc = $doc_string]
142            mod $mod_name {}
143        };
144    }
145    doc_comment!(include_str!("../README.md"), readme);
146}
147
148#[cold]
149#[inline(always)]
150fn cold() {}
151
152/// Create a [`PyArray`] with one, two or three dimensions.
153///
154/// This macro is backed by [`ndarray::array`].
155///
156/// # Example
157///
158/// ```
159/// use numpy::pyo3::Python;
160/// use numpy::ndarray::array;
161/// use numpy::{pyarray, PyArrayMethods};
162///
163/// Python::with_gil(|py| {
164///     let array = pyarray![py, [1, 2], [3, 4]];
165///
166///     assert_eq!(
167///         array.readonly().as_array(),
168///         array![[1, 2], [3, 4]]
169///     );
170/// });
171#[macro_export]
172macro_rules! pyarray {
173    ($py: ident, $([$([$($x:expr),* $(,)*]),+ $(,)*]),+ $(,)*) => {{
174        $crate::IntoPyArray::into_pyarray($crate::array![$([$([$($x,)*],)*],)*], $py)
175    }};
176    ($py: ident, $([$($x:expr),* $(,)*]),+ $(,)*) => {{
177        $crate::IntoPyArray::into_pyarray($crate::array![$([$($x,)*],)*], $py)
178    }};
179    ($py: ident, $($x:expr),* $(,)*) => {{
180        $crate::IntoPyArray::into_pyarray($crate::array![$($x,)*], $py)
181    }};
182}
183
184/// Deprecated name for [`pyarray`].
185#[deprecated(since = "0.23.0", note = "renamed to `pyarray`")]
186#[macro_export]
187macro_rules! pyarray_bound {
188    ($py: ident, $([$([$($x:expr),* $(,)*]),+ $(,)*]),+ $(,)*) => {{
189        $crate::IntoPyArray::into_pyarray($crate::array![$([$([$($x,)*],)*],)*], $py)
190    }};
191    ($py: ident, $([$($x:expr),* $(,)*]),+ $(,)*) => {{
192        $crate::IntoPyArray::into_pyarray($crate::array![$([$($x,)*],)*], $py)
193    }};
194    ($py: ident, $($x:expr),* $(,)*) => {{
195        $crate::IntoPyArray::into_pyarray($crate::array![$($x,)*], $py)
196    }};
197}