lichtung-plot-ndarray 0.3.0

Direct scientific plotting from logical ndarray views and columns
Documentation
//! Independent column domains; scientific validation and grouping stay native.

use super::{context, Context, PlotAdapter};
use crate::capture::Capture;
use crate::error::{length, BindingResult};
use crate::{
    binding::{ArraySource, CategoryInput, NumericInput},
    kind,
    plots::{
        HistogramComposite, HistogramGeometry, HistogramInput, HistogramKde, RaincloudGeometry,
        RaincloudInput,
    },
    stats::HistogramStat,
    AdapterError, Plot,
};

// Each domain has its own selector context and length. Only the main context is
// moved into the frontend; auxiliary borrows end after these snapshots.
macro_rules! columnar_geometry {
    ($family:ident, $direct:ident, $from:ident, $bind:ident,
        ($first:ident: $input:ident => $method:ident $(, $arg:ident: $arg_input:ident => $arg_method:ident)*),
        ($(($aux:ident => $head:ident: $head_input:ident => $head_method:ident $(, $tail:ident: $tail_input:ident => $tail_method:ident)*)),+),
        ($($dimension:ident),+), $points:expr, $plot:expr) => {
        impl<'source> PlotAdapter<'source, kind::$family> {
            /// Snapshot complete geometry from direct columns in main/auxiliary
            /// domain order, followed by scientific dimension names.
            #[expect(clippy::too_many_arguments, reason = "complete columnar geometry keeps every scientific role explicit")]
            pub fn $direct(
                $first: impl $input, $($arg: impl $arg_input,)*
                $($head: impl $head_input, $($tail: impl $tail_input,)*)+
                $($dimension: impl Into<String>),+
            ) -> std::result::Result<Self, AdapterError> {
                $(let $aux = None;)+
                Self::$bind(None, $($aux,)+ $first, $($arg,)* $($head, $($tail,)*)+ $($dimension),+)
            }

            /// Snapshot independently selected/direct component columns. The main
            /// source is retained; each optional auxiliary source is used only
            /// for its own domain, with no cross-domain selector fallback.
            #[expect(clippy::too_many_arguments, reason = "independent sources precede explicit complete geometry roles")]
            pub fn $from(
                source: impl ArraySource + 'source, $($aux: Option<&dyn ArraySource>,)+
                $first: impl $input, $($arg: impl $arg_input,)*
                $($head: impl $head_input, $($tail: impl $tail_input,)*)+
                $($dimension: impl Into<String>),+
            ) -> std::result::Result<Self, AdapterError> {
                Self::$bind(context(source)?, $($aux,)+ $first, $($arg,)* $($head, $($tail,)*)+ $($dimension),+)
            }

            #[expect(clippy::too_many_arguments, reason = "private extraction mirrors the public complete geometry roles")]
            fn $bind(
                source: Context<'source>, $($aux: Option<&dyn ArraySource>,)+
                $first: impl $input, $($arg: impl $arg_input,)*
                $($head: impl $head_input, $($tail: impl $tail_input,)*)+
                $($dimension: impl Into<String>),+
            ) -> BindingResult<Self> {
                $(if let Some(aux) = $aux { aux.validate()?; })+
                let capture = Capture::new(source.as_deref());
                let $first = capture.bind($first, 1, |input, source| input.$method(source, stringify!($first)))?;
                let len = $first.len();
                $(let $arg = capture.bind($arg, 1, |input, source| input.$arg_method(source, stringify!($arg)))?;
                length(stringify!($arg), $arg.name(), len, $arg.len())?;)*
                $(let auxiliary = Capture::new($aux);
                let $head = auxiliary.bind($head, 1, |input, source| input.$head_method(source, stringify!($head)))?;
                let len = $head.len();
                $(let $tail = auxiliary.bind($tail, 1, |input, source| input.$tail_method(source, stringify!($tail)))?;
                length(stringify!($tail), $tail.name(), len, $tail.len())?;)*)+
                let points = $points;
                let reference = capture.reference();
                let mut adapter = Self::bound($plot, source, None, reference);
                adapter.bindings.geometry_points = points;
                Ok(adapter)
            }
        }
    };
}

impl<'source> PlotAdapter<'source, kind::Histogram> {
    /// Snapshot supplied bin edges and heights, with their declared statistic.
    pub fn geometry(
        lower: impl NumericInput,
        upper: impl NumericInput,
        height: impl NumericInput,
        stat: HistogramStat,
    ) -> std::result::Result<Self, AdapterError> {
        Self::bind_geometry(None, lower, upper, height, stat)
    }

