Skip to main content

lichtung_plot_ndarray/frontend/
constructors.rs

1use super::{context, Context, PlotAdapter};
2use crate::error::{length, BindingResult};
3use crate::{
4    kind, AdapterError, ArraySource, AxisInput, AxisValues, BarInput, Bounds, CategoryInput,
5    CategoryValues, CoefficientInput, ColumnsInput, DumbbellEndpoints, ErrorBar, HistogramInput,
6    NumericInput, NumericValues, Plot,
7};
8
9trait Slots {
10    fn slots(&self) -> usize;
11}
12impl Slots for NumericValues {
13    fn slots(&self) -> usize {
14        self.len()
15    }
16}
17impl Slots for CategoryValues {
18    fn slots(&self) -> usize {
19        self.len()
20    }
21}
22impl Slots for AxisValues {
23    fn slots(&self) -> usize {
24        match self {
25            Self::Numeric(values) => values.len(),
26            Self::Category(values) => values.len(),
27        }
28    }
29}
30
31macro_rules! records {
32    ($kind:ident,$new:ident,$from:ident,$bind:ident,
33        ($first:ident:$first_trait:ident=>$first_method:ident $(,$arg:ident:$input:ident=>$method:ident)*),
34        ($($policy:ident:$ty:ty),*),$plot:expr) => {
35        impl<'source> PlotAdapter<'source,kind::$kind> {
36            #[doc=concat!("Bind direct inputs for native ",stringify!($kind)," ",stringify!($new)," mode.")]
37            pub fn $new($first:impl $first_trait,$($arg:impl $input,)*$($policy:$ty),*)->std::result::Result<Self,AdapterError> { Self::$bind(None,$first,$($arg,)*$($policy),*) }
38            #[doc=concat!("Bind logical source columns/direct inputs for native ",stringify!($kind)," ",stringify!($new)," mode.")]
39            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),*) }
40            fn $bind(source:Context<'source>,$first:impl $first_trait,$($arg:impl $input,)*$($policy:$ty),*)->BindingResult<Self> {
41                let $first=$first.$first_method(source.as_deref(),stringify!($first))?; let len=$first.slots();
42                $(let $arg=$arg.$method(source.as_deref(),stringify!($arg))?; length(stringify!($arg),$arg.name(),len,$arg.slots())?;)*
43                Ok(Self::bound($plot,source,Some(len)))
44            }
45        }
46    };
47}
48records!(Regression,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::regression(x,y));
49records!(Marginal,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::marginal(x,y));
50records!(Histogram,new,from_data,samples_input,(samples:NumericInput=>bind_numeric),(),Plot::histogram(HistogramInput::samples(samples)));
51records!(Density,new,from_data,samples_input,(value:NumericInput=>bind_numeric),(),Plot::density(value));
52records!(Qq,new,from_data,samples_input,(value:NumericInput=>bind_numeric),(),Plot::qq(value));
53records!(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)));
54records!(Trajectory,new,from_data,coordinates,(x:AxisInput=>bind_axis,y:NumericInput=>bind_numeric,group:CategoryInput=>bind_category),(),Plot::trajectory(x,y,group));
55records!(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));
56records!(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));
57records!(LinePath,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric,group:CategoryInput=>bind_category),(),Plot::line_path(x,y,group));
58records!(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)));
59records!(Coefficient,new,from_data,estimates_input,(term:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric),(),Plot::coefficient(term,CoefficientInput::estimates(estimate)));
60records!(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))));
61records!(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));
62records!(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));
63records!(Heatmap,records,records_from_data,records_input,(x:CategoryInput=>bind_category,y:CategoryInput=>bind_category,fill:NumericInput=>bind_numeric),(),Plot::heatmap(x,y,fill));
64records!(StackedBar,new,from_data,estimates_input,(category:CategoryInput=>bind_category,value:NumericInput=>bind_numeric,series:CategoryInput=>bind_category),(),Plot::stacked_bar(category,value,series));
65records!(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));
66records!(Beeswarm,new,from_data,samples_input,(category:CategoryInput=>bind_category,value:NumericInput=>bind_numeric,color:NumericInput=>bind_numeric),(),Plot::beeswarm(category,value,color));
67records!(Waterfall,new,from_data,deltas_input,(category:CategoryInput=>bind_category,delta:NumericInput=>bind_numeric),(base:f64),Plot::waterfall(category,delta,base));
68macro_rules! bar_modes {
69    ($family:ident,$native:ident) => {
70        records!($family,new,from_data,samples_input,(category:CategoryInput=>bind_category,samples:NumericInput=>bind_numeric),(),Plot::$native(category,BarInput::samples(samples)));
71        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)));
72        records!($family,estimates,estimates_from_data,estimates_input,(category:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric),(),Plot::$native(category,BarInput::estimates(estimate)));
73        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))));
74    };
75}
76bar_modes!(Bar, bar);
77bar_modes!(HorizontalBar, horizontal_bar);
78impl PlotAdapter<'_, kind::Line> {
79    /// Bind bounds with exactly the line's single-variable or selected-column shape.
80    pub fn band(
81        mut self,
82        lower: impl crate::NumericSeriesInput,
83        upper: impl crate::NumericSeriesInput,
84    ) -> std::result::Result<Self, AdapterError> {
85        let native_lower = lower.native_slots();
86        let native_upper = upper.native_slots();
87        let (lower, lower_shape) = lower.bind_series(self.source.as_deref(), "lower")?;
88        let (upper, upper_shape) = upper.bind_series(self.source.as_deref(), "upper")?;
89        for (shape, native) in [(&lower_shape, native_lower), (&upper_shape, native_upper)] {
90            match (&self.bindings.expansion, shape) {
91                (_, None) if native => {}
92                (None, None) => {}
93                (Some(expansion), Some((rows, columns, _)))
94                    if *rows == expansion.rows && columns.len() == expansion.keys.len() => {}
95                _ => {
96                    return Err(crate::error::binding(
97                        "band",
98                        "bounds must match the line's single-variable or selected-column shape",
99                    ))
100                }
101            }
102        }
103        self.aligned("lower", lower.name(), lower.len())?;
104        self.aligned("upper", upper.name(), upper.len())?;
105        self.plot = self.plot.band(Bounds::new(lower, upper));
106        Ok(self)
107    }
108}
109impl<'source> PlotAdapter<'source, kind::Matrix> {
110    /// Use direct matrix columns as variables and rows as observations.
111    pub fn new(variables: impl ColumnsInput) -> std::result::Result<Self, AdapterError> {
112        Self::matrix_input(None, variables)
113    }
114    /// Select ordered logical columns, or `..` for every column.
115    pub fn from_data(
116        source: impl ArraySource + 'source,
117        columns: impl ColumnsInput,
118    ) -> std::result::Result<Self, AdapterError> {
119        Self::matrix_input(context(source)?, columns)
120    }
121    /// Explicit numeric discovery on a homogeneous source uses all columns.
122    pub fn numeric_from_data(
123        source: impl ArraySource + 'source,
124    ) -> std::result::Result<Self, AdapterError> {
125        Self::from_data(source, ..)
126    }
127    fn matrix_input(source: Context<'source>, variables: impl ColumnsInput) -> BindingResult<Self> {
128        let local = variables.local_identities();
129        let (rows, columns) = variables.bind_columns(source.as_deref())?;
130        let keys = columns
131            .iter()
132            .map(|(index, _)| {
133                if local {
134                    Ok(format!("__lichtung_matrix_{index}"))
135                } else {
136                    crate::source::identity(source.as_deref(), *index, "matrix variables")
137                }
138            })
139            .collect::<BindingResult<Vec<_>>>()?;
140        let labels = columns
141            .iter()
142            .map(|(index, _)| crate::source::name(*index))
143            .collect::<Vec<_>>();
144        let values = columns
145            .into_iter()
146            .zip(&keys)
147            .map(|((_, values), key)| NumericValues::nullable(key, values))
148            .collect();
149        let mut adapter = Self::bound(Plot::matrix(values), source, Some(rows));
150        adapter.bindings.matrix_keys = Some(keys);
151        if local {
152            adapter.column_labels(labels)
153        } else {
154            Ok(adapter)
155        }
156    }
157}