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::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/// Source-free binding state paired with one native exact-family [`Plot`].
37///
38/// [`PlotAdapter::into_parts`] moves this state out without retaining the array
39/// lookup context. It preserves alignment, generated origins and the adapter's
40/// current native label/facet policies for later restoration.
41///
42/// Keep this metadata paired with the Plot configuration that produced it.
43/// The family marker prevents cross-family pairing, not mismatched versions of
44/// the same family. Metadata contains neither a Plot nor a lookup source.
45#[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    /// Resolve an actual generated field's key variable for a binding bridge.
60    #[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    /// Apply the existing alpha row/cell alignment to a captured host variable.
74    #[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    /// Actual geometry of a wide record binding.
88    #[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    /// Actual explicitly rectangular domain, if present.
96    #[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    /// Actual row-to-cell expansion count for binding bridges.
105    #[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    /// The actual generated field and its retained, ordered column identities.
114    /// Binding bridges can resolve external keys without consulting a new source.
115    #[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/// A native exact-family plot and an optional safely borrowed array lookup context.
122/// Direct views are snapshotted and released at each binding; `.into()` releases
123/// the retained source and moves the owned native plot without rendering.
124/// [`Self::into_parts`] also preserves the source-free binding metadata.
125#[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    /// End source lookup and move out the native Plot with its binding metadata.
190    ///
191    /// This does not render, prepare scientific data or retain the source borrow.
192    /// Keep both returned values from the same configuration together.
193    ///
194    /// ```
195    /// use lichtung_plot_ndarray::{Scatter, plots::PlotKind};
196    /// use ndarray::array;
197    ///
198    /// let (plot, metadata) = {
199    ///     let source = array![[0., 1.], [1., 0.]];
200    ///     let adapted = Scatter::from_data(source.view(), 0, 1)?;
201    ///     adapted.into_parts()
202    /// };
203    /// let restored = Scatter::from_parts(plot, metadata);
204    /// assert_eq!(restored.kind(), PlotKind::Scatter);
205    /// # Ok::<(), lichtung_plot_ndarray::AdapterError>(())
206    /// ```
207    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    /// Inspect the native exact family without erasing it.
249    pub fn kind(&self) -> PlotKind {
250        self.plot.kind()
251    }
252    /// Replace the authored label policy, retaining captured variable identities.
253    #[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    /// Bind unique exact IDs, never repeating row IDs across expanded cells.
260    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    /// Apply a complete native facet without reinterpreting its slots.
277    #[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    /// Split panel rows by a row-scoped categorical variable.
287    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    /// Split panel columns by a row-scoped categorical variable.
295    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    /// Cross two row-scoped categorical variables, replacing the complete facet.
303    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    /// Wrap a row-scoped categorical variable into a positive number of columns.
318    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    /// Change scale sharing on an existing facet; each new facet resets this policy.
330    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    /// Restore a native Plot and its metadata without a lookup source.
344    ///
345    /// No scientific validation or version check runs here. The caller must
346    /// supply the matching Plot/metadata configuration; the family marker alone
347    /// does not establish that they came from the same version.
348    /// Direct variable bindings remain available; selectors need an explicit
349    /// source through [`Self::from_parts_with_data`].
350    ///
351    /// Metadata from another family cannot be paired with this Plot:
352    ///
353    /// ```compile_fail
354    /// use lichtung_plot_ndarray::{kind, Plot, Scatter, binding::BindingMetadata};
355    ///
356    /// fn wrong_family(plot: Plot<kind::Scatter>, metadata: BindingMetadata<kind::Line>) {
357    ///     let _ = Scatter::from_parts(plot, metadata);
358    /// }
359    /// ```
360    #[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    /// Restore a matching Plot/metadata pair with a new array lookup context.
370    ///
371    /// Validates the source's structural validity shape exactly as `from_data`
372    /// does, without rebinding existing values, rendering or scientific preflight.
373    /// The source height need not equal the old Plot's slots; subsequent bindings
374    /// retain their existing domain-specific alignment checks.
375    ///
376    /// The caller must keep the Plot and metadata from the same configuration.
377    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    /// End source lookup and return the native erased plot.
405    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}