    /// Snapshot the selected bin columns and retain only their main lookup context.
    pub fn geometry_from_data(
        source: impl ArraySource + 'source,
        lower: impl NumericInput,
        upper: impl NumericInput,
        height: impl NumericInput,
        stat: HistogramStat,
    ) -> std::result::Result<Self, AdapterError> {
        Self::bind_geometry(context(source)?, lower, upper, height, stat)
    }

    fn bind_geometry(
        source: Context<'source>,
        lower: impl NumericInput,
        upper: impl NumericInput,
        height: impl NumericInput,
        stat: HistogramStat,
    ) -> BindingResult<Self> {
        let capture = Capture::new(source.as_deref());
        let lower = capture.bind(lower, 1, |input, source| {
            input.bind_numeric(source, "bin_lower")
        })?;
        let upper = capture.bind(upper, 1, |input, source| {
            input.bind_numeric(source, "bin_upper")
        })?;
        let height = capture.bind(height, 1, |input, source| {
            input.bind_numeric(source, stat.name())
        })?;
        length("bin_upper", upper.name(), lower.len(), upper.len())?;
        length("bin_height", height.name(), lower.len(), height.len())?;
        let geometry = HistogramGeometry::bins(lower, upper, height, stat);
        let reference = capture.reference();
        Ok(Self::bound(
            Plot::histogram(HistogramInput::geometry(geometry)),
            source,
            None,
            reference,
        ))
    }
}

columnar_geometry!(Raincloud, geometry, geometry_from_data, raincloud_geometry,
(category: CategoryInput => bind_category, q1: NumericInput => bind_numeric,
    median: NumericInput => bind_numeric, q3: NumericInput => bind_numeric),
((density_source => density_category: CategoryInput => bind_category,
    density_y: NumericInput => bind_numeric, normalized_width: NumericInput => bind_numeric),
 (points_source => point_category: CategoryInput => bind_category,
    point_y: NumericInput => bind_numeric, normalized_strip: NumericInput => bind_numeric)),
(category_dimension, value_dimension), Some(point_y.len()),
Plot::raincloud(RaincloudInput::geometry(RaincloudGeometry::new(category_dimension, value_dimension, category, q1, median, q3, density_category, density_y, normalized_width, point_category, point_y, normalized_strip))));

columnar_geometry!(Raincloud, geometry_with_hue, geometry_with_hue_from_data, hued_raincloud_geometry,
(category: CategoryInput => bind_category, hue: CategoryInput => bind_category,
    q1: NumericInput => bind_numeric, median: NumericInput => bind_numeric, q3: NumericInput => bind_numeric),
((density_source => density_category: CategoryInput => bind_category, density_hue: CategoryInput => bind_category,
    density_y: NumericInput => bind_numeric, normalized_width: NumericInput => bind_numeric),
 (points_source => point_category: CategoryInput => bind_category, point_hue: CategoryInput => bind_category,
    point_y: NumericInput => bind_numeric, normalized_strip: NumericInput => bind_numeric)),
(category_dimension, value_dimension, hue_dimension), Some(point_y.len()),
Plot::raincloud(RaincloudInput::geometry(RaincloudGeometry::new(category_dimension, value_dimension, category, q1, median, q3, density_category, density_y, normalized_width, point_category, point_y, normalized_strip).with_hue(hue_dimension, hue, density_hue, point_hue))));

impl PlotAdapter<'_, kind::Raincloud> {
    /// Consume an already owned native raincloud geometry directly.
    pub fn from_geometry(geometry: RaincloudGeometry) -> Self {
        let len = geometry.point_y().len();
        Self::bound(
            Plot::raincloud(RaincloudInput::geometry(geometry)),
            None,
            Some(len),
            None,
        )
    }

    /// Borrow the actual supplied raincloud geometry.
    pub fn get_geometry(&self) -> Option<&RaincloudGeometry> {
        self.plot.get_geometry()
    }
}

