Skip to main content

lichtung_plot/
data.rs

1//! Private semantic value access shared by plot renderers.
2
3pub use crate::input::AxisValues;
4pub use crate::spec::{Bounds, EstimateStatus};
5pub use crate::values::SourceRows;
6pub use arrays::{ArrayElementType, ArrayValueType, ArrayValues, NdArray};
7#[doc(hidden)]
8/// The actual native collection capture, for source-free adapter restoration.
9#[doc(hidden)]
10pub enum CapturedCollection<'a> {
11    /// A wide expansion whose original column projection is retained.
12    Wide(&'a DataSourceInfo),
13    /// A rectangular heatmap's actual positional coordinates.
14    Grid {
15        /// Original selected cell rectangle.
16        source: &'a DataSourceInfo,
17        /// Actual column coordinates.
18        x: &'a crate::CategoryValues,
19        /// Actual row coordinates.
20        y: &'a crate::CategoryValues,
21    },
22    /// Ordered native Matrix variables.
23    Matrix(&'a VariableValues),
24}
25
26pub use binding::CapturedValue;
27pub(crate) use binding::VectorSource;
28pub use binding::{
29    BindingGeneration, BindingSelector, BindingSelectorKind, BindingSlice, DataSourceInfo,
30    DataSourceRef,
31};
32#[doc(hidden)]
33pub use binding::{ColumnKeyLookup, ColumnKeySource, GeneratedColumns};
34pub(crate) use identity::InstanceId;
35pub use integer::{ExactInteger, IntegerValues};
36pub(crate) use key::key_bytes;
37pub use key::{
38    IntervalClosed, IntervalKey, KeyColumns, KeyValues, NamedKeyValues, RawKey, RawKeyValues,
39    UnavailableKey,
40};
41pub use payload::{DataPayload, DataValueType};
42pub(crate) use protocol::{select_value, DomainSlot};
43pub use protocol::{
44    AxisValueType, ComponentPathPart, DataComponentInfo, DataDomainInfo, DataDomainRef,
45    DataRoleInfo, DataRoleRef, DataSelector, DataValue, MemberAddress, SourceMember, SourceMembers,
46    SourceMembersEntry,
47};
48pub use roles::DataRole;
49pub use status::EstimateStatusBinding;
50pub use temporal::{
51    Date, DateValues, Duration, DurationUnit, DurationValues, LocalTimestamp, TimeValues, TimeZone,
52    Timestamp,
53};
54pub use variables::{NamedNumericValues, VariableValues};
55
56use crate::{BooleanValues, CategoryValues, Error, NumericValues};
57
58mod arrays;
59pub(crate) mod binding;
60pub(crate) mod category;
61pub(crate) mod group_key;
62mod identity;
63mod integer;
64mod key;
65mod payload;
66pub use group_key::{GroupDimension, GroupDimensionRef, GroupKey, GroupKeys};
67mod grouped;
68pub use grouped::GroupedObservations;
69mod protocol;
70mod roles;
71pub(crate) mod source;
72mod status;
73mod temporal;
74mod variables;
75
76#[cfg(test)]
77mod values_tests {
78    use super::*;
79
80    #[test]
81    fn original_source_selection_survives_projection_and_alpha_materialization() {
82        let reference = DataSourceRef::capture();
83        let next = reference.recapture();
84        assert_ne!(reference, next);
85        assert!(reference.same_source(&next));
86        assert!(!reference.same_source(&DataSourceRef::capture()));
87        let key = RawKey::Tuple(vec![
88            RawKey::from("measurement"),
89            RawKey::Integer(17.into()),
90        ]);
91        let source = DataSourceInfo::selected(
92            reference.clone(),
93            BindingSelector::Key(key.clone()),
94            Some(vec![key.clone()]),
95            vec![4],
96            vec![3, 7],
97            vec![3],
98        );
99        let values = NumericValues::new("internal", [-0., -0., 0.5, 0.5, 1., 1.])
100            .with_field_key(key.clone(), "measurement")
101            .with_repeated_source(source, 2)
102            .unwrap();
103        let mapped = crate::scales::AlphaValues::linear(values, (0., 1.), (0., 1.)).unwrap();
104        let selected = mapped.select([3, 0, 5, 0]).unwrap();
105        let raw = selected.get_numeric_source().unwrap();
106        assert_eq!(raw.name(), "measurement");
107        assert_eq!(raw.field_key(), Some(&key));
108        assert_eq!(raw.get_source().reference(), &reference);
109        assert_eq!(raw.get_source().selected_indices(), Some(&[4][..]));
110        assert_eq!(raw.get_source().source_shape(), &[3, 7]);
111        assert_eq!(raw.get_source().selected_shape(), &[3]);
112        assert_eq!(
113            (0..raw.len())
114                .map(|index| raw.source_slot(index))
115                .collect::<Vec<_>>(),
116            [Some(1), Some(0), Some(2), Some(0)]
117        );
118        assert_eq!(
119            raw.get(1).flatten().unwrap().to_bits(),
120            (-0.0_f64).to_bits()
121        );
122    }
123
124    #[test]
125    fn direct_alpha_preserves_authored_values_and_checked_source_relations() {
126        let source = DataSourceInfo::direct(vec![2]);
127        let values = NumericValues::new("opacity", [-0., 0.75]);
128        assert!(values
129            .clone()
130            .with_repeated_source(source.clone(), 0)
131            .is_err());
132        assert!(values
133            .clone()
134            .with_repeated_source(source.clone(), 2)
135            .is_err());
136        assert!(values
137            .clone()
138            .with_source_slots(source.clone(), vec![0, 2])
139            .is_err());
140        let values = values.with_source(source.clone()).unwrap();
141        let alpha = crate::scales::AlphaValues::try_from(values).unwrap();
142        assert_eq!(alpha.get(0).unwrap().to_bits(), 0.0_f64.to_bits());
143        let selected = alpha.select([1, 0, 1]).unwrap();
144        let original = selected.get_numeric_source().unwrap();
145        assert_eq!(original.get_source(), &source);
146        assert_eq!(
147            original.get(1).flatten().unwrap().to_bits(),
148            (-0.0_f64).to_bits()
149        );
150        assert_eq!(original.source_slot(2), Some(1));
151    }
152
153    #[test]
154    fn original_values_distinguish_validity_from_finiteness_and_identity() {
155        let numbers = NumericValues::nullable(
156            "numeric",
157            [Some(f64::NAN), None, Some(-0.), Some(f64::INFINITY)],
158        );
159        assert!(numbers.get(0).flatten().unwrap().is_nan());
160        assert_eq!(numbers.get(1), Some(None));
161        assert_eq!(
162            numbers.get(2).flatten().unwrap().to_bits(),
163            (-0.0_f64).to_bits()
164        );
165        assert_eq!(numbers.get(3).flatten(), Some(f64::INFINITY));
166        assert_eq!(numbers.is_valid(0), Some(true));
167        assert_eq!(numbers.is_valid(1), Some(false));
168        assert_eq!(numbers.is_valid(4), None);
169        let categories = CategoryValues::nullable("category", [Some(""), None, Some("A")]).unwrap();
170        assert_eq!(
171            categories.iter().collect::<Vec<_>>(),
172            [Some(""), None, Some("A")]
173        );
174        assert_eq!(categories.levels(), ["", "A"]);
175        let booleans = BooleanValues::nullable("boolean", [Some(false), None, Some(true)]);
176        assert_eq!(
177            booleans.iter().collect::<Vec<_>>(),
178            [Some(false), None, Some(true)]
179        );
180    }
181
182    #[test]
183    fn exact_keys_keep_arbitrary_magnitude_and_temporal_fields() {
184        let huge = ExactInteger::from_parts(false, &[1; 24]).unwrap();
185        assert!(huge.to_u128().is_none());
186        assert_eq!(ExactInteger::from(i128::MIN).to_i128(), Some(i128::MIN));
187        assert_eq!(ExactInteger::from(u128::MAX).to_u128(), Some(u128::MAX));
188        assert_eq!(
189            ExactInteger::from_parts(true, &[0, 0]).unwrap(),
190            ExactInteger::from(0)
191        );
192        assert!(
193            ExactInteger::from_parts(true, huge.magnitude_be()).unwrap()
194                < ExactInteger::from(i128::MIN)
195        );
196        let values =
197            IntegerValues::nullable("counts", [Some(huge.clone()), None, Some(2.into())]).unwrap();
198        assert_eq!(values.get(0), Some(Some(&huge)));
199        assert_eq!(values.is_valid(1), Some(false));
200        assert_eq!(values.get(3), None);
201        assert!(Date::new(1900, 2, 29).is_err());
202        let date = Date::new(2000, 2, 29).unwrap();
203        let instant = Timestamp::new(
204            -1,
205            999_999_999,
206            Some(TimeZone::FixedOffset(0)),
207            Some(0),
208            None,
209        )
210        .unwrap();
211        assert_eq!(instant.unix_ns(), -1);
212        let local = LocalTimestamp::new(date, 1, 2, 3, 7).unwrap();
213        let key = RawKey::Tuple(vec![RawKey::Integer(huge), RawKey::LocalTimestamp(local)]);
214        let keys = RawKeyValues::nullable(
215            "raw",
216            [
217                Some(key.clone()),
218                None,
219                Some(key.clone()),
220                Some(RawKey::Instant(instant)),
221            ],
222        )
223        .unwrap();
224        assert_eq!(keys.levels().len(), 2);
225        assert_eq!(keys.get(2), Some(Some(&key)));
226        assert_eq!(keys.is_valid(1), Some(false));
227        assert_ne!(RawKey::Float(-0.), RawKey::Float(0.));
228    }
229}
230
231pub(crate) const X: &str = "__x";
232pub(crate) const Y: &str = "__y";
233pub(crate) const HUE: &str = "__hue";
234pub(crate) const GROUP: &str = "__group";
235pub(crate) const SERIES: &str = "__series";
236pub(crate) const COLOR: &str = "__color";
237pub(crate) const INTERVAL_LOWER: &str = "__interval_lower";
238pub(crate) const INTERVAL_UPPER: &str = "__interval_upper";
239pub(crate) const BAR_INTERVAL_LOWER: &str = "__bar_interval_lower";
240pub(crate) const BAR_INTERVAL_UPPER: &str = "__bar_interval_upper";
241pub(crate) const BAR_UNITS: &str = "__bar_units";
242pub(crate) const HIGHLIGHT_CELLS: &str = "__highlight_cells";
243pub(crate) const DUMBBELL_RIGHT: &str = "__dumbbell_right";
244pub(crate) const FACET_ROW: &str = "__facet_row";
245pub(crate) const FACET_COLUMN: &str = "__facet_column";
246pub(crate) const FACET_WRAP: &str = "__facet_wrap";
247
248#[derive(Debug, Clone, Copy)]
249pub(crate) enum DataColumn<'a> {
250    Numeric(&'a NumericValues),
251    Category(&'a CategoryValues),
252    Boolean(&'a BooleanValues),
253}
254
255impl<'a> DataColumn<'a> {
256    pub(crate) const fn is_numeric(self) -> bool {
257        matches!(self, Self::Numeric(_))
258    }
259
260    pub(crate) fn name(self) -> &'a str {
261        match self {
262            Self::Numeric(values) => values.name(),
263            Self::Category(values) => values.name(),
264            Self::Boolean(values) => values.name(),
265        }
266    }
267
268    pub(crate) fn len(self) -> usize {
269        match self {
270            Self::Numeric(values) => values.len(),
271            Self::Category(values) => values.len(),
272            Self::Boolean(values) => values.len(),
273        }
274    }
275}
276
277/// Global axis inputs normally installed on a generic facet child Plot.
278#[derive(Clone, Copy)]
279pub(crate) struct FacetAxisSources<'a> {
280    pub(crate) hues: Option<&'a [String]>,
281    pub(crate) groups: Option<&'a [String]>,
282    pub(crate) conditions: Option<&'a [String]>,
283}
284
285/// A borrowed semantic plot view, optionally restricted to selected source rows.
286#[derive(Clone, Copy)]
287pub(crate) struct PlotData<'src, 'op> {
288    source: &'src crate::builder::PlotDescription,
289    rows: Option<&'op [usize]>,
290    diagnostic_rows: DiagnosticRows<'src, 'op>,
291    numeric_facet: Option<&'op crate::layout::FacetCell>,
292    scope: &'op crate::orchestrator::registration::Scope,
293    operation: &'op crate::font::canonical::OperationContext,
294    row_source: &'op source::RowSourceContext<'src>,
295}
296
297#[derive(Clone, Copy)]
298pub(crate) enum DiagnosticRows<'src, 'op> {
299    Native(Option<&'src crate::data::SourceRows>),
300    Selected(&'op [usize]),
301}
302
303impl std::fmt::Debug for PlotData<'_, '_> {
304    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305        formatter
306            .debug_struct("PlotData")
307            .field("height", &self.height())
308            .field("is_full_plot", &self.is_full_plot())
309            .finish_non_exhaustive()
310    }
311}
312
313impl<'src, 'op> PlotData<'src, 'op> {
314    pub(crate) fn checked(
315        source: &'src crate::builder::PlotDescription,
316        scope: &'op crate::orchestrator::registration::Scope,
317        row_source: &'op source::RowSourceContext<'src>,
318        operation: &'op crate::font::canonical::OperationContext,
319    ) -> Result<Self, Error> {
320        row_source.check(source, scope, operation)?;
321        let (rows, diagnostic_rows) = scope.rows.selected().map_or_else(
322            || (None, DiagnosticRows::Native(source.source_row_map())),
323            |(rows, diagnostic_rows)| (Some(rows), DiagnosticRows::Selected(diagnostic_rows)),
324        );
325        Ok(Self {
326            source,
327            rows,
328            diagnostic_rows,
329            numeric_facet: scope.numeric_owner.facet.as_ref(),
330            scope,
331            operation,
332            row_source,
333        })
334    }
335
336    pub(crate) const fn numeric_facet(self) -> Option<&'op crate::layout::FacetCell> {
337        self.numeric_facet
338    }
339
340    pub(crate) fn facet_selector(
341        self,
342    ) -> Result<Option<crate::orchestrator::registration::FacetSelector<'src, 'op>>, Error> {
343        if self.height() == 0 {
344            return Ok(None);
345        }
346        self.source
347            .facet_spec()
348            .zip(self.numeric_facet())
349            .map(|(schema, levels)| {
350                crate::orchestrator::registration::FacetSelector::checked(schema, levels)
351            })
352            .transpose()
353    }
354
355    pub(crate) const fn source_resources(self) -> &'op crate::font::canonical::OperationContext {
356        self.operation
357    }
358
359    #[cfg(test)]
360    pub(crate) const fn plot_id(self) -> &'op crate::orchestrator::registration::PlotOccurrenceId {
361        self.row_source.owner()
362    }
363
364    pub(crate) fn column(self, key: &str) -> Result<DataColumn<'src>, Error> {
365        #[cfg(test)]
366        SOURCE_COLUMN_READS.with(|calls| calls.set(calls.get() + 1));
367        self.source
368            .data_column(key)
369            .ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))
370    }
371
372    pub(crate) fn height(self) -> usize {
373        self.rows
374            .map_or_else(|| self.source.row_count(), <[usize]>::len)
375    }
376
377    pub(crate) const fn is_full_plot(self) -> bool {
378        self.rows.is_none()
379    }
380
381    fn member_context(
382        self,
383        row: usize,
384        binding: RawKey,
385        column: &str,
386    ) -> crate::errors::ErrorContext {
387        use crate::{
388            elements::LayerSlot,
389            errors::{ErrorContext, OperationPhase},
390            layout::PanelPath,
391        };
392        let mut panel = PanelPath::root();
393        if let Some((row, column)) = self.scope.numeric_owner.canvas {
394            panel = panel.panel(row, column);
395        }
396        if let Some(facet) = self.numeric_facet {
397            panel = panel.facet(facet.clone());
398        }
399        let member = if self.source.source_row_map().is_some() {
400            MemberAddress::RowId(self.source_row(row))
401        } else {
402            MemberAddress::Slot(self.row_index(row))
403        };
404        let mut context = ErrorContext::new()
405            .with_operation(OperationPhase::Prepare)
406            .with_panel(panel)
407            .with_layer(LayerSlot::Primary)
408            .with_member(member)
409            .with_binding(binding);
410        if let Some(role) = self.source.column_role(column) {
411            context = context.with_role(role);
412        }
413        context
414    }
415
416    pub(crate) fn source_row(self, local_row: usize) -> usize {
417        let diagnostic = match self.diagnostic_rows {
418            DiagnosticRows::Native(rows) => rows.and_then(|rows| rows.as_slice().get(local_row)),
419            DiagnosticRows::Selected(rows) => rows.get(local_row),
420        };
421        diagnostic
422            .copied()
423            .unwrap_or_else(|| self.row_index(local_row))
424    }
425
426    pub(crate) fn estimate_statuses(
427        self,
428    ) -> Result<Option<Vec<crate::data::EstimateStatus>>, Error> {
429        let Some(statuses) = self.source.estimate_status_values() else {
430            return Ok(None);
431        };
432        crate::data::source::collect_source((0..self.height())
433            .map(|row| {
434
435                statuses.get(self.row_index(row)).copied().ok_or_else(|| {
436                    Error::Data(format!(
437                        "estimate status values are shorter than the aligned plot input at source row {}",
438                        self.source_row(row)
439                    ).into())
440                })
441            }))
442            .map(Some)
443    }
444
445    pub(crate) fn row_index(self, local_row: usize) -> usize {
446        self.rows
447            .and_then(|rows| rows.get(local_row))
448            .copied()
449            .unwrap_or(local_row)
450    }
451
452    /// Alpha arrays align with complete original input slots, not public row IDs.
453    pub(crate) fn observation_alpha(
454        self,
455        alpha: &crate::alpha::PreparedAlpha,
456        local_row: usize,
457    ) -> Result<Option<crate::alpha::ResolvedAlpha>, Error> {
458        if local_row >= self.height() {
459            return Err(Error::Data(
460                format!("alpha local row {local_row} is outside the selected input").into(),
461            ));
462        }
463        alpha.observation(self.row_index(local_row), self.source_row(local_row))
464    }
465}
466
467/// Isolated scientific fixtures borrow the same build binding as production.
468/// No prepared owner or operation-backed view can escape the callback.
469#[cfg(test)]
470pub(crate) fn with_source_data_for_test<'src, T>(
471    source: &'src crate::Plot,
472    operation: &crate::font::canonical::OperationContext,
473    rows: crate::orchestrator::registration::RowSelection,
474    visit: impl FnOnce(PlotData<'src, '_>) -> T,
475) -> Result<T, Error> {
476    let scope = crate::orchestrator::registration::Scope::new(
477        source.description(),
478        operation,
479        0,
480        crate::layout::ComponentAddress::root().child(crate::layout::AddressRole::PlotBody, 0)?,
481        rows,
482        None,
483        None,
484    )?;
485    let mut registry =
486        crate::orchestrator::registration::PlotRegistryBuilder::new(operation.root_identity());
487    let policy = crate::orchestrator::registration::PlotScopePolicy::for_source(
488        source.description(),
489        scope.numeric_owner.facet.as_ref(),
490    );
491    let id = registry.reserve(
492        source.description(),
493        scope.address,
494        scope.numeric_owner,
495        scope.axis_numeric_owner,
496        scope.rows,
497        scope.render_name,
498        policy,
499        source.description().resolve_theme()?,
500        operation,
501    )?;
502    Ok(visit(registry.data(&id, operation)?))
503}
504
505pub(crate) fn strict_finite_f64(
506    data: PlotData<'_, '_>,
507    column: &str,
508    plot: &str,
509) -> Result<Vec<f64>, Error> {
510    let DataColumn::Numeric(values) = data.column(column)? else {
511        return Err(Error::Data(
512            format!(
513                "{plot}: value {:?} must be numeric",
514                data.column(column)?.name()
515            )
516            .into(),
517        ));
518    };
519    crate::data::source::collect_source((0..data.height()).map(|row| {
520        match values.get(data.row_index(row)) {
521            Some(Some(value)) if value.is_finite() => Ok(value),
522            Some(value) => {
523                use crate::errors::{Diagnostic, DiagnosticKind};
524                let status = value.map_or_else(
525                    || "null".to_owned(),
526                    |value| format!("non-finite value {value}"),
527                );
528                let binding = values
529                    .field_key()
530                    .cloned()
531                    .unwrap_or_else(|| RawKey::from(values.name()));
532                Err(Error::Data(
533                    Diagnostic::new(
534                        DiagnosticKind::InvalidValue {
535                            value: value.map(RawKey::Float),
536                            constraint: "present finite numeric value".to_owned(),
537                        },
538                        format!(
539                            "{plot}: value {:?} contains {status} at source row {}",
540                            values.name(),
541                            data.source_row(row)
542                        ),
543                    )
544                    .with_context(data.member_context(row, binding, column)),
545                ))
546            }
547            None => Err(length_error(plot, values.name(), row)),
548        }
549    }))
550}
551
552#[cfg(test)]
553thread_local! {
554    pub(crate) static SOURCE_COLUMN_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
555}
556
557pub(crate) fn strict_numeric_value(
558    values: &NumericValues,
559    row: usize,
560    plot: &str,
561) -> Result<f64, Error> {
562    match values.get(row) {
563        Some(Some(value)) if value.is_finite() => Ok(value),
564        Some(Some(value)) => Err(Error::Data(
565            format!(
566                "{plot}: value {:?} contains non-finite value {value} at source row {}",
567                values.name(),
568                row
569            )
570            .into(),
571        )),
572        Some(None) => Err(Error::Data(
573            format!(
574                "{plot}: value {:?} contains null at source row {}",
575                values.name(),
576                row
577            )
578            .into(),
579        )),
580        None => unreachable!("row is bounded by NumericValues::len"),
581    }
582}
583
584pub(crate) fn strict_category_at<'a>(
585    values: &'a CategoryValues,
586    input_slot: usize,
587    diagnostic_row: usize,
588    context: &str,
589) -> Result<&'a str, Error> {
590    match values.get(input_slot) {
591        Some(Some(value)) => Ok(value),
592        Some(None) => Err(Error::Data(
593            format!(
594                "{context}: value {:?} contains null at source row {diagnostic_row}",
595                values.name()
596            )
597            .into(),
598        )),
599        None => Err(length_error(context, values.name(), input_slot)),
600    }
601}
602
603pub(crate) fn strict_numeric_at(
604    values: &NumericValues,
605    input_slot: usize,
606    diagnostic_row: usize,
607    context: &str,
608) -> Result<f64, Error> {
609    match values.get(input_slot) {
610        Some(Some(value)) if value.is_finite() => Ok(value),
611        Some(Some(value)) => Err(Error::Data(format!(
612            "{context}: value {:?} contains non-finite value {value} at source row {diagnostic_row}",
613            values.name()
614        ).into())),
615        Some(None) => Err(Error::Data(format!(
616            "{context}: value {:?} contains null at source row {diagnostic_row}",
617            values.name()
618        ).into())),
619        None => Err(length_error(context, values.name(), input_slot)),
620    }
621}
622
623pub(crate) fn strict_source_strings(
624    values: &CategoryValues,
625    rows: Option<&crate::data::SourceRows>,
626    context: &str,
627) -> Result<Vec<String>, Error> {
628    source::collect_source((0..values.len()).map(|slot| {
629        let diagnostic = rows
630            .and_then(|rows| rows.as_slice().get(slot))
631            .copied()
632            .unwrap_or(slot);
633        source::copy_source_string(strict_category_at(values, slot, diagnostic, context)?)
634    }))
635}
636
637pub(crate) fn strict_source_f64(
638    values: &NumericValues,
639    rows: Option<&crate::data::SourceRows>,
640    context: &str,
641) -> Result<Vec<f64>, Error> {
642    source::collect_source((0..values.len()).map(|slot| {
643        let diagnostic = rows
644            .and_then(|rows| rows.as_slice().get(slot))
645            .copied()
646            .unwrap_or(slot);
647        strict_numeric_at(values, slot, diagnostic, context)
648    }))
649}
650
651pub(crate) fn strict_source_normalized_strings(
652    values: &CategoryValues,
653    rows: Option<&crate::data::SourceRows>,
654    context: &str,
655    role: &str,
656) -> Result<Vec<String>, Error> {
657    source::collect_source(strict_source_strings(values, rows, context)?.into_iter().enumerate().map(|(slot, value)| {
658        let normalized = source::normalize_source_string(&value)?;
659        if normalized.is_empty() {
660            let diagnostic = rows.and_then(|rows| rows.as_slice().get(slot)).copied().unwrap_or(slot);
661            Err(Error::Data(format!("{context}: {role} label is empty after whitespace normalization at source row {diagnostic}").into()))
662        } else {
663            Ok(normalized)
664        }
665    }))
666}
667
668pub(crate) fn nullable_finite_f64(
669    data: PlotData<'_, '_>,
670    column: &str,
671    plot: &str,
672) -> Result<Vec<Option<f64>>, Error> {
673    let DataColumn::Numeric(values) = data.column(column)? else {
674        return Err(Error::Data(
675            format!(
676                "{plot}: value {:?} must be numeric",
677                data.column(column)?.name()
678            )
679            .into(),
680        ));
681    };
682    crate::data::source::collect_source((0..data.height()).map(|row| {
683        match values.get(data.row_index(row)) {
684            Some(Some(value)) if value.is_finite() => Ok(Some(value)),
685            Some(Some(value)) => Err(Error::Data(
686                format!(
687                    "{plot}: value {:?} contains non-finite value {value} at source row {}",
688                    values.name(),
689                    data.source_row(row)
690                )
691                .into(),
692            )),
693            Some(None) => Ok(None),
694            None => Err(length_error(plot, values.name(), row)),
695        }
696    }))
697}
698
699pub(crate) fn strict_bool(
700    data: PlotData<'_, '_>,
701    column: &str,
702    plot: &str,
703) -> Result<Vec<bool>, Error> {
704    let DataColumn::Boolean(values) = data.column(column)? else {
705        return Err(Error::Data(
706            format!(
707                "{plot}: value {:?} must be Boolean",
708                data.column(column)?.name()
709            )
710            .into(),
711        ));
712    };
713    crate::data::source::collect_source((0..data.height()).map(|row| {
714        match values.get(data.row_index(row)) {
715            Some(Some(value)) => Ok(value),
716            Some(None) => Err(Error::Data(
717                format!(
718                    "{plot}: value {:?} contains null at source row {}",
719                    values.name(),
720                    data.source_row(row)
721                )
722                .into(),
723            )),
724            None => Err(length_error(plot, values.name(), row)),
725        }
726    }))
727}
728
729pub(crate) fn aligned_finite_rows(
730    data: PlotData<'_, '_>,
731    x_column: &str,
732    y_column: &str,
733    plot: &str,
734) -> Result<Vec<(usize, f64, f64)>, Error> {
735    let x = optional_finite_f64(data, x_column, plot)?;
736    let y = optional_finite_f64(data, y_column, plot)?;
737    if x.len() != y.len() {
738        return Err(Error::Data(
739            format!(
740                "{plot}: aligned value length mismatch {} vs {}",
741                x.len(),
742                y.len()
743            )
744            .into(),
745        ));
746    }
747    let mut rows = Vec::new();
748    crate::data::source::reserve_source(&mut rows, x.len())?;
749
750    rows.extend(
751        x.into_iter()
752            .zip(y)
753            .enumerate()
754            .filter_map(|(row, (x, y))| Some((row, x?, y?))),
755    );
756    Ok(rows)
757}
758
759fn optional_finite_f64(
760    data: PlotData<'_, '_>,
761    column: &str,
762    plot: &str,
763) -> Result<Vec<Option<f64>>, Error> {
764    let DataColumn::Numeric(values) = data.column(column)? else {
765        return Err(Error::Data(
766            format!(
767                "{plot}: value {:?} must be numeric",
768                data.column(column)?.name()
769            )
770            .into(),
771        ));
772    };
773    crate::data::source::collect_source((0..data.height()).map(|row| {
774        match values.get(data.row_index(row)) {
775            Some(Some(value)) if value.is_infinite() => Err(Error::Data(
776                format!(
777                    "{plot}: value {:?} contains infinite value {value} at source row {}",
778                    values.name(),
779                    data.source_row(row)
780                )
781                .into(),
782            )),
783            Some(Some(value)) if value.is_nan() => Ok(None),
784            Some(value) => Ok(value),
785            None => Err(length_error(plot, values.name(), row)),
786        }
787    }))
788}
789
790#[derive(Debug)]
791pub(crate) struct CollectiveChannels {
792    pub(crate) groups: Option<Vec<String>>,
793    pub(crate) hues: Option<Vec<String>>,
794    pub(crate) group_levels: Vec<String>,
795    pub(crate) hue_levels: Vec<String>,
796}
797
798#[derive(Debug, Clone, PartialEq, Eq, Hash)]
799pub(crate) struct CollectivePair {
800    pub(crate) group: Option<String>,
801    pub(crate) hue: Option<String>,
802}
803
804impl CollectivePair {
805    pub(crate) fn description(&self, collapsed: bool) -> String {
806        match (&self.group, &self.hue, collapsed) {
807            (Some(group), _, true) | (Some(group), None, false) => {
808                format!("graphical group {group:?}")
809            }
810            (Some(group), Some(hue), false) => {
811                format!("graphical group {group:?} with hue {hue:?}")
812            }
813            (None, Some(hue), _) => format!("hue {hue:?}"),
814            (None, None, _) => "ungrouped series".to_string(),
815        }
816    }
817}
818
819#[derive(Debug)]
820pub(crate) struct ObservedCollectives {
821    pub(crate) rows: Vec<CollectivePair>,
822    pub(crate) identities: Vec<CollectivePair>,
823    pub(crate) group_levels: Vec<String>,
824    pub(crate) hue_levels: Vec<String>,
825    pub(crate) collapsed: bool,
826}
827
828pub(crate) fn observed_collectives(
829    data: PlotData<'_, '_>,
830    group_column: Option<&str>,
831    hue_column: Option<&str>,
832    retained_rows: Option<&[usize]>,
833    plot: &str,
834) -> Result<ObservedCollectives, Error> {
835    let mut row_indices = Vec::new();
836    crate::data::source::reserve_source(
837        &mut row_indices,
838        retained_rows.map_or(data.height(), <[usize]>::len),
839    )?;
840    if let Some(rows) = retained_rows {
841        row_indices.extend_from_slice(rows);
842    } else {
843        row_indices.extend(0..data.height());
844    }
845    let groups = group_column
846        .map(|column| strict_strings_for_rows(data, column, &row_indices, plot))
847        .transpose()?;
848    let hues = hue_column
849        .map(|column| strict_strings_for_rows(data, column, &row_indices, plot))
850        .transpose()?;
851    finish_observed_collectives(
852        groups,
853        hues,
854        data.source,
855        row_indices.len(),
856        |index| data.source_row(row_indices[index]),
857        plot,
858    )
859}
860
861#[expect(
862    clippy::needless_pass_by_value,
863    reason = "the decoded source arrays belong to this reduction and are not retained by its callers"
864)]
865fn finish_observed_collectives(
866    groups: Option<Vec<String>>,
867    hues: Option<Vec<String>>,
868    source: &crate::builder::PlotDescription,
869    row_count: usize,
870    diagnostic_row: impl Fn(usize) -> usize,
871    plot: &str,
872) -> Result<ObservedCollectives, Error> {
873    let collapsed = source.same_group_hue_field();
874    if collapsed {
875        let group = source.legend_group_values().expect("actual group field");
876        let hue = source.legend_hue_values().expect("actual hue field");
877        let (Some(groups), Some(hues)) = (groups.as_ref(), hues.as_ref()) else {
878            return Err(Error::Data(
879                format!(
880                    "{plot}: equal graphical group and hue names require both categorical channels"
881                )
882                .into(),
883            ));
884        };
885        if let Some(index) = groups
886            .iter()
887            .zip(hues)
888            .position(|(group_level, hue_level)| !group.same_level_key(group_level, hue, hue_level))
889        {
890            return Err(Error::Data(format!(
891                "{plot}: graphical group and hue share semantic name {:?} but differ at source row {}",
892                group.original_name(),
893                diagnostic_row(index)
894            ).into()));
895        }
896    }
897
898    let rows = crate::data::source::collect_source((0..row_count).map(|index| {
899        Ok(CollectivePair {
900            group: groups
901                .as_ref()
902                .map(|values| crate::data::source::copy_source_string(&values[index]))
903                .transpose()?,
904            hue: hues
905                .as_ref()
906                .map(|values| crate::data::source::copy_source_string(&values[index]))
907                .transpose()?,
908        })
909    }))?;
910    let group_levels = groups.as_ref().map_or_else(
911        || Ok(Vec::new()),
912        |values| crate::data::source::source_levels(values),
913    )?;
914    let hue_levels = hues.as_ref().map_or_else(
915        || Ok(Vec::new()),
916        |values| crate::data::source::source_levels(values),
917    )?;
918    let mut identities = Vec::new();
919    crate::data::source::reserve_source(&mut identities, rows.len())?;
920    if groups.is_some() {
921        for group in &group_levels {
922            for identity in &rows {
923                if identity.group.as_ref() != Some(group) {
924                    continue;
925                }
926                if crate::data::source::source_position(&identities, |seen| seen == identity)
927                    .is_none()
928                {
929                    identities.push(crate::data::source::copy_source_pair(identity)?);
930                }
931            }
932        }
933    } else {
934        for identity in &rows {
935            if crate::data::source::source_position(&identities, |seen| seen == identity).is_none()
936            {
937                identities.push(crate::data::source::copy_source_pair(identity)?);
938            }
939        }
940    }
941
942    Ok(ObservedCollectives {
943        rows,
944        identities,
945        group_levels,
946        hue_levels,
947        collapsed,
948    })
949}
950
951fn strict_strings_for_rows(
952    data: PlotData<'_, '_>,
953    column: &str,
954    rows: &[usize],
955    plot: &str,
956) -> Result<Vec<String>, Error> {
957    let DataColumn::Category(values) = data.column(column)? else {
958        return Err(Error::Data(
959            format!(
960                "{plot}: value {:?} must be categorical",
961                data.column(column)?.name()
962            )
963            .into(),
964        ));
965    };
966    crate::data::source::collect_source(rows.iter().map(|row| {
967        match values.get(data.row_index(*row)) {
968            Some(Some(value)) => crate::data::source::copy_source_string(value),
969            Some(None) => Err(Error::Data(
970                format!(
971                    "{plot}: value {:?} contains null at source row {}",
972                    values.name(),
973                    data.source_row(*row)
974                )
975                .into(),
976            )),
977            None => Err(length_error(plot, values.name(), *row)),
978        }
979    }))
980}
981
982pub(crate) fn collective_channels(
983    data: PlotData<'_, '_>,
984    group_column: Option<&str>,
985    hue_column: Option<&str>,
986    cells: Option<&[String]>,
987    plot: &str,
988) -> Result<CollectiveChannels, Error> {
989    let groups = group_column
990        .map(|column| strict_strings(data, column, plot))
991        .transpose()?;
992    let hues = hue_column
993        .map(|column| strict_strings(data, column, plot))
994        .transpose()?;
995    let row_count = data.height();
996    finish_collective_channels(
997        groups,
998        hues,
999        cells,
1000        row_count,
1001        |row| data.source_row(row),
1002        plot,
1003    )
1004}
1005
1006pub(crate) fn finish_collective_channels(
1007    groups: Option<Vec<String>>,
1008    hues: Option<Vec<String>>,
1009    cells: Option<&[String]>,
1010    row_count: usize,
1011    diagnostic_row: impl Fn(usize) -> usize,
1012    plot: &str,
1013) -> Result<CollectiveChannels, Error> {
1014    if groups
1015        .as_ref()
1016        .is_some_and(|values| values.len() != row_count)
1017        || hues
1018            .as_ref()
1019            .is_some_and(|values| values.len() != row_count)
1020        || cells.is_some_and(|values| values.len() != row_count)
1021    {
1022        return Err(Error::Data(
1023            format!(
1024                "{plot}: graphical group, hue, and mark-cell values must align with the plot input"
1025            )
1026            .into(),
1027        ));
1028    }
1029
1030    if let Some(hues_ref) = hues.as_ref() {
1031        let mut marks: Vec<(Option<&str>, Option<&str>, &str)> = Vec::new();
1032        crate::data::source::reserve_source(&mut marks, row_count)?;
1033        for row in 0..row_count {
1034            let cell = cells.map(|values| values[row].as_str());
1035            let group = groups.as_ref().map(|values| values[row].as_str());
1036            let hue = hues_ref[row].as_str();
1037            if let Some(index) =
1038                crate::data::source::source_position(&marks, |(seen_cell, seen_group, _)| {
1039                    *seen_cell == cell && *seen_group == group
1040                })
1041            {
1042                let (_, _, seen_hue) = &marks[index];
1043                if *seen_hue != hue {
1044                    return Err(Error::Data(format!(
1045                        "{plot}: each collective mark must have exactly one hue; found {seen_hue:?} and {hue:?} at source row {}",
1046                        diagnostic_row(row)
1047                    ).into()));
1048                }
1049            } else {
1050                marks.push((cell, group, hue));
1051            }
1052        }
1053    }
1054
1055    Ok(CollectiveChannels {
1056        group_levels: groups.as_ref().map_or_else(
1057            || Ok(Vec::new()),
1058            |values| crate::data::source::source_levels(values),
1059        )?,
1060        hue_levels: hues.as_ref().map_or_else(
1061            || Ok(Vec::new()),
1062            |values| crate::data::source::source_levels(values),
1063        )?,
1064        groups,
1065        hues,
1066    })
1067}
1068
1069pub(crate) fn source_collective_channels(
1070    source: &crate::builder::PlotDescription,
1071    cells: Option<&[String]>,
1072    context: &str,
1073) -> Result<CollectiveChannels, Error> {
1074    let strings = |key: &str| {
1075        let column = source
1076            .data_column(key)
1077            .ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))?;
1078        let DataColumn::Category(values) = column else {
1079            return Err(Error::Data(
1080                format!("{context}: value {:?} must be categorical", column.name()).into(),
1081            ));
1082        };
1083        strict_source_strings(values, None, context)
1084    };
1085    let groups = source.group_col().map(strings).transpose()?;
1086    let hues = source.hue_col().map(strings).transpose()?;
1087    finish_collective_channels(groups, hues, cells, source.row_count(), |row| row, context)
1088}
1089
1090pub(crate) fn observed_source_collectives(
1091    source: &crate::builder::PlotDescription,
1092    context: &str,
1093) -> Result<ObservedCollectives, Error> {
1094    let rows = source.source_row_map();
1095    let mut row_indices = Vec::new();
1096    self::source::reserve_source(&mut row_indices, source.row_count())?;
1097    row_indices.extend(0..source.row_count());
1098    let strings = |key: &str| {
1099        let column = source
1100            .data_column(key)
1101            .ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))?;
1102        let DataColumn::Category(values) = column else {
1103            return Err(Error::Data(
1104                format!("{context}: value {:?} must be categorical", column.name()).into(),
1105            ));
1106        };
1107        strict_source_strings(values, rows, context)
1108    };
1109    let groups = source.group_col().map(strings).transpose()?;
1110    let hues = source.hue_col().map(strings).transpose()?;
1111    finish_observed_collectives(
1112        groups,
1113        hues,
1114        source,
1115        row_indices.len(),
1116        |slot| {
1117            let slot = row_indices[slot];
1118            rows.and_then(|rows| rows.as_slice().get(slot))
1119                .copied()
1120                .unwrap_or(slot)
1121        },
1122        context,
1123    )
1124}
1125
1126pub(crate) fn stable_levels(values: &[String]) -> Vec<String> {
1127    let mut levels = Vec::new();
1128    for value in values {
1129        if !levels.contains(value) {
1130            levels.push(value.clone());
1131        }
1132    }
1133    levels
1134}
1135
1136pub(crate) fn explicit_category_order(
1137    observed: &[String],
1138    requested: &[String],
1139    context: &str,
1140    allow_unobserved: bool,
1141) -> Result<Vec<String>, Error> {
1142    let mut seen = Vec::new();
1143    crate::data::source::reserve_source(&mut seen, requested.len())?;
1144    for level in requested {
1145        if seen.contains(level) {
1146            return Err(Error::Data(
1147                format!("{context}: explicit category order contains duplicate level {level:?}")
1148                    .into(),
1149            ));
1150        }
1151
1152        if !allow_unobserved && !observed.contains(level) {
1153            return Err(Error::Data(
1154                format!("{context}: explicit category order contains unknown level {level:?}")
1155                    .into(),
1156            ));
1157        }
1158        seen.push(crate::data::source::copy_source_string(level)?);
1159    }
1160    for level in observed {
1161        if !seen.contains(level) {
1162            return Err(Error::Data(
1163                format!("{context}: explicit category order omits observed level {level:?}").into(),
1164            ));
1165        }
1166    }
1167    if allow_unobserved {
1168        seen.retain(|level| observed.contains(level));
1169    }
1170    Ok(seen)
1171}
1172
1173pub(crate) fn strict_strings(
1174    data: PlotData<'_, '_>,
1175    column: &str,
1176    plot: &str,
1177) -> Result<Vec<String>, Error> {
1178    let DataColumn::Category(values) = data.column(column)? else {
1179        return Err(Error::Data(
1180            format!(
1181                "{plot}: value {:?} must be categorical",
1182                data.column(column)?.name()
1183            )
1184            .into(),
1185        ));
1186    };
1187    crate::data::source::collect_source((0..data.height()).map(|row| {
1188        match values.get(data.row_index(row)) {
1189            Some(Some(value)) => crate::data::source::copy_source_string(value),
1190            Some(None) => {
1191                use crate::errors::{Diagnostic, DiagnosticKind};
1192                let binding = values
1193                    .field_key()
1194                    .cloned()
1195                    .unwrap_or_else(|| RawKey::from(values.name()));
1196                Err(Error::Data(
1197                    Diagnostic::new(
1198                        DiagnosticKind::InvalidValue {
1199                            value: None,
1200                            constraint: "present category".to_owned(),
1201                        },
1202                        format!(
1203                            "{plot}: value {:?} contains null at source row {}",
1204                            values.name(),
1205                            data.source_row(row)
1206                        ),
1207                    )
1208                    .with_context(data.member_context(row, binding, column)),
1209                ))
1210            }
1211            None => Err(length_error(plot, values.name(), row)),
1212        }
1213    }))
1214}
1215
1216pub(crate) fn strict_normalized_strings(
1217    data: PlotData<'_, '_>,
1218    column: &str,
1219    plot: &str,
1220    role: &str,
1221) -> Result<Vec<String>, Error> {
1222    crate::data::source::collect_source(
1223        strict_strings(data, column, plot)?
1224            .into_iter()
1225            .enumerate()
1226            .map(|(row, value)| {
1227                let normalized = crate::data::source::normalize_source_string(&value)?;
1228                if normalized.is_empty() {
1229                    Err(Error::Data(
1230                        format!(
1231                    "{plot}: {role} label is empty after whitespace normalization at source row {}",
1232                    data.source_row(row)
1233                )
1234                        .into(),
1235                    ))
1236                } else {
1237                    Ok(normalized)
1238                }
1239            }),
1240    )
1241}
1242
1243pub(crate) fn collapse_whitespace(value: &str) -> String {
1244    value.split_whitespace().collect::<Vec<_>>().join(" ")
1245}
1246
1247pub(crate) fn min_max(
1248    values: impl IntoIterator<Item = f64>,
1249    plot: &str,
1250) -> Result<(f64, f64), Error> {
1251    let mut range: Option<(f64, f64)> = None;
1252    for value in values {
1253        if !value.is_finite() {
1254            return Err(Error::Data(
1255                format!("{plot}: cannot compute range from non-finite value {value}").into(),
1256            ));
1257        }
1258        range = Some(range.map_or((value, value), |(lo, hi)| (lo.min(value), hi.max(value))));
1259    }
1260    range.ok_or_else(|| Error::Data(format!("{plot}: cannot compute range from no values").into()))
1261}
1262
1263fn length_error(plot: &str, name: &str, row: usize) -> Error {
1264    Error::Data(
1265        format!("{plot}: value {name:?} is shorter than the aligned plot input at row {row}")
1266            .into(),
1267    )
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    use super::*;
1273
1274    #[test]
1275    fn typed_source_reads_keep_full_read_precedence_and_diagnostic_rows() {
1276        let values = CategoryValues::nullable("category", [Some("   "), None]).unwrap();
1277        let rows = crate::data::SourceRows::new([70, 901]).unwrap();
1278        let error = strict_source_normalized_strings(&values, Some(&rows), "source", "category")
1279            .unwrap_err();
1280        assert_eq!(
1281            error.to_string(),
1282            "data error: source: value \"category\" contains null at source row 901"
1283        );
1284        let values = CategoryValues::new("category", ["  ", "valid"]).unwrap();
1285        let error = strict_source_normalized_strings(&values, Some(&rows), "source", "category")
1286            .unwrap_err();
1287        assert_eq!(error.to_string(), "data error: source: category label is empty after whitespace normalization at source row 70");
1288        let numbers = NumericValues::new("value", [3.0, f64::INFINITY]);
1289        assert_eq!(
1290            strict_numeric_at(&numbers, 0, 901, "source")
1291                .unwrap()
1292                .to_bits(),
1293            3.0_f64.to_bits()
1294        );
1295        assert_eq!(
1296            strict_source_f64(&numbers, Some(&rows), "source")
1297                .unwrap_err()
1298                .to_string(),
1299            "data error: source: value \"value\" contains non-finite value inf at source row 901"
1300        );
1301    }
1302}