lichtung-plot-ndarray 0.2.0

Direct scientific plotting from logical ndarray views and columns
Documentation
//! Supplemental layers bind their own data and never inherit parent fields.
use crate::capture::Capture;
use crate::error::{length, BindingResult};
use crate::frontend::{context, Context};
use crate::{
    binding::{ArraySource, CategoryInput, NumericInput},
    elements::{BarPointLayer, PointLayer},
    text::TextLayout,
    AdapterError, CategoryValues, Color, NumericValues, Text,
};

/// An independent native point layer with its own optional array label context.
#[derive(Clone)]
pub struct PointLayerAdapter<'source> {
    layer: PointLayer,
    source: Context<'source>,
    source_ref: Option<crate::data::DataSourceRef>,
    len: usize,
}
impl<'source> PointLayerAdapter<'source> {
    /// Snapshot coordinates independently of the parent line's record count.
    pub fn new(
        x: impl NumericInput,
        y: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::bind(None, x, y)
    }
    /// Bind coordinates and retain only this layer's source for later labels.
    pub fn from_data(
        source: impl ArraySource + 'source,
        x: impl NumericInput,
        y: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::bind(context(source)?, x, y)
    }
    fn bind(
        source: Context<'source>,
        x: impl NumericInput,
        y: impl NumericInput,
    ) -> BindingResult<Self> {
        let capture = Capture::new(source.as_deref());
        let x = capture.bind(x, 1, |input, source| {
            input.bind_numeric(source, "point layer x")
        })?;
        let y = capture.bind(y, 1, |input, source| {
            input.bind_numeric(source, "point layer y")
        })?;
        let len = x.len();
        length("point layer y", y.name(), len, y.len())?;
        let source_ref = capture.reference();
        Ok(Self {
            layer: PointLayer::new(x, y),
            source,
            source_ref,
            len,
        })
    }
    /// Bind labels against the layer's own coordinates, not the parent source.
    pub fn labels(mut self, labels: impl CategoryInput) -> std::result::Result<Self, AdapterError> {
        let capture = Capture::recapture(self.source.as_deref(), self.source_ref.as_ref());
        let labels = capture.bind(labels, 1, |input, source| {
            input.bind_category(source, "point layer labels")
        })?;
        length("point layer labels", labels.name(), self.len, labels.len())?;
        self.layer = self.layer.labels(labels);
        Ok(self)
    }
    /// Replace the native exact-paint override.
    #[must_use]
    pub fn color(mut self, color: Color) -> Self {
        self.layer = self.layer.color(color);
        self
    }
    /// Replace the radius, retaining the native result/error type.
    pub fn radius(mut self, radius: u32) -> crate::Result<Self> {
        self.layer = self.layer.radius(radius)?;
        Ok(self)
    }
    /// Override point/label alpha with a finite opacity coefficient.
    pub fn alpha(mut self, alpha: f64) -> std::result::Result<Self, AdapterError> {
        self.layer = self.layer.alpha(alpha)?;
        Ok(self)
    }
    /// Supply a complete-layer legend identity, independently of point labels.
    #[must_use]
    pub fn legend_label(mut self, label: impl Into<Text>) -> Self {
        self.layer = self.layer.legend_label(label);
        self
    }
    /// Remove the legend label's local style through the native slot operation.
    #[must_use]
    pub fn clear_legend_label_style(mut self) -> Self {
        self.layer = self.layer.clear_legend_label_style();
        self
    }
    /// Remove the legend label's local layout through the native slot operation.
    #[must_use]
    pub fn clear_legend_label_layout(mut self) -> Self {
        self.layer = self.layer.clear_legend_label_layout();
        self
    }
    /// Replace native label layout.
    #[must_use]
    pub fn label_text_layout(mut self, layout: TextLayout) -> Self {
        self.layer = self.layer.label_text_layout(layout);
        self
    }
    /// Inspect the native paint override.
    pub fn get_color(&self) -> Option<Color> {
        self.layer.get_color()
    }
    /// Inspect the native radius override.
    pub fn get_radius(&self) -> Option<u32> {
        self.layer.get_radius()
    }
    /// Inspect the native alpha override.
    pub fn get_alpha(&self) -> Option<f64> {
        self.layer.get_alpha()
    }
}
impl From<PointLayerAdapter<'_>> for PointLayer {
    fn from(adapter: PointLayerAdapter<'_>) -> Self {
        adapter.layer
    }
}

