lichtung-plot-ndarray 0.3.0

Direct scientific plotting from logical ndarray views and columns
Documentation
//! The core's lazy recipe input bridge uses the same logical ndarray slots
//! and explicit validity as the ordinary adapter.

use ndarray::{ArrayView1, ArrayView2, Axis};

use crate::{
    binding::ArrayElement,
    data::RawKeyValues,
    recipe::{BindingColumnType, BindingField, BindingInput, BindingObject},
    Error, Result,
};

/// Inferred marker for the ndarray source protocol.
#[doc(hidden)]
pub struct NdarrayBinding;

fn native_error(error: crate::AdapterError) -> Error {
    match error {
        crate::AdapterError::Native(error) => error,
        error => Error::Data(error.to_string().into()),
    }
}

fn vector<'a, T: ArrayElement>(
    view: ArrayView1<'_, T>,
    validity: Option<ArrayView1<'_, bool>>,
    name: &str,
) -> Result<BindingObject<'a>> {
    let dtype = if T::NUMERIC {
        BindingColumnType::Numeric
    } else if T::CATEGORY {
        BindingColumnType::Category
    } else {
        BindingColumnType::Boolean
    };
    let values = crate::snapshot::values(view, validity, ArrayElement::recipe_key, "recipe values")
        .map_err(native_error)?;
    Ok(BindingObject::typed_keys(
        RawKeyValues::nullable(name, values)?,
        dtype,
    ))
}

fn table<'a, T: ArrayElement>(
    view: ArrayView2<'a, T>,
    validity: Option<ArrayView2<'a, bool>>,
) -> Result<BindingObject<'a>> {
    if validity
        .as_ref()
        .is_some_and(|validity| validity.shape() != view.shape())
    {
        return Err(Error::Data(
            "recipe ndarray validity must match its actual shape".into(),
        ));
    }
    let (rows, columns) = view.dim();
    let mut fields = Vec::new();
    for index in 0..columns {
        let name = crate::source::name(index);
        let column = view.index_axis_move(Axis(1), index);
        let present = validity.map(|present| present.index_axis_move(Axis(1), index));
        let value = BindingObject::deferred({
            let name = name.clone();
            move || {
                vector(
                    column.view(),
                    present.as_ref().map(|mask| mask.view()),
                    &name,
                )
            }
        });
        fields.push(BindingField::new(None, name, T::NUMERIC, value));
    }
    Ok(BindingObject::table(rows, fields))
}

impl<T: ArrayElement> BindingInput<NdarrayBinding> for ArrayView1<'_, T> {
    fn binding_object(&self) -> Result<BindingObject<'_>> {
        vector(self.view(), None, "value")
    }
}
impl<T: ArrayElement> BindingInput<NdarrayBinding> for (ArrayView1<'_, T>, ArrayView1<'_, bool>) {
    fn binding_object(&self) -> Result<BindingObject<'_>> {
        vector(self.0.view(), Some(self.1.view()), "value")
    }
}
impl<T: ArrayElement> BindingInput<NdarrayBinding> for ArrayView2<'_, T> {
    fn binding_object(&self) -> Result<BindingObject<'_>> {
        table(self.view(), None)
    }
}
impl<T: ArrayElement> BindingInput<NdarrayBinding> for (ArrayView2<'_, T>, ArrayView2<'_, bool>) {
    fn binding_object(&self) -> Result<BindingObject<'_>> {
        table(self.0.view(), Some(self.1.view()))
    }
}

