Certainly! Below is an example of how you can achieve this using pyo3 v0.25 and rust-numpy v0.25. The Rust code will accept a 2D NumPy array with any dtype and memory layout, convert it to a C-contiguous f64 array, and then return the sum of all the elements.
Rust Code (Cargo.toml)
First, ensure your Cargo.toml includes the necessary dependencies:
[package]
name = "numpy_example"
version = "0.1.0"
edition = "2021"
[dependencies]
pyo3 = { version = "0.25", features = ["extension-module"] }
numpy = "0.25"
[lib]
crate-type = ["cdylib"]
Rust Code (lib.rs)
Here is the Rust code that defines the conversion and the sum function:
use pyo3::prelude::*;
use pyo3::types::PyModule;
use numpy::{PyArray2, PyReadonlyArray2, IntoPyArray, Element, ToPyArray};
use ndarray::{ArrayView2, Array2};
/// Converts a 2D NumPy array of any dtype and memory layout to a C-contiguous f64 array.
fn convert_to_f64_c_contiguous(array: PyReadonlyArray2<'_, Element>) -> PyResult<Py<PyArray2<f64>>> {
// Get a view of the input array
let view: ArrayView2<'_, Element> = array.as_array();
// Create a new C-contiguous f64 array with the same shape
let mut f64_array = Array2::<f64>::zeros(view.raw_dim());
// Iterate over the input array and convert each element to f64
for ((i, j), value) in view.indexed_iter() {
let f64_value: f64 = value.extract().map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
f64_array[[i, j]] = f64_value;
}
// Convert the ndarray Array2 to a PyArray2 and ensure it is C-contiguous
let py_array = f64_array.into_pyarray_bound(array.py()).to_owned().into_py(array.py());
let c_contiguous_array = PyArray2::from_owned_array(array.py(), f64_array.view().into_dimensionality(), f64_array.as_slice().unwrap())
.map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
Ok(c_contiguous_array.into())
}
/// Returns the sum of all elements in a 2D NumPy array.
#[pyfunction]
fn sum_2d_array(array: PyReadonlyArray2<'_, Element>) -> PyResult<f64> {
// Convert the input array to a C-contiguous f64 array
let c_contiguous_array = convert_to_f64_c_contiguous(array)?;
let c_contiguous_array = c_contiguous_array.as_ref(array.py());
// Sum all elements in the array
let sum: f64 = c_contiguous_array.as_array().iter().sum();
Ok(sum)
}
/// This module is a python module implemented in Rust.
#[pymodule]
fn numpy_example(py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_2d_array, m)?)?;
Ok(())
}
Python Code
Here is an example Python script that uses the Rust function:
import numpy as np
import numpy_example
# Create a 2D NumPy array with any dtype and memory layout
array = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
# array = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]], dtype=np.float32, order='F') # You can test with different dtypes and layouts
# Call the Rust function and print the result
result = numpy_example.sum_2d_array(array)
print(f"Sum of all elements: {result}")
Explanation
-
Dependencies:
pyo3 = { version = "0.25", features = ["extension-module"] } for creating Python bindings.
numpy = "0.25" for handling NumPy arrays in Rust.
-
convert_to_f64_c_contiguous Function:
- Accepts a
PyReadonlyArray2<'_, Element>, which can handle any NumPy array dtype.
- Converts each element to
f64 and stores it in a new Array2::<f64>.
- Converts the
Array2 to a PyArray2<f64> and ensures it is C-contiguous using PyArray2::from_owned_array
-
sum_2d_array Function:
- Calls
convert_to_f64_c_contiguous to get a C-contiguous f64 array.
- Sums all elements in the array and returns the result.
-
Python Script:
- Creates a 2D NumPy array.
- Calls the
sum_2d_array function from the Rust module and prints the result.
This setup ensures that the Rust code can handle any 2D NumPy array, regardless of its dtype or memory layout, and correctly convert it to a C-contiguous f64 array before summing its elements.