lichtung-plot-ndarray 0.3.0

Direct scientific plotting from logical ndarray views and columns
Documentation
use super::{context, Context, PlotAdapter};
use crate::capture::Capture;
use crate::error::{length, BindingResult};
use crate::{
    binding::{
        ArraySource, AxisInput, CategoryInput, ColorSourceInput, ColumnsInput, NumericInput,
    },
    data::{AxisValues, Bounds},
    kind,
    plots::{BarInput, CoefficientInput, DumbbellEndpoints, HistogramInput},
    stats::ErrorBar,
    AdapterError, CategoryValues, NumericValues, Plot,
};

trait Slots {
    fn slots(&self) -> usize;
}
impl Slots for NumericValues {
    fn slots(&self) -> usize {
        self.len()
    }
}
impl Slots for CategoryValues {
    fn slots(&self) -> usize {
        self.len()
    }
}
impl Slots for AxisValues {
    fn slots(&self) -> usize {
        self.len()
    }
}

macro_rules! records {
    ($kind:ident,$new:ident,$from:ident,$bind:ident,
        ($first:ident:$first_trait:ident=>$first_method:ident $(,$arg:ident:$input:ident=>$method:ident)*),
        ($($policy:ident:$ty:ty),*),$plot:expr) => {
        impl<'source> PlotAdapter<'source,kind::$kind> {
            #[doc=concat!("Bind direct inputs for native ",stringify!($kind)," ",stringify!($new)," mode.")]
            pub fn $new($first:impl $first_trait,$($arg:impl $input,)*$($policy:$ty),*)->std::result::Result<Self,AdapterError> { Self::$bind(None,$first,$($arg,)*$($policy),*) }
            #[doc=concat!("Bind logical source columns/direct inputs for native ",stringify!($kind)," ",stringify!($new)," mode.")]
            pub fn $from(source:impl ArraySource+'source,$first:impl $first_trait,$($arg:impl $input,)*$($policy:$ty),*)->std::result::Result<Self,AdapterError> { Self::$bind(context(source)?,$first,$($arg,)*$($policy),*) }
            fn $bind(source:Context<'source>,$first:impl $first_trait,$($arg:impl $input,)*$($policy:$ty),*)->BindingResult<Self> {
                let capture = Capture::new(source.as_deref());
                let $first = capture.bind($first, 1, |input, source| input.$first_method(source, stringify!($first)))?;
                let len = $first.slots();
                $(let $arg = capture.bind($arg, 1, |input, source| input.$method(source, stringify!($arg)))?;
                  length(stringify!($arg), $arg.name(), len, $arg.slots())?;)*
                let reference = capture.reference();
                Ok(Self::bound($plot, source, Some(len), reference))
            }
        }
    };
}
records!(Regression,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::regression(x,y));
records!(Marginal,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::marginal(x,y));
records!(Histogram,new,from_data,samples_input,(samples:NumericInput=>bind_numeric),(),Plot::histogram(HistogramInput::samples(samples)));
records!(Density,new,from_data,samples_input,(value:NumericInput=>bind_numeric),(),Plot::density(value));
records!(Qq,new,from_data,samples_input,(value:NumericInput=>bind_numeric),(),Plot::qq(value));
records!(PointInterval,new,from_data,estimates_input,(category:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric,lower:NumericInput=>bind_numeric,upper:NumericInput=>bind_numeric),(),Plot::point_interval(category,estimate,Bounds::new(lower,upper)));
records!(Trajectory,new,from_data,coordinates,(x:AxisInput=>bind_axis,y:NumericInput=>bind_numeric,group:CategoryInput=>bind_category),(),Plot::trajectory(x,y,group));
records!(Trajectory,new_numeric_x,from_data_numeric_x,numeric_coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric,group:CategoryInput=>bind_category),(),Plot::trajectory(x,y,group));
records!(Trajectory,new_categorical_x,from_data_categorical_x,category_coordinates,(x:CategoryInput=>bind_category,y:NumericInput=>bind_numeric,group:CategoryInput=>bind_category),(),Plot::trajectory(x,y,group));
records!(LinePath,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::line_path(x,y));
records!(LinePath,grouped,grouped_from_data,grouped_coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric,group:CategoryInput=>bind_category),(),Plot::line_path_grouped(x,y,group));
records!(Interaction,new,from_data,estimates_input,(condition:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric,group:CategoryInput=>bind_category,lower:NumericInput=>bind_numeric,upper:NumericInput=>bind_numeric),(),Plot::interaction(condition,estimate,group,Bounds::new(lower,upper)));
records!(Coefficient,new,from_data,estimates_input,(term:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric),(),Plot::coefficient(term,CoefficientInput::estimates(estimate)));
records!(Coefficient,with_intervals,with_intervals_from_data,interval_input,(term:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric,lower:NumericInput=>bind_numeric,upper:NumericInput=>bind_numeric),(),Plot::coefficient(term,CoefficientInput::estimates_with_intervals(estimate,Bounds::new(lower,upper))));
records!(Forest,new,from_data,estimates_input,(term:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric,lower:NumericInput=>bind_numeric,upper:NumericInput=>bind_numeric),(reference:f64),Plot::forest(term,estimate,Bounds::new(lower,upper),reference));
records!(Dumbbell,new,from_data,paired_input,(category:CategoryInput=>bind_category,left:NumericInput=>bind_numeric,right:NumericInput=>bind_numeric),(endpoints:DumbbellEndpoints),Plot::dumbbell(category,left,right,endpoints));
records!(Heatmap,records,records_from_data,records_input,(x:CategoryInput=>bind_category,y:CategoryInput=>bind_category,fill:NumericInput=>bind_numeric),(),Plot::heatmap(x,y,fill));
records!(StackedBar,new,from_data,estimates_input,(category:CategoryInput=>bind_category,value:NumericInput=>bind_numeric,series:CategoryInput=>bind_category),(),Plot::stacked_bar(category,value,series));
records!(StackedHorizontalBar,new,from_data,estimates_input,(category:CategoryInput=>bind_category,value:NumericInput=>bind_numeric,series:CategoryInput=>bind_category),(),Plot::stacked_horizontal_bar(category,value,series));
records!(Beeswarm,new,from_data,samples_input,(category:CategoryInput=>bind_category,value:NumericInput=>bind_numeric),(),Plot::beeswarm(category,value));
impl<'source> PlotAdapter<'source, kind::Beeswarm> {
    /// Bind direct observations with a fixed or continuously mapped color.
    pub fn colored(
        category: impl CategoryInput,
        value: impl NumericInput,
        color: impl ColorSourceInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::colored_input(None, category, value, color)
    }

