lichtung-plot-ndarray 0.3.0

Direct scientific plotting from logical ndarray views and columns
Documentation
use std::rc::Rc;

use ndarray::{array, Array2};

use crate::{formatting::Labels, kind, layout::FacetScales, AdapterError, Line, Plot, Scatter};

#[test]
fn single_and_grouped_line_path_constructors_bind_actual_rows() {
    let source = array![[0., 0.], [5., 5.], [1., 1.], [4., 4.], [0., 2.], [3., 3.]];
    let group = array!["A", "B", "A", "B", "A", "B"];
    let single = crate::LinePath::from_data(source.view(), 0, 1).unwrap();
    let grouped = crate::LinePath::grouped_from_data(source.view(), 0, 1, group.view()).unwrap();
    single.clone().show_markers(false).render().unwrap();
    grouped.render().unwrap();
    crate::LinePath::new(source.column(0), source.column(1))
        .unwrap()
        .preflight()
        .unwrap();
    crate::LinePath::grouped(source.column(0), source.column(1), group.view())
        .unwrap()
        .preflight()
        .unwrap();
    assert!(crate::LinePath::from_data(source.view(), 0, 1)
        .unwrap()
        .hue(group.view())
        .unwrap()
        .preflight()
        .is_ok());
}

#[test]
fn beeswarm_color_sources_bind_only_numeric_selections() {
    let values = array![[0., 10.], [1., 20.], [2., 30.]];
    let categories = array!["A", "A", "B"];
    let color = crate::Color::hex("#1D457980").unwrap();
    crate::Beeswarm::new(categories.view(), values.column(0))
        .unwrap()
        .render()
        .unwrap();
    let plain = crate::Beeswarm::from_data(values.view(), categories.view(), 0).unwrap();
    plain.clone().preflight().unwrap();
    crate::Beeswarm::colored(categories.view(), values.column(0), color)
        .unwrap()
        .render()
        .unwrap();
    crate::Beeswarm::colored_from_data(values.view(), categories.view(), 0, 1)
        .unwrap()
        .render()
        .unwrap();
    crate::Beeswarm::colored_from_data(values.view(), categories.view(), 0, color)
        .unwrap()
        .preflight()
        .unwrap();
    assert!(matches!(
        crate::Beeswarm::colored_from_data(values.view(), categories.view(), 0, 2),
        Err(AdapterError::Column { index: 2, .. })
    ));
    assert!(
        crate::Beeswarm::colored(categories.view(), values.column(0), array![0.].view()).is_err()
    );
}

