lichtung-plot-ndarray 0.2.0

Direct scientific plotting from logical ndarray views and columns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Exact-family ownership and source-aware data binding.
use std::marker::PhantomData;
use std::rc::Rc;

use crate::capture::Capture;
use crate::error::{binding, length, BindingResult};
use crate::{
    binding::{ArraySource, CategoryInput, SourceRowsInput},
    formatting::Labels,
    kind,
    layout::{FacetScales, FacetSpec},
    plots::PlotKind,
    AdapterError, CategoryValues, Plot,
};

mod alpha;
mod constructors;
mod forwarding;
mod geometry;
mod grid;
#[cfg(test)]
mod metadata_tests;
#[cfg(test)]
mod projection_tests;
mod status;
mod wide;

pub(crate) type Context<'source> = Option<Rc<dyn ArraySource + 'source>>;
pub(crate) fn context<'source>(
    source: impl ArraySource + 'source,
) -> BindingResult<Context<'source>> {
    source.validate()?;
    Ok(Some(Rc::new(source)))
}

/// Source-free binding state paired with one native exact-family [`Plot`].
///
/// [`PlotAdapter::into_parts`] moves this state out without retaining the array
/// lookup context. It preserves alignment, generated origins and the adapter's
/// current native label/facet policies for later restoration.
///
/// Keep this metadata paired with the Plot configuration that produced it.
/// The family marker prevents cross-family pairing, not mismatched versions of
/// the same family. Metadata contains neither a Plot nor a lookup source.
#[derive(Clone)]
pub struct BindingMetadata<K: kind::Marker> {
    len: Option<usize>,
    source_ref: Option<crate::data::DataSourceRef>,
    geometry_points: Option<usize>,
    labels: Labels,
    facet: Option<FacetSpec>,
    grid: Option<grid::Grid>,
    expansion: Option<wide::Expansion>,
    matrix_keys: Option<Vec<String>>,
    marker: PhantomData<K>,
}

impl<K: kind::Marker> BindingMetadata<K> {
    /// Resolve an actual generated field's key variable for a binding bridge.
    #[doc(hidden)]
    pub fn column_alpha_key(
        &self,
        source: Option<&dyn ArraySource>,
        input: impl SourceRowsInput,
    ) -> BindingResult<crate::CategoryValues> {
        let expansion = self
            .expansion
            .as_ref()
            .ok_or_else(|| binding("column alpha", "no generated variable dimension"))?;
        expansion.column_key(&Capture::new(source), source, input)
    }

    /// Apply the existing alpha row/cell alignment to a captured host variable.
    #[doc(hidden)]
    pub fn expand_alpha(
        &self,
        values: crate::scales::AlphaValues,
        rows: bool,
    ) -> BindingResult<crate::scales::AlphaValues> {
        crate::alpha::expand(
            values,
            self.geometry_points.or(self.len),
            if rows { self.row_copies() } else { 1 },
        )
    }

    /// Actual geometry of a wide record binding.
    #[doc(hidden)]
    pub fn wide_shape(&self) -> Option<(usize, usize)> {
        self.expansion
            .as_ref()
            .map(|wide| (wide.rows, wide.keys.len()))
    }

    /// Actual explicitly rectangular domain, if present.
    #[doc(hidden)]
    pub fn cell_shape(&self) -> Option<(usize, usize)> {
        self.grid
            .as_ref()
            .map(|grid| (grid.rows(), grid.columns()))
            .or_else(|| self.wide_shape())
    }

    /// Actual row-to-cell expansion count for binding bridges.
    #[doc(hidden)]
    pub fn row_copies(&self) -> usize {
        self.expansion.as_ref().map_or_else(
            || self.grid.as_ref().map_or(1, grid::Grid::columns),
            |wide| wide.keys.len(),
        )
    }

    /// The actual generated field and its retained, ordered column identities.
    /// Binding bridges can resolve external keys without consulting a new source.
    #[doc(hidden)]
    pub fn named_generated_columns(&self) -> Option<(&str, &[String], &[crate::data::RawKey])> {
        self.expansion.as_ref()?.named_columns()
    }
}

/// A native exact-family plot and an optional safely borrowed array lookup context.
/// Direct views are snapshotted and released at each binding; `.into()` releases
/// the retained source and moves the owned native plot without rendering.
/// [`Self::into_parts`] also preserves the source-free binding metadata.
#[derive(Clone)]
pub struct PlotAdapter<'source, K: kind::Marker> {
    plot: Plot<K>,
    pub(crate) source: Context<'source>,
    bindings: BindingMetadata<K>,
}