/// Independent observations positioned at prepared native ordinary-bar centers.
#[derive(Clone)]
pub struct BarPointLayerAdapter<'source> {
    layer: BarPointLayer,
    source: Context<'source>,
    source_ref: Option<crate::data::DataSourceRef>,
}
impl<'source> BarPointLayerAdapter<'source> {
    /// Bind direct categories and values.
    pub fn new(
        category: impl CategoryInput,
        value: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::bind(None, category, value)
    }
    /// Bind this layer's own source, independently of parent bar observations.
    pub fn from_data(
        source: impl ArraySource + 'source,
        category: impl CategoryInput,
        value: impl NumericInput,
    ) -> std::result::Result<Self, AdapterError> {
        Self::bind(context(source)?, category, value)
    }
    fn bind(
        source: Context<'source>,
        category: impl CategoryInput,
        value: impl NumericInput,
    ) -> BindingResult<Self> {
        let capture = Capture::new(source.as_deref());
        let category = capture.bind(category, 1, |input, source| {
            input.bind_category(source, "bar point layer category")
        })?;
        let value = capture.bind(value, 1, |input, source| {
            input.bind_numeric(source, "bar point layer value")
        })?;
        length(
            "bar point layer value",
            value.name(),
            category.len(),
            value.len(),
        )?;
        let source_ref = capture.reference();
        Ok(Self {
            layer: BarPointLayer::new(category, value),
            source,
            source_ref,
        })
    }
    /// Bind positioned series in this layer's own source.
    pub fn series(mut self, series: impl CategoryInput) -> std::result::Result<Self, AdapterError> {
        let capture = Capture::recapture(self.source.as_deref(), self.source_ref.as_ref());
        let series = capture.bind(series, 1, |input, source| {
            input.bind_category(source, "bar point layer series")
        })?;
        length(
            "bar point layer series",
            series.name(),
            self.layer.values().len(),
            series.len(),
        )?;
        self.layer = self.layer.series(series);
        Ok(self)
    }
    /// Inspect native categories.
    pub fn category_values(&self) -> &CategoryValues {
        self.layer.category_values()
    }
    /// Inspect optional native positioned-series values.
    pub fn series_values(&self) -> Option<&CategoryValues> {
        self.layer.series_values()
    }
    /// Inspect owned numeric values.
    pub fn values(&self) -> &NumericValues {
        self.layer.values()
    }
    /// Override the complete fixed paint of this layer.
    #[must_use]
    pub fn color(mut self, color: Color) -> Self {
        self.layer = self.layer.color(color);
        self
    }
    /// Override the positive point radius.
    pub fn radius(mut self, radius: u32) -> std::result::Result<Self, AdapterError> {
        self.layer = self.layer.radius(radius)?;
        Ok(self)
    }
    /// Read the explicit paint, if supplied.
    pub fn get_color(&self) -> Option<Color> {
        self.layer.get_color()
    }
    /// Read the explicit radius, if supplied.
    pub fn get_radius(&self) -> Option<u32> {
        self.layer.get_radius()
    }
}
impl From<BarPointLayerAdapter<'_>> for BarPointLayer {
    fn from(adapter: BarPointLayerAdapter<'_>) -> Self {
        adapter.layer
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ndarray::array;

    #[test]
    fn bar_point_layer_keeps_optional_style_and_independent_lookup() {
        let values = array![[1.25], [2.25]];
        let category = array!["A", "B"];
        let series = array!["S2", "S1"];
        let layer =
            BarPointLayerAdapter::from_data(values.view(), category.view(), 0usize).unwrap();
        assert!(layer.get_color().is_none() && layer.get_radius().is_none());
        let fixed = Color::rgba(23, 34, 45, 0.).unwrap();
        let layer = layer
            .color(fixed)
            .radius(6)
            .unwrap()
            .series(series.view())
            .unwrap();
        assert_eq!(layer.get_color(), Some(fixed));
        assert_eq!(layer.get_radius(), Some(6));
        let native: BarPointLayer = layer.into();
        assert_eq!(native.series_values().unwrap().get(0), Some(Some("S2")));
        assert_eq!(native.values().get(1), Some(Some(2.25)));
    }
}