#[test]
fn native_queries_preserve_source_lookup() {
    let source = array![["A", "left"], ["B", "right"]];
    let labels = Labels::raw().alias("x", "Time");
    let theme = crate::Theme::nature();
    let adapted = theme
        .with_context(|| {
            Scatter::from_data(source.view(), array![0., 1.].view(), array![1., 2.].view())
        })
        .unwrap()
        .labels(labels.clone())
        .theme(crate::Theme::science())
        .theme(None);
    assert!(adapted.get_theme().is_none());
    assert_eq!(adapted.get_default_theme(), Some(&theme));
    assert_eq!(adapted.get_labels(), &labels);
    assert!(adapted.get_facet().is_none());
    let page = crate::Canvas::grid(1, 2)
        .unwrap()
        .panel(0, 0, &adapted)
        .unwrap()
        .name_panel(0, 0, "overview")
        .unwrap()
        .reserve(0, 1, (160., 96.))
        .unwrap()
        .name_panel(0, 1, "detail")
        .unwrap()
        .panel_named("detail", adapted.clone())
        .unwrap();
    assert_eq!(
        page.data_roles_in(&crate::layout::PanelPath::root().panel_named("overview"))
            .unwrap()
            .len(),
        page.data_roles_in(&crate::layout::PanelPath::root().panel(0, 0))
            .unwrap()
            .len()
    );
    page.preflight().unwrap();
    let adapted = adapted.facet_column(0usize).unwrap();
    assert!(std::ptr::eq(
        adapted.get_facet().unwrap(),
        adapted.plot.get_facet().unwrap()
    ));
    let cancel = crate::operation::CancelToken::new();
    cancel.cancel();
    let options = crate::operation::OperationOptions::default().cancellation(cancel);
    assert!(matches!(
        adapted.preflight_with_operation(&options),
        Err(crate::Error::Cancelled)
    ));
    adapted.preflight().unwrap();
    assert!(matches!(
        adapted.clone().hue(2usize),
        Err(AdapterError::Column { index: 2, .. })
    ));
    let (plot, metadata) = adapted.into_parts();
    let adapted = crate::Theme::chi()
        .with_context(|| Scatter::from_parts_with_data(plot, metadata, source.view()))
        .unwrap();
    assert_eq!(adapted.get_default_theme(), Some(&theme));
    let adapted = adapted
        .size_with_unit(8.0, 6.0, crate::layout::SizeUnit::Inch)
        .unwrap()
        .hue(1usize)
        .unwrap();
    adapted.preflight().unwrap();
    let output: crate::Output = adapted
        .render_with_operation(
            &crate::operation::OperationOptions::default()
                .cancellation(crate::operation::CancelToken::new()),
        )
        .unwrap();
    assert_eq!((output.width(), output.height()), (768.0, 576.0));
    assert_eq!(
        output.physical_size().unwrap().unit(),
        crate::layout::SizeUnit::Inch
    );
}

#[test]
fn source_free_pair_outlives_source_and_restores_validated_lookup() {
    let (plot, metadata) = {
        let source = array![[0., 1.], [1., 0.]];
        let adapted = Scatter::from_data(source.view(), 0, 1).unwrap();
        let lookup = Rc::downgrade(adapted.source.as_ref().unwrap());
        let pair = adapted.into_parts();
        assert!(lookup.upgrade().is_none());
        pair
    };
    let restored = Scatter::from_parts(plot, metadata);
    assert!(matches!(
        restored.clone().hue(0usize),
        Err(AdapterError::MissingSource { role: "hue", .. })
    ));
    let groups = array!["a", "b"];
    assert!(restored.clone().hue(groups.view()).is_ok());
    let (plot, metadata) = restored.into_parts();

    let values = Array2::<f64>::zeros((2, 2));
    let wrong_validity = Array2::from_elem((1, 4), true);
    assert!(matches!(
        Scatter::from_parts_with_data(
            plot.clone(),
            metadata.clone(),
            (values.view(), wrong_validity.view()),
        ),
        Err(AdapterError::Shape { expected, actual, .. })
            if expected == [2, 2] && actual == [1, 4]
    ));

    // Source restoration itself does not impose the old observation count.
    let longer = array![["a"], ["b"], ["c"]];
    let restored =
        Scatter::from_parts_with_data(plot.clone(), metadata.clone(), longer.view()).unwrap();
    assert!(matches!(
        restored.hue(0usize),
        Err(AdapterError::Native(crate::Error::Data(_)))
    ));
    let lookup = array![["a"], ["b"]];
    let restored = Scatter::from_parts_with_data(plot, metadata, lookup.view())
        .unwrap()
        .hue(0usize)
        .unwrap();
    assert_eq!(restored.kind(), crate::plots::PlotKind::Scatter);
}

#[test]
fn restored_policy_caches_keep_replacements_and_native_validation() {
    let source = array![[0., 1., 4.], [5., 2., 5.], [20., 3., 6.]];
    let adapted = Line::from_data(source.view(), 0, [2, 1])
        .unwrap()
        .labels(Labels::humanized().alias("discarded", "Old"))
        .column_labels(["Old right", "Old left"])
        .unwrap()
        .facet_columns_row()
        .unwrap();
    let (plot, metadata) = adapted.into_parts();
    let adapted = Line::from_parts(plot, metadata)
        .facet_scales(FacetScales::FreeY)
        .unwrap()
        .labels(Labels::raw().alias("retained", "Kept"));
    let (plot, metadata) = adapted.into_parts();
    let replacement = array![Some("a"), None, Some("b")];
    let adapted = Line::from_parts(plot, metadata)
        .column_labels(["Right", "Left"])
        .unwrap()
        .facet_column(replacement.view())
        .unwrap();
    assert_eq!(
        adapted.bindings.labels,
        Labels::raw().alias("retained", "Kept").aliases([
            (crate::source::name(2), "Right"),
            (crate::source::name(1), "Left"),
        ])
    );
    let (plot, metadata) = adapted.into_parts();
    let adapted = Line::from_parts(plot, metadata)
        .facet_scales(FacetScales::FreeX)
        .unwrap();
    // Changing scales must keep the replacement facet, not resurrect the old
    // generated one. Nullable facet applicability remains a native error.
    let native: Plot<kind::Line> = adapted.into();
    assert!(
        matches!(native.preflight(), Err(crate::Error::Data(detail)) if detail.message().contains("facet") && detail.message().contains("null"))
    );
}

#[test]
fn original_data_roles_retain_adapter_lookup_and_own_values() {
    use crate::{
        data::{DataRole, MemberAddress},
        elements::LayerSlot,
    };
    let data = array![[1., 7., 3.], [2., 9., 4.]];
    let adapter = crate::Line::from_data(data.view(), 0usize, &[2usize, 1][..]).unwrap();
    let layer = adapter
        .read_element(&adapter.element_ref(LayerSlot::Primary).unwrap())
        .unwrap();
    let y = layer.values(DataRole::Y).unwrap();
    let x = adapter.data(DataRole::X).unwrap();
    assert_eq!(x.info().domain(), y.info().domain());
    assert_eq!(x.info().source(), y.info().source());
    assert_eq!(
        y.numeric().unwrap().iter().collect::<Vec<_>>(),
        vec![Some(3.), Some(7.), Some(4.), Some(9.)]
    );
    let entries = y.members(1usize).unwrap().unwrap();
    assert_eq!(
        entries.entries()[0].members().unwrap()[0].address(),
        &MemberAddress::Index(vec![0, 1])
    );
    let adapter = adapter.point_alpha(0.5).unwrap();
    assert!(adapter.data(DataRole::PointAlpha).is_err());
    let adapter = adapter.hue(0usize);
    // Numeric arrays cannot implicitly supply a string hue.
    assert!(adapter.is_err());
    drop(adapter);
    drop(data);
    assert_eq!(layer.numeric(DataRole::Y).unwrap().get(3), Some(Some(9.)));
}

#[test]
fn histogram_result_preserves_bound_source_and_native_result_identity() {
    use crate::{
        data::{DataPayload, DataRole},
        plots::HistogramResult,
        stats::{BinField, HistogramBins, ScientificResult},
    };
    let source = array![[0.], [0.5], [3.]];
    let plot = crate::Histogram::from_data(source.view(), 0).unwrap();
    let plot = plot.bins(HistogramBins::Count(3));
    let actual = plot.data(DataRole::Samples).unwrap();
    let result: HistogramResult = plot.stat_result().unwrap();
    let DataPayload::Integer(counts) = result.bins().values(BinField::Count).unwrap() else {
        panic!("exact count")
    };
    assert_eq!(counts.len(), 3);
    let members = result.bins().get_members(BinField::Count).unwrap()[0]
        .as_ref()
        .unwrap();
    assert_eq!(
        members.entries()[0].source().reference(),
        actual.info().source().unwrap()
    );
    let run = plot.render_with_results().unwrap();
    assert!(matches!(
        run.results()[0].value(),
        ScientificResult::Histogram(_)
    ));
    let supplied = crate::Histogram::from_geometry(result.geometry().clone());
    let replay = supplied.stat_result().unwrap();
    assert_eq!(replay.geometry(), result.geometry());
    assert!(replay.denominator().is_none());
}

#[test]
fn native_density_probability_and_fit_results_forward_exact_types() {
    let x = array![1., 2., 3.];
    let y = array![1., 2., 4.];
    let density: crate::plots::DensityResult = crate::Density::new(x.view())
        .unwrap()
        .stat_result()
        .unwrap();
    let qq: crate::plots::ProbabilityPlotResult =
        crate::Qq::new(y.view()).unwrap().stat_result().unwrap();
    let fit: crate::stats::FitResult = crate::Regression::new(x.view(), y.view())
        .unwrap()
        .stat_result()
        .unwrap();
    assert!(density.bandwidth().is_some());
    assert_eq!(qq.observed().len(), 3);
    assert_eq!(fit.groups()[0].observations().original_slots(), &[0, 1, 2]);
}

#[test]
fn adapter_composition_accepts_the_native_source_directly() {
    use crate::composition::{compose, ImageAsset, Placement};
    let data = array![[0., 2.], [1., 3.], [2., 1.]];
    let plot = Scatter::from_data(data.view(), 0usize, 1usize)
        .unwrap()
        .size(600, 420);
    let badge = ImageAsset::from_svg_bytes(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="green"/></svg>"#).unwrap();
    let composite = plot
        .compose([Placement::at(&badge, (0., 0.)).unwrap()])
        .unwrap();
    assert_eq!((composite.width(), composite.height()), (600., 420.));
    let nested = compose(&badge, [Placement::at(&plot, (0., 0.)).unwrap()]).unwrap();
    assert!(nested.output().layout_report().is_err());
    let viewport = composite.layout_report().unwrap().viewport();
    assert_eq!((viewport.width(), viewport.height()), (600., 420.));
    assert_eq!((nested.width(), nested.height()), (20., 10.));
    assert!(plot.get_theme().is_none());
}

#[test]
fn adapter_publication_retains_source_and_uses_the_native_stream_and_pixels() {
    use crate::output::{Format, PixelOptions, PixelTarget, PngSizing};
    let data = array![["A"], ["B"], ["A"]];
    let x = array![0., 1., 2.];
    let y = array![2., 3., 1.];
    let plot = Scatter::from_data(data.view(), x.view(), y.view())
        .unwrap()
        .size(600, 420);
    let svg = plot.encode(Format::svg()).unwrap();
    let mut stream = Vec::new();
    plot.write_to(&mut stream, Format::svg()).unwrap();
    assert_eq!(svg.as_ref(), &stream);
    let pixels = plot
        .pixels_with_options(PixelOptions::default().sizing(PngSizing::Width(60)))
        .unwrap();
    assert_eq!((pixels.width(), pixels.height()), (60, 42));
    let mut storage = vec![0; pixels.as_bytes().len()];
    plot.pixels_into(PixelTarget::rgba8(&mut storage, 60, 42, 240).unwrap())
        .unwrap();
    assert_eq!(storage, pixels.as_bytes());
    let region =
        crate::output::ExportRegion::rect(crate::layout::Rect::new(10., 20., 60., 42.).unwrap())
            .pad(crate::layout::Insets::all(
                crate::layout::Length::px(2.).unwrap(),
            ));
    let options = PixelOptions::default()
        .region(region.clone())
        .transparent(true);
    let cropped = plot.pixels_with_options(options.clone()).unwrap();
    assert_eq!((cropped.width(), cropped.height()), (64, 46));
    let mut destination = vec![19; cropped.as_bytes().len()];
    plot.pixels_into_with_options(
        PixelTarget::rgba8(&mut destination, 64, 46, 256).unwrap(),
        options,
    )
    .unwrap();
    assert_eq!(destination, cropped.as_bytes());
    let format = Format::png()
        .region(region)
        .sizing(PngSizing::Source)
        .transparent(true);
    let bytes = plot.encode(format.clone()).unwrap();
    let mut stream = Vec::new();
    plot.write_to(&mut stream, format).unwrap();
    assert_eq!(&*bytes, &stream);
    plot.hue(0usize).unwrap().preflight().unwrap();
}