Skip to main content

lichtung_plot_ndarray/frontend/
geometry.rs

1//! Independent column domains; scientific validation and grouping stay native.
2
3use super::{context, Context, PlotAdapter};
4use crate::capture::Capture;
5use crate::error::{length, BindingResult};
6use crate::{
7    binding::{ArraySource, CategoryInput, NumericInput},
8    kind,
9    plots::{
10        HistogramComposite, HistogramGeometry, HistogramInput, HistogramKde, RaincloudGeometry,
11        RaincloudInput,
12    },
13    stats::HistogramStat,
14    AdapterError, Plot,
15};
16
17// Each domain has its own selector context and length. Only the main context is
18// moved into the frontend; auxiliary borrows end after these snapshots.
19macro_rules! columnar_geometry {
20    ($family:ident, $direct:ident, $from:ident, $bind:ident,
21        ($first:ident: $input:ident => $method:ident $(, $arg:ident: $arg_input:ident => $arg_method:ident)*),
22        ($(($aux:ident => $head:ident: $head_input:ident => $head_method:ident $(, $tail:ident: $tail_input:ident => $tail_method:ident)*)),+),
23        ($($dimension:ident),+), $points:expr, $plot:expr) => {
24        impl<'source> PlotAdapter<'source, kind::$family> {
25            /// Snapshot complete geometry from direct columns in main/auxiliary
26            /// domain order, followed by scientific dimension names.
27            #[expect(clippy::too_many_arguments, reason = "complete columnar geometry keeps every scientific role explicit")]
28            pub fn $direct(
29                $first: impl $input, $($arg: impl $arg_input,)*
30                $($head: impl $head_input, $($tail: impl $tail_input,)*)+
31                $($dimension: impl Into<String>),+
32            ) -> std::result::Result<Self, AdapterError> {
33                $(let $aux = None;)+
34                Self::$bind(None, $($aux,)+ $first, $($arg,)* $($head, $($tail,)*)+ $($dimension),+)
35            }
36
37            /// Snapshot independently selected/direct component columns. The main
38            /// source is retained; each optional auxiliary source is used only
39            /// for its own domain, with no cross-domain selector fallback.
40            #[expect(clippy::too_many_arguments, reason = "independent sources precede explicit complete geometry roles")]
41            pub fn $from(
42                source: impl ArraySource + 'source, $($aux: Option<&dyn ArraySource>,)+
43                $first: impl $input, $($arg: impl $arg_input,)*
44                $($head: impl $head_input, $($tail: impl $tail_input,)*)+
45                $($dimension: impl Into<String>),+
46            ) -> std::result::Result<Self, AdapterError> {
47                Self::$bind(context(source)?, $($aux,)+ $first, $($arg,)* $($head, $($tail,)*)+ $($dimension),+)
48            }
49
50            #[expect(clippy::too_many_arguments, reason = "private extraction mirrors the public complete geometry roles")]
51            fn $bind(
52                source: Context<'source>, $($aux: Option<&dyn ArraySource>,)+
53                $first: impl $input, $($arg: impl $arg_input,)*
54                $($head: impl $head_input, $($tail: impl $tail_input,)*)+
55                $($dimension: impl Into<String>),+
56            ) -> BindingResult<Self> {
57                $(if let Some(aux) = $aux { aux.validate()?; })+
58                let capture = Capture::new(source.as_deref());
59                let $first = capture.bind($first, 1, |input, source| input.$method(source, stringify!($first)))?;
60                let len = $first.len();
61                $(let $arg = capture.bind($arg, 1, |input, source| input.$arg_method(source, stringify!($arg)))?;
62                length(stringify!($arg), $arg.name(), len, $arg.len())?;)*
63                $(let auxiliary = Capture::new($aux);
64                let $head = auxiliary.bind($head, 1, |input, source| input.$head_method(source, stringify!($head)))?;
65                let len = $head.len();
66                $(let $tail = auxiliary.bind($tail, 1, |input, source| input.$tail_method(source, stringify!($tail)))?;
67                length(stringify!($tail), $tail.name(), len, $tail.len())?;)*)+
68                let points = $points;
69                let reference = capture.reference();
70                let mut adapter = Self::bound($plot, source, None, reference);
71                adapter.bindings.geometry_points = points;
72                Ok(adapter)
73            }
74        }
75    };
76}
77
78impl<'source> PlotAdapter<'source, kind::Histogram> {
79    /// Snapshot supplied bin edges and heights, with their declared statistic.
80    pub fn geometry(
81        lower: impl NumericInput,
82        upper: impl NumericInput,
83        height: impl NumericInput,
84        stat: HistogramStat,
85    ) -> std::result::Result<Self, AdapterError> {
86        Self::bind_geometry(None, lower, upper, height, stat)
87    }
88
89    /// Snapshot the selected bin columns and retain only their main lookup context.
90    pub fn geometry_from_data(
91        source: impl ArraySource + 'source,
92        lower: impl NumericInput,
93        upper: impl NumericInput,
94        height: impl NumericInput,
95        stat: HistogramStat,
96    ) -> std::result::Result<Self, AdapterError> {
97        Self::bind_geometry(context(source)?, lower, upper, height, stat)
98    }
99
100    fn bind_geometry(
101        source: Context<'source>,
102        lower: impl NumericInput,
103        upper: impl NumericInput,
104        height: impl NumericInput,
105        stat: HistogramStat,
106    ) -> BindingResult<Self> {
107        let capture = Capture::new(source.as_deref());
108        let lower = capture.bind(lower, 1, |input, source| {
109            input.bind_numeric(source, "bin_lower")
110        })?;
111        let upper = capture.bind(upper, 1, |input, source| {
112            input.bind_numeric(source, "bin_upper")
113        })?;
114        let height = capture.bind(height, 1, |input, source| {
115            input.bind_numeric(source, stat.name())
116        })?;
117        length("bin_upper", upper.name(), lower.len(), upper.len())?;
118        length("bin_height", height.name(), lower.len(), height.len())?;
119        let geometry = HistogramGeometry::bins(lower, upper, height, stat);
120        let reference = capture.reference();
121        Ok(Self::bound(
122            Plot::histogram(HistogramInput::geometry(geometry)),
123            source,
124            None,
125            reference,
126        ))
127    }
128}
129
130columnar_geometry!(Raincloud, geometry, geometry_from_data, raincloud_geometry,
131(category: CategoryInput => bind_category, q1: NumericInput => bind_numeric,
132    median: NumericInput => bind_numeric, q3: NumericInput => bind_numeric),
133((density_source => density_category: CategoryInput => bind_category,
134    density_y: NumericInput => bind_numeric, normalized_width: NumericInput => bind_numeric),
135 (points_source => point_category: CategoryInput => bind_category,
136    point_y: NumericInput => bind_numeric, normalized_strip: NumericInput => bind_numeric)),
137(category_dimension, value_dimension), Some(point_y.len()),
138Plot::raincloud(RaincloudInput::geometry(RaincloudGeometry::new(category_dimension, value_dimension, category, q1, median, q3, density_category, density_y, normalized_width, point_category, point_y, normalized_strip))));
139
140columnar_geometry!(Raincloud, geometry_with_hue, geometry_with_hue_from_data, hued_raincloud_geometry,
141(category: CategoryInput => bind_category, hue: CategoryInput => bind_category,
142    q1: NumericInput => bind_numeric, median: NumericInput => bind_numeric, q3: NumericInput => bind_numeric),
143((density_source => density_category: CategoryInput => bind_category, density_hue: CategoryInput => bind_category,
144    density_y: NumericInput => bind_numeric, normalized_width: NumericInput => bind_numeric),
145 (points_source => point_category: CategoryInput => bind_category, point_hue: CategoryInput => bind_category,
146    point_y: NumericInput => bind_numeric, normalized_strip: NumericInput => bind_numeric)),
147(category_dimension, value_dimension, hue_dimension), Some(point_y.len()),
148Plot::raincloud(RaincloudInput::geometry(RaincloudGeometry::new(category_dimension, value_dimension, category, q1, median, q3, density_category, density_y, normalized_width, point_category, point_y, normalized_strip).with_hue(hue_dimension, hue, density_hue, point_hue))));
149
150impl PlotAdapter<'_, kind::Raincloud> {
151    /// Consume an already owned native raincloud geometry directly.
152    pub fn from_geometry(geometry: RaincloudGeometry) -> Self {
153        let len = geometry.point_y().len();
154        Self::bound(
155            Plot::raincloud(RaincloudInput::geometry(geometry)),
156            None,
157            Some(len),
158            None,
159        )
160    }
161
162    /// Borrow the actual supplied raincloud geometry.
163    pub fn get_geometry(&self) -> Option<&RaincloudGeometry> {
164        self.plot.get_geometry()
165    }
166}
167
168impl PlotAdapter<'_, kind::Histogram> {
169    /// Consume an already owned native histogram geometry directly.
170    pub fn from_geometry(geometry: HistogramGeometry) -> Self {
171        Self::bound(
172            Plot::histogram(HistogramInput::geometry(geometry)),
173            None,
174            None,
175            None,
176        )
177    }
178
179    /// Borrow the actual supplied geometry, if any.
180    pub fn get_geometry(&self) -> Option<&HistogramGeometry> {
181        self.plot.get_geometry()
182    }
183
184    /// Add or replace the given KDE using direct columns in its own domain.
185    pub fn kde(
186        self,
187        x: impl NumericInput,
188        density: impl NumericInput,
189    ) -> std::result::Result<Self, AdapterError> {
190        self.bind_supplied_kde(None, x, density)
191    }
192
193    /// Snapshot KDE columns from their own auxiliary source.
194    pub fn kde_from_data(
195        self,
196        source: impl ArraySource,
197        x: impl NumericInput,
198        density: impl NumericInput,
199    ) -> std::result::Result<Self, AdapterError> {
200        source.validate()?;
201        self.bind_supplied_kde(Some(&source), x, density)
202    }
203
204    fn bind_supplied_kde(
205        mut self,
206        source: Option<&dyn ArraySource>,
207        x: impl NumericInput,
208        density: impl NumericInput,
209    ) -> BindingResult<Self> {
210        let capture = Capture::new(source);
211        let x = capture.bind(x, 1, |input, source| input.bind_numeric(source, "KDE x"))?;
212        let density = capture.bind(density, 1, |input, source| {
213            input.bind_numeric(source, "KDE density")
214        })?;
215        length("KDE density", density.name(), x.len(), density.len())?;
216        self.plot = self.plot.kde(x, density)?;
217        Ok(self)
218    }
219
220    /// Add or replace independently supplied rug segments from direct columns.
221    pub fn rug(
222        self,
223        x: impl NumericInput,
224        baseline: impl NumericInput,
225        top: impl NumericInput,
226    ) -> std::result::Result<Self, AdapterError> {
227        self.bind_rug(None, x, baseline, top)
228    }
229
230    /// Snapshot rug columns from their own auxiliary source.
231    pub fn rug_from_data(
232        self,
233        source: impl ArraySource,
234        x: impl NumericInput,
235        baseline: impl NumericInput,
236        top: impl NumericInput,
237    ) -> std::result::Result<Self, AdapterError> {
238        source.validate()?;
239        self.bind_rug(Some(&source), x, baseline, top)
240    }
241
242    fn bind_rug(
243        mut self,
244        source: Option<&dyn ArraySource>,
245        x: impl NumericInput,
246        baseline: impl NumericInput,
247        top: impl NumericInput,
248    ) -> BindingResult<Self> {
249        let capture = Capture::new(source);
250        let x = capture.bind(x, 1, |input, source| input.bind_numeric(source, "value"))?;
251        let baseline = capture.bind(baseline, 1, |input, source| {
252            input.bind_numeric(source, "rug_baseline")
253        })?;
254        let top = capture.bind(top, 1, |input, source| {
255            input.bind_numeric(source, "rug_top")
256        })?;
257        length("rug_baseline", baseline.name(), x.len(), baseline.len())?;
258        length("rug_top", top.name(), x.len(), top.len())?;
259        self.plot = self.plot.rug(x, baseline, top)?;
260        Ok(self)
261    }
262
263    /// Set the original scientific x dimension of supplied geometry.
264    pub fn value_dimension(
265        mut self,
266        name: impl Into<String>,
267    ) -> std::result::Result<Self, AdapterError> {
268        self.plot = self.plot.value_dimension(name)?;
269        Ok(self)
270    }
271
272    /// Set the original scientific height dimension of supplied geometry.
273    pub fn height_dimension(
274        mut self,
275        name: impl Into<String>,
276    ) -> std::result::Result<Self, AdapterError> {
277        self.plot = self.plot.height_dimension(name)?;
278        Ok(self)
279    }
280
281    /// Snapshot direct KDE columns for the sample-owned KDE+rug composite.
282    /// Samples, bins, stat and the main lookup context are unchanged.
283    pub fn composite_precomputed_kde(
284        self,
285        x: impl NumericInput,
286        y: impl NumericInput,
287    ) -> std::result::Result<Self, AdapterError> {
288        self.bind_kde(None, x, y)
289    }
290
291    /// Snapshot KDE from an independent source, retaining no borrow of it and
292    /// never using the main source as a selector fallback.
293    pub fn composite_precomputed_kde_from_data(
294        self,
295        source: impl ArraySource,
296        x: impl NumericInput,
297        y: impl NumericInput,
298    ) -> std::result::Result<Self, AdapterError> {
299        source.validate()?;
300        self.bind_kde(Some(&source), x, y)
301    }
302
303    fn bind_kde(
304        mut self,
305        source: Option<&dyn ArraySource>,
306        x: impl NumericInput,
307        y: impl NumericInput,
308    ) -> BindingResult<Self> {
309        let capture = Capture::new(source);
310        let x = capture.bind(x, 1, |input, source| input.bind_numeric(source, "KDE x"))?;
311        let y = capture.bind(y, 1, |input, source| input.bind_numeric(source, "KDE y"))?;
312        length("KDE y", y.name(), x.len(), y.len())?;
313        self.plot = self
314            .plot
315            .composite(HistogramComposite::KdeAndRug(HistogramKde::Precomputed {
316                x,
317                y,
318            }));
319        Ok(self)
320    }
321}
322
323#[cfg(test)]
324mod tests;