sarah-quinones/faer-rs

PyArray2 into faer to simplify python interfaces to rust routines using faer

Opened this issue · 1 comments

Currently my pyO3 bindings that call some rust routines that use faer look something like:

use numpy::{IntoPyArray, PyArray2, PyReadonlyArray2};
use pyo3::{exceptions::PyRuntimeError, pymodule, types::PyModule, PyResult, Python};
use faer::{prelude::*}
// ...

#[pymodule]
fn rust_lib<'py>(_py: Python<'py>, m: &'py PyModule)
    -> PyResult<()>
{
   #[pyfn(m)]
    fn rpca<'py>(py: Python<'py>, a_py: PyReadonlyArray2<'py, f64>, n_rank: usize, n_iters: usize, n_oversamples: usize)
        -> &'py PyArray2<f64>
    {
        let a_ndarray = a_py.as_array();
        let a_faer = a_ndarray.view().into_faer();
        // ... faer-rs math
        ndarray_result.into_pyarray(py)
    }
}

I'm unsure if I am using the best approach.

Desired Solution:

// ...

   #[pyfn(m)]
    fn rpca<'py>(py: Python<'py>, a_py: PyReadonlyArray2<'py, f64>, n_rank: usize, n_iters: usize, n_oversamples: usize)
        -> &'py PyArray2<f64>
    {
        let a_faer = a_py.into_faer();
        // ... faer-rs math
        faer_result.into_pyarray(py)
    }

I would be interested as well in something like this but I think it is something more to do with how this implemented in the crate used for type conversion from and to Numpy arrays.

As stated in the introduction to their docs this is something that has been somehow implemented for the nalgebra crate by implementing the ToPyArray trait. I guess something similar could probably be done for faer.