lichtung-plot-ndarray 0.2.0

Direct scientific plotting from logical ndarray views and columns
Documentation
use ndarray::array;

use crate::{kind, scales::AlphaValues, AdapterError, NumericValues, Plot, Raincloud};

fn render<K: kind::Marker>(plot: &Plot<K>, case: &str) -> String {
    let path = std::env::temp_dir().join(format!(
        "lichtung-ndarray-geometry-{}-{case}.svg",
        std::process::id()
    ));
    plot.svg_preserve_text(&path).unwrap();
    let text = std::fs::read_to_string(&path).unwrap();
    std::fs::remove_file(path).unwrap();
    text
}

#[test]
fn supplied_histogram_components_have_independent_lookup_and_dimensions() {
    use crate::{stats::HistogramStat, Histogram};
    let bins = array![[0., 1., 0.25], [1., 3., 0.25], [3., 4., 0.25]];
    let curve = array![[0., 0.1], [1., 0.2], [2., 0.4], [3., 0.2], [4., 0.1]];
    let obs = array![[0.5, 0., 0.05], [3.5, 0., 0.05]];
    let bins_only =
        Histogram::geometry_from_data(bins.view(), 0, 1, 2, HistogramStat::Density).unwrap();
    assert_eq!(
        bins_only.get_geometry().unwrap().get_value_dimension(),
        "value"
    );
    assert_eq!(
        bins_only.get_geometry().unwrap().get_height_dimension(),
        "Column 3"
    );
    assert!(matches!(
        bins_only.clone().kde_from_data(curve.view(), 0, 2),
        Err(AdapterError::Column { index: 2, .. })
    ));
    assert!(matches!(
        bins_only.clone().kde(0, 1),
        Err(AdapterError::MissingSource { .. })
    ));
    let plot = bins_only
        .kde_from_data(curve.view(), 0, 1)
        .unwrap()
        .rug_from_data(obs.view(), 0, 1, 2)
        .unwrap()
        .height_dimension("height")
        .unwrap();
    drop(curve);
    drop(obs);
    let geometry = plot.get_geometry().unwrap();
    let bin_values = geometry.get_bins();
    let bin_source = bin_values.bin_lower().get_source().reference();
    assert_eq!(bin_source, bin_values.bin_upper().get_source().reference());
    assert_eq!(bin_source, bin_values.bin_height().get_source().reference());
    assert_eq!(
        bin_values.bin_height().get_source().selected_indices(),
        Some(&[2][..])
    );
    let (curve_x, curve_density) = geometry.get_kde().unwrap().get_precomputed().unwrap();
    let curve_source = curve_x.get_source().reference();
    assert_eq!(curve_source, curve_density.get_source().reference());
    assert!(!bin_source.same_source(curve_source));
    let rug = geometry.get_rug().unwrap();
    assert_eq!(
        rug.rug_x().get_source().reference(),
        rug.rug_top().get_source().reference()
    );
    assert!(!curve_source.same_source(rug.rug_x().get_source().reference()));
    assert_eq!(geometry.get_value_dimension(), "Column 1");
    assert_eq!(geometry.get_height_dimension(), "height");
    assert_eq!(curve_x.len(), 5);
    assert_eq!(geometry.get_rug().unwrap().rug_x().get(1), Some(Some(3.5)));
    let edited = plot
        .clone()
        .kde(array![0., 4.].view(), array![0.2, 0.2].view())
        .unwrap();
    let replaced = edited.get_geometry().unwrap();
    assert_eq!(replaced.get_bins(), geometry.get_bins());
    assert_eq!(replaced.get_rug(), geometry.get_rug());
    assert_eq!(
        replaced
            .get_kde()
            .unwrap()
            .get_precomputed()
            .unwrap()
            .0
            .len(),
        2
    );
    assert_eq!(replaced.get_height_dimension(), "height");
    drop(edited);
    let native: Plot<kind::Histogram> = plot.into();
    drop(bins);
    native.preflight().unwrap();
    assert!(render(&native, "histogram-supplied").contains("Height"));

    let direct = Histogram::geometry(
        array![0.].view(),
        array![1.].view(),
        array![2.].view(),
        HistogramStat::Count,
    )
    .unwrap()
    .rug(array![0.5].view(), array![0.].view(), array![0.1].view())
    .unwrap();
    assert_eq!(
        direct.get_geometry().unwrap().get_value_dimension(),
        "value"
    );
    assert_eq!(
        direct.get_geometry().unwrap().get_height_dimension(),
        "count"
    );
    direct.preflight().unwrap();
}

