pedalkernel_validate/
npy.rs1use ndarray::Array1;
42use ndarray_npy::{ReadNpyError, WriteNpyError};
43use std::path::Path;
44use thiserror::Error;
45
46#[derive(Error, Debug)]
47pub enum NpyError {
48 #[error("Failed to read NPY file: {0}")]
49 ReadError(#[from] ReadNpyError),
50 #[error("Failed to write NPY file: {0}")]
51 WriteError(#[from] WriteNpyError),
52 #[error("IO error: {0}")]
53 IoError(#[from] std::io::Error),
54}
55
56pub fn read_f64(path: impl AsRef<Path>) -> Result<Vec<f64>, NpyError> {
58 let arr: Array1<f64> = ndarray_npy::read_npy(path)?;
59 Ok(arr.to_vec())
60}
61
62pub fn write_f64(path: impl AsRef<Path>, data: &[f64]) -> Result<(), NpyError> {
64 let path = path.as_ref();
65
66 if let Some(parent) = path.parent() {
68 std::fs::create_dir_all(parent)?;
69 }
70
71 let arr = Array1::from_vec(data.to_vec());
72 ndarray_npy::write_npy(path, &arr)?;
73 Ok(())
74}
75
76pub fn exists(path: impl AsRef<Path>) -> bool {
78 path.as_ref().exists()
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84 use tempfile::NamedTempFile;
85
86 #[test]
87 fn roundtrip_f64_array() {
88 let data: Vec<f64> = (0..100).map(|i| i as f64 * 0.1).collect();
89
90 let tmpfile = NamedTempFile::new().unwrap();
91 let path = tmpfile.path().to_path_buf();
92
93 write_f64(&path, &data).unwrap();
95
96 let loaded = read_f64(&path).unwrap();
98
99 assert_eq!(data.len(), loaded.len());
100 for (a, b) in data.iter().zip(loaded.iter()) {
101 assert!((a - b).abs() < 1e-10);
102 }
103 }
104}