I'm having issues with attempting to call functions from within other functions in pyo3 with rust.
When I try, and change the output type to a pyresult to get the functions to chain together, I just end up with a whole host of other errors and I was wondering if anyone knew what I need to do to make these functions work together in pyo3.
use ndarray;
use numpy::{IntoPyArray, PyArray1, PyArray2, PyArrayDyn, PyReadonlyArrayDyn, PyReadonlyArray1};
use pyo3::prelude::*;
/// Formats the sum of two numbers as string.
#[pyfunction]
fn generate_data() -> (Vec<f64>, Vec<f64>) {
let x_values = vec![0.01, 0.02, 0.05, 0.10, 0.20, 0.50, 1.00, 2.00, 5.00];
let y_values = vec![129867.0, 284533.0, 655220.0, 1469586.0, 3359871.0, 5820969.0, 13009337.0, 22875222.0, 43101398.0];
let x_values_f64: Vec<f64> = x_values.into_iter().map(|x| x as f64).collect();
let y_values_f64: Vec<f64> = y_values.into_iter().map(|y| y as f64).collect();
(x_values_f64, y_values_f64)
}
#[pyfunction]
fn calculate_mean(
values: PyReadonlyArrayDyn<f64>) -> f64 {
let values = values.as_array();
let n = values.len() as f64;
let values = values.iter().sum::<f64>() / n;
values
}
#[pyfunction]
fn calculate_slope(x_vals: PyReadonlyArrayDyn<f64>, y_vals: PyReadonlyArrayDyn<f64>) -> f64 {
let x_vals = x_vals.as_array();
let y_vals = y_vals.as_array();
let x_vals_n = x_vals.len() as f64;
// let x_vals_mean = x_vals.iter().sum::<f64>() / x_vals_n;
let y_vals_n = y_vals.len() as f64;
// let y_vals_mean = y_vals.iter().sum::<f64>() / y_vals_n;
let x_vals_mean = calculate_mean(x_vals);
let y_vals_mean = calculate_mean(y_vals);
let numerator = x_vals
.iter()
.zip(y_vals.iter())
.map(|(&xi, &yi)| (xi - x_vals_mean) * (yi - y_vals_mean))
.sum::<f64>();
let denominator = x_vals
.iter()
.map(|&xi| (xi - x_vals_mean).powi(2))
.sum::<f64>();
numerator / denominator
}
The error is:
error[E0308]: mismatched types
--> src/lib.rs:45:38
|
45 | let y_vals_mean = calculate_mean(y_vals);
| -------------- ^^^^^^ expected PyReadonlyArray<'_, f64, Dim<IxDynImpl>>, found ArrayBase<ViewRepr<&f64>, Dim<IxDynImpl>>
| |
| arguments to this function are incorrect
|
= note: expected struct PyReadonlyArray<'_, f64, Dim<IxDynImpl>>
found struct ArrayBase<ViewRepr<&f64>, Dim<IxDynImpl>>
I've tried changing types back and forth to a number of different options but end up with a list of different errors.