macro_rules! families {
    ($($family:ident),+) => {$ (
        #[doc = concat!("ndarray frontend for native ", stringify!($family), ".")]
        pub type $family<'source> = PlotAdapter<'source, kind::$family>;
    )+};
}
families!(
    Scatter,
    Histogram,
    Density,
    Qq,
    PointInterval,
    Line,
    Trajectory,
    LinePath,
    Interaction,
    Coefficient,
    Forest,
    Dumbbell,
    Heatmap,
    Bar,
    HorizontalBar,
    StackedBar,
    StackedHorizontalBar,
    Boxplot,
    Violin,
    Raincloud,
    Regression,
    Marginal,
    Matrix,
    Beeswarm,
    Waterfall
);

impl<'source, K: kind::Marker> PlotAdapter<'source, K> {
    fn bound(
        plot: Plot<K>,
        source: Context<'source>,
        len: Option<usize>,
        source_ref: Option<crate::data::DataSourceRef>,
    ) -> Self {
        Self {
            plot,
            source,
            bindings: BindingMetadata {
                len,
                source_ref,
                geometry_points: None,
                labels: Labels::default(),
                facet: None,
                grid: None,
                expansion: None,
                matrix_keys: None,
                marker: PhantomData,
            },
        }
    }
    /// End source lookup and move out the native Plot with its binding metadata.
    ///
    /// This does not render, prepare scientific data or retain the source borrow.
    /// Keep both returned values from the same configuration together.
    ///
    /// ```
    /// use lichtung_plot_ndarray::{Scatter, plots::PlotKind};
    /// use ndarray::array;
    ///
    /// let (plot, metadata) = {
    ///     let source = array![[0., 1.], [1., 0.]];
    ///     let adapted = Scatter::from_data(source.view(), 0, 1)?;
    ///     adapted.into_parts()
    /// };
    /// let restored = Scatter::from_parts(plot, metadata);
    /// assert_eq!(restored.kind(), PlotKind::Scatter);
    /// # Ok::<(), lichtung_plot_ndarray::AdapterError>(())
    /// ```
    pub fn into_parts(self) -> (Plot<K>, BindingMetadata<K>) {
        (self.plot, self.bindings)
    }
    fn aligned(&self, role: &'static str, name: &str, actual: usize) -> BindingResult<()> {
        if let Some(expected) = self.bindings.len {
            length(role, name, expected, actual)?;
        }
        Ok(())
    }
    fn row_copies(&self) -> usize {
        self.bindings.row_copies()
    }
    fn alpha_len(&self) -> Option<usize> {
        self.bindings.geometry_points.or(self.bindings.len)
    }
    fn category_rows(
        &self,
        values: impl CategoryInput,
        role: &'static str,
    ) -> BindingResult<CategoryValues> {
        let capture = self.capture();
        self.captured_category(&capture, values, role, self.row_copies())
    }

