Skip to main content

lichtung_plot_ndarray/
frontend.rs

1//! Exact-family ownership and source-aware data binding.
2use 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/// Source-free binding state paired with one native exact-family [`Plot`].
32///
33/// [`PlotAdapter::into_parts`] moves this state out without retaining the array
34/// lookup context. It preserves alignment, generated origins and the adapter's
35/// current native label/facet policies for later restoration.
36///
37/// Keep this metadata paired with the Plot configuration that produced it.
38/// The family marker prevents cross-family pairing, not mismatched versions of
39/// the same family. Metadata contains neither a Plot nor a lookup source.
40#[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/// A native exact-family plot and an optional safely borrowed array lookup context.
53/// Direct views are snapshotted and released at each binding; `.into()` releases
54/// the retained source and moves the owned native plot without rendering.
55/// [`Self::into_parts`] also preserves the source-free binding metadata.
56#[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    /// End source lookup and move out the native Plot with its binding metadata.
115    ///
116    /// This does not render, prepare scientific data or retain the source borrow.
117    /// Keep both returned values from the same configuration together.
118    ///
119    /// ```
120    /// use lichtung_plot_ndarray::{Scatter, PlotKind};
121    /// use ndarray::array;
122    ///
123    /// let (plot, metadata) = {
124    ///     let source = array![[0., 1.], [1., 0.]];
125    ///     let adapted = Scatter::from_data(source.view(), 0, 1)?;
126    ///     adapted.into_parts()
127    /// };
128    /// let restored = Scatter::from_parts(plot, metadata);
129    /// assert_eq!(restored.kind(), PlotKind::Scatter);
130    /// # Ok::<(), lichtung_plot_ndarray::AdapterError>(())
131    /// ```
132    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    /// Inspect the native exact family without erasing it.
161    pub fn kind(&self) -> PlotKind {
162        self.plot.kind()
163    }
164    /// Replace the entire native label policy, including generated aliases.
165    #[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    /// Bind unique exact IDs, never repeating row IDs across expanded cells.
172    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    /// Apply a complete native facet without reinterpreting its slots.
190    #[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    /// Split panel rows by a row-scoped categorical variable.
200    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    /// Split panel columns by a row-scoped categorical variable.
208    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    /// Cross two row-scoped categorical variables, replacing the complete facet.
216    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    /// Wrap a row-scoped categorical variable into a positive number of columns.
229    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    /// Change scale sharing on an existing facet; each new facet resets this policy.
241    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    /// Restore a native Plot and its metadata without a lookup source.
255    ///
256    /// No scientific validation or version check runs here. The caller must
257    /// supply the matching Plot/metadata configuration; the family marker alone
258    /// does not establish that they came from the same version.
259    /// Direct variable bindings remain available; selectors need an explicit
260    /// source through [`Self::from_parts_with_data`].
261    ///
262    /// Metadata from another family cannot be paired with this Plot:
263    ///
264    /// ```compile_fail
265    /// use lichtung_plot_ndarray::{kind, BindingMetadata, Plot, Scatter};
266    ///
267    /// fn wrong_family(plot: Plot<kind::Scatter>, metadata: BindingMetadata<kind::Line>) {
268    ///     let _ = Scatter::from_parts(plot, metadata);
269    /// }
270    /// ```
271    #[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    /// Restore a matching Plot/metadata pair with a new array lookup context.
281    ///
282    /// Validates the source's structural validity shape exactly as `from_data`
283    /// does, without rebinding existing values, rendering or scientific preflight.
284    /// The source height need not equal the old Plot's slots; subsequent bindings
285    /// retain their existing domain-specific alignment checks.
286    ///
287    /// The caller must keep the Plot and metadata from the same configuration.
288    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    /// End source lookup and return the native erased plot.
315    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}