impl<K: crate::kind::Marker> BindingInput<NdarrayBinding> for &crate::frontend::PlotAdapter<'_, K> {
    fn binding_object(&self) -> Result<BindingObject<'_>> {
        Ok(BindingObject::content((*self).into()))
    }
}
impl<K: crate::kind::Marker> BindingInput<NdarrayBinding> for crate::frontend::PlotAdapter<'_, K> {
    fn binding_object(&self) -> Result<BindingObject<'_>> {
        Ok(BindingObject::content(self.into()))
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        data::DataRole,
        recipe::{Bindings, RecipeFigure},
        Line,
    };
    use ndarray::{array, s};

    #[test]
    fn style_application_keeps_the_adapter_lookup_context() {
        use crate::{recipe::PlotRecipeScope, Theme};
        let january = array![[0_i64, 20], [1, 21]];
        let february = array![[4_i64, 24, 101], [5, 26, 102]];
        let source = Line::from_data(january.view(), 0, 1).unwrap();
        let target = Line::from_data(february.view(), 0, 1).unwrap();
        let id = 2;
        let style = source
            .theme(Theme::nature())
            .get_recipe_with_scope(PlotRecipeScope::Style)
            .unwrap();
        let updated = target
            .default_theme(Theme::chi())
            .apply_style(&style)
            .unwrap()
            .source_rows(id)
            .unwrap();
        assert_eq!(updated.get_theme(), Some(&Theme::nature()));
        assert_eq!(updated.get_default_theme(), Some(&Theme::chi()));
        assert_eq!(
            updated
                .data(DataRole::Y)
                .unwrap()
                .numeric()
                .unwrap()
                .iter()
                .collect::<Vec<_>>(),
            [Some(24.), Some(26.)]
        );
        let recipe = updated.get_recipe().unwrap();
        assert_eq!(recipe.bindings().len(), 1);
        assert!(recipe.bindings()[0]
            .requirements()
            .iter()
            .any(|role| role.role() == "plot.source_rows"));
    }

    #[test]
    fn borrowed_ndarray_recipe_arguments_select_logical_positions_and_preserve_masks() {
        let original = array![[0., 20.], [2., 23.]];
        let recipe = Line::from_data(original.view(), 0, 1)
            .unwrap()
            .get_recipe()
            .unwrap();
        assert_eq!(recipe.bindings()[0].name(), "data");
        let replacement = array![[0., 21.], [1., 22.], [2., 24.]];
        let valid = array![[true, true], [true, false], [true, true]];
        let view = replacement.slice(s![..;-1,..]);
        let mask = valid.slice(s![..;-1,..]);
        let RecipeFigure::Line(plot) = recipe.build_with([("data", (view, mask))]).unwrap() else {
            panic!("Line")
        };
        let values = plot.data(DataRole::Y).unwrap().numeric().unwrap();
        assert_eq!(
            values.iter().collect::<Vec<_>>(),
            [Some(24.), None, Some(21.)]
        );
        assert_eq!(
            values.get_source().selector(),
            Some(&crate::data::BindingSelector::Index(1))
        );
        let direct = Line::new(original.column(0), original.column(1))
            .unwrap()
            .get_recipe()
            .unwrap();
        let registry = Bindings::new()
            .bind("x", replacement.column(0))
            .unwrap()
            .bind("y", replacement.column(1))
            .unwrap();
        assert!(direct.build_with(&registry).is_ok());
    }
    #[test]
    fn wide_recipe_preserves_ordered_rectangles_and_actual_row_coordinates() {
        use crate::data::{BindingGeneration, BindingSelector, RawKey};
        use lichtung_plot::output::{PngOptions, PngSizing};
        let original = array![
            [0., 2., 4., 1., 3., 3., 5.],
            [5., 3., 5., 2., 4., 4., 6.],
            [20., 4., 6., 3., 5., 5., 7.]
        ];
        let plot = Line::from_data(original.view(), 0, [2, 1])
            .unwrap()
            .band([4, 3], [6, 5])
            .unwrap();
        let recipe = plot.get_recipe().unwrap();
        assert_eq!(recipe.bindings().len(), 1);
        let binding = &recipe.bindings()[0];
        let y = binding
            .requirements()
            .iter()
            .find(|r| r.role() == "plot.input.wide.y")
            .unwrap();
        assert_eq!(y.selector(), &BindingSelector::Indices(vec![2, 1]));
        assert_eq!(y.shape(), ["plot.rows", "plot.columns"]);
        let x = binding
            .requirements()
            .iter()
            .find(|r| r.role() == "plot.input.wide.x")
            .unwrap();
        assert_eq!(x.shape(), ["plot.rows"]);
        let RecipeFigure::Line(built) = recipe.build_with([("data", original.view())]).unwrap()
        else {
            panic!("Line")
        };
        assert_eq!(
            built
                .data(DataRole::X)
                .unwrap()
                .numeric()
                .unwrap()
                .iter()
                .collect::<Vec<_>>(),
            [Some(0.), Some(0.), Some(5.), Some(5.), Some(20.), Some(20.)]
        );
        let values = built.data(DataRole::Y).unwrap().numeric().unwrap();
        assert_eq!(
            values.iter().collect::<Vec<_>>(),
            [Some(4.), Some(2.), Some(5.), Some(3.), Some(6.), Some(4.)]
        );
        assert_eq!(
            values.get_source().generation(),
            Some(BindingGeneration::WideExpansion)
        );
        let hue = built.data(DataRole::Hue).unwrap();
        let crate::data::DataPayload::RawKeys(identities) = hue.value() else {
            panic!("raw generated keys")
        };
        assert_eq!(identities.levels(), [RawKey::from(2), RawKey::from(1)]);
        let options = PngOptions {
            sizing: PngSizing::Source,
            ..PngOptions::default()
        };
        assert_eq!(
            built.encode(options).unwrap(),
            plot.encode(options).unwrap()
        );
        assert_eq!(built.get_recipe().unwrap().bindings().len(), 1);
    }
    #[test]
    fn heatmap_recipe_keeps_shape_and_original_positional_keys() {
        use crate::{data::RawKey, Heatmap};
        let data = array![[1., 3., 5.], [2., 4., 6.]];
        let cells = data.slice(s![.., ..;-1]);
        let highlights = array![[false, true, false], [true, false, true]];
        let ids = array![[11_u64, 12, 13], [21, 22, 23]];
        let plot = Heatmap::new(cells)
            .unwrap()
            .x_labels(["C", "B", "A"])
            .unwrap()
            .y_labels(["Top", "Bottom"])
            .unwrap()
            .highlight_cells(highlights.view())
            .unwrap()
            .source_rows_cells(ids.view())
            .unwrap()
            .size(900, 650);
        let recipe = plot.get_recipe().unwrap();
        let registry = Bindings::new()
            .bind("fill", cells)
            .unwrap()
            .bind("highlight_cells", highlights.view())
            .unwrap()
            .bind("source_rows", ids.view())
            .unwrap();
        let RecipeFigure::Heatmap(built) = recipe.build_with(&registry).unwrap() else {
            panic!("heatmap")
        };
        let values = built.data(DataRole::X).unwrap();
        let crate::data::DataPayload::RawKeys(values) = values.value() else {
            panic!("grid keys")
        };
        assert_eq!(
            values.iter().flatten().cloned().collect::<Vec<_>>(),
            [0_usize, 1, 2, 0, 1, 2].map(RawKey::from)
        );
        assert_eq!(
            built
                .render()
                .unwrap()
                .encode(lichtung_plot::output::Format::png())
                .unwrap(),
            plot.render()
                .unwrap()
                .encode(lichtung_plot::output::Format::png())
                .unwrap()
        );
        let wrong = Bindings::new()
            .bind("fill", cells)
            .unwrap()
            .bind("highlight_cells", highlights.t())
            .unwrap()
            .bind("source_rows", ids.view())
            .unwrap();
        assert!(recipe.build_with(&wrong).is_err());
    }
}