1use std::marker::PhantomData;
3use std::rc::Rc;
4
5use crate::capture::Capture;
6use crate::error::{binding, length, BindingResult};
7use crate::{
8 binding::{ArraySource, CategoryInput, SourceRowsInput},
9 formatting::Labels,
10 kind,
11 layout::{FacetScales, FacetSpec},
12 plots::PlotKind,
13 AdapterError, CategoryValues, Plot,
14};
15
16mod alpha;
17mod constructors;
18mod forwarding;
19mod geometry;
20mod grid;
21#[cfg(test)]
22mod metadata_tests;
23#[cfg(test)]
24mod projection_tests;
25mod status;
26mod wide;
27
28pub(crate) type Context<'source> = Option<Rc<dyn ArraySource + 'source>>;
29pub(crate) fn context<'source>(
30 source: impl ArraySource + 'source,
31) -> BindingResult<Context<'source>> {
32 source.validate()?;
33 Ok(Some(Rc::new(source)))
34}
35
36#[derive(Clone)]
46pub struct BindingMetadata<K: kind::Marker> {
47 len: Option<usize>,
48 source_ref: Option<crate::data::DataSourceRef>,
49 geometry_points: Option<usize>,
50 labels: Labels,
51 facet: Option<FacetSpec>,
52 grid: Option<grid::Grid>,
53 expansion: Option<wide::Expansion>,
54 matrix_keys: Option<Vec<String>>,
55 marker: PhantomData<K>,
56}
57
58impl<K: kind::Marker> BindingMetadata<K> {
59 #[doc(hidden)]
61 pub fn column_alpha_key(
62 &self,
63 source: Option<&dyn ArraySource>,
64 input: impl SourceRowsInput,
65 ) -> BindingResult<crate::CategoryValues> {
66 let expansion = self
67 .expansion
68 .as_ref()
69 .ok_or_else(|| binding("column alpha", "no generated variable dimension"))?;
70 expansion.column_key(&Capture::new(source), source, input)
71 }
72
73 #[doc(hidden)]
75 pub fn expand_alpha(
76 &self,
77 values: crate::scales::AlphaValues,
78 rows: bool,
79 ) -> BindingResult<crate::scales::AlphaValues> {
80 crate::alpha::expand(
81 values,
82 self.geometry_points.or(self.len),
83 if rows { self.row_copies() } else { 1 },
84 )
85 }
86
87 #[doc(hidden)]
89 pub fn wide_shape(&self) -> Option<(usize, usize)> {
90 self.expansion
91 .as_ref()
92 .map(|wide| (wide.rows, wide.keys.len()))
93 }
94
95 #[doc(hidden)]
97 pub fn cell_shape(&self) -> Option<(usize, usize)> {
98 self.grid
99 .as_ref()
100 .map(|grid| (grid.rows(), grid.columns()))
101 .or_else(|| self.wide_shape())
102 }
103
104 #[doc(hidden)]
106 pub fn row_copies(&self) -> usize {
107 self.expansion.as_ref().map_or_else(
108 || self.grid.as_ref().map_or(1, grid::Grid::columns),
109 |wide| wide.keys.len(),
110 )
111 }
112
113 #[doc(hidden)]
116 pub fn named_generated_columns(&self) -> Option<(&str, &[String], &[crate::data::RawKey])> {
117 self.expansion.as_ref()?.named_columns()
118 }
119}
120
121#[derive(Clone)]
126pub struct PlotAdapter<'source, K: kind::Marker> {
127 plot: Plot<K>,
128 pub(crate) source: Context<'source>,
129 bindings: BindingMetadata<K>,
130}
131
132macro_rules! families {
133 ($($family:ident),+) => {$ (
134 #[doc = concat!("ndarray frontend for native ", stringify!($family), ".")]
135 pub type $family<'source> = PlotAdapter<'source, kind::$family>;
136 )+};
137}
138families!(
139 Scatter,
140 Histogram,
141 Density,
142 Qq,
143 PointInterval,
144 Line,
145 Trajectory,
146 LinePath,
147 Interaction,
148 Coefficient,
149 Forest,
150 Dumbbell,
151 Heatmap,
152 Bar,
153 HorizontalBar,
154 StackedBar,
155 StackedHorizontalBar,
156 Boxplot,
157 Violin,
158 Raincloud,
159 Regression,
160 Marginal,
161 Matrix,
162 Beeswarm,
163 Waterfall
164);
165
166impl<'source, K: kind::Marker> PlotAdapter<'source, K> {
167 fn bound(
168 plot: Plot<K>,
169 source: Context<'source>,
170 len: Option<usize>,
171 source_ref: Option<crate::data::DataSourceRef>,
172 ) -> Self {
173 Self {
174 plot,
175 source,
176 bindings: BindingMetadata {
177 len,
178 source_ref,
179 geometry_points: None,
180 labels: Labels::default(),
181 facet: None,
182 grid: None,
183 expansion: None,
184 matrix_keys: None,
185 marker: PhantomData,
186 },
187 }
188 }
189 pub fn into_parts(self) -> (Plot<K>, BindingMetadata<K>) {
208 (self.plot, self.bindings)
209 }
210 fn aligned(&self, role: &'static str, name: &str, actual: usize) -> BindingResult<()> {
211 if let Some(expected) = self.bindings.len {
212 length(role, name, expected, actual)?;
213 }
214 Ok(())
215 }
216 fn row_copies(&self) -> usize {
217 self.bindings.row_copies()
218 }
219 fn alpha_len(&self) -> Option<usize> {
220 self.bindings.geometry_points.or(self.bindings.len)
221 }
222 fn category_rows(
223 &self,
224 values: impl CategoryInput,
225 role: &'static str,
226 ) -> BindingResult<CategoryValues> {
227 let capture = self.capture();
228 self.captured_category(&capture, values, role, self.row_copies())
229 }
230
231 pub(crate) fn capture(&self) -> Capture<'_> {
232 Capture::recapture(self.source.as_deref(), self.bindings.source_ref.as_ref())
233 }
234
235 fn captured_category(
236 &self,
237 capture: &Capture<'_>,
238 values: impl CategoryInput,
239 role: &'static str,
240 copies: usize,
241 ) -> BindingResult<crate::CategoryValues> {
242 let values = capture.bind(values, copies, |input, source| {
243 input.bind_category_repeated(source, role, copies)
244 })?;
245 self.aligned(role, values.name(), values.len())?;
246 Ok(values)
247 }
248 pub fn kind(&self) -> PlotKind {
250 self.plot.kind()
251 }
252 #[must_use]
254 pub fn labels(mut self, labels: Labels) -> Self {
255 self.plot = self.plot.labels(labels);
256 self.bindings.labels = self.plot.get_labels().clone();
257 self
258 }
259 pub fn source_rows(
261 mut self,
262 values: impl SourceRowsInput,
263 ) -> std::result::Result<Self, AdapterError>
264 where
265 K: kind::SourceRows,
266 {
267 self.cell_shape(&values, "source rows")?;
268 let capture = self.capture();
269 let values = capture.bind(values, 1, |input, source| {
270 input.bind_source_rows_repeated(source, "source rows", self.row_copies())
271 })?;
272 self.aligned("source rows", "source rows", values.len())?;
273 self.plot = self.plot.source_rows(values);
274 Ok(self)
275 }
276 #[must_use]
278 pub fn facet(mut self, facet: FacetSpec) -> Self
279 where
280 K: kind::Facet,
281 {
282 self.bindings.facet = Some(facet.clone());
283 self.plot = self.plot.facet(facet);
284 self
285 }
286 pub fn facet_row(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
288 where
289 K: kind::Facet,
290 {
291 let values = self.category_rows(values, "facet row")?;
292 Ok(self.facet(FacetSpec::row(values)))
293 }
294 pub fn facet_column(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
296 where
297 K: kind::Facet,
298 {
299 let values = self.category_rows(values, "facet column")?;
300 Ok(self.facet(FacetSpec::column(values)))
301 }
302 pub fn facet_grid(
304 self,
305 row: impl CategoryInput,
306 column: impl CategoryInput,
307 ) -> std::result::Result<Self, AdapterError>
308 where
309 K: kind::Facet,
310 {
311 let capture = self.capture();
312 let copies = self.row_copies();
313 let row = self.captured_category(&capture, row, "facet row", copies)?;
314 let column = self.captured_category(&capture, column, "facet column", copies)?;
315 Ok(self.facet(FacetSpec::grid(row, column)?))
316 }
317 pub fn facet_wrap(
319 self,
320 values: impl CategoryInput,
321 columns: usize,
322 ) -> std::result::Result<Self, AdapterError>
323 where
324 K: kind::Facet,
325 {
326 let values = self.category_rows(values, "facet wrap")?;
327 Ok(self.facet(FacetSpec::wrap(values, columns)?))
328 }
329 pub fn facet_scales(self, scales: FacetScales) -> std::result::Result<Self, AdapterError>
331 where
332 K: kind::Facet,
333 {
334 let facet = self
335 .bindings
336 .facet
337 .clone()
338 .ok_or_else(|| binding("facet scales", "select a facet first"))?;
339 Ok(self.facet(facet.scales(scales)))
340 }
341}
342impl<K: kind::Marker> PlotAdapter<'static, K> {
343 #[must_use]
361 pub fn from_parts(plot: Plot<K>, metadata: BindingMetadata<K>) -> Self {
362 Self {
363 plot,
364 source: None,
365 bindings: metadata,
366 }
367 }
368
369 pub fn from_parts_with_data<'source>(
378 plot: Plot<K>,
379 mut metadata: BindingMetadata<K>,
380 source: impl ArraySource + 'source,
381 ) -> std::result::Result<PlotAdapter<'source, K>, AdapterError> {
382 metadata.source_ref = Some(crate::data::DataSourceRef::capture());
383 Ok(PlotAdapter {
384 plot,
385 source: context(source)?,
386 bindings: metadata,
387 })
388 }
389}
390macro_rules! category_binding {
391 ($name:ident,$cap:ident) => {
392 impl<K:kind::$cap> PlotAdapter<'_,K> {
393 #[doc = concat!("Bind row-scoped native ",stringify!($name)," from a column or categorical vector.")]
394 pub fn $name(mut self,values:impl CategoryInput) -> std::result::Result<Self,AdapterError> {
395 let values=self.category_rows(values,stringify!($name))?; self.plot=self.plot.$name(values); Ok(self)
396 }
397 }
398 };
399}
400category_binding!(hue, Hue);
401category_binding!(group, Group);
402category_binding!(series, Series);
403impl<K: kind::ExactFamily> PlotAdapter<'_, K> {
404 pub fn erase(self) -> Plot<kind::Any> {
406 self.plot.erase()
407 }
408}
409impl<K: kind::Marker> From<PlotAdapter<'_, K>> for Plot<K> {
410 fn from(adapter: PlotAdapter<'_, K>) -> Self {
411 adapter.plot
412 }
413}