crisol-core 1.2.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Scientific container readers: HDF5, NetCDF, and Zarr.
//!
//! ```
//! ```
//! # #[cfg(feature = "hdf5")]
//! let _ = crisol_core::data::read_hdf5("missing.h5");
//! ```
//! ```

use std::path::Path;

use super::column::Column;
use super::dataset::Dataset;
use super::source::DataError;

#[cfg(all(feature = "hdf5", feature = "threads"))]
/// Read the numeric datasets of an HDF5 file.
///
/// # Errors
/// When the file cannot be opened, a dataset is missing, or a rank is unsupported.
/// # Example
///
/// ```
/// # use crisol_core::data::read_hdf5;
/// let _ = read_hdf5("missing.h5");
/// ```
pub fn read_hdf5(path: impl AsRef<Path>) -> Result<Dataset, DataError> {
    let file = hdf5_pure::File::open(path.as_ref()).map_err(|error| DataError::Connector(error.to_string()))?;
    let names = file
        .root()
        .datasets()
        .map_err(|error| DataError::Connector(error.to_string()))?;
    let mut columns = Vec::new();
    for name in names {
        let dataset = file
            .dataset(&name)
            .map_err(|error| DataError::Connector(error.to_string()))?;
        let shape = dataset
            .shape()
            .map_err(|error| DataError::Connector(error.to_string()))?;
        let values = dataset
            .read_f64()
            .map_err(|error| DataError::Connector(error.to_string()))?;
        columns.extend(columns_from_flat(&name, &shape, values)?);
    }
    if columns.is_empty() {
        return Err(DataError::Unsupported(
            "the HDF5 file has no numeric datasets".to_owned(),
        ));
    }
    Ok(Dataset::from_columns(columns))
}

#[cfg(all(feature = "netcdf", feature = "threads"))]
/// Read the numeric variables of a NetCDF file.
///
/// # Errors
/// When the file cannot be opened or a variable has an unsupported rank.
/// # Example
///
/// ```
/// # use crisol_core::data::read_netcdf;
/// let _ = read_netcdf("missing.nc");
/// ```
pub fn read_netcdf(path: impl AsRef<Path>) -> Result<Dataset, DataError> {
    let file = netcdf_reader::NcFile::open(path.as_ref()).map_err(|error| DataError::Connector(error.to_string()))?;
    let variables = file
        .variables()
        .map_err(|error| DataError::Connector(error.to_string()))?;
    let mut columns = Vec::new();
    for variable in variables {
        let name = variable.name();
        let shape = variable.shape().to_vec();
        let values = file
            .read_variable_as_f64(name)
            .map_err(|error| DataError::Connector(error.to_string()))?;
        let values = values.iter().copied().collect::<Vec<_>>();
        columns.extend(columns_from_flat(name, &shape, values)?);
    }
    if columns.is_empty() {
        return Err(DataError::Unsupported(
            "the NetCDF file has no numeric variables".to_owned(),
        ));
    }
    Ok(Dataset::from_columns(columns))
}