    pub(crate) fn capture(&self) -> Capture<'_> {
        Capture::recapture(self.source.as_deref(), self.bindings.source_ref.as_ref())
    }

    fn captured_category(
        &self,
        capture: &Capture<'_>,
        values: impl CategoryInput,
        role: &'static str,
        copies: usize,
    ) -> BindingResult<crate::CategoryValues> {
        let values = capture.bind(values, copies, |input, source| {
            input.bind_category_repeated(source, role, copies)
        })?;
        self.aligned(role, values.name(), values.len())?;
        Ok(values)
    }
    /// Inspect the native exact family without erasing it.
    pub fn kind(&self) -> PlotKind {
        self.plot.kind()
    }
    /// Replace the authored label policy, retaining captured variable identities.
    #[must_use]
    pub fn labels(mut self, labels: Labels) -> Self {
        self.plot = self.plot.labels(labels);
        self.bindings.labels = self.plot.get_labels().clone();
        self
    }
    /// Bind unique exact IDs, never repeating row IDs across expanded cells.
    pub fn source_rows(
        mut self,
        values: impl SourceRowsInput,
    ) -> std::result::Result<Self, AdapterError>
    where
        K: kind::SourceRows,
    {
        self.cell_shape(&values, "source rows")?;
        let capture = self.capture();
        let values = capture.bind(values, 1, |input, source| {
            input.bind_source_rows_repeated(source, "source rows", self.row_copies())
        })?;
        self.aligned("source rows", "source rows", values.len())?;
        self.plot = self.plot.source_rows(values);
        Ok(self)
    }
    /// Apply a complete native facet without reinterpreting its slots.
    #[must_use]
    pub fn facet(mut self, facet: FacetSpec) -> Self
    where
        K: kind::Facet,
    {
        self.bindings.facet = Some(facet.clone());
        self.plot = self.plot.facet(facet);
        self
    }
    /// Split panel rows by a row-scoped categorical variable.
    pub fn facet_row(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
    where
        K: kind::Facet,
    {
        let values = self.category_rows(values, "facet row")?;
        Ok(self.facet(FacetSpec::row(values)))
    }
    /// Split panel columns by a row-scoped categorical variable.
    pub fn facet_column(self, values: impl CategoryInput) -> std::result::Result<Self, AdapterError>
    where
        K: kind::Facet,
    {
        let values = self.category_rows(values, "facet column")?;
        Ok(self.facet(FacetSpec::column(values)))
    }
    /// Cross two row-scoped categorical variables, replacing the complete facet.
    pub fn facet_grid(
        self,
        row: impl CategoryInput,
        column: impl CategoryInput,
    ) -> std::result::Result<Self, AdapterError>
    where
        K: kind::Facet,
    {
        let capture = self.capture();
        let copies = self.row_copies();
        let row = self.captured_category(&capture, row, "facet row", copies)?;
        let column = self.captured_category(&capture, column, "facet column", copies)?;
        Ok(self.facet(FacetSpec::grid(row, column)?))
    }
    /// Wrap a row-scoped categorical variable into a positive number of columns.
    pub fn facet_wrap(
        self,
        values: impl CategoryInput,
        columns: usize,
    ) -> std::result::Result<Self, AdapterError>
    where
        K: kind::Facet,
    {
        let values = self.category_rows(values, "facet wrap")?;
        Ok(self.facet(FacetSpec::wrap(values, columns)?))
    }
    /// Change scale sharing on an existing facet; each new facet resets this policy.
    pub fn facet_scales(self, scales: FacetScales) -> std::result::Result<Self, AdapterError>
    where
        K: kind::Facet,
    {
        let facet = self
            .bindings
            .facet
            .clone()
            .ok_or_else(|| binding("facet scales", "select a facet first"))?;
        Ok(self.facet(facet.scales(scales)))
    }
}
impl<K: kind::Marker> PlotAdapter<'static, K> {
    /// Restore a native Plot and its metadata without a lookup source.
    ///
    /// No scientific validation or version check runs here. The caller must
    /// supply the matching Plot/metadata configuration; the family marker alone
    /// does not establish that they came from the same version.
    /// Direct variable bindings remain available; selectors need an explicit
    /// source through [`Self::from_parts_with_data`].
    ///
    /// Metadata from another family cannot be paired with this Plot:
    ///
    /// ```compile_fail
    /// use lichtung_plot_ndarray::{kind, Plot, Scatter, binding::BindingMetadata};
    ///
    /// fn wrong_family(plot: Plot<kind::Scatter>, metadata: BindingMetadata<kind::Line>) {
    ///     let _ = Scatter::from_parts(plot, metadata);
    /// }
    /// ```
    #[must_use]
    pub fn from_parts(plot: Plot<K>, metadata: BindingMetadata<K>) -> Self {
        Self {
            plot,
            source: None,
            bindings: metadata,
        }
    }

    /// Restore a matching Plot/metadata pair with a new array lookup context.
    ///
    /// Validates the source's structural validity shape exactly as `from_data`
    /// does, without rebinding existing values, rendering or scientific preflight.
    /// The source height need not equal the old Plot's slots; subsequent bindings
    /// retain their existing domain-specific alignment checks.
    ///
    /// The caller must keep the Plot and metadata from the same configuration.
    pub fn from_parts_with_data<'source>(
        plot: Plot<K>,
        mut metadata: BindingMetadata<K>,
        source: impl ArraySource + 'source,
    ) -> std::result::Result<PlotAdapter<'source, K>, AdapterError> {
        metadata.source_ref = Some(crate::data::DataSourceRef::capture());
        Ok(PlotAdapter {
            plot,
            source: context(source)?,
            bindings: metadata,
        })
    }
}
macro_rules! category_binding {
    ($name:ident,$cap:ident) => {
        impl<K:kind::$cap> PlotAdapter<'_,K> {
            #[doc = concat!("Bind row-scoped native ",stringify!($name)," from a column or categorical vector.")]
            pub fn $name(mut self,values:impl CategoryInput) -> std::result::Result<Self,AdapterError> {
                let values=self.category_rows(values,stringify!($name))?; self.plot=self.plot.$name(values); Ok(self)
            }
        }
    };
}
category_binding!(hue, Hue);
category_binding!(group, Group);
category_binding!(series, Series);
impl<K: kind::ExactFamily> PlotAdapter<'_, K> {
    /// End source lookup and return the native erased plot.
    pub fn erase(self) -> Plot<kind::Any> {
        self.plot.erase()
    }
}
impl<K: kind::Marker> From<PlotAdapter<'_, K>> for Plot<K> {
    fn from(adapter: PlotAdapter<'_, K>) -> Self {
        adapter.plot
    }
}