    /// Bind source columns or direct values with a fixed or mapped color.
    pub fn colored_from_data(
        source: impl ArraySource + 'source,
        category: impl CategoryInput,
        value: impl NumericInput,
        color: impl ColorSourceInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::colored_input(context(source)?, category, value, color)
    }

    fn colored_input(
        source: Context<'source>,
        category: impl CategoryInput,
        value: impl NumericInput,
        color: impl ColorSourceInput,
    ) -> BindingResult<Self> {
        let capture = Capture::new(source.as_deref());
        let category = capture.bind(category, 1, |input, source| {
            input.bind_category(source, "category")
        })?;
        let value = capture.bind(value, 1, |input, source| {
            input.bind_numeric(source, "value")
        })?;
        let len = category.len();
        length("value", value.name(), len, value.len())?;
        let reference = capture.reference();
        let color = color.bind_color_source(source.as_deref(), len, reference.as_ref())?;
        Ok(Self::bound(
            Plot::beeswarm_colored(category, value, color),
            source,
            Some(len),
            reference,
        ))
    }
}
records!(Waterfall,new,from_data,deltas_input,(category:CategoryInput=>bind_category,delta:NumericInput=>bind_numeric),(base:f64),Plot::waterfall(category,delta,base));
macro_rules! bar_modes {
    ($family:ident,$native:ident) => {
        records!($family,new,from_data,samples_input,(category:CategoryInput=>bind_category,samples:NumericInput=>bind_numeric),(),Plot::$native(category,BarInput::samples(samples)));
        records!($family,with_error_bar,with_error_bar_from_data,configured_samples_input,(category:CategoryInput=>bind_category,samples:NumericInput=>bind_numeric),(policy:impl Into<ErrorBar>),Plot::$native(category,BarInput::samples(samples).error_bar(policy)));
        records!($family,estimates,estimates_from_data,estimates_input,(category:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric),(),Plot::$native(category,BarInput::estimates(estimate)));
        records!($family,estimates_with_error_bars,estimates_with_error_bars_from_data,interval_input,(category:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric,lower:NumericInput=>bind_numeric,upper:NumericInput=>bind_numeric),(),Plot::$native(category,BarInput::estimates_with_error_bars(estimate,Bounds::new(lower,upper))));
    };
}
bar_modes!(Bar, bar);
bar_modes!(HorizontalBar, horizontal_bar);
impl PlotAdapter<'_, kind::Line> {
    /// Bind bounds with exactly the line's single-variable or selected-column shape.
    pub fn band(
        mut self,
        lower: impl crate::binding::NumericSeriesInput,
        upper: impl crate::binding::NumericSeriesInput,
    ) -> std::result::Result<Self, AdapterError> {
        let native_lower = lower.native_slots();
        let native_upper = upper.native_slots();
        let capture = self.capture();
        let (lower, lower_shape) = capture.series(lower, "lower")?;
        let (upper, upper_shape) = capture.series(upper, "upper")?;
        for (shape, native) in [(&lower_shape, native_lower), (&upper_shape, native_upper)] {
            match (&self.bindings.expansion, shape) {
                (_, None) if native => {}
                (None, None) => {}
                (Some(expansion), Some((rows, columns, _)))
                    if *rows == expansion.rows && columns.len() == expansion.keys.len() => {}
                _ => {
                    return Err(crate::error::binding(
                        "band",
                        "bounds must match the line's single-variable or selected-column shape",
                    ))
                }
            }
        }
        self.aligned("lower", lower.name(), lower.len())?;
        self.aligned("upper", upper.name(), upper.len())?;
        self.plot = self.plot.band(Bounds::new(lower, upper));
        Ok(self)
    }
}
impl<'source> PlotAdapter<'source, kind::Matrix> {
    /// Use direct matrix columns as variables and rows as observations.
    pub fn new(variables: impl ColumnsInput) -> std::result::Result<Self, AdapterError> {
        Self::matrix_input(None, variables)
    }
    /// Select ordered logical columns, or `..` for every column.
    pub fn from_data(
        source: impl ArraySource + 'source,
        columns: impl ColumnsInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::matrix_input(context(source)?, columns)
    }
    /// Explicit numeric discovery on a homogeneous source uses all columns.
    pub fn numeric_from_data(
        source: impl ArraySource + 'source,
    ) -> std::result::Result<Self, AdapterError> {
        Self::from_data(source, crate::input::NumericColumns)
    }
    fn matrix_input(source: Context<'source>, variables: impl ColumnsInput) -> BindingResult<Self> {
        let local = variables.local_identities();
        let capture = Capture::new(source.as_deref());
        let ((rows, columns), origin) = capture.columns(variables)?;
        let keys = columns
            .iter()
            .map(|(index, _)| {
                if local {
                    Ok(format!("__lichtung_matrix_{index}"))
                } else {
                    crate::source::identity(source.as_deref(), *index, "matrix variables")
                }
            })
            .collect::<BindingResult<Vec<_>>>()?;
        let labels = origin.selected_names().map_or_else(
            || {
                columns
                    .iter()
                    .map(|(index, _)| crate::source::name(*index))
                    .collect()
            },
            <[String]>::to_vec,
        );
        let width = columns.len();
        let values = columns
            .into_iter()
            .zip(&keys)
            .enumerate()
            .map(|(column, ((_, values), key))| {
                let values = NumericValues::nullable(key, values).with_source_slots(
                    origin.clone(),
                    (0..rows).map(|row| row * width + column).collect(),
                )?;
                let values = if let Some((raw, name)) = origin.field(column) {
                    values.with_field_key(raw, name)
                } else {
                    let position = origin
                        .selected_indices()
                        .map_or(column, |indices| indices[column]);
                    values.with_field_key(
                        crate::data::RawKey::Integer(position.into()),
                        &labels[column],
                    )
                };
                Ok(values)
            })
            .collect::<BindingResult<Vec<_>>>()?;
        let reference = capture.reference();
        let mut adapter = Self::bound(Plot::matrix(values), source, Some(rows), reference);
        adapter.bindings.matrix_keys = Some(keys);
        if local {
            let mut policy = adapter.bindings.labels.clone();
            for (index, (raw, display)) in adapter
                .bindings
                .matrix_keys
                .as_ref()
                .expect("actual Matrix keys")
                .iter()
                .zip(labels)
                .enumerate()
            {
                let key = origin
                    .selected_keys()
                    .and_then(|keys| keys.get(index))
                    .cloned()
                    .unwrap_or_else(|| {
                        crate::data::RawKey::from(
                            origin
                                .selected_indices()
                                .map_or(index, |indices| indices[index]),
                        )
                    });
                policy = policy.capture_alias(raw, Some(key), display);
            }
            adapter = adapter.labels(policy);
        }
        Ok(adapter)
    }
}