1use std::marker::PhantomData;
3use std::rc::Rc;
4
5use crate::error::{binding, length, BindingResult};
6use crate::{
7 kind, AdapterError, ArraySource, CategoryInput, CategoryValues, FacetScales, FacetSpec, Labels,
8 Plot, PlotKind, SourceRowsInput,
9};
10
11mod alpha;
12mod constructors;
13mod forwarding;
14mod geometry;
15mod grid;
16#[cfg(test)]
17mod metadata_tests;
18#[cfg(test)]
19mod projection_tests;
20mod status;
21mod wide;
22
23pub(crate) type Context<'source> = Option<Rc<dyn ArraySource + 'source>>;
24pub(crate) fn context<'source>(
25 source: impl ArraySource + 'source,
26) -> BindingResult<Context<'source>> {
27 source.validate()?;
28 Ok(Some(Rc::new(source)))
29}
30
31#[derive(Clone)]
41pub struct BindingMetadata<K: kind::Marker> {
42 len: Option<usize>,
43 geometry_points: Option<usize>,
44 labels: Labels,
45 facet: Option<FacetSpec>,
46 grid: Option<grid::Grid>,
47 expansion: Option<wide::Expansion>,
48 matrix_keys: Option<Vec<String>>,
49 marker: PhantomData<K>,
50}
51
52#[derive(Clone)]
57pub struct PlotAdapter<'source, K: kind::Marker> {
58 plot: Plot<K>,
59 pub(crate) source: Context<'source>,
60 bindings: BindingMetadata<K>,
61}
62
63macro_rules! families {
64 ($($family:ident),+) => {$ (
65 #[doc = concat!("ndarray frontend for native ", stringify!($family), ".")]
66 pub type $family<'source> = PlotAdapter<'source, kind::$family>;
67 )+};
68}
69families!(
70 Scatter,
71 Histogram,
72 Density,
73 Qq,
74 PointInterval,
75 Line,
76 Trajectory,
77 LinePath,
78 Interaction,
79 Coefficient,
80 Forest,
81 Dumbbell,
82 Heatmap,
83 Bar,
84 HorizontalBar,
85 StackedBar,
86 StackedHorizontalBar,
87 Boxplot,
88 Violin,
89 Raincloud,
90 Regression,
91 Marginal,
92 Matrix,
93 Beeswarm,
94 Waterfall
95);
96
97impl<'source, K: kind::Marker> PlotAdapter<'source, K> {
98 fn bound(plot: Plot<K>, source: Context<'source>, len: Option<usize>) -> Self {
99 Self {
100 plot,
101 source,
102 bindings: BindingMetadata {
103 len,
104 geometry_points: None,
105 labels: Labels::default(),
106 facet: None,
107 grid: None,
108 expansion: None,
109 matrix_keys: None,
110 marker: PhantomData,
111 },
112 }
113 }
114 pub fn into_parts(self) -> (Plot<K>, BindingMetadata<K>) {
133 (self.plot, self.bindings)
134 }
135 fn aligned(&self, role: &'static str, name: &str, actual: usize) -> BindingResult<()> {
136 if let Some(expected) = self.bindings.len {
137 length(role, name, expected, actual)?;
138 }
139 Ok(())
140 }
141 fn row_copies(&self) -> usize {
142 self.bindings.expansion.as_ref().map_or_else(
143 || self.bindings.grid.as_ref().map_or(1, grid::Grid::columns),
144 |wide| wide.keys.len(),
145 )
146 }
147 fn alpha_len(&self) -> Option<usize> {
148 self.bindings.geometry_points.or(self.bindings.len)
149 }
150 fn category_rows(
151 &self,
152 values: impl CategoryInput,
153 role: &'static str,
154 ) -> BindingResult<CategoryValues> {
155 let values =
156 values.bind_category_repeated(self.source.as_deref(), role, self.row_copies())?;
157 self.aligned(role, values.name(), values.len())?;
158 Ok(values)
159 }
160 pub fn kind(&self) -> PlotKind {
162 self.plot.kind()
163 }
164 #[must_use]
166 pub fn labels(mut self, labels: Labels) -> Self {
167 self.bindings.labels = labels.clone();
168 self.plot = self.plot.labels(labels);
169 self
170 }
171 pub fn source_rows(
173 mut self,
174 values: impl SourceRowsInput,
175 ) -> std::result::Result<Self, AdapterError>
176 where
177 K: kind::SourceRows,
178 {
179 self.cell_shape(&values, "source rows")?;
180 let values = values.bind_source_rows_repeated(
181 self.source.as_deref(),
182 "source rows",
183 self.row_copies(),
184 )?;
185 self.aligned("source rows", "source rows", values.len())?;
186 self.plot = self.plot.source_rows(values);
187 Ok(self)
188 }
189 #[must_use]
191 pub fn facet(mut self, facet: FacetSpec) -> Self
192 where
193 K: kind::Facet,
194 {
195 self.bindings.facet = Some(facet.clone());
196 self.plot = self.plot.facet(facet);
197 self
198 }
199 pub fn facet_row(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
201 where
202 K: kind::Facet,
203 {
204 let values = self.category_rows(values, "facet row")?;
205 Ok(self.facet(FacetSpec::row(values)))
206 }
207 pub fn facet_column(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
209 where
210 K: kind::Facet,
211 {
212 let values = self.category_rows(values, "facet column")?;
213 Ok(self.facet(FacetSpec::column(values)))
214 }
215 pub fn facet_grid(
217 self,
218 row: impl CategoryInput,
219 column: impl CategoryInput,
220 ) -> std::result::Result<Self, AdapterError>
221 where
222 K: kind::Facet,
223 {
224 let row = self.category_rows(row, "facet row")?;
225 let column = self.category_rows(column, "facet column")?;
226 Ok(self.facet(FacetSpec::grid(row, column)?))
227 }
228 pub fn facet_wrap(
230 self,
231 values: impl CategoryInput,
232 columns: usize,
233 ) -> std::result::Result<Self, AdapterError>
234 where
235 K: kind::Facet,
236 {
237 let values = self.category_rows(values, "facet wrap")?;
238 Ok(self.facet(FacetSpec::wrap(values, columns)?))
239 }
240 pub fn facet_scales(self, scales: FacetScales) -> std::result::Result<Self, AdapterError>
242 where
243 K: kind::Facet,
244 {
245 let facet = self
246 .bindings
247 .facet
248 .clone()
249 .ok_or_else(|| binding("facet scales", "select a facet first"))?;
250 Ok(self.facet(facet.scales(scales)))
251 }
252}
253impl<K: kind::Marker> PlotAdapter<'static, K> {
254 #[must_use]
272 pub fn from_parts(plot: Plot<K>, metadata: BindingMetadata<K>) -> Self {
273 Self {
274 plot,
275 source: None,
276 bindings: metadata,
277 }
278 }
279
280 pub fn from_parts_with_data<'source>(
289 plot: Plot<K>,
290 metadata: BindingMetadata<K>,
291 source: impl ArraySource + 'source,
292 ) -> std::result::Result<PlotAdapter<'source, K>, AdapterError> {
293 Ok(PlotAdapter {
294 plot,
295 source: context(source)?,
296 bindings: metadata,
297 })
298 }
299}
300macro_rules! category_binding {
301 ($name:ident,$cap:ident) => {
302 impl<K:kind::$cap> PlotAdapter<'_,K> {
303 #[doc = concat!("Bind row-scoped native ",stringify!($name)," from a column or categorical vector.")]
304 pub fn $name(mut self,values:impl CategoryInput) -> std::result::Result<Self,AdapterError> {
305 let values=self.category_rows(values,stringify!($name))?; self.plot=self.plot.$name(values); Ok(self)
306 }
307 }
308 };
309}
310category_binding!(hue, Hue);
311category_binding!(group, Group);
312category_binding!(series, Series);
313impl<K: kind::ExactFamily> PlotAdapter<'_, K> {
314 pub fn erase(self) -> Plot<kind::Any> {
316 self.plot.erase()
317 }
318}
319impl<K: kind::Marker> From<PlotAdapter<'_, K>> for Plot<K> {
320 fn from(adapter: PlotAdapter<'_, K>) -> Self {
321 adapter.plot
322 }
323}