1use super::{context, Context, PlotAdapter};
2use crate::capture::Capture;
3use crate::error::{length, BindingResult};
4use crate::{
5 binding::{
6 ArraySource, AxisInput, CategoryInput, ColorSourceInput, ColumnsInput, NumericInput,
7 },
8 data::{AxisValues, Bounds},
9 kind,
10 plots::{BarInput, CoefficientInput, DumbbellEndpoints, HistogramInput},
11 stats::ErrorBar,
12 AdapterError, CategoryValues, NumericValues, Plot,
13};
14
15trait Slots {
16 fn slots(&self) -> usize;
17}
18impl Slots for NumericValues {
19 fn slots(&self) -> usize {
20 self.len()
21 }
22}
23impl Slots for CategoryValues {
24 fn slots(&self) -> usize {
25 self.len()
26 }
27}
28impl Slots for AxisValues {
29 fn slots(&self) -> usize {
30 self.len()
31 }
32}
33
34macro_rules! records {
35 ($kind:ident,$new:ident,$from:ident,$bind:ident,
36 ($first:ident:$first_trait:ident=>$first_method:ident $(,$arg:ident:$input:ident=>$method:ident)*),
37 ($($policy:ident:$ty:ty),*),$plot:expr) => {
38 impl<'source> PlotAdapter<'source,kind::$kind> {
39 #[doc=concat!("Bind direct inputs for native ",stringify!($kind)," ",stringify!($new)," mode.")]
40 pub fn $new($first:impl $first_trait,$($arg:impl $input,)*$($policy:$ty),*)->std::result::Result<Self,AdapterError> { Self::$bind(None,$first,$($arg,)*$($policy),*) }
41 #[doc=concat!("Bind logical source columns/direct inputs for native ",stringify!($kind)," ",stringify!($new)," mode.")]
42 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),*) }
43 fn $bind(source:Context<'source>,$first:impl $first_trait,$($arg:impl $input,)*$($policy:$ty),*)->BindingResult<Self> {
44 let capture = Capture::new(source.as_deref());
45 let $first = capture.bind($first, 1, |input, source| input.$first_method(source, stringify!($first)))?;
46 let len = $first.slots();
47 $(let $arg = capture.bind($arg, 1, |input, source| input.$method(source, stringify!($arg)))?;
48 length(stringify!($arg), $arg.name(), len, $arg.slots())?;)*
49 let reference = capture.reference();
50 Ok(Self::bound($plot, source, Some(len), reference))
51 }
52 }
53 };
54}
55records!(Regression,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::regression(x,y));
56records!(Marginal,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::marginal(x,y));
57records!(Histogram,new,from_data,samples_input,(samples:NumericInput=>bind_numeric),(),Plot::histogram(HistogramInput::samples(samples)));
58records!(Density,new,from_data,samples_input,(value:NumericInput=>bind_numeric),(),Plot::density(value));
59records!(Qq,new,from_data,samples_input,(value:NumericInput=>bind_numeric),(),Plot::qq(value));
60records!(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)));
61records!(Trajectory,new,from_data,coordinates,(x:AxisInput=>bind_axis,y:NumericInput=>bind_numeric,group:CategoryInput=>bind_category),(),Plot::trajectory(x,y,group));
62records!(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));
63records!(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));
64records!(LinePath,new,from_data,coordinates,(x:NumericInput=>bind_numeric,y:NumericInput=>bind_numeric),(),Plot::line_path(x,y));
65records!(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));
66records!(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)));
67records!(Coefficient,new,from_data,estimates_input,(term:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric),(),Plot::coefficient(term,CoefficientInput::estimates(estimate)));
68records!(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))));
69records!(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));
70records!(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));
71records!(Heatmap,records,records_from_data,records_input,(x:CategoryInput=>bind_category,y:CategoryInput=>bind_category,fill:NumericInput=>bind_numeric),(),Plot::heatmap(x,y,fill));
72records!(StackedBar,new,from_data,estimates_input,(category:CategoryInput=>bind_category,value:NumericInput=>bind_numeric,series:CategoryInput=>bind_category),(),Plot::stacked_bar(category,value,series));
73records!(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));
74records!(Beeswarm,new,from_data,samples_input,(category:CategoryInput=>bind_category,value:NumericInput=>bind_numeric),(),Plot::beeswarm(category,value));
75impl<'source> PlotAdapter<'source, kind::Beeswarm> {
76 pub fn colored(
78 category: impl CategoryInput,
79 value: impl NumericInput,
80 color: impl ColorSourceInput,
81 ) -> std::result::Result<Self, AdapterError> {
82 Self::colored_input(None, category, value, color)
83 }
84
85 pub fn colored_from_data(
87 source: impl ArraySource + 'source,
88 category: impl CategoryInput,
89 value: impl NumericInput,
90 color: impl ColorSourceInput,
91 ) -> std::result::Result<Self, AdapterError> {
92 Self::colored_input(context(source)?, category, value, color)
93 }
94
95 fn colored_input(
96 source: Context<'source>,
97 category: impl CategoryInput,
98 value: impl NumericInput,
99 color: impl ColorSourceInput,
100 ) -> BindingResult<Self> {
101 let capture = Capture::new(source.as_deref());
102 let category = capture.bind(category, 1, |input, source| {
103 input.bind_category(source, "category")
104 })?;
105 let value = capture.bind(value, 1, |input, source| {
106 input.bind_numeric(source, "value")
107 })?;
108 let len = category.len();
109 length("value", value.name(), len, value.len())?;
110 let reference = capture.reference();
111 let color = color.bind_color_source(source.as_deref(), len, reference.as_ref())?;
112 Ok(Self::bound(
113 Plot::beeswarm_colored(category, value, color),
114 source,
115 Some(len),
116 reference,
117 ))
118 }
119}
120records!(Waterfall,new,from_data,deltas_input,(category:CategoryInput=>bind_category,delta:NumericInput=>bind_numeric),(base:f64),Plot::waterfall(category,delta,base));
121macro_rules! bar_modes {
122 ($family:ident,$native:ident) => {
123 records!($family,new,from_data,samples_input,(category:CategoryInput=>bind_category,samples:NumericInput=>bind_numeric),(),Plot::$native(category,BarInput::samples(samples)));
124 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)));
125 records!($family,estimates,estimates_from_data,estimates_input,(category:CategoryInput=>bind_category,estimate:NumericInput=>bind_numeric),(),Plot::$native(category,BarInput::estimates(estimate)));
126 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))));
127 };
128}
129bar_modes!(Bar, bar);
130bar_modes!(HorizontalBar, horizontal_bar);
131impl PlotAdapter<'_, kind::Line> {
132 pub fn band(
134 mut self,
135 lower: impl crate::binding::NumericSeriesInput,
136 upper: impl crate::binding::NumericSeriesInput,
137 ) -> std::result::Result<Self, AdapterError> {
138 let native_lower = lower.native_slots();
139 let native_upper = upper.native_slots();
140 let capture = self.capture();
141 let (lower, lower_shape) = capture.series(lower, "lower")?;
142 let (upper, upper_shape) = capture.series(upper, "upper")?;
143 for (shape, native) in [(&lower_shape, native_lower), (&upper_shape, native_upper)] {
144 match (&self.bindings.expansion, shape) {
145 (_, None) if native => {}
146 (None, None) => {}
147 (Some(expansion), Some((rows, columns, _)))
148 if *rows == expansion.rows && columns.len() == expansion.keys.len() => {}
149 _ => {
150 return Err(crate::error::binding(
151 "band",
152 "bounds must match the line's single-variable or selected-column shape",
153 ))
154 }
155 }
156 }
157 self.aligned("lower", lower.name(), lower.len())?;
158 self.aligned("upper", upper.name(), upper.len())?;
159 self.plot = self.plot.band(Bounds::new(lower, upper));
160 Ok(self)
161 }
162}
163impl<'source> PlotAdapter<'source, kind::Matrix> {
164 pub fn new(variables: impl ColumnsInput) -> std::result::Result<Self, AdapterError> {
166 Self::matrix_input(None, variables)
167 }
168 pub fn from_data(
170 source: impl ArraySource + 'source,
171 columns: impl ColumnsInput,
172 ) -> std::result::Result<Self, AdapterError> {
173 Self::matrix_input(context(source)?, columns)
174 }
175 pub fn numeric_from_data(
177 source: impl ArraySource + 'source,
178 ) -> std::result::Result<Self, AdapterError> {
179 Self::from_data(source, crate::input::NumericColumns)
180 }
181 fn matrix_input(source: Context<'source>, variables: impl ColumnsInput) -> BindingResult<Self> {
182 let local = variables.local_identities();
183 let capture = Capture::new(source.as_deref());
184 let ((rows, columns), origin) = capture.columns(variables)?;
185 let keys = columns
186 .iter()
187 .map(|(index, _)| {
188 if local {
189 Ok(format!("__lichtung_matrix_{index}"))
190 } else {
191 crate::source::identity(source.as_deref(), *index, "matrix variables")
192 }
193 })
194 .collect::<BindingResult<Vec<_>>>()?;
195 let labels = origin.selected_names().map_or_else(
196 || {
197 columns
198 .iter()
199 .map(|(index, _)| crate::source::name(*index))
200 .collect()
201 },
202 <[String]>::to_vec,
203 );
204 let width = columns.len();
205 let values = columns
206 .into_iter()
207 .zip(&keys)
208 .enumerate()
209 .map(|(column, ((_, values), key))| {
210 let values = NumericValues::nullable(key, values).with_source_slots(
211 origin.clone(),
212 (0..rows).map(|row| row * width + column).collect(),
213 )?;
214 let values = if let Some((raw, name)) = origin.field(column) {
215 values.with_field_key(raw, name)
216 } else {
217 let position = origin
218 .selected_indices()
219 .map_or(column, |indices| indices[column]);
220 values.with_field_key(
221 crate::data::RawKey::Integer(position.into()),
222 &labels[column],
223 )
224 };
225 Ok(values)
226 })
227 .collect::<BindingResult<Vec<_>>>()?;
228 let reference = capture.reference();
229 let mut adapter = Self::bound(Plot::matrix(values), source, Some(rows), reference);
230 adapter.bindings.matrix_keys = Some(keys);
231 if local {
232 let mut policy = adapter.bindings.labels.clone();
233 for (index, (raw, display)) in adapter
234 .bindings
235 .matrix_keys
236 .as_ref()
237 .expect("actual Matrix keys")
238 .iter()
239 .zip(labels)
240 .enumerate()
241 {
242 let key = origin
243 .selected_keys()
244 .and_then(|keys| keys.get(index))
245 .cloned()
246 .unwrap_or_else(|| {
247 crate::data::RawKey::from(
248 origin
249 .selected_indices()
250 .map_or(index, |indices| indices[index]),
251 )
252 });
253 policy = policy.capture_alias(raw, Some(key), display);
254 }
255 adapter = adapter.labels(policy);
256 }
257 Ok(adapter)
258 }
259}