Skip to main content

lichtung_plot/builder/
accessors.rs

1use crate::Error;
2
3use super::{Plot, PlotDescription};
4use crate::data::{
5    DataColumn, BAR_INTERVAL_LOWER, BAR_INTERVAL_UPPER, BAR_UNITS, COLOR, DUMBBELL_RIGHT,
6    FACET_COLUMN, FACET_ROW, FACET_WRAP, GROUP, HEATMAP_HIGHLIGHT, HUE, INTERVAL_LOWER,
7    INTERVAL_UPPER, SERIES, X, Y,
8};
9use crate::input::{AxisValues, PlotInput};
10use crate::layers::{BarPointLayer, GuideSpec, PointLayer};
11use crate::layout::AuthoredAxisSpec;
12use crate::layout::AxisTick;
13use crate::render::backend::PointStyle;
14use crate::spec::{
15    AxisScale, BarInput, BarSpacing, Bootstrap, CategoryOrder, ConfidenceIntervalAlgorithm,
16    DumbbellEndpoints, ErrorBarKind, HeatmapAnnotations, HeatmapLayout, HeatmapNullRowAnnotation,
17    HistogramBins, HistogramComposite, HistogramStat, LegendPolicy, LegendPosition, LinePathStyle,
18    PlotKind, PlotTextAnnotation, QqLine, RawOverlay, RegressionBand, WaterfallLabels,
19};
20use crate::{HistogramGeometry, NumericFormat, RaincloudGeometry};
21
22impl PlotDescription {
23    pub(crate) fn text_layouts(&self) -> &crate::text::roles::TextRoles {
24        &self.payload.text_layouts
25    }
26
27    pub(crate) fn theme_spec(&self) -> Option<&crate::theme::Theme> {
28        self.payload.theme.as_deref()
29    }
30
31    pub(crate) fn resolve_theme(&self) -> Result<crate::theme::ResolvedTheme, Error> {
32        let mut theme = match self.theme_spec() {
33            Some(theme) => theme.resolve(),
34            None => crate::theme::Theme::publication().resolve(),
35        }?;
36        theme.text_layouts = self.payload.text_layouts.clone();
37        theme.apply_text_defaults(self.kind());
38        Ok(theme)
39    }
40
41    pub(crate) fn source_row_map(&self) -> Option<&crate::SourceRows> {
42        self.payload.source_rows.as_ref()
43    }
44
45    pub(crate) fn configured_source_rows(&self) -> Result<Option<&crate::SourceRows>, Error> {
46        if let Some(rows) = self.source_row_map() {
47            if rows.len() != self.row_count() {
48                return Err(Error::Data(format!(
49                    "chart source-row map has length {}, but chart data has {} rows",
50                    rows.len(),
51                    self.row_count()
52                )));
53            }
54        }
55        Ok(self.source_row_map())
56    }
57
58    pub(crate) fn row_count(&self) -> usize {
59        self.payload.input.len()
60    }
61
62    fn series_values(&self) -> Option<&crate::CategoryValues> {
63        self.payload
64            .input
65            .required_series()
66            .or(self.payload.series.as_ref())
67    }
68
69    fn group_values(&self) -> Option<&crate::CategoryValues> {
70        self.payload
71            .input
72            .required_group()
73            .or(self.payload.group.as_ref())
74    }
75
76    fn color_values(&self) -> Option<&crate::NumericValues> {
77        self.payload.input.continuous_color()
78    }
79
80    pub(crate) fn x_col(&self) -> Option<&'static str> {
81        self.payload.input.x_name().map(|_| X)
82    }
83
84    pub(crate) fn y_col(&self) -> Option<&'static str> {
85        self.payload.input.y_name().map(|_| Y)
86    }
87
88    pub(crate) fn hue_col(&self) -> Option<&'static str> {
89        if self.kind.uses_unified_series() {
90            self.series_values().map(|_| SERIES)
91        } else {
92            self.payload.hue.as_ref().map(|_| HUE)
93        }
94    }
95
96    pub(crate) fn hue_name(&self) -> Option<&str> {
97        if self.kind.uses_unified_series() {
98            self.series_values().map(crate::CategoryValues::name)
99        } else {
100            self.payload.hue.as_ref().map(crate::CategoryValues::name)
101        }
102    }
103
104    pub(crate) fn hue_field(&self) -> Option<crate::data::category::RawField> {
105        if self.kind.uses_unified_series() {
106            self.series_values().map(crate::CategoryValues::raw_field)
107        } else {
108            self.payload
109                .hue
110                .as_ref()
111                .map(crate::CategoryValues::raw_field)
112        }
113    }
114
115    pub(crate) fn group_col(&self) -> Option<&'static str> {
116        if self.kind.uses_unified_series() {
117            self.series_values().map(|_| SERIES)
118        } else {
119            self.group_values().map(|_| GROUP)
120        }
121    }
122
123    pub(crate) fn group_name(&self) -> Option<&str> {
124        if self.kind.uses_unified_series() {
125            self.series_values().map(crate::CategoryValues::name)
126        } else {
127            self.group_values().map(crate::CategoryValues::name)
128        }
129    }
130
131    pub(crate) fn color_col(&self) -> Option<&'static str> {
132        self.color_values().map(|_| COLOR)
133    }
134
135    pub(crate) fn data_column(&self, key: &str) -> Option<DataColumn<'_>> {
136        if key == X {
137            return self.x_data_column();
138        }
139        if key == Y {
140            return self.y_data_column();
141        }
142        match key {
143            HUE => self.payload.hue.as_ref().map(DataColumn::Category),
144            GROUP => self.group_values().map(DataColumn::Category),
145            SERIES => self.series_values().map(DataColumn::Category),
146            COLOR => self.color_values().map(DataColumn::Numeric),
147            HEATMAP_HIGHLIGHT => self
148                .payload
149                .heatmap_highlight
150                .as_ref()
151                .map(DataColumn::Boolean),
152            INTERVAL_LOWER => self
153                .drawable_bounds()
154                .map(|bounds| DataColumn::Numeric(bounds.lower())),
155            INTERVAL_UPPER => self
156                .drawable_bounds()
157                .map(|bounds| DataColumn::Numeric(bounds.upper())),
158            BAR_INTERVAL_LOWER => self
159                .bar_input()
160                .and_then(BarInput::bounds)
161                .map(|bounds| DataColumn::Numeric(bounds.lower())),
162            BAR_INTERVAL_UPPER => self
163                .bar_input()
164                .and_then(BarInput::bounds)
165                .map(|bounds| DataColumn::Numeric(bounds.upper())),
166            BAR_UNITS => self
167                .bar_input()
168                .and_then(BarInput::error_bar)
169                .and_then(|error_bar| match error_bar.kind() {
170                    ErrorBarKind::ConfidenceInterval(interval) => match &interval.algorithm {
171                        ConfidenceIntervalAlgorithm::Bootstrap(Bootstrap {
172                            units: Some(units),
173                            ..
174                        }) => Some(DataColumn::Category(units)),
175                        ConfidenceIntervalAlgorithm::Bootstrap(Bootstrap {
176                            units: None, ..
177                        })
178                        | ConfidenceIntervalAlgorithm::StudentT => None,
179                    },
180                    ErrorBarKind::Hidden
181                    | ErrorBarKind::StandardDeviation(_)
182                    | ErrorBarKind::PercentileInterval(_)
183                    | ErrorBarKind::StandardError(_) => None,
184                }),
185            DUMBBELL_RIGHT => match self.payload.input.as_ref() {
186                PlotInput::Dumbbell { right, .. } => Some(DataColumn::Numeric(right)),
187                _ => None,
188            },
189            FACET_ROW => self
190                .payload
191                .facet
192                .as_ref()
193                .and_then(crate::FacetSpec::row_values)
194                .map(DataColumn::Category),
195            FACET_COLUMN => self
196                .payload
197                .facet
198                .as_ref()
199                .and_then(crate::FacetSpec::column_values)
200                .map(DataColumn::Category),
201            FACET_WRAP => self
202                .payload
203                .facet
204                .as_ref()
205                .and_then(crate::FacetSpec::wrap_values)
206                .map(DataColumn::Category),
207            _ => self
208                .payload
209                .facet
210                .as_ref()
211                .and_then(|facet| facet.values().find(|values| values.name() == key))
212                .map(DataColumn::Category)
213                .or_else(|| match self.payload.input.as_ref() {
214                    PlotInput::Matrix { variables } => variables
215                        .iter()
216                        .find(|values| values.name() == key)
217                        .map(DataColumn::Numeric),
218                    _ => None,
219                }),
220        }
221    }
222
223    fn x_data_column(&self) -> Option<DataColumn<'_>> {
224        match self.payload.input.as_ref() {
225            PlotInput::Scatter { x, .. }
226            | PlotInput::Regression { x, .. }
227            | PlotInput::Marginal { x, .. }
228            | PlotInput::LinePath { x, .. } => Some(DataColumn::Numeric(x)),
229            PlotInput::Histogram { input } => input.samples_input().map(DataColumn::Numeric),
230            PlotInput::Density { values } | PlotInput::Qq { values } => {
231                Some(DataColumn::Numeric(values))
232            }
233            PlotInput::PointInterval { estimate, .. } | PlotInput::Forest { estimate, .. } => {
234                Some(DataColumn::Numeric(estimate))
235            }
236            PlotInput::Coefficient { input, .. } => Some(DataColumn::Numeric(input.values())),
237            PlotInput::Line { x, .. } | PlotInput::Trajectory { x, .. } => match x {
238                AxisValues::Numeric(values) => Some(DataColumn::Numeric(values)),
239                AxisValues::Category(values) => Some(DataColumn::Category(values)),
240            },
241            PlotInput::Interaction { condition, .. }
242            | PlotInput::Dumbbell {
243                category: condition,
244                ..
245            }
246            | PlotInput::Heatmap { x: condition, .. }
247            | PlotInput::Bar {
248                category: condition,
249                ..
250            }
251            | PlotInput::HorizontalBar {
252                category: condition,
253                ..
254            }
255            | PlotInput::StackedBar {
256                category: condition,
257                ..
258            }
259            | PlotInput::StackedHorizontalBar {
260                category: condition,
261                ..
262            }
263            | PlotInput::Boxplot {
264                category: condition,
265                ..
266            }
267            | PlotInput::Violin {
268                category: condition,
269                ..
270            }
271            | PlotInput::Waterfall {
272                labels: condition, ..
273            } => Some(DataColumn::Category(condition)),
274            PlotInput::Raincloud { input } => input
275                .samples_input()
276                .map(|(category, _)| DataColumn::Category(category)),
277            PlotInput::Beeswarm { value, .. } => Some(DataColumn::Numeric(value)),
278            PlotInput::Matrix { .. } => None,
279        }
280    }
281
282    fn y_data_column(&self) -> Option<DataColumn<'_>> {
283        match self.payload.input.as_ref() {
284            PlotInput::Scatter { y, .. }
285            | PlotInput::Line { y, .. }
286            | PlotInput::Trajectory { y, .. }
287            | PlotInput::LinePath { y, .. }
288            | PlotInput::Regression { y, .. }
289            | PlotInput::Marginal { y, .. } => Some(DataColumn::Numeric(y)),
290            PlotInput::PointInterval { category, .. }
291            | PlotInput::Coefficient { term: category, .. }
292            | PlotInput::Forest { term: category, .. }
293            | PlotInput::Beeswarm { category, .. } => Some(DataColumn::Category(category)),
294            PlotInput::Interaction { estimate, .. }
295            | PlotInput::Dumbbell { left: estimate, .. }
296            | PlotInput::StackedBar {
297                value: estimate, ..
298            }
299            | PlotInput::StackedHorizontalBar {
300                value: estimate, ..
301            }
302            | PlotInput::Boxplot {
303                value: estimate, ..
304            }
305            | PlotInput::Violin {
306                value: estimate, ..
307            }
308            | PlotInput::Waterfall {
309                deltas: estimate, ..
310            } => Some(DataColumn::Numeric(estimate)),
311            PlotInput::Raincloud { input } => input
312                .samples_input()
313                .map(|(_, values)| DataColumn::Numeric(values)),
314            PlotInput::Bar { input, .. } | PlotInput::HorizontalBar { input, .. } => {
315                Some(DataColumn::Numeric(input.values()))
316            }
317            PlotInput::Heatmap { y, .. } => Some(DataColumn::Category(y)),
318            PlotInput::Histogram { .. }
319            | PlotInput::Density { .. }
320            | PlotInput::Qq { .. }
321            | PlotInput::Matrix { .. } => None,
322        }
323    }
324
325    pub(crate) fn automatic_axis_category_values(
326        &self,
327        kind: PlotKind,
328        x_axis: bool,
329    ) -> Option<&crate::CategoryValues> {
330        let column = if x_axis {
331            match kind {
332                PlotKind::Interaction
333                | PlotKind::Heatmap
334                | PlotKind::Bar
335                | PlotKind::StackedBar
336                | PlotKind::Boxplot
337                | PlotKind::Violin
338                | PlotKind::Raincloud
339                | PlotKind::Line
340                | PlotKind::Trajectory
341                | PlotKind::LinePath => self.x_data_column(),
342                _ => None,
343            }
344        } else {
345            match kind {
346                PlotKind::PointInterval
347                | PlotKind::Coefficient
348                | PlotKind::Forest
349                | PlotKind::Beeswarm
350                | PlotKind::Heatmap => self.y_data_column(),
351                PlotKind::Dumbbell
352                | PlotKind::HorizontalBar
353                | PlotKind::StackedHorizontalBar
354                | PlotKind::Waterfall => self.x_data_column(),
355                _ => None,
356            }
357        };
358        match column {
359            Some(DataColumn::Category(values)) => Some(values),
360            Some(DataColumn::Numeric(_) | DataColumn::Boolean(_)) | None => None,
361        }
362    }
363
364    #[expect(
365        clippy::too_many_lines,
366        reason = "one exhaustive closed-input match keeps every family's aligned channels auditable"
367    )]
368    pub(crate) fn aligned_columns(&self) -> Vec<DataColumn<'_>> {
369        let mut columns = match self.payload.input.as_ref() {
370            PlotInput::Scatter { x, y }
371            | PlotInput::Regression { x, y }
372            | PlotInput::Marginal { x, y } => {
373                vec![DataColumn::Numeric(x), DataColumn::Numeric(y)]
374            }
375            PlotInput::Histogram { input } => input
376                .samples_input()
377                .map_or_else(Vec::new, |values| vec![DataColumn::Numeric(values)]),
378            PlotInput::Density { values } | PlotInput::Qq { values } => {
379                vec![DataColumn::Numeric(values)]
380            }
381            PlotInput::PointInterval {
382                estimate, category, ..
383            }
384            | PlotInput::Forest {
385                estimate,
386                term: category,
387                ..
388            } => vec![
389                DataColumn::Numeric(estimate),
390                DataColumn::Category(category),
391            ],
392            PlotInput::Coefficient { input, term } => vec![
393                DataColumn::Numeric(input.values()),
394                DataColumn::Category(term),
395            ],
396            PlotInput::Line { x, y } => {
397                let x = match x {
398                    AxisValues::Numeric(values) => DataColumn::Numeric(values),
399                    AxisValues::Category(values) => DataColumn::Category(values),
400                };
401                vec![x, DataColumn::Numeric(y)]
402            }
403            PlotInput::Trajectory { x, y, group } => {
404                let x = match x {
405                    AxisValues::Numeric(values) => DataColumn::Numeric(values),
406                    AxisValues::Category(values) => DataColumn::Category(values),
407                };
408                vec![x, DataColumn::Numeric(y), DataColumn::Category(group)]
409            }
410            PlotInput::LinePath { x, y, group } => vec![
411                DataColumn::Numeric(x),
412                DataColumn::Numeric(y),
413                DataColumn::Category(group),
414            ],
415            PlotInput::Interaction {
416                condition,
417                estimate,
418                group,
419                ..
420            } => vec![
421                DataColumn::Category(condition),
422                DataColumn::Numeric(estimate),
423                DataColumn::Category(group),
424            ],
425            PlotInput::Dumbbell {
426                category,
427                left,
428                right,
429                ..
430            } => vec![
431                DataColumn::Category(category),
432                DataColumn::Numeric(left),
433                DataColumn::Numeric(right),
434            ],
435            PlotInput::Heatmap { x, y, fill } => vec![
436                DataColumn::Category(x),
437                DataColumn::Category(y),
438                DataColumn::Numeric(fill),
439            ],
440            PlotInput::Bar { category, input } | PlotInput::HorizontalBar { category, input } => {
441                let mut columns = vec![
442                    DataColumn::Category(category),
443                    DataColumn::Numeric(input.values()),
444                ];
445                if let Some(bounds) = input.bounds() {
446                    columns.push(DataColumn::Numeric(bounds.lower()));
447                    columns.push(DataColumn::Numeric(bounds.upper()));
448                }
449                if let Some(DataColumn::Category(units)) = self.data_column(BAR_UNITS) {
450                    columns.push(DataColumn::Category(units));
451                }
452                columns
453            }
454            PlotInput::StackedBar {
455                category,
456                value,
457                series,
458            }
459            | PlotInput::StackedHorizontalBar {
460                category,
461                value,
462                series,
463            } => vec![
464                DataColumn::Category(category),
465                DataColumn::Numeric(value),
466                DataColumn::Category(series),
467            ],
468            PlotInput::Boxplot { category, value } | PlotInput::Violin { category, value } => {
469                vec![DataColumn::Category(category), DataColumn::Numeric(value)]
470            }
471            PlotInput::Beeswarm {
472                category,
473                value,
474                color,
475            } => vec![
476                DataColumn::Category(category),
477                DataColumn::Numeric(value),
478                DataColumn::Numeric(color),
479            ],
480            PlotInput::Raincloud { input } => {
481                input.samples_input().map_or_else(Vec::new, |input| {
482                    vec![DataColumn::Category(input.0), DataColumn::Numeric(input.1)]
483                })
484            }
485            PlotInput::Matrix { variables } => variables.iter().map(DataColumn::Numeric).collect(),
486            PlotInput::Waterfall { labels, deltas, .. } => {
487                vec![DataColumn::Category(labels), DataColumn::Numeric(deltas)]
488            }
489        };
490        columns.extend(self.payload.series.iter().map(DataColumn::Category));
491        columns.extend(self.payload.hue.iter().map(DataColumn::Category));
492        columns.extend(self.payload.group.iter().map(DataColumn::Category));
493        if let Some(bounds) = self.drawable_bounds() {
494            columns.push(DataColumn::Numeric(bounds.lower()));
495            columns.push(DataColumn::Numeric(bounds.upper()));
496        }
497        columns.extend(
498            self.payload
499                .heatmap_highlight
500                .iter()
501                .map(DataColumn::Boolean),
502        );
503        if let Some(facet) = &self.payload.facet {
504            columns.extend(facet.values().map(DataColumn::Category));
505        }
506        columns
507    }
508
509    /// Heatmap colorbar title, if explicitly configured.
510    #[must_use]
511    pub(crate) fn color_label_text(&self) -> Option<&str> {
512        self.payload.color_label.provided().map(crate::Text::as_str)
513    }
514
515    pub(crate) fn copy_color_title(&self) -> Result<crate::Text, Error> {
516        self.payload.color_label.try_copy()
517    }
518
519    pub(crate) fn same_color_title(&self, title: &crate::Text) -> bool {
520        self.payload.color_label == *title
521    }
522
523    pub(crate) fn authored_raincloud_hue_title(&self) -> Option<(&str, &crate::Text)> {
524        let raw_hue = self.raincloud_geometry_input()?.hue_dimension.as_deref()?;
525        self.payload
526            .raincloud_hue_label
527            .provided()
528            .map(|title| (raw_hue, title))
529    }
530
531    pub(crate) fn copy_raincloud_hue_title(&self) -> Result<crate::Text, Error> {
532        self.payload.raincloud_hue_label.try_copy()
533    }
534
535    pub(crate) fn same_raincloud_hue_title(&self, title: &crate::Text) -> bool {
536        self.payload.raincloud_hue_label == *title
537    }
538
539    /// Requested heatmap coordinate layout.
540    #[must_use]
541    pub(crate) fn heatmap_layout_spec(&self) -> HeatmapLayout {
542        self.payload.heatmap_layout
543    }
544
545    /// Requested categorical heatmap label-fit policy.
546    #[must_use]
547    pub(crate) fn continuous_color_scale_spec(&self) -> Option<&crate::ContinuousColorScale> {
548        self.payload.continuous_color_scale.as_ref()
549    }
550
551    /// Resolve the complete caller selection against its owning default mapping.
552    pub(crate) fn continuous_selection_in(
553        &self,
554        owner: &crate::theme::ColorScales,
555    ) -> Result<crate::theme::ContinuousColorScale, crate::Error> {
556        use crate::theme::ContinuousColorScale;
557        let family = match self.kind() {
558            crate::PlotKind::Heatmap => "heatmap",
559            crate::PlotKind::Beeswarm => "beeswarm",
560            _ => {
561                return Err(crate::Error::Render(
562                    "continuous selection requires Heatmap or Beeswarm".into(),
563                ))
564            }
565        };
566        let context = |error| match error {
567            crate::Error::Data(message) => crate::Error::Data(format!("{family}: {message}")),
568            error => error,
569        };
570        let default;
571        let selection = if let Some(selection) = self.continuous_color_scale_spec() {
572            selection
573        } else {
574            default = ContinuousColorScale::sequential(None, None)?;
575            &default
576        };
577        selection.resolved_in(owner).map_err(context)
578    }
579
580    /// Requested heatmap annotation policy.
581    #[must_use]
582    pub(crate) fn heatmap_annotations_spec(&self) -> &HeatmapAnnotations {
583        &self.payload.heatmap_annotations
584    }
585
586    /// Caller-owned annotations for fully-null heatmap rows.
587    #[must_use]
588    pub(crate) fn heatmap_null_row_annotations_spec(&self) -> &[HeatmapNullRowAnnotation] {
589        &self.payload.heatmap_null_row_annotations
590    }
591
592    pub(crate) fn heatmap_highlight_col(&self) -> Option<&'static str> {
593        self.payload
594            .heatmap_highlight
595            .as_ref()
596            .map(|_| HEATMAP_HIGHLIGHT)
597    }
598
599    /// Fixed numeric labels configured for point-only coefficient estimates.
600    #[must_use]
601    pub(crate) fn estimate_labels_spec(&self) -> Option<&NumericFormat> {
602        self.payload.estimate_labels.as_ref()
603    }
604
605    pub(crate) const fn significance_mark_style_override(
606        &self,
607    ) -> Option<crate::SignificanceMarkStyle> {
608        self.significance_mark_style
609    }
610
611    pub(crate) fn category_order_spec(&self) -> &CategoryOrder {
612        &self.payload.category_orders.primary
613    }
614
615    pub(crate) fn x_category_order_spec(&self) -> &CategoryOrder {
616        &self.payload.category_orders.x
617    }
618
619    pub(crate) fn y_category_order_spec(&self) -> &CategoryOrder {
620        &self.payload.category_orders.y
621    }
622
623    /// Requested histogram bin-selection strategy.
624    #[must_use]
625    pub(crate) fn histogram_bins_spec(&self) -> HistogramBins {
626        self.payload.histogram_bins
627    }
628
629    /// Requested histogram vertical-axis normalization.
630    #[must_use]
631    pub(crate) fn histogram_stat_spec(&self) -> HistogramStat {
632        self.payload.histogram_stat
633    }
634
635    /// Requested optional histogram density-and-rug composition.
636    #[must_use]
637    pub(crate) fn histogram_composite_spec(&self) -> &HistogramComposite {
638        &self.payload.histogram_composite
639    }
640
641    pub(crate) fn histogram_composite_geometry_input(&self) -> Option<&HistogramGeometry> {
642        match self.payload.input.as_ref() {
643            PlotInput::Histogram { input } => input.geometry_input(),
644            _ => None,
645        }
646    }
647
648    /// Requested normal Q-Q reference-line policy.
649    #[must_use]
650    pub(crate) fn qq_line_spec(&self) -> QqLine {
651        self.payload.qq_line
652    }
653
654    /// Whether values should be colored according to their sign.
655    #[must_use]
656    pub(crate) fn colors_by_sign(&self) -> bool {
657        self.payload.color_by_sign
658    }
659
660    /// Whether the renderer should draw a zero reference line.
661    #[must_use]
662    pub(crate) fn zero_line_visible(&self) -> bool {
663        self.payload.zero_line
664    }
665
666    pub(crate) fn interval_bound_cols(&self) -> Option<(&'static str, &'static str)> {
667        self.drawable_bounds()
668            .map(|_| (INTERVAL_LOWER, INTERVAL_UPPER))
669    }
670
671    fn drawable_bounds(&self) -> Option<&crate::Bounds> {
672        match self.payload.input.as_ref() {
673            PlotInput::PointInterval { bounds, .. }
674            | PlotInput::Interaction { bounds, .. }
675            | PlotInput::Forest { bounds, .. } => Some(bounds),
676            PlotInput::Coefficient { input, .. } => input.bounds(),
677            _ => self.payload.line_band.as_ref(),
678        }
679    }
680
681    pub(crate) fn line_band_configured(&self) -> bool {
682        self.payload.line_band.is_some()
683    }
684
685    pub(crate) fn bar_input(&self) -> Option<&BarInput> {
686        match self.payload.input.as_ref() {
687            PlotInput::Bar { input, .. } | PlotInput::HorizontalBar { input, .. } => Some(input),
688            _ => None,
689        }
690    }
691
692    pub(crate) fn bar_bound_cols(&self) -> Option<(&'static str, &'static str)> {
693        self.bar_input()
694            .and_then(BarInput::bounds)
695            .map(|_| (BAR_INTERVAL_LOWER, BAR_INTERVAL_UPPER))
696    }
697
698    pub(crate) fn bar_units_col(&self) -> Option<&'static str> {
699        self.data_column(BAR_UNITS).map(|_| BAR_UNITS)
700    }
701
702    pub(crate) fn estimate_status_values(&self) -> Option<&[crate::EstimateStatus]> {
703        self.payload.estimate_status.as_deref()
704    }
705
706    pub(crate) fn markers_visible(&self) -> bool {
707        self.payload.markers_visible
708    }
709
710    /// Configured confidence-band policy for generated regression plots.
711    #[must_use]
712    pub(crate) const fn regression_band_spec(&self) -> RegressionBand {
713        self.regression_band
714    }
715
716    /// Configured complete-path color and legend policy.
717    #[must_use]
718    pub(crate) const fn line_path_style_spec(&self) -> LinePathStyle {
719        self.line_path_style
720    }
721
722    /// Configured original-observation overlay.
723    #[must_use]
724    pub(crate) const fn raw_overlay_spec(&self) -> RawOverlay {
725        self.raw_overlay
726    }
727
728    pub(crate) fn raincloud_geometry_input(&self) -> Option<&RaincloudGeometry> {
729        match self.payload.input.as_ref() {
730            PlotInput::Raincloud { input } => input.geometry_input(),
731            _ => None,
732        }
733    }
734
735    pub(crate) fn coefficient_reference_line_value(&self) -> Option<f64> {
736        self.payload.coefficient_reference_line
737    }
738
739    pub(crate) fn forest_reference_value(&self) -> f64 {
740        match self.payload.input.as_ref() {
741            PlotInput::Forest { reference, .. } => *reference,
742            _ => 0.0,
743        }
744    }
745
746    pub(crate) fn axis_scale_spec(&self) -> AxisScale {
747        self.payload.axis_scale
748    }
749
750    pub(crate) const fn interaction_connectors_spec(&self) -> Option<bool> {
751        self.interaction_connectors
752    }
753
754    pub(crate) const fn interaction_connectors_visible(&self) -> bool {
755        match self.interaction_connectors {
756            Some(visible) => visible,
757            None => true,
758        }
759    }
760
761    pub(crate) fn interaction_styles_spec(&self) -> Option<&[crate::InteractionStyle]> {
762        self.payload.interaction_styles.as_deref()
763    }
764
765    pub(crate) fn categorical_color_scale_spec(&self) -> Option<&crate::CategoricalColorScale> {
766        self.payload.categorical_color_scale.as_ref()
767    }
768
769    pub(crate) fn categorical_map_spec(&self) -> Option<&crate::CategoricalColorMap> {
770        self.categorical_color_scale_spec()
771            .and_then(crate::CategoricalColorScale::map)
772    }
773
774    /// Caller-owned panel-corner text annotations.
775    #[must_use]
776    pub(crate) fn panel_text_annotations(&self) -> &[PlotTextAnnotation] {
777        &self.payload.panel_text_annotations
778    }
779
780    pub(crate) fn waterfall_base(&self) -> Option<f64> {
781        match self.payload.input.as_ref() {
782            PlotInput::Waterfall { base, .. } => Some(*base),
783            _ => None,
784        }
785    }
786
787    /// Caller-owned waterfall annotation labels, if configured.
788    #[must_use]
789    pub(crate) fn waterfall_labels_spec(&self) -> Option<&WaterfallLabels> {
790        self.payload.waterfall_labels.as_ref()
791    }
792
793    pub(crate) fn total_format_spec(
794        &self,
795    ) -> Option<&std::sync::Arc<crate::numeric::format::NumericFormat>> {
796        self.payload.total_format.as_ref()
797    }
798
799    pub(crate) fn dumbbell_right_col(&self) -> Option<&'static str> {
800        matches!(self.payload.input.as_ref(), PlotInput::Dumbbell { .. }).then_some(DUMBBELL_RIGHT)
801    }
802
803    /// Required endpoint labels and colors for a dumbbell plot.
804    #[must_use]
805    pub(crate) fn dumbbell_endpoints_spec(&self) -> Option<&DumbbellEndpoints> {
806        match self.payload.input.as_ref() {
807            PlotInput::Dumbbell { endpoints, .. } => Some(endpoints),
808            _ => None,
809        }
810    }
811
812    /// The chart title, if any.
813    #[must_use]
814    pub(crate) fn title_text(&self) -> Option<&str> {
815        self.title.provided().map(crate::Text::as_str)
816    }
817
818    /// The chart subtitle, if any.
819    #[must_use]
820    pub(crate) fn subtitle_text(&self) -> Option<&str> {
821        self.subtitle.provided().map(crate::Text::as_str)
822    }
823
824    /// The chart caption, if any.
825    #[must_use]
826    pub(crate) fn caption_text(&self) -> Option<&str> {
827        self.payload.caption.provided().map(crate::Text::as_str)
828    }
829
830    pub(crate) fn prose(&self) -> [Option<&crate::Text>; 3] {
831        [&self.title, &self.subtitle, &self.payload.caption].map(crate::Text::provided)
832    }
833
834    pub(crate) fn prose_alignments(&self) -> [Option<crate::TextAlignment>; 3] {
835        [&self.title, &self.subtitle, &self.payload.caption].map(crate::Text::alignment_request)
836    }
837
838    pub(crate) fn copy_prose(&self) -> Result<[crate::Text; 3], Error> {
839        Ok([
840            self.title.try_copy()?,
841            self.subtitle.try_copy()?,
842            self.payload.caption.try_copy()?,
843        ])
844    }
845
846    pub(crate) fn same_prose(&self, prose: &[crate::Text; 3]) -> bool {
847        [&self.title, &self.subtitle, &self.payload.caption]
848            .into_iter()
849            .zip(prose)
850            .all(|(left, right)| left == right)
851    }
852
853    pub(crate) fn validate_display_text(&self) -> Result<(), Error> {
854        for (source, role) in [
855            (self.title_text(), "plot title"),
856            (self.subtitle_text(), "plot subtitle"),
857            (self.caption_text(), "plot caption"),
858            (
859                self.payload.x_label.provided().map(crate::Text::as_str),
860                "x-axis title",
861            ),
862            (
863                self.payload.y_label.provided().map(crate::Text::as_str),
864                "y-axis title",
865            ),
866            (self.color_label_text(), "color guide title"),
867            (
868                self.payload
869                    .raincloud_hue_label
870                    .provided()
871                    .map(crate::Text::as_str),
872                "raincloud hue guide title",
873            ),
874        ] {
875            if let Some(source) = source {
876                crate::text::validate_for(source, role)?;
877            }
878        }
879        Ok(())
880    }
881
882    pub(crate) fn resolve_label(&self, raw: &str) -> Result<String, Error> {
883        self.payload.labels.resolve(raw)
884    }
885
886    pub(crate) fn get_labels(&self) -> &crate::Labels {
887        &self.payload.labels
888    }
889
890    pub(crate) fn resolve_axis_label_domain<'b>(
891        &self,
892        domain: &str,
893        raw_labels: impl IntoIterator<Item = &'b str>,
894    ) -> Result<Vec<String>, Error> {
895        self.payload.labels.resolve_domain(domain, raw_labels)
896    }
897
898    pub(crate) fn copy_axis_titles(&self) -> Result<[crate::Text; 2], Error> {
899        Ok([
900            self.payload.x_label.try_copy()?,
901            self.payload.y_label.try_copy()?,
902        ])
903    }
904
905    pub(crate) fn same_axis_titles(&self, titles: &[crate::Text; 2]) -> bool {
906        self.payload.x_label == titles[0] && self.payload.y_label == titles[1]
907    }
908
909    pub(crate) fn prepare_axis_labels(
910        &self,
911
912        policy: Option<&crate::Labels>,
913    ) -> Result<[Option<crate::Text>; 2], Error> {
914        let mut labels = [None, None];
915        for ((target, source), authored) in labels
916            .iter_mut()
917            .zip(self.axis_label_sources(self.kind))
918            .zip([
919                self.payload.x_label.provided(),
920                self.payload.y_label.provided(),
921            ])
922        {
923            *target = if let Some(text) = authored {
924                text.required_source("axis title")?;
925                Some(text.try_copy()?)
926            } else {
927                source
928                    .map(|(raw, inferred)| {
929                        if inferred {
930                            policy
931                                .unwrap_or(&self.payload.labels)
932                                .resolve(raw)
933                                .map(crate::Text::from)
934                        } else {
935                            crate::text::validate_for(raw, "axis title")?;
936                            crate::data::source::copy_source_string(raw).map(crate::Text::from)
937                        }
938                    })
939                    .transpose()?
940            };
941        }
942        Ok(labels)
943    }
944
945    pub(crate) fn resolve_label_domain<'b>(
946        &self,
947        domain: &str,
948        raw_labels: impl IntoIterator<Item = &'b str>,
949    ) -> Result<Vec<String>, crate::Error> {
950        self.payload.labels.resolve_domain(domain, raw_labels)
951    }
952
953    fn axis_label_sources(&self, kind: PlotKind) -> [Option<(&str, bool)>; 2] {
954        let x_name = self.payload.input.x_name().map(|name| (name, true));
955        let y_name = self.payload.input.y_name().map(|name| (name, true));
956        let x = match kind {
957            PlotKind::HorizontalBar
958            | PlotKind::StackedHorizontalBar
959            | PlotKind::Waterfall
960            | PlotKind::Dumbbell => y_name,
961            PlotKind::Qq => Some(("Theoretical normal quantiles", false)),
962            PlotKind::Histogram => self.histogram_composite_geometry_input().map_or_else(
963                || x_name,
964                |input| Some((input.value_dimension.as_str(), true)),
965            ),
966            PlotKind::Raincloud => self.raincloud_geometry_input().map_or_else(
967                || x_name,
968                |input| Some((input.category_dimension.as_str(), true)),
969            ),
970            PlotKind::Matrix => None,
971            _ => x_name,
972        };
973        let y = match kind {
974            PlotKind::HorizontalBar
975            | PlotKind::StackedHorizontalBar
976            | PlotKind::Waterfall
977            | PlotKind::Dumbbell
978            | PlotKind::Qq => x_name,
979            PlotKind::Histogram => self.histogram_composite_geometry_input().map_or_else(
980                || match self.payload.histogram_stat {
981                    HistogramStat::Count => Some(("Count", false)),
982                    HistogramStat::Probability => Some(("Probability", false)),
983                    HistogramStat::Density => Some(("Density", false)),
984                },
985                |input| Some((input.density_dimension.as_str(), true)),
986            ),
987            PlotKind::Raincloud => self.raincloud_geometry_input().map_or_else(
988                || y_name,
989                |input| Some((input.value_dimension.as_str(), true)),
990            ),
991            PlotKind::Density => Some(("Density", false)),
992            PlotKind::Matrix => None,
993            _ => y_name,
994        };
995        [x, y]
996    }
997
998    pub(crate) fn prepare_color_label(
999        &self,
1000
1001        policy: Option<&crate::Labels>,
1002    ) -> Result<crate::Text, Error> {
1003        if let Some(label) = self.payload.color_label.provided() {
1004            label.required_source("color guide title")?;
1005            label.try_copy()
1006        } else if let Some(values) = self.color_values() {
1007            policy
1008                .unwrap_or(&self.payload.labels)
1009                .resolve(values.name())
1010                .map(crate::Text::from)
1011        } else {
1012            Ok(crate::Text::new(String::new()))
1013        }
1014    }
1015
1016    pub(crate) fn color_dimension_key(&self) -> Option<&str> {
1017        self.color_values().map(crate::NumericValues::name)
1018    }
1019
1020    pub(crate) fn legend_title_key(&self) -> &str {
1021        self.payload
1022            .interaction_styles
1023            .as_ref()
1024            .and(self.group_values())
1025            .map(crate::CategoryValues::name)
1026            .or_else(|| self.hue_dimension_key())
1027            .unwrap_or("series")
1028    }
1029
1030    pub(crate) fn collective_legend_identity(
1031        &self,
1032        pair: &crate::data::CollectivePair,
1033    ) -> Result<crate::decorations::legend::GuideEntryIdentity, Error> {
1034        match (
1035            self.group_name(),
1036            pair.group.as_deref(),
1037            self.hue_name(),
1038            pair.hue.as_deref(),
1039        ) {
1040            (Some(group_field), Some(group_value), Some(hue_field), Some(hue_value))
1041                if group_field == hue_field =>
1042            {
1043                if group_value != hue_value {
1044                    return Err(Error::Render(
1045                        "same-field collective legend identity contains different values".into(),
1046                    ));
1047                }
1048                crate::decorations::legend::GuideEntryIdentity::category(group_field, group_value)
1049            }
1050            (Some(group_field), Some(group_value), Some(hue_field), Some(hue_value)) => {
1051                crate::decorations::legend::GuideEntryIdentity::pair(
1052                    group_field,
1053                    group_value,
1054                    hue_field,
1055                    hue_value,
1056                )
1057            }
1058            (Some(group_field), Some(group_value), _, None) => {
1059                crate::decorations::legend::GuideEntryIdentity::category(group_field, group_value)
1060            }
1061            (_, None, Some(hue_field), Some(hue_value)) => {
1062                crate::decorations::legend::GuideEntryIdentity::category(hue_field, hue_value)
1063            }
1064            _ => Err(Error::Render(
1065                "collective legend identity has no resolved group or hue value".into(),
1066            )),
1067        }
1068    }
1069
1070    /// Payload identities own both strings under the projection's gate.
1071    pub(crate) fn point_legend_identity(
1072        &self,
1073        label: &str,
1074    ) -> Result<crate::decorations::legend::GuideEntryIdentity, Error> {
1075        if self.payload.interaction_styles.is_none() && self.hue_dimension_key().is_none() {
1076            return Err(Error::Render(
1077                "categorical guide entry has no prepared field".into(),
1078            ));
1079        }
1080        crate::decorations::legend::GuideEntryIdentity::category(self.legend_title_key(), label)
1081    }
1082
1083    pub(crate) fn hue_dimension_key(&self) -> Option<&str> {
1084        self.hue_name().or_else(|| {
1085            self.raincloud_geometry_input()
1086                .and_then(|input| input.hue_dimension.as_deref())
1087        })
1088    }
1089
1090    pub(crate) fn categorical_color_field(&self) -> Option<&str> {
1091        if self.colors_by_sign() {
1092            None
1093        } else {
1094            self.hue_dimension_key().or_else(|| {
1095                (self.kind() == crate::PlotKind::Interaction)
1096                    .then(|| self.group_name())
1097                    .flatten()
1098            })
1099        }
1100    }
1101
1102    pub(crate) fn categorical_field(&self) -> Option<crate::data::category::RawField> {
1103        self.hue_field()
1104            .or_else(|| {
1105                self.raincloud_geometry_input()
1106                    .and_then(|input| input.hue_dimension.as_deref())
1107                    .map(|field| {
1108                        crate::data::category::RawField::from_shared(std::sync::Arc::from(field))
1109                    })
1110            })
1111            .or_else(|| {
1112                if self.kind() == crate::PlotKind::Interaction {
1113                    self.group_values().map(crate::CategoryValues::raw_field)
1114                } else if matches!(
1115                    self.kind(),
1116                    crate::PlotKind::Bar
1117                        | crate::PlotKind::HorizontalBar
1118                        | crate::PlotKind::StackedBar
1119                        | crate::PlotKind::StackedHorizontalBar
1120                        | crate::PlotKind::Boxplot
1121                        | crate::PlotKind::Violin
1122                        | crate::PlotKind::Raincloud
1123                ) {
1124                    self.x_data_column()
1125                        .and_then(|column| match column {
1126                            DataColumn::Category(values) => Some(values.raw_field()),
1127                            _ => None,
1128                        })
1129                        .or_else(|| {
1130                            self.raincloud_geometry_input().map(|input| {
1131                                crate::data::category::RawField::from_shared(std::sync::Arc::from(
1132                                    input.category_dimension.as_str(),
1133                                ))
1134                            })
1135                        })
1136                } else {
1137                    None
1138                }
1139            })
1140    }
1141
1142    /// Borrow x-axis scale configuration.
1143    #[must_use]
1144    pub(crate) fn x_axis_spec(&self) -> &AuthoredAxisSpec {
1145        &self.payload.axes[0]
1146    }
1147
1148    pub(crate) fn explicit_x_ticks(&self) -> Option<&[AxisTick]> {
1149        self.payload.axes[0].exact_ticks.as_deref()
1150    }
1151
1152    pub(crate) fn y_axis_spec(&self) -> &AuthoredAxisSpec {
1153        &self.payload.axes[1]
1154    }
1155
1156    pub(crate) fn explicit_y_ticks(&self) -> Option<&[AxisTick]> {
1157        self.payload.axes[1].exact_ticks.as_deref()
1158    }
1159
1160    pub(crate) fn guides(&self) -> &[GuideSpec] {
1161        &self.payload.guides
1162    }
1163
1164    pub(crate) fn point_layers(&self) -> &[PointLayer] {
1165        &self.payload.point_layers
1166    }
1167
1168    pub(crate) fn bar_point_layers(&self) -> &[BarPointLayer] {
1169        &self.payload.bar_point_layers
1170    }
1171
1172    pub(crate) fn significance_annotations(
1173        &self,
1174    ) -> &[crate::significance::SignificanceAnnotation] {
1175        &self.payload.significance
1176    }
1177
1178    pub(crate) const fn sizing_request(&self) -> crate::layout::RootRequest {
1179        self.root_size
1180    }
1181
1182    pub(crate) fn matrix_variables(&self) -> Option<&[crate::NumericValues]> {
1183        match self.payload.input.as_ref() {
1184            PlotInput::Matrix { variables } => Some(variables),
1185            _ => None,
1186        }
1187    }
1188
1189    pub(crate) fn bar_spacing_spec(&self) -> BarSpacing {
1190        self.payload.bar_spacing
1191    }
1192
1193    pub(crate) fn point_style(
1194        &self,
1195        theme: &crate::theme::ResolvedTheme,
1196        color: (u8, u8, u8),
1197        radius: u32,
1198    ) -> PointStyle {
1199        theme.marks.get_points().get_primary().backend_style(
1200            color,
1201            radius,
1202            self.payload.point_outline_visible,
1203        )
1204    }
1205
1206    pub(crate) fn distribution_point_style(
1207        &self,
1208        role: &crate::theme::mark::SizedPointTheme,
1209        color: (u8, u8, u8),
1210    ) -> PointStyle {
1211        role.backend_style(color, self.payload.point_outline_visible)
1212    }
1213
1214    pub(crate) fn legend_policy_spec(&self) -> LegendPolicy {
1215        self.payload.legend_policy
1216    }
1217
1218    pub(crate) fn legend_position_spec(&self) -> LegendPosition {
1219        self.payload.legend_policy.position()
1220    }
1221
1222    pub(crate) fn color_label_format_spec(
1223        &self,
1224    ) -> Option<&std::sync::Arc<crate::numeric::format::NumericFormat>> {
1225        self.payload.color_label_format.as_ref()
1226    }
1227
1228    pub(crate) const fn kind(&self) -> PlotKind {
1229        self.kind
1230    }
1231}
1232
1233impl<K: crate::kind::Facet> Plot<K> {
1234    /// Borrow the currently bound facet without validating or rebinding its data.
1235    #[must_use]
1236    pub fn get_facet(&self) -> Option<&crate::FacetSpec> {
1237        self.description.payload.facet.as_ref()
1238    }
1239}
1240
1241impl<K: crate::kind::Marker> Plot<K> {
1242    /// Current authored label policy, without resolving or validating labels.
1243    #[must_use]
1244    pub fn get_labels(&self) -> &crate::Labels {
1245        self.description.get_labels()
1246    }
1247
1248    pub(crate) const fn description(&self) -> &PlotDescription {
1249        &self.description
1250    }
1251
1252    pub(crate) fn into_description(self) -> PlotDescription {
1253        self.description
1254    }
1255
1256    /// Selected semantic plot kind.
1257    #[must_use]
1258    pub const fn kind(&self) -> PlotKind {
1259        self.description.kind
1260    }
1261}