Created
May 13, 2024 23:08
-
-
Save valdo404/7b3263b7c6077d1cc653343e480a467d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn vec_to_numpy<>(py: Python, vec: Vec<ResultData>) -> PyResult<PyObject> { | |
let numpy: &PyAny = PyModule::import(py, "numpy")?; | |
let dtype: Py<PyList> = PyList::new(py, &vec![ | |
("day", "datetime64[D]"), | |
("h3_index", "S15"), ("sunrise", "datetime64[s]"), | |
("sunset", "datetime64[s]"), | |
("midnight", "datetime64[s]")]).into_py(py); | |
let length_py: Py<PyLong> = to_py_int(py, vec.len() as c_long)?; | |
let length_any_py: Py<PyAny> = length_py.into_any(); | |
let length: &PyAny = length_any_py.as_ref(py); | |
let dtype_as_py: &PyAny = dtype.as_ref(py); | |
let locals: Bound<PyDict> = [("np", numpy), ("size", length), ("dtype", dtype_as_py)].into_py_dict_bound(py); | |
const CODE: &str = r#" | |
empty_array = np.empty(size, dtype=dtype)"#; | |
py.run_bound(CODE, None, Some(&locals)).expect("It did not work"); | |
let np_array = locals.as_ref().get_item("empty_array")?; | |
for (i, ResultData { duration_days: duration_days, h3_index: h3_index, sunrise: sunrise, sunset: sunset, midnight: midnight }) in vec.iter().enumerate() { | |
let duration_days_py: &Py<PyAny> = &to_py_int(py, duration_days.clone() / (24*3600))?.into_any(); | |
let h3_index_py: &Py<PyAny> = &PyBytes::new_bound(py, h3_index).unbind().into_any(); | |
let sunrise_py: &Py<PyAny> = &to_py_int(py, sunrise.clone())?.into_any(); | |
let sunset_py: &Py<PyAny> = &to_py_int(py, sunset.clone())?.into_any(); | |
let midnight_py: &Py<PyAny> = &to_py_int(py, midnight.clone())?.into_any(); | |
let elements: Bound<PyTuple> = PyTuple::new_bound(py, [duration_days_py, h3_index_py, sunrise_py, sunset_py, midnight_py]); | |
let value = PyTuple::new_bound(py, elements); | |
let as_py_int = to_py_int(py, i as c_long)?.clone(); | |
np_array.call_method1("__setitem__", (as_py_int, value))?; | |
} | |
Ok(np_array.into()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment