Skip to content

Commit 5271427

Browse files
committed
Begin adding optional support for nalgebra types.
1 parent 9a7bde2 commit 5271427

File tree

4 files changed

+41
-0
lines changed

4 files changed

+41
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Changelog
22

33
- Unreleased
4+
- Add conversions from datatypes provided by the [`nalgebra` crate](https://nalgebra.org/). ([#347](https://github.com/PyO3/rust-numpy/pull/347))
45
- Drop our wrapper for NumPy iterators which were deprecated in v0.16.0 as ndarray's iteration facilities are almost always preferable. ([#324](https://github.com/PyO3/rust-numpy/pull/324))
56

67
- v0.17.2

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ license = "BSD-2-Clause"
1818
ahash = "0.7"
1919
half = { version = "1.8", default-features = false, optional = true }
2020
libc = "0.2"
21+
nalgebra = { version = "0.31", default-features = false, optional = true }
2122
num-complex = ">= 0.2, < 0.5"
2223
num-integer = "0.1"
2324
num-traits = "0.2"

src/convert.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,30 @@ where
183183
}
184184
}
185185

186+
#[cfg(feature = "nalgebra")]
187+
impl<N, R, C, S> ToPyArray for nalgebra::Matrix<N, R, C, S>
188+
where
189+
N: nalgebra::Scalar + Element,
190+
R: nalgebra::Dim,
191+
C: nalgebra::Dim,
192+
S: nalgebra::storage::Storage<N, R, C>,
193+
{
194+
type Item = N;
195+
type Dim = crate::Ix2;
196+
197+
fn to_pyarray<'py>(&self, py: Python<'py>) -> &'py PyArray<Self::Item, Self::Dim> {
198+
unsafe {
199+
let array = PyArray::new(py, (self.nrows(), self.ncols()), false);
200+
for r in 0..self.nrows() {
201+
for c in 0..self.ncols() {
202+
*array.uget_mut((r, c)) = self.get_unchecked((r, c)).clone();
203+
}
204+
}
205+
array
206+
}
207+
}
208+
}
209+
186210
pub(crate) trait ArrayExt {
187211
fn npy_strides(&self) -> [npyffi::npy_intp; 32];
188212
fn order(&self) -> Option<c_int>;

tests/to_py.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,3 +298,18 @@ fn slice_container_type_confusion() {
298298
let _py_arr = vec![1, 2, 3].into_pyarray(py);
299299
});
300300
}
301+
302+
#[cfg(feature = "nalgebra")]
303+
#[test]
304+
fn matrix_to_numpy() {
305+
let matrix = nalgebra::Matrix3::<i32>::new(0, 1, 2, 3, 4, 5, 6, 7, 8);
306+
307+
Python::with_gil(|py| {
308+
let array = matrix.to_pyarray(py);
309+
310+
assert_eq!(
311+
array.readonly().as_array(),
312+
array![[0, 1, 2], [3, 4, 5], [6, 7, 8]],
313+
);
314+
});
315+
}

0 commit comments

Comments
 (0)