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