#[cfg(all(feature = "zarr", feature = "threads"))]
/// Read a Zarr v2 array directory.
///
/// Supports C-order `<f8`, `<f4`, `<i8`, and `<i4` arrays with no compressor.
///
/// # Errors
/// When the metadata or a chunk is invalid, or the array has an unsupported rank.
/// # Example
///
/// ```
/// use crisol_core::data::read_zarr;
/// let _ = read_zarr("missing.zarr");
/// ```
pub fn read_zarr(path: impl AsRef<Path>) -> Result<Dataset, DataError> {
    let path = path.as_ref();
    let metadata = read_text(&path.join(".zarray"))?;
    let value: serde_json::Value =
        serde_json::from_str(&metadata).map_err(|error| DataError::Connector(error.to_string()))?;
    let shape = value
        .get("shape")
        .and_then(serde_json::Value::as_array)
        .ok_or_else(|| DataError::Unsupported("Zarr metadata has no shape".to_owned()))?
        .iter()
        .filter_map(serde_json::Value::as_u64)
        .collect::<Vec<_>>();
    let chunks = value
        .get("chunks")
        .and_then(serde_json::Value::as_array)
        .ok_or_else(|| DataError::Unsupported("Zarr metadata has no chunks".to_owned()))?
        .iter()
        .filter_map(serde_json::Value::as_u64)
        .collect::<Vec<_>>();
    let dtype = value
        .get("dtype")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| DataError::Unsupported("Zarr metadata has no dtype".to_owned()))?;
    if value.get("compressor").is_some_and(|compressor| !compressor.is_null()) {
        return Err(DataError::Unsupported(
            "compressed Zarr arrays are not supported".to_owned(),
        ));
    }
    let separator = value
        .get("dimension_separator")
        .and_then(serde_json::Value::as_str)
        .unwrap_or(".");
    if shape.len() != chunks.len() || !matches!(shape.len(), 1 | 2) {
        return Err(DataError::Unsupported(
            "only 1D and 2D Zarr arrays are supported".to_owned(),
        ));
    }
    let fill = value
        .get("fill_value")
        .and_then(serde_json::Value::as_f64)
        .unwrap_or(f64::NAN);
    let width_bytes = match dtype {
        "<f8" | "<i8" => 8,
        "<f4" | "<i4" => 4,
        other => {
            return Err(DataError::Unsupported(format!("unsupported Zarr dtype `{other}`")));
        }
    };
    let mut values = vec![fill; shape.iter().product::<u64>() as usize];
    let width = shape.last().copied().unwrap_or(1) as usize;
    let chunk_width = chunks.last().copied().unwrap_or(1) as usize;
    let rows = shape.first().copied().unwrap_or(1) as usize;
    let chunk_rows = chunks.first().copied().unwrap_or(1) as usize;
    let chunks_x = width.div_ceil(chunk_width);
    let chunks_y = if shape.len() == 1 { 1 } else { rows.div_ceil(chunk_rows) };
    for chunk_y in 0..chunks_y {
        for chunk_x in 0..chunks_x {
            let key = if shape.len() == 1 {
                chunk_x.to_string()
            } else {
                format!("{chunk_y}{separator}{chunk_x}")
            };
            let Some(bytes) = read_chunk(&path.join(key)) else {
                continue;
            };
            let start_x = chunk_x * chunk_width;
            let start_y = chunk_y * chunk_rows;
            let chunk_cols = chunk_width.min(width.saturating_sub(start_x));
            let chunk_lines = if shape.len() == 1 {
                1
            } else {
                chunk_rows.min(rows.saturating_sub(start_y))
            };
            for line in 0..chunk_lines {
                for column in 0..chunk_cols {
                    let offset = (line * chunk_width + column) * width_bytes;
                    let Some(bytes) = bytes.get(offset..offset + width_bytes) else {
                        continue;
                    };
                    let value = match dtype {
                        "<f8" => f64::from_le_bytes(bytes.try_into().unwrap_or([0; 8])),
                        "<f4" => f64::from(f32::from_le_bytes(bytes.try_into().unwrap_or([0; 4]))),
                        "<i8" => i64::from_le_bytes(bytes.try_into().unwrap_or([0; 8])) as f64,
                        "<i4" => i32::from_le_bytes(bytes.try_into().unwrap_or([0; 4])) as f64,
                        other => {
                            return Err(DataError::Unsupported(format!("unsupported Zarr dtype `{other}`")));
                        }
                    };
                    let row = start_y + line;
                    let column = start_x + column;
                    let index = if shape.len() == 1 { column } else { row * width + column };
                    if let Some(slot) = values.get_mut(index) {
                        *slot = value;
                    }
                }
            }
        }
    }
    Ok(Dataset::from_columns(columns_from_flat("zarr", &shape, values)?))
}

#[cfg(feature = "threads")]
fn read_text(path: &Path) -> Result<String, DataError> {
    std::fs::read_to_string(path).map_err(|error| DataError::Connector(error.to_string()))
}

#[cfg(feature = "threads")]
fn read_chunk(path: &Path) -> Option<Vec<u8>> {
    std::fs::read(path).ok()
}

/// Turn a row-major numeric block into columns. Rank 1 is one column; rank 2 is one
/// column per second axis; higher ranks are rejected.
fn columns_from_flat(name: &str, shape: &[u64], values: Vec<f64>) -> Result<Vec<Column>, DataError> {
    match shape {
        [_rows] => Ok(vec![Column::floats(name, values)]),
        [rows, width] => {
            let rows = *rows as usize;
            let width = *width as usize;
            if values.len() != rows * width {
                return Err(DataError::Connector(format!("{name}: shape does not match the data")));
            }
            Ok((0..width)
                .map(|column| {
                    let values = (0..rows)
                        .map(|row| values.get(row * width + column).copied().unwrap_or(f64::NAN))
                        .collect::<Vec<_>>();
                    Column::floats(format!("{name}[{column}]"), values)
                })
                .collect())
        }
        _ => Err(DataError::Unsupported(format!(
            "dataset `{name}` has rank {}; only 1D and 2D are supported",
            shape.len()
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn flat_blocks_become_one_or_many_columns() {
        let one = columns_from_flat("v", &[3], vec![1.0, 2.0, 3.0]).expect("1d");
        assert_eq!(one.len(), 1);
        let two = columns_from_flat("m", &[2, 3], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).expect("2d");
        assert_eq!(two.len(), 3);
        assert_eq!(two[1].name, "m[1]");
        assert!(columns_from_flat("bad", &[2], vec![]).is_ok());
        assert!(columns_from_flat("bad", &[1, 2, 3], vec![1.0]).is_err());
    }
}