#[test]
fn raincloud_geometry_uses_point_rows_for_alpha_but_only_summary_for_lookup() {
    let summary = array![["a", "one"], ["b", "one"]];
    let density = array![["b", "one"], ["a", "one"], ["b", "one"], ["a", "one"]];
    let points = array![[0., 0.25], [0.5, 0.5], [1., 0.75]];
    let adapted = Raincloud::geometry_with_hue_from_data(
        summary.view(),
        Some(&density.view()),
        Some(&points.view()),
        0,
        1,
        array![-1., -1.].view(),
        array![0., 0.].view(),
        array![1., 1.].view(),
        0,
        1,
        array![-2., -2., 2., 2.].view(),
        array![0.5, 0.5, 0.5, 0.5].view(),
        array!["b", "a", "b"].view(),
        array!["one", "one", "one"].view(),
        0,
        1,
        "category",
        "value",
        "cohort",
    )
    .unwrap();
    let geometry: crate::plots::RaincloudGeometry = adapted.stat_result().unwrap();
    assert!(geometry.get_profiles().is_none());
    assert_eq!(geometry.domains().len(), 3);
    assert_eq!(
        Raincloud::from_geometry(geometry.clone())
            .stat_result()
            .unwrap(),
        geometry
    );
    drop(density);
    drop(points);
    let alpha = array![0., 230., 128.];
    let adapted = adapted
        .point_alpha_linear(alpha.view(), (0., 255.), (0.0, 1.0))
        .unwrap();
    assert!(matches!(
        adapted.clone().point_alpha_linear(array![1., 2.].view(), (0., 255.), (0.0, 1.0)),
        Err(AdapterError::Native(crate::Error::Data(detail)))
            if matches!(detail.kind(), crate::errors::DiagnosticKind::ShapeMismatch { expected, actual }
                if expected == &[3] && actual == &[2])
    ));
    // The primary string table must not silently become the numeric points source.
    assert!(matches!(
        adapted
            .clone()
            .point_alpha_linear(0, (0., 255.), (0.0, 1.0)),
        Err(AdapterError::UnsupportedElement { .. })
    ));
    let adapted = adapted
        .line_alpha_keyed_map(
            [("category", 0), ("cohort", 1)],
            NumericValues::new("quality", [0.25, 0.75]),
            |values| AlphaValues::linear(values, (0., 1.), (80.0 / 255.0, 240.0 / 255.0)),
        )
        .unwrap()
        .fill_alpha(180.0 / 255.0)
        .unwrap();
    assert_hue_title_forwarding(&adapted);
    let native: Plot<kind::Raincloud> = adapted.labels(crate::formatting::Labels::raw()).into();
    drop(summary);
    native.preflight().unwrap();
    let svg = render(&native, "interleaved");
    assert!(svg.contains("category") && svg.contains("value") && svg.contains("cohort"));
}

fn assert_hue_title_forwarding(adapted: &Raincloud<'_>) {
    let style = crate::Theme::publication()
        .typography()
        .get_guides()
        .get_legend_title()
        .clone()
        .color(crate::Color::rgb(32, 81, 130))
        .unwrap();
    let layout =
        crate::text::TextLayout::default().fit(crate::text::TextFit::range(9., 9.).unwrap());
    let title = crate::Text::new("Custom cohort")
        .style(style.clone())
        .layout(layout.clone());
    let with_title = adapted.clone().hue_label(title);
    with_title.preflight().unwrap();
    let reference: Plot<kind::Raincloud> = adapted.clone().into();
    let cleared_style: Plot<kind::Raincloud> = with_title.clone().clear_hue_label_style().into();
    let cleared_layout: Plot<kind::Raincloud> = with_title.clear_hue_label_layout().into();
    let expected_style = reference
        .clone()
        .hue_label(crate::Text::new("Custom cohort").layout(layout));
    let expected_layout = reference.hue_label(crate::Text::new("Custom cohort").style(style));
    assert_eq!(
        render(&cleared_style, "cleared-style"),
        render(&expected_style, "expected-style")
    );
    assert_eq!(
        render(&cleared_layout, "cleared-layout"),
        render(&expected_layout, "expected-layout")
    );
}