impl PlotAdapter<'_, kind::Histogram> {
    /// Consume an already owned native histogram geometry directly.
    pub fn from_geometry(geometry: HistogramGeometry) -> Self {
        Self::bound(
            Plot::histogram(HistogramInput::geometry(geometry)),
            None,
            None,
            None,
        )
    }

    /// Borrow the actual supplied geometry, if any.
    pub fn get_geometry(&self) -> Option<&HistogramGeometry> {
        self.plot.get_geometry()
    }

    /// Add or replace the given KDE using direct columns in its own domain.
    pub fn kde(
        self,
        x: impl NumericInput,
        density: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        self.bind_supplied_kde(None, x, density)
    }

    /// Snapshot KDE columns from their own auxiliary source.
    pub fn kde_from_data(
        self,
        source: impl ArraySource,
        x: impl NumericInput,
        density: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        source.validate()?;
        self.bind_supplied_kde(Some(&source), x, density)
    }

    fn bind_supplied_kde(
        mut self,
        source: Option<&dyn ArraySource>,
        x: impl NumericInput,
        density: impl NumericInput,
    ) -> BindingResult<Self> {
        let capture = Capture::new(source);
        let x = capture.bind(x, 1, |input, source| input.bind_numeric(source, "KDE x"))?;
        let density = capture.bind(density, 1, |input, source| {
            input.bind_numeric(source, "KDE density")
        })?;
        length("KDE density", density.name(), x.len(), density.len())?;
        self.plot = self.plot.kde(x, density)?;
        Ok(self)
    }

    /// Add or replace independently supplied rug segments from direct columns.
    pub fn rug(
        self,
        x: impl NumericInput,
        baseline: impl NumericInput,
        top: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        self.bind_rug(None, x, baseline, top)
    }

    /// Snapshot rug columns from their own auxiliary source.
    pub fn rug_from_data(
        self,
        source: impl ArraySource,
        x: impl NumericInput,
        baseline: impl NumericInput,
        top: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        source.validate()?;
        self.bind_rug(Some(&source), x, baseline, top)
    }

    fn bind_rug(
        mut self,
        source: Option<&dyn ArraySource>,
        x: impl NumericInput,
        baseline: impl NumericInput,
        top: impl NumericInput,
    ) -> BindingResult<Self> {
        let capture = Capture::new(source);
        let x = capture.bind(x, 1, |input, source| input.bind_numeric(source, "value"))?;
        let baseline = capture.bind(baseline, 1, |input, source| {
            input.bind_numeric(source, "rug_baseline")
        })?;
        let top = capture.bind(top, 1, |input, source| {
            input.bind_numeric(source, "rug_top")
        })?;
        length("rug_baseline", baseline.name(), x.len(), baseline.len())?;
        length("rug_top", top.name(), x.len(), top.len())?;
        self.plot = self.plot.rug(x, baseline, top)?;
        Ok(self)
    }

    /// Set the original scientific x dimension of supplied geometry.
    pub fn value_dimension(
        mut self,
        name: impl Into<String>,
    ) -> std::result::Result<Self, AdapterError> {
        self.plot = self.plot.value_dimension(name)?;
        Ok(self)
    }

    /// Set the original scientific height dimension of supplied geometry.
    pub fn height_dimension(
        mut self,
        name: impl Into<String>,
    ) -> std::result::Result<Self, AdapterError> {
        self.plot = self.plot.height_dimension(name)?;
        Ok(self)
    }

    /// Snapshot direct KDE columns for the sample-owned KDE+rug composite.
    /// Samples, bins, stat and the main lookup context are unchanged.
    pub fn composite_precomputed_kde(
        self,
        x: impl NumericInput,
        y: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        self.bind_kde(None, x, y)
    }

    /// Snapshot KDE from an independent source, retaining no borrow of it and
    /// never using the main source as a selector fallback.
    pub fn composite_precomputed_kde_from_data(
        self,
        source: impl ArraySource,
        x: impl NumericInput,
        y: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        source.validate()?;
        self.bind_kde(Some(&source), x, y)
    }

    fn bind_kde(
        mut self,
        source: Option<&dyn ArraySource>,
        x: impl NumericInput,
        y: impl NumericInput,
    ) -> BindingResult<Self> {
        let capture = Capture::new(source);
        let x = capture.bind(x, 1, |input, source| input.bind_numeric(source, "KDE x"))?;
        let y = capture.bind(y, 1, |input, source| input.bind_numeric(source, "KDE y"))?;
        length("KDE y", y.name(), x.len(), y.len())?;
        self.plot = self
            .plot
            .composite(HistogramComposite::KdeAndRug(HistogramKde::Precomputed {
                x,
                y,
            }));
        Ok(self)
    }
}

#[cfg(test)]
mod tests;