lichtung-plot-ndarray 0.2.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 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().memory_limit_bytes(128 * 1024 * 1024),
        )
        .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]);
}