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    grid: Option<grid::Grid>,
52    expansion: Option<wide::Expansion>,
53    matrix_keys: Option<Vec<String>>,
54    marker: PhantomData<K>,
55}
56
57impl<K: kind::Marker> BindingMetadata<K> {
58    /// Restore source-free editing metadata from an actual native collection.
59    #[doc(hidden)]
60    pub fn restore_collection(plot: &Plot<K>) -> BindingResult<Option<Self>> {
61        use crate::data::CapturedCollection;
62        let Some(collection) = plot.captured_collection() else {
63            return Ok(None);
64        };
65        let (len, grid, expansion, matrix_keys) = match collection {
66            CapturedCollection::Wide(source) => {
67                let expansion = wide::Expansion::restore(source)?;
68                (
69                    expansion.rows.checked_mul(expansion.keys.len()),
70                    None,
71                    Some(expansion),
72                    None,
73                )
74            }
75            CapturedCollection::Grid { source, x, y } => (
76                Some(x.len()),
77                Some(grid::Grid::restore(source, x, y)),
78                None,
79                None,
80            ),
81            CapturedCollection::Matrix(variables) => {
82                let keys = variables
83                    .variables()
84                    .iter()
85                    .map(|column| column.values.name().to_owned())
86                    .collect();
87                (
88                    variables.get_at(0).map(|column| column.values.len()),
89                    None,
90                    None,
91                    Some(keys),
92                )
93            }
94        };
95        Ok(Some(Self {
96            len,
97            source_ref: None,
98            geometry_points: None,
99            labels: plot.get_labels().clone(),
100            grid,
101            expansion,
102            matrix_keys,
103            marker: PhantomData,
104        }))
105    }
106
107    /// Resolve an actual generated field's key variable for a binding bridge.
108    #[doc(hidden)]
109    pub fn column_alpha_key(
110        &self,
111        source: Option<&dyn ArraySource>,
112        input: impl SourceRowsInput,
113    ) -> BindingResult<crate::CategoryValues> {
114        let expansion = self
115            .expansion
116            .as_ref()
117            .ok_or_else(|| binding("column alpha", "no generated variable dimension"))?;
118        expansion.column_key(&Capture::new(source), source, input)
119    }
120
121    /// Apply the existing alpha row/cell alignment to a captured host variable.
122    #[doc(hidden)]
123    pub fn expand_alpha(
124        &self,
125        values: crate::scales::AlphaValues,
126        rows: bool,
127    ) -> BindingResult<crate::scales::AlphaValues> {
128        crate::alpha::expand(
129            values,
130            self.geometry_points.or(self.len),
131            if rows { self.row_copies() } else { 1 },
132            rows && self.cell_shape().is_some(),
133        )
134    }
135
136    /// Actual geometry of a wide record binding.
137    #[doc(hidden)]
138    pub fn wide_shape(&self) -> Option<(usize, usize)> {
139        self.expansion
140            .as_ref()
141            .map(|wide| (wide.rows, wide.keys.len()))
142    }
143
144    /// Actual explicitly rectangular domain, if present.
145    #[doc(hidden)]
146    pub fn cell_shape(&self) -> Option<(usize, usize)> {
147        self.grid
148            .as_ref()
149            .map(|grid| (grid.rows(), grid.columns()))
150            .or_else(|| self.wide_shape())
151    }
152
153    /// Actual row-to-cell expansion count for binding bridges.
154    #[doc(hidden)]
155    pub fn row_copies(&self) -> usize {
156        self.expansion.as_ref().map_or_else(
157            || self.grid.as_ref().map_or(1, grid::Grid::columns),
158            |wide| wide.keys.len(),
159        )
160    }
161
162    /// The actual generated field and its retained, ordered column identities.
163    /// Binding bridges can resolve external keys without consulting a new source.
164    #[doc(hidden)]
165    pub fn named_generated_columns(&self) -> Option<(&str, &[String], &[crate::data::RawKey])> {
166        self.expansion.as_ref()?.named_columns()
167    }
168}
169
170/// A native exact-family plot and an optional safely borrowed array lookup context.
171/// Direct views are snapshotted and released at each binding; `.into()` releases
172/// the retained source and moves the owned native plot without rendering.
173/// [`Self::into_parts`] also preserves the source-free binding metadata.
174#[derive(Clone)]
175pub struct PlotAdapter<'source, K: kind::Marker> {
176    plot: Plot<K>,
177    pub(crate) source: Context<'source>,
178    bindings: BindingMetadata<K>,
179}
180
181macro_rules! families {
182    ($($family:ident),+) => {$ (
183        #[doc = concat!("ndarray frontend for native ", stringify!($family), ".")]
184        pub type $family<'source> = PlotAdapter<'source, kind::$family>;
185    )+};
186}
187families!(
188    Scatter,
189    Histogram,
190    Density,
191    Qq,
192    PointInterval,
193    Line,
194    Trajectory,
195    LinePath,
196    Interaction,
197    Coefficient,
198    Forest,
199    Dumbbell,
200    Heatmap,
201    Bar,
202    HorizontalBar,
203    StackedBar,
204    StackedHorizontalBar,
205    Boxplot,
206    Violin,
207    Raincloud,
208    Regression,
209    Marginal,
210    Matrix,
211    Beeswarm,
212    Waterfall
213);
214
215impl<'source, K: kind::Marker> PlotAdapter<'source, K> {
216    fn bound(
217        plot: Plot<K>,
218        source: Context<'source>,
219        len: Option<usize>,
220        source_ref: Option<crate::data::DataSourceRef>,
221    ) -> Self {
222        Self {
223            plot,
224            source,
225            bindings: BindingMetadata {
226                len,
227                source_ref,
228                geometry_points: None,
229                labels: Labels::default(),
230                grid: None,
231                expansion: None,
232                matrix_keys: None,
233                marker: PhantomData,
234            },
235        }
236    }
237    /// End source lookup and move out the native Plot with its binding metadata.
238    ///
239    /// This does not render, prepare scientific data or retain the source borrow.
240    /// Keep both returned values from the same configuration together.
241    ///
242    /// ```
243    /// use lichtung_plot_ndarray::{Scatter, plots::PlotKind};
244    /// use ndarray::array;
245    ///
246    /// let (plot, metadata) = {
247    ///     let source = array![[0., 1.], [1., 0.]];
248    ///     let adapted = Scatter::from_data(source.view(), 0, 1)?;
249    ///     adapted.into_parts()
250    /// };
251    /// let restored = Scatter::from_parts(plot, metadata);
252    /// assert_eq!(restored.kind(), PlotKind::Scatter);
253    /// # Ok::<(), lichtung_plot_ndarray::AdapterError>(())
254    /// ```
255    pub fn into_parts(self) -> (Plot<K>, BindingMetadata<K>) {
256        (self.plot, self.bindings)
257    }
258    fn aligned(&self, role: &'static str, name: &str, actual: usize) -> BindingResult<()> {
259        if let Some(expected) = self.bindings.len {
260            length(role, name, expected, actual)?;
261        }
262        Ok(())
263    }
264    fn row_copies(&self) -> usize {
265        self.bindings.row_copies()
266    }
267    fn alpha_len(&self) -> Option<usize> {
268        self.bindings.geometry_points.or(self.bindings.len)
269    }
270    fn category_rows(
271        &self,
272        values: impl CategoryInput,
273        role: &'static str,
274    ) -> BindingResult<CategoryValues> {
275        let capture = self.capture();
276        self.captured_category(&capture, values, role, self.row_copies(), true)
277    }
278
279    pub(crate) fn capture(&self) -> Capture<'_> {
280        Capture::recapture(self.source.as_deref(), self.bindings.source_ref.as_ref())
281    }
282
283    fn captured_category(
284        &self,
285        capture: &Capture<'_>,
286        values: impl CategoryInput,
287        role: &'static str,
288        copies: usize,
289        rows: bool,
290    ) -> BindingResult<crate::CategoryValues> {
291        let values = capture.bind_scoped(
292            values,
293            copies,
294            rows && self.bindings.cell_shape().is_some(),
295            |input, source| input.bind_category_repeated(source, role, copies),
296        )?;
297        self.aligned(role, values.name(), values.len())?;
298        Ok(values)
299    }
300    /// Inspect the native exact family without erasing it.
301    pub fn kind(&self) -> PlotKind {
302        self.plot.kind()
303    }
304    /// Replace the authored label policy, retaining captured variable identities.
305    #[must_use]
306    pub fn labels(mut self, labels: Labels) -> Self {
307        self.plot = self.plot.labels(labels);
308        self.bindings.labels = self.plot.get_labels().clone();
309        self
310    }
311    /// Bind unique exact IDs, never repeating row IDs across expanded cells.
312    pub fn source_rows(
313        mut self,
314        values: impl SourceRowsInput,
315    ) -> std::result::Result<Self, AdapterError>
316    where
317        K: kind::SourceRows,
318    {
319        self.cell_shape(&values, "source rows")?;
320        let capture = self.capture();
321        let values = capture.bind(values, 1, |input, source| {
322            input.bind_source_rows_repeated(source, "source rows", self.row_copies())
323        })?;
324        self.aligned("source rows", "source rows", values.len())?;
325        self.plot = self.plot.source_rows(values);
326        Ok(self)
327    }
328    /// Apply a complete native facet without reinterpreting its slots.
329    #[must_use]
330    pub fn facet(mut self, facet: FacetSpec) -> Self
331    where
332        K: kind::Facet,
333    {
334        self.plot = self.plot.facet(facet);
335        self
336    }
337    /// Split panel rows by a row-scoped categorical variable.
338    pub fn facet_row(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
339    where
340        K: kind::Facet,
341    {
342        let values = self.category_rows(values, "facet row")?;
343        Ok(self.facet(FacetSpec::row(values)))
344    }
345    /// Split panel columns by a row-scoped categorical variable.
346    pub fn facet_column(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
347    where
348        K: kind::Facet,
349    {
350        let values = self.category_rows(values, "facet column")?;
351        Ok(self.facet(FacetSpec::column(values)))
352    }
353    /// Cross two row-scoped categorical variables, replacing the complete facet.
354    pub fn facet_grid(
355        self,
356        row: impl CategoryInput,
357        column: impl CategoryInput,
358    ) -> std::result::Result<Self, AdapterError>
359    where
360        K: kind::Facet,
361    {
362        let capture = self.capture();
363        let copies = self.row_copies();
364        let row = self.captured_category(&capture, row, "facet row", copies, true)?;
365        let column = self.captured_category(&capture, column, "facet column", copies, true)?;
366        Ok(self.facet(FacetSpec::grid(row, column)?))
367    }
368    /// Wrap a row-scoped categorical variable into a positive number of columns.
369    pub fn facet_wrap(
370        self,
371        values: impl CategoryInput,
372        columns: usize,
373    ) -> std::result::Result<Self, AdapterError>
374    where
375        K: kind::Facet,
376    {
377        let values = self.category_rows(values, "facet wrap")?;
378        Ok(self.facet(FacetSpec::wrap(values, columns)?))
379    }
380    /// Change scale sharing on an existing facet; each new facet resets this policy.
381    pub fn facet_scales(self, scales: FacetScales) -> std::result::Result<Self, AdapterError>
382    where
383        K: kind::Facet,
384    {
385        let facet = self
386            .plot
387            .get_facet()
388            .cloned()
389            .ok_or_else(|| binding("facet scales", "select a facet first"))?;
390        Ok(self.facet(facet.scales(scales)))
391    }
392}
393impl<K: kind::Marker> PlotAdapter<'static, K> {
394    /// Restore a native Plot and its metadata without a lookup source.
395    ///
396    /// No scientific validation or version check runs here. The caller must
397    /// supply the matching Plot/metadata configuration; the family marker alone
398    /// does not establish that they came from the same version.
399    /// Direct variable bindings remain available; selectors need an explicit
400    /// source through [`Self::from_parts_with_data`].
401    ///
402    /// Metadata from another family cannot be paired with this Plot:
403    ///
404    /// ```compile_fail
405    /// use lichtung_plot_ndarray::{kind, Plot, Scatter, binding::BindingMetadata};
406    ///
407    /// fn wrong_family(plot: Plot<kind::Scatter>, metadata: BindingMetadata<kind::Line>) {
408    ///     let _ = Scatter::from_parts(plot, metadata);
409    /// }
410    /// ```
411    #[must_use]
412    pub fn from_parts(plot: Plot<K>, metadata: BindingMetadata<K>) -> Self {
413        Self {
414            plot,
415            source: None,
416            bindings: metadata,
417        }
418    }
419
420    /// Restore a matching Plot/metadata pair with a new array lookup context.
421    ///
422    /// Validates the source's structural validity shape exactly as `from_data`
423    /// does, without rebinding existing values, rendering or scientific preflight.
424    /// The source height need not equal the old Plot's slots; subsequent bindings
425    /// retain their existing domain-specific alignment checks.
426    ///
427    /// The caller must keep the Plot and metadata from the same configuration.
428    pub fn from_parts_with_data<'source>(
429        plot: Plot<K>,
430        mut metadata: BindingMetadata<K>,
431        source: impl ArraySource + 'source,
432    ) -> std::result::Result<PlotAdapter<'source, K>, AdapterError> {
433        metadata.source_ref = Some(crate::data::DataSourceRef::capture());
434        Ok(PlotAdapter {
435            plot,
436            source: context(source)?,
437            bindings: metadata,
438        })
439    }
440}
441macro_rules! category_binding {
442    ($name:ident,$cap:ident) => {
443        impl<K:kind::$cap> PlotAdapter<'_,K> {
444            #[doc = concat!("Bind row-scoped native ",stringify!($name)," from a column or categorical vector.")]
445            pub fn $name(mut self,values:impl CategoryInput) -> std::result::Result<Self,AdapterError> {
446                let values=self.category_rows(values,stringify!($name))?; self.plot=self.plot.$name(values); Ok(self)
447            }
448        }
449    };
450}
451category_binding!(hue, Hue);
452category_binding!(group, Group);
453category_binding!(series, Series);
454impl<K: kind::ExactFamily> PlotAdapter<'_, K> {
455    /// End source lookup and return the native erased plot.
456    pub fn erase(self) -> Plot<kind::Any> {
457        self.plot.erase()
458    }
459}
460impl<K: kind::Marker> From<PlotAdapter<'_, K>> for Plot<K> {
461    fn from(adapter: PlotAdapter<'_, K>) -> Self {
462        adapter.plot
463    }
464}
465
466impl<K: kind::ExactFamily> From<PlotAdapter<'_, K>> for crate::layout::PanelContent {
467    fn from(adapter: PlotAdapter<'_, K>) -> Self {
468        adapter.plot.into()
469    }
470}
471
472impl<K: kind::ExactFamily> From<&PlotAdapter<'_, K>> for crate::layout::PanelContent {
473    fn from(adapter: &PlotAdapter<'_, K>) -> Self {
474        (&adapter.plot).into()
475    }
476}
477
478impl<K: kind::Marker> From<PlotAdapter<'_, K>> for crate::composition::CompositionSource {
479    fn from(adapter: PlotAdapter<'_, K>) -> Self {
480        adapter.plot.into()
481    }
482}
483impl<K: kind::Marker> From<&PlotAdapter<'_, K>> for crate::composition::CompositionSource {
484    fn from(adapter: &PlotAdapter<'_, K>) -> Self {
485        (&adapter.plot).into()
486    }
487}