rust-numpy icon indicating copy to clipboard operation
rust-numpy copied to clipboard

Converting ndarray::Array2 into numpy::ndarray::Array2

Open jondoesntgit opened this issue 1 year ago • 3 comments

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

jondoesntgit avatar Oct 03 '24 13:10 jondoesntgit

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)

Icxolu avatar Oct 03 '24 16:10 Icxolu

Is there a plan to reintroduce support in future versions?

jondoesntgit avatar Oct 04 '24 00:10 jondoesntgit

Follow progress in #439

davidhewitt avatar Oct 04 '24 08:10 davidhewitt

This can be closed I believe

MatthieuDartiailh avatar Jan 07 '25 11:01 MatthieuDartiailh