Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting ndarray::Array2 into numpy::ndarray::Array2 #446

Open
jondoesntgit opened this issue Oct 3, 2024 · 3 comments
Open

Converting ndarray::Array2 into numpy::ndarray::Array2 #446

jondoesntgit opened this issue Oct 3, 2024 · 3 comments

Comments

@jondoesntgit
Copy link

jondoesntgit commented Oct 3, 2024

I'm calling another library that doesn't use the numpy crate. It only uses the "vanilla" ndarray crate, and as such returns an ndarray::Array2 object. For the life of me, I haven't been able to figure out how to get this converted into a Python object. Here's some code that shows that I can convert a numpy::ndarray::Array2 object into python, but I can't do it with play ndarray::Array2 objects.

I would like to avoid having to clone the data from the ndarray to the numpy::ndarray object, and I'd also like to avoid writing unsafe to create a new object with a pointer.

use pyo3::prelude::*;
use pyo3::Python;
use ndarray::{Array2 as ndArray2};
use numpy::ndarray::{Array2 as npArray2};
use numpy::{PyArray, PyArrayMethods, IntoPyArray, PyArray2};
//use crate::vapor_cell;

#[pyfunction]
fn simulate_vapor_cell(py: Python) -> PyResult<Bound<PyArray2<f64>>> {
    
    // The following works with npArray2, but not ndArray2
    let array = npArray2::from_shape_fn((2,3), |(i, j, k)| {
        i as f64 + j as f64
    });
    let py_array = array.into_pyarray_bound(py);
    Ok(py_array)
}

Cargo.toml

[package]
name = "my_library"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[dependencies]
ndarray = "0.16.1"
num = "0.4"
numpy = "0.21.0"
serde = {version = "1.0.210", features=["derive"]}
thiserror = "1.0.64"
toml = "0.8.19"

[dependencies.pyo3]
#pyo3 = {version = "0.22.3", features = ["extension-module"]}

version = "0.21.0"
optional = true
# "abi3-py38" tells pyo3 (and maturin) to build using the stable ABI with minimum Python version 3.8
features = ["abi3-py38"]

[features]
wheel = ["pyo3"] # Add any dependencies here
@Icxolu
Copy link
Contributor

Icxolu commented Oct 3, 2024

The current version of rust-numpy is only compatiple with ndarray until 0.15, which is why the conversion does not work in your case. So you currently have to downgrade to 0.15 to make it work. (numpy::ndarray is a reexport of a compatible ndarray)

@jondoesntgit
Copy link
Author

Is there a plan to reintroduce support in future versions?

@davidhewitt
Copy link
Member

Follow progress in #439

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants