nalgebra-numpy
This crate provides conversion between nalgebra
and numpy
.
It is intended to be used when you want to share nalgebra matrices between Python and Rust code,
for example with inline-python
.
Conversion from numpy to nalgebra.
It is possible to create either a view or a copy of a numpy array.
You can use matrix_from_numpy
to copy the data into a new matrix,
or one of matrix_slice_from_numpy
or matrix_slice_mut_from_numpy
to create a view.
If a numpy array is not compatible with the requested matrix type,
an error is returned.
Keep in mind though that the borrow checker can not enforce rules on data managed by a Python object. You could potentially keep an immutable view around in Rust, and then modify the data from Python. For this reason, creating any view -- even an immutable one -- is unsafe.
Conversion from nalgebra to numpy.
A nalgebra matrix can also be converted to a numpy array, using matrix_to_numpy
.
This function always creates a copy.
Since all nalgebra arrays can be represented as a numpy array,
this directly returns a pyo3::PyObject
rather than a Result
.
Examples.
Copy a numpy array to a new fixed size matrix:
use ;
use ;
let gil = acquire_gil;
let context = new_with_gil.unwrap;
python!
let matrix = context.globals.get_item.unwrap;
let matrix : Matrix3 = matrix_from_numpy?;
assert_eq!;
Dynamic matrices are also supported:
use DMatrix;
#
let matrix : = matrix_from_numpy?;
assert_eq!;
And so are partially dynamic matrices:
use ;
let matrix : = matrix_from_numpy?;
assert_eq!;
A conversion to python object looks as follows:
use matrix_to_numpy;
use Matrix3;
use python;
let gil = acquire_gil;
let matrix = matrix_to_numpy;
python!