pub use crate::input::AxisValues;
pub use crate::spec::{Bounds, EstimateStatus};
pub use crate::values::SourceRows;
pub use arrays::{ArrayElementType, ArrayValueType, ArrayValues, NdArray};
#[doc(hidden)]
#[doc(hidden)]
pub enum CapturedCollection<'a> {
Wide(&'a DataSourceInfo),
Grid {
source: &'a DataSourceInfo,
x: &'a crate::CategoryValues,
y: &'a crate::CategoryValues,
},
Matrix(&'a VariableValues),
}
pub use binding::CapturedValue;
pub(crate) use binding::VectorSource;
pub use binding::{
BindingGeneration, BindingSelector, BindingSelectorKind, BindingSlice, DataSourceInfo,
DataSourceRef,
};
#[doc(hidden)]
pub use binding::{ColumnKeyLookup, ColumnKeySource, GeneratedColumns};
pub(crate) use identity::InstanceId;
pub use integer::{ExactInteger, IntegerValues};
pub(crate) use key::key_bytes;
pub use key::{
IntervalClosed, IntervalKey, KeyColumns, KeyValues, NamedKeyValues, RawKey, RawKeyValues,
UnavailableKey,
};
pub use payload::{DataPayload, DataValueType};
pub(crate) use protocol::{select_value, DomainSlot};
pub use protocol::{
AxisValueType, ComponentPathPart, DataComponentInfo, DataDomainInfo, DataDomainRef,
DataRoleInfo, DataRoleRef, DataSelector, DataValue, MemberAddress, SourceMember, SourceMembers,
SourceMembersEntry,
};
pub use roles::DataRole;
pub use status::EstimateStatusBinding;
pub use temporal::{
Date, DateValues, Duration, DurationUnit, DurationValues, LocalTimestamp, TimeValues, TimeZone,
Timestamp,
};
pub use variables::{NamedNumericValues, VariableValues};
use crate::{BooleanValues, CategoryValues, Error, NumericValues};
mod arrays;
pub(crate) mod binding;
pub(crate) mod category;
pub(crate) mod group_key;
mod identity;
mod integer;
mod key;
mod payload;
pub use group_key::{GroupDimension, GroupDimensionRef, GroupKey, GroupKeys};
mod grouped;
pub use grouped::GroupedObservations;
mod protocol;
mod roles;
pub(crate) mod source;
mod status;
mod temporal;
mod variables;
#[cfg(test)]
mod values_tests {
use super::*;
#[test]
fn original_source_selection_survives_projection_and_alpha_materialization() {
let reference = DataSourceRef::capture();
let next = reference.recapture();
assert_ne!(reference, next);
assert!(reference.same_source(&next));
assert!(!reference.same_source(&DataSourceRef::capture()));
let key = RawKey::Tuple(vec![
RawKey::from("measurement"),
RawKey::Integer(17.into()),
]);
let source = DataSourceInfo::selected(
reference.clone(),
BindingSelector::Key(key.clone()),
Some(vec![key.clone()]),
vec![4],
vec![3, 7],
vec![3],
);
let values = NumericValues::new("internal", [-0., -0., 0.5, 0.5, 1., 1.])
.with_field_key(key.clone(), "measurement")
.with_repeated_source(source, 2)
.unwrap();
let mapped = crate::scales::AlphaValues::linear(values, (0., 1.), (0., 1.)).unwrap();
let selected = mapped.select([3, 0, 5, 0]).unwrap();
let raw = selected.get_numeric_source().unwrap();
assert_eq!(raw.name(), "measurement");
assert_eq!(raw.field_key(), Some(&key));
assert_eq!(raw.get_source().reference(), &reference);
assert_eq!(raw.get_source().selected_indices(), Some(&[4][..]));
assert_eq!(raw.get_source().source_shape(), &[3, 7]);
assert_eq!(raw.get_source().selected_shape(), &[3]);
assert_eq!(
(0..raw.len())
.map(|index| raw.source_slot(index))
.collect::<Vec<_>>(),
[Some(1), Some(0), Some(2), Some(0)]
);
assert_eq!(
raw.get(1).flatten().unwrap().to_bits(),
(-0.0_f64).to_bits()
);
}
#[test]
fn direct_alpha_preserves_authored_values_and_checked_source_relations() {
let source = DataSourceInfo::direct(vec![2]);
let values = NumericValues::new("opacity", [-0., 0.75]);
assert!(values
.clone()
.with_repeated_source(source.clone(), 0)
.is_err());
assert!(values
.clone()
.with_repeated_source(source.clone(), 2)
.is_err());
assert!(values
.clone()
.with_source_slots(source.clone(), vec![0, 2])
.is_err());
let values = values.with_source(source.clone()).unwrap();
let alpha = crate::scales::AlphaValues::try_from(values).unwrap();
assert_eq!(alpha.get(0).unwrap().to_bits(), 0.0_f64.to_bits());
let selected = alpha.select([1, 0, 1]).unwrap();
let original = selected.get_numeric_source().unwrap();
assert_eq!(original.get_source(), &source);
assert_eq!(
original.get(1).flatten().unwrap().to_bits(),
(-0.0_f64).to_bits()
);
assert_eq!(original.source_slot(2), Some(1));
}
#[test]
fn original_values_distinguish_validity_from_finiteness_and_identity() {
let numbers = NumericValues::nullable(
"numeric",
[Some(f64::NAN), None, Some(-0.), Some(f64::INFINITY)],
);
assert!(numbers.get(0).flatten().unwrap().is_nan());
assert_eq!(numbers.get(1), Some(None));
assert_eq!(
numbers.get(2).flatten().unwrap().to_bits(),
(-0.0_f64).to_bits()
);
assert_eq!(numbers.get(3).flatten(), Some(f64::INFINITY));
assert_eq!(numbers.is_valid(0), Some(true));
assert_eq!(numbers.is_valid(1), Some(false));
assert_eq!(numbers.is_valid(4), None);
let categories = CategoryValues::nullable("category", [Some(""), None, Some("A")]).unwrap();
assert_eq!(
categories.iter().collect::<Vec<_>>(),
[Some(""), None, Some("A")]
);
assert_eq!(categories.levels(), ["", "A"]);
let booleans = BooleanValues::nullable("boolean", [Some(false), None, Some(true)]);
assert_eq!(
booleans.iter().collect::<Vec<_>>(),
[Some(false), None, Some(true)]
);
}
#[test]
fn exact_keys_keep_arbitrary_magnitude_and_temporal_fields() {
let huge = ExactInteger::from_parts(false, &[1; 24]).unwrap();
assert!(huge.to_u128().is_none());
assert_eq!(ExactInteger::from(i128::MIN).to_i128(), Some(i128::MIN));
assert_eq!(ExactInteger::from(u128::MAX).to_u128(), Some(u128::MAX));
assert_eq!(
ExactInteger::from_parts(true, &[0, 0]).unwrap(),
ExactInteger::from(0)
);
assert!(
ExactInteger::from_parts(true, huge.magnitude_be()).unwrap()
< ExactInteger::from(i128::MIN)
);
let values =
IntegerValues::nullable("counts", [Some(huge.clone()), None, Some(2.into())]).unwrap();
assert_eq!(values.get(0), Some(Some(&huge)));
assert_eq!(values.is_valid(1), Some(false));
assert_eq!(values.get(3), None);
assert!(Date::new(1900, 2, 29).is_err());
let date = Date::new(2000, 2, 29).unwrap();
let instant = Timestamp::new(
-1,
999_999_999,
Some(TimeZone::FixedOffset(0)),
Some(0),
None,
)
.unwrap();
assert_eq!(instant.unix_ns(), -1);
let local = LocalTimestamp::new(date, 1, 2, 3, 7).unwrap();
let key = RawKey::Tuple(vec![RawKey::Integer(huge), RawKey::LocalTimestamp(local)]);
let keys = RawKeyValues::nullable(
"raw",
[
Some(key.clone()),
None,
Some(key.clone()),
Some(RawKey::Instant(instant)),
],
)
.unwrap();
assert_eq!(keys.levels().len(), 2);
assert_eq!(keys.get(2), Some(Some(&key)));
assert_eq!(keys.is_valid(1), Some(false));
assert_ne!(RawKey::Float(-0.), RawKey::Float(0.));
}
}
pub(crate) const X: &str = "__x";
pub(crate) const Y: &str = "__y";
pub(crate) const HUE: &str = "__hue";
pub(crate) const GROUP: &str = "__group";
pub(crate) const SERIES: &str = "__series";
pub(crate) const COLOR: &str = "__color";
pub(crate) const INTERVAL_LOWER: &str = "__interval_lower";
pub(crate) const INTERVAL_UPPER: &str = "__interval_upper";
pub(crate) const BAR_INTERVAL_LOWER: &str = "__bar_interval_lower";
pub(crate) const BAR_INTERVAL_UPPER: &str = "__bar_interval_upper";
pub(crate) const BAR_UNITS: &str = "__bar_units";
pub(crate) const HIGHLIGHT_CELLS: &str = "__highlight_cells";
pub(crate) const DUMBBELL_RIGHT: &str = "__dumbbell_right";
pub(crate) const FACET_ROW: &str = "__facet_row";
pub(crate) const FACET_COLUMN: &str = "__facet_column";
pub(crate) const FACET_WRAP: &str = "__facet_wrap";
#[derive(Debug, Clone, Copy)]
pub(crate) enum DataColumn<'a> {
Numeric(&'a NumericValues),
Category(&'a CategoryValues),
Boolean(&'a BooleanValues),
}
impl<'a> DataColumn<'a> {
pub(crate) const fn is_numeric(self) -> bool {
matches!(self, Self::Numeric(_))
}
pub(crate) fn name(self) -> &'a str {
match self {
Self::Numeric(values) => values.name(),
Self::Category(values) => values.name(),
Self::Boolean(values) => values.name(),
}
}
pub(crate) fn len(self) -> usize {
match self {
Self::Numeric(values) => values.len(),
Self::Category(values) => values.len(),
Self::Boolean(values) => values.len(),
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct FacetAxisSources<'a> {
pub(crate) hues: Option<&'a [String]>,
pub(crate) groups: Option<&'a [String]>,
pub(crate) conditions: Option<&'a [String]>,
}
#[derive(Clone, Copy)]
pub(crate) struct PlotData<'src, 'op> {
source: &'src crate::builder::PlotDescription,
rows: Option<&'op [usize]>,
diagnostic_rows: DiagnosticRows<'src, 'op>,
numeric_facet: Option<&'op crate::layout::FacetCell>,
scope: &'op crate::orchestrator::registration::Scope,
operation: &'op crate::font::canonical::OperationContext,
row_source: &'op source::RowSourceContext<'src>,
}
#[derive(Clone, Copy)]
pub(crate) enum DiagnosticRows<'src, 'op> {
Native(Option<&'src crate::data::SourceRows>),
Selected(&'op [usize]),
}
impl std::fmt::Debug for PlotData<'_, '_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PlotData")
.field("height", &self.height())
.field("is_full_plot", &self.is_full_plot())
.finish_non_exhaustive()
}
}
impl<'src, 'op> PlotData<'src, 'op> {
pub(crate) fn checked(
source: &'src crate::builder::PlotDescription,
scope: &'op crate::orchestrator::registration::Scope,
row_source: &'op source::RowSourceContext<'src>,
operation: &'op crate::font::canonical::OperationContext,
) -> Result<Self, Error> {
row_source.check(source, scope, operation)?;
let (rows, diagnostic_rows) = scope.rows.selected().map_or_else(
|| (None, DiagnosticRows::Native(source.source_row_map())),
|(rows, diagnostic_rows)| (Some(rows), DiagnosticRows::Selected(diagnostic_rows)),
);
Ok(Self {
source,
rows,
diagnostic_rows,
numeric_facet: scope.numeric_owner.facet.as_ref(),
scope,
operation,
row_source,
})
}
pub(crate) const fn numeric_facet(self) -> Option<&'op crate::layout::FacetCell> {
self.numeric_facet
}
pub(crate) fn facet_selector(
self,
) -> Result<Option<crate::orchestrator::registration::FacetSelector<'src, 'op>>, Error> {
if self.height() == 0 {
return Ok(None);
}
self.source
.facet_spec()
.zip(self.numeric_facet())
.map(|(schema, levels)| {
crate::orchestrator::registration::FacetSelector::checked(schema, levels)
})
.transpose()
}
pub(crate) const fn source_resources(self) -> &'op crate::font::canonical::OperationContext {
self.operation
}
#[cfg(test)]
pub(crate) const fn plot_id(self) -> &'op crate::orchestrator::registration::PlotOccurrenceId {
self.row_source.owner()
}
pub(crate) fn column(self, key: &str) -> Result<DataColumn<'src>, Error> {
#[cfg(test)]
SOURCE_COLUMN_READS.with(|calls| calls.set(calls.get() + 1));
self.source
.data_column(key)
.ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))
}
pub(crate) fn height(self) -> usize {
self.rows
.map_or_else(|| self.source.row_count(), <[usize]>::len)
}
pub(crate) const fn is_full_plot(self) -> bool {
self.rows.is_none()
}
fn member_context(
self,
row: usize,
binding: RawKey,
column: &str,
) -> crate::errors::ErrorContext {
use crate::{
elements::LayerSlot,
errors::{ErrorContext, OperationPhase},
layout::PanelPath,
};
let mut panel = PanelPath::root();
if let Some((row, column)) = self.scope.numeric_owner.canvas {
panel = panel.panel(row, column);
}
if let Some(facet) = self.numeric_facet {
panel = panel.facet(facet.clone());
}
let member = if self.source.source_row_map().is_some() {
MemberAddress::RowId(self.source_row(row))
} else {
MemberAddress::Slot(self.row_index(row))
};
let mut context = ErrorContext::new()
.with_operation(OperationPhase::Prepare)
.with_panel(panel)
.with_layer(LayerSlot::Primary)
.with_member(member)
.with_binding(binding);
if let Some(role) = self.source.column_role(column) {
context = context.with_role(role);
}
context
}
pub(crate) fn source_row(self, local_row: usize) -> usize {
let diagnostic = match self.diagnostic_rows {
DiagnosticRows::Native(rows) => rows.and_then(|rows| rows.as_slice().get(local_row)),
DiagnosticRows::Selected(rows) => rows.get(local_row),
};
diagnostic
.copied()
.unwrap_or_else(|| self.row_index(local_row))
}
pub(crate) fn estimate_statuses(
self,
) -> Result<Option<Vec<crate::data::EstimateStatus>>, Error> {
let Some(statuses) = self.source.estimate_status_values() else {
return Ok(None);
};
crate::data::source::collect_source((0..self.height())
.map(|row| {
statuses.get(self.row_index(row)).copied().ok_or_else(|| {
Error::Data(format!(
"estimate status values are shorter than the aligned plot input at source row {}",
self.source_row(row)
).into())
})
}))
.map(Some)
}
pub(crate) fn row_index(self, local_row: usize) -> usize {
self.rows
.and_then(|rows| rows.get(local_row))
.copied()
.unwrap_or(local_row)
}
pub(crate) fn observation_alpha(
self,
alpha: &crate::alpha::PreparedAlpha,
local_row: usize,
) -> Result<Option<crate::alpha::ResolvedAlpha>, Error> {
if local_row >= self.height() {
return Err(Error::Data(
format!("alpha local row {local_row} is outside the selected input").into(),
));
}
alpha.observation(self.row_index(local_row), self.source_row(local_row))
}
}
#[cfg(test)]
pub(crate) fn with_source_data_for_test<'src, T>(
source: &'src crate::Plot,
operation: &crate::font::canonical::OperationContext,
rows: crate::orchestrator::registration::RowSelection,
visit: impl FnOnce(PlotData<'src, '_>) -> T,
) -> Result<T, Error> {
let scope = crate::orchestrator::registration::Scope::new(
source.description(),
operation,
0,
crate::layout::ComponentAddress::root().child(crate::layout::AddressRole::PlotBody, 0)?,
rows,
None,
None,
)?;
let mut registry =
crate::orchestrator::registration::PlotRegistryBuilder::new(operation.root_identity());
let policy = crate::orchestrator::registration::PlotScopePolicy::for_source(
source.description(),
scope.numeric_owner.facet.as_ref(),
);
let id = registry.reserve(
source.description(),
scope.address,
scope.numeric_owner,
scope.axis_numeric_owner,
scope.rows,
scope.render_name,
policy,
source.description().resolve_theme()?,
operation,
)?;
Ok(visit(registry.data(&id, operation)?))
}
pub(crate) fn strict_finite_f64(
data: PlotData<'_, '_>,
column: &str,
plot: &str,
) -> Result<Vec<f64>, Error> {
let DataColumn::Numeric(values) = data.column(column)? else {
return Err(Error::Data(
format!(
"{plot}: value {:?} must be numeric",
data.column(column)?.name()
)
.into(),
));
};
crate::data::source::collect_source((0..data.height()).map(|row| {
match values.get(data.row_index(row)) {
Some(Some(value)) if value.is_finite() => Ok(value),
Some(value) => {
use crate::errors::{Diagnostic, DiagnosticKind};
let status = value.map_or_else(
|| "null".to_owned(),
|value| format!("non-finite value {value}"),
);
let binding = values
.field_key()
.cloned()
.unwrap_or_else(|| RawKey::from(values.name()));
Err(Error::Data(
Diagnostic::new(
DiagnosticKind::InvalidValue {
value: value.map(RawKey::Float),
constraint: "present finite numeric value".to_owned(),
},
format!(
"{plot}: value {:?} contains {status} at source row {}",
values.name(),
data.source_row(row)
),
)
.with_context(data.member_context(row, binding, column)),
))
}
None => Err(length_error(plot, values.name(), row)),
}
}))
}
#[cfg(test)]
thread_local! {
pub(crate) static SOURCE_COLUMN_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub(crate) fn strict_numeric_value(
values: &NumericValues,
row: usize,
plot: &str,
) -> Result<f64, Error> {
match values.get(row) {
Some(Some(value)) if value.is_finite() => Ok(value),
Some(Some(value)) => Err(Error::Data(
format!(
"{plot}: value {:?} contains non-finite value {value} at source row {}",
values.name(),
row
)
.into(),
)),
Some(None) => Err(Error::Data(
format!(
"{plot}: value {:?} contains null at source row {}",
values.name(),
row
)
.into(),
)),
None => unreachable!("row is bounded by NumericValues::len"),
}
}
pub(crate) fn strict_category_at<'a>(
values: &'a CategoryValues,
input_slot: usize,
diagnostic_row: usize,
context: &str,
) -> Result<&'a str, Error> {
match values.get(input_slot) {
Some(Some(value)) => Ok(value),
Some(None) => Err(Error::Data(
format!(
"{context}: value {:?} contains null at source row {diagnostic_row}",
values.name()
)
.into(),
)),
None => Err(length_error(context, values.name(), input_slot)),
}
}
pub(crate) fn strict_numeric_at(
values: &NumericValues,
input_slot: usize,
diagnostic_row: usize,
context: &str,
) -> Result<f64, Error> {
match values.get(input_slot) {
Some(Some(value)) if value.is_finite() => Ok(value),
Some(Some(value)) => Err(Error::Data(format!(
"{context}: value {:?} contains non-finite value {value} at source row {diagnostic_row}",
values.name()
).into())),
Some(None) => Err(Error::Data(format!(
"{context}: value {:?} contains null at source row {diagnostic_row}",
values.name()
).into())),
None => Err(length_error(context, values.name(), input_slot)),
}
}
pub(crate) fn strict_source_strings(
values: &CategoryValues,
rows: Option<&crate::data::SourceRows>,
context: &str,
) -> Result<Vec<String>, Error> {
source::collect_source((0..values.len()).map(|slot| {
let diagnostic = rows
.and_then(|rows| rows.as_slice().get(slot))
.copied()
.unwrap_or(slot);
source::copy_source_string(strict_category_at(values, slot, diagnostic, context)?)
}))
}
pub(crate) fn strict_source_f64(
values: &NumericValues,
rows: Option<&crate::data::SourceRows>,
context: &str,
) -> Result<Vec<f64>, Error> {
source::collect_source((0..values.len()).map(|slot| {
let diagnostic = rows
.and_then(|rows| rows.as_slice().get(slot))
.copied()
.unwrap_or(slot);
strict_numeric_at(values, slot, diagnostic, context)
}))
}
pub(crate) fn strict_source_normalized_strings(
values: &CategoryValues,
rows: Option<&crate::data::SourceRows>,
context: &str,
role: &str,
) -> Result<Vec<String>, Error> {
source::collect_source(strict_source_strings(values, rows, context)?.into_iter().enumerate().map(|(slot, value)| {
let normalized = source::normalize_source_string(&value)?;
if normalized.is_empty() {
let diagnostic = rows.and_then(|rows| rows.as_slice().get(slot)).copied().unwrap_or(slot);
Err(Error::Data(format!("{context}: {role} label is empty after whitespace normalization at source row {diagnostic}").into()))
} else {
Ok(normalized)
}
}))
}
pub(crate) fn nullable_finite_f64(
data: PlotData<'_, '_>,
column: &str,
plot: &str,
) -> Result<Vec<Option<f64>>, Error> {
let DataColumn::Numeric(values) = data.column(column)? else {
return Err(Error::Data(
format!(
"{plot}: value {:?} must be numeric",
data.column(column)?.name()
)
.into(),
));
};
crate::data::source::collect_source((0..data.height()).map(|row| {
match values.get(data.row_index(row)) {
Some(Some(value)) if value.is_finite() => Ok(Some(value)),
Some(Some(value)) => Err(Error::Data(
format!(
"{plot}: value {:?} contains non-finite value {value} at source row {}",
values.name(),
data.source_row(row)
)
.into(),
)),
Some(None) => Ok(None),
None => Err(length_error(plot, values.name(), row)),
}
}))
}
pub(crate) fn strict_bool(
data: PlotData<'_, '_>,
column: &str,
plot: &str,
) -> Result<Vec<bool>, Error> {
let DataColumn::Boolean(values) = data.column(column)? else {
return Err(Error::Data(
format!(
"{plot}: value {:?} must be Boolean",
data.column(column)?.name()
)
.into(),
));
};
crate::data::source::collect_source((0..data.height()).map(|row| {
match values.get(data.row_index(row)) {
Some(Some(value)) => Ok(value),
Some(None) => Err(Error::Data(
format!(
"{plot}: value {:?} contains null at source row {}",
values.name(),
data.source_row(row)
)
.into(),
)),
None => Err(length_error(plot, values.name(), row)),
}
}))
}
pub(crate) fn aligned_finite_rows(
data: PlotData<'_, '_>,
x_column: &str,
y_column: &str,
plot: &str,
) -> Result<Vec<(usize, f64, f64)>, Error> {
let x = optional_finite_f64(data, x_column, plot)?;
let y = optional_finite_f64(data, y_column, plot)?;
if x.len() != y.len() {
return Err(Error::Data(
format!(
"{plot}: aligned value length mismatch {} vs {}",
x.len(),
y.len()
)
.into(),
));
}
let mut rows = Vec::new();
crate::data::source::reserve_source(&mut rows, x.len())?;
rows.extend(
x.into_iter()
.zip(y)
.enumerate()
.filter_map(|(row, (x, y))| Some((row, x?, y?))),
);
Ok(rows)
}
fn optional_finite_f64(
data: PlotData<'_, '_>,
column: &str,
plot: &str,
) -> Result<Vec<Option<f64>>, Error> {
let DataColumn::Numeric(values) = data.column(column)? else {
return Err(Error::Data(
format!(
"{plot}: value {:?} must be numeric",
data.column(column)?.name()
)
.into(),
));
};
crate::data::source::collect_source((0..data.height()).map(|row| {
match values.get(data.row_index(row)) {
Some(Some(value)) if value.is_infinite() => Err(Error::Data(
format!(
"{plot}: value {:?} contains infinite value {value} at source row {}",
values.name(),
data.source_row(row)
)
.into(),
)),
Some(Some(value)) if value.is_nan() => Ok(None),
Some(value) => Ok(value),
None => Err(length_error(plot, values.name(), row)),
}
}))
}
#[derive(Debug)]
pub(crate) struct CollectiveChannels {
pub(crate) groups: Option<Vec<String>>,
pub(crate) hues: Option<Vec<String>>,
pub(crate) group_levels: Vec<String>,
pub(crate) hue_levels: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct CollectivePair {
pub(crate) group: Option<String>,
pub(crate) hue: Option<String>,
}
impl CollectivePair {
pub(crate) fn description(&self, collapsed: bool) -> String {
match (&self.group, &self.hue, collapsed) {
(Some(group), _, true) | (Some(group), None, false) => {
format!("graphical group {group:?}")
}
(Some(group), Some(hue), false) => {
format!("graphical group {group:?} with hue {hue:?}")
}
(None, Some(hue), _) => format!("hue {hue:?}"),
(None, None, _) => "ungrouped series".to_string(),
}
}
}
#[derive(Debug)]
pub(crate) struct ObservedCollectives {
pub(crate) rows: Vec<CollectivePair>,
pub(crate) identities: Vec<CollectivePair>,
pub(crate) group_levels: Vec<String>,
pub(crate) hue_levels: Vec<String>,
pub(crate) collapsed: bool,
}
pub(crate) fn observed_collectives(
data: PlotData<'_, '_>,
group_column: Option<&str>,
hue_column: Option<&str>,
retained_rows: Option<&[usize]>,
plot: &str,
) -> Result<ObservedCollectives, Error> {
let mut row_indices = Vec::new();
crate::data::source::reserve_source(
&mut row_indices,
retained_rows.map_or(data.height(), <[usize]>::len),
)?;
if let Some(rows) = retained_rows {
row_indices.extend_from_slice(rows);
} else {
row_indices.extend(0..data.height());
}
let groups = group_column
.map(|column| strict_strings_for_rows(data, column, &row_indices, plot))
.transpose()?;
let hues = hue_column
.map(|column| strict_strings_for_rows(data, column, &row_indices, plot))
.transpose()?;
finish_observed_collectives(
groups,
hues,
data.source,
row_indices.len(),
|index| data.source_row(row_indices[index]),
plot,
)
}
#[expect(
clippy::needless_pass_by_value,
reason = "the decoded source arrays belong to this reduction and are not retained by its callers"
)]
fn finish_observed_collectives(
groups: Option<Vec<String>>,
hues: Option<Vec<String>>,
source: &crate::builder::PlotDescription,
row_count: usize,
diagnostic_row: impl Fn(usize) -> usize,
plot: &str,
) -> Result<ObservedCollectives, Error> {
let collapsed = source.same_group_hue_field();
if collapsed {
let group = source.legend_group_values().expect("actual group field");
let hue = source.legend_hue_values().expect("actual hue field");
let (Some(groups), Some(hues)) = (groups.as_ref(), hues.as_ref()) else {
return Err(Error::Data(
format!(
"{plot}: equal graphical group and hue names require both categorical channels"
)
.into(),
));
};
if let Some(index) = groups
.iter()
.zip(hues)
.position(|(group_level, hue_level)| !group.same_level_key(group_level, hue, hue_level))
{
return Err(Error::Data(format!(
"{plot}: graphical group and hue share semantic name {:?} but differ at source row {}",
group.original_name(),
diagnostic_row(index)
).into()));
}
}
let rows = crate::data::source::collect_source((0..row_count).map(|index| {
Ok(CollectivePair {
group: groups
.as_ref()
.map(|values| crate::data::source::copy_source_string(&values[index]))
.transpose()?,
hue: hues
.as_ref()
.map(|values| crate::data::source::copy_source_string(&values[index]))
.transpose()?,
})
}))?;
let group_levels = groups.as_ref().map_or_else(
|| Ok(Vec::new()),
|values| crate::data::source::source_levels(values),
)?;
let hue_levels = hues.as_ref().map_or_else(
|| Ok(Vec::new()),
|values| crate::data::source::source_levels(values),
)?;
let mut identities = Vec::new();
crate::data::source::reserve_source(&mut identities, rows.len())?;
if groups.is_some() {
for group in &group_levels {
for identity in &rows {
if identity.group.as_ref() != Some(group) {
continue;
}
if crate::data::source::source_position(&identities, |seen| seen == identity)
.is_none()
{
identities.push(crate::data::source::copy_source_pair(identity)?);
}
}
}
} else {
for identity in &rows {
if crate::data::source::source_position(&identities, |seen| seen == identity).is_none()
{
identities.push(crate::data::source::copy_source_pair(identity)?);
}
}
}
Ok(ObservedCollectives {
rows,
identities,
group_levels,
hue_levels,
collapsed,
})
}
fn strict_strings_for_rows(
data: PlotData<'_, '_>,
column: &str,
rows: &[usize],
plot: &str,
) -> Result<Vec<String>, Error> {
let DataColumn::Category(values) = data.column(column)? else {
return Err(Error::Data(
format!(
"{plot}: value {:?} must be categorical",
data.column(column)?.name()
)
.into(),
));
};
crate::data::source::collect_source(rows.iter().map(|row| {
match values.get(data.row_index(*row)) {
Some(Some(value)) => crate::data::source::copy_source_string(value),
Some(None) => Err(Error::Data(
format!(
"{plot}: value {:?} contains null at source row {}",
values.name(),
data.source_row(*row)
)
.into(),
)),
None => Err(length_error(plot, values.name(), *row)),
}
}))
}
pub(crate) fn collective_channels(
data: PlotData<'_, '_>,
group_column: Option<&str>,
hue_column: Option<&str>,
cells: Option<&[String]>,
plot: &str,
) -> Result<CollectiveChannels, Error> {
let groups = group_column
.map(|column| strict_strings(data, column, plot))
.transpose()?;
let hues = hue_column
.map(|column| strict_strings(data, column, plot))
.transpose()?;
let row_count = data.height();
finish_collective_channels(
groups,
hues,
cells,
row_count,
|row| data.source_row(row),
plot,
)
}
pub(crate) fn finish_collective_channels(
groups: Option<Vec<String>>,
hues: Option<Vec<String>>,
cells: Option<&[String]>,
row_count: usize,
diagnostic_row: impl Fn(usize) -> usize,
plot: &str,
) -> Result<CollectiveChannels, Error> {
if groups
.as_ref()
.is_some_and(|values| values.len() != row_count)
|| hues
.as_ref()
.is_some_and(|values| values.len() != row_count)
|| cells.is_some_and(|values| values.len() != row_count)
{
return Err(Error::Data(
format!(
"{plot}: graphical group, hue, and mark-cell values must align with the plot input"
)
.into(),
));
}
if let Some(hues_ref) = hues.as_ref() {
let mut marks: Vec<(Option<&str>, Option<&str>, &str)> = Vec::new();
crate::data::source::reserve_source(&mut marks, row_count)?;
for row in 0..row_count {
let cell = cells.map(|values| values[row].as_str());
let group = groups.as_ref().map(|values| values[row].as_str());
let hue = hues_ref[row].as_str();
if let Some(index) =
crate::data::source::source_position(&marks, |(seen_cell, seen_group, _)| {
*seen_cell == cell && *seen_group == group
})
{
let (_, _, seen_hue) = &marks[index];
if *seen_hue != hue {
return Err(Error::Data(format!(
"{plot}: each collective mark must have exactly one hue; found {seen_hue:?} and {hue:?} at source row {}",
diagnostic_row(row)
).into()));
}
} else {
marks.push((cell, group, hue));
}
}
}
Ok(CollectiveChannels {
group_levels: groups.as_ref().map_or_else(
|| Ok(Vec::new()),
|values| crate::data::source::source_levels(values),
)?,
hue_levels: hues.as_ref().map_or_else(
|| Ok(Vec::new()),
|values| crate::data::source::source_levels(values),
)?,
groups,
hues,
})
}
pub(crate) fn source_collective_channels(
source: &crate::builder::PlotDescription,
cells: Option<&[String]>,
context: &str,
) -> Result<CollectiveChannels, Error> {
let strings = |key: &str| {
let column = source
.data_column(key)
.ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))?;
let DataColumn::Category(values) = column else {
return Err(Error::Data(
format!("{context}: value {:?} must be categorical", column.name()).into(),
));
};
strict_source_strings(values, None, context)
};
let groups = source.group_col().map(strings).transpose()?;
let hues = source.hue_col().map(strings).transpose()?;
finish_collective_channels(groups, hues, cells, source.row_count(), |row| row, context)
}
pub(crate) fn observed_source_collectives(
source: &crate::builder::PlotDescription,
context: &str,
) -> Result<ObservedCollectives, Error> {
let rows = source.source_row_map();
let mut row_indices = Vec::new();
self::source::reserve_source(&mut row_indices, source.row_count())?;
row_indices.extend(0..source.row_count());
let strings = |key: &str| {
let column = source
.data_column(key)
.ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))?;
let DataColumn::Category(values) = column else {
return Err(Error::Data(
format!("{context}: value {:?} must be categorical", column.name()).into(),
));
};
strict_source_strings(values, rows, context)
};
let groups = source.group_col().map(strings).transpose()?;
let hues = source.hue_col().map(strings).transpose()?;
finish_observed_collectives(
groups,
hues,
source,
row_indices.len(),
|slot| {
let slot = row_indices[slot];
rows.and_then(|rows| rows.as_slice().get(slot))
.copied()
.unwrap_or(slot)
},
context,
)
}
pub(crate) fn stable_levels(values: &[String]) -> Vec<String> {
let mut levels = Vec::new();
for value in values {
if !levels.contains(value) {
levels.push(value.clone());
}
}
levels
}
pub(crate) fn explicit_category_order(
observed: &[String],
requested: &[String],
context: &str,
allow_unobserved: bool,
) -> Result<Vec<String>, Error> {
let mut seen = Vec::new();
crate::data::source::reserve_source(&mut seen, requested.len())?;
for level in requested {
if seen.contains(level) {
return Err(Error::Data(
format!("{context}: explicit category order contains duplicate level {level:?}")
.into(),
));
}
if !allow_unobserved && !observed.contains(level) {
return Err(Error::Data(
format!("{context}: explicit category order contains unknown level {level:?}")
.into(),
));
}
seen.push(crate::data::source::copy_source_string(level)?);
}
for level in observed {
if !seen.contains(level) {
return Err(Error::Data(
format!("{context}: explicit category order omits observed level {level:?}").into(),
));
}
}
if allow_unobserved {
seen.retain(|level| observed.contains(level));
}
Ok(seen)
}
pub(crate) fn strict_strings(
data: PlotData<'_, '_>,
column: &str,
plot: &str,
) -> Result<Vec<String>, Error> {
let DataColumn::Category(values) = data.column(column)? else {
return Err(Error::Data(
format!(
"{plot}: value {:?} must be categorical",
data.column(column)?.name()
)
.into(),
));
};
crate::data::source::collect_source((0..data.height()).map(|row| {
match values.get(data.row_index(row)) {
Some(Some(value)) => crate::data::source::copy_source_string(value),
Some(None) => {
use crate::errors::{Diagnostic, DiagnosticKind};
let binding = values
.field_key()
.cloned()
.unwrap_or_else(|| RawKey::from(values.name()));
Err(Error::Data(
Diagnostic::new(
DiagnosticKind::InvalidValue {
value: None,
constraint: "present category".to_owned(),
},
format!(
"{plot}: value {:?} contains null at source row {}",
values.name(),
data.source_row(row)
),
)
.with_context(data.member_context(row, binding, column)),
))
}
None => Err(length_error(plot, values.name(), row)),
}
}))
}
pub(crate) fn strict_normalized_strings(
data: PlotData<'_, '_>,
column: &str,
plot: &str,
role: &str,
) -> Result<Vec<String>, Error> {
crate::data::source::collect_source(
strict_strings(data, column, plot)?
.into_iter()
.enumerate()
.map(|(row, value)| {
let normalized = crate::data::source::normalize_source_string(&value)?;
if normalized.is_empty() {
Err(Error::Data(
format!(
"{plot}: {role} label is empty after whitespace normalization at source row {}",
data.source_row(row)
)
.into(),
))
} else {
Ok(normalized)
}
}),
)
}
pub(crate) fn collapse_whitespace(value: &str) -> String {
value.split_whitespace().collect::<Vec<_>>().join(" ")
}
pub(crate) fn min_max(
values: impl IntoIterator<Item = f64>,
plot: &str,
) -> Result<(f64, f64), Error> {
let mut range: Option<(f64, f64)> = None;
for value in values {
if !value.is_finite() {
return Err(Error::Data(
format!("{plot}: cannot compute range from non-finite value {value}").into(),
));
}
range = Some(range.map_or((value, value), |(lo, hi)| (lo.min(value), hi.max(value))));
}
range.ok_or_else(|| Error::Data(format!("{plot}: cannot compute range from no values").into()))
}
fn length_error(plot: &str, name: &str, row: usize) -> Error {
Error::Data(
format!("{plot}: value {name:?} is shorter than the aligned plot input at row {row}")
.into(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn typed_source_reads_keep_full_read_precedence_and_diagnostic_rows() {
let values = CategoryValues::nullable("category", [Some(" "), None]).unwrap();
let rows = crate::data::SourceRows::new([70, 901]).unwrap();
let error = strict_source_normalized_strings(&values, Some(&rows), "source", "category")
.unwrap_err();
assert_eq!(
error.to_string(),
"data error: source: value \"category\" contains null at source row 901"
);
let values = CategoryValues::new("category", [" ", "valid"]).unwrap();
let error = strict_source_normalized_strings(&values, Some(&rows), "source", "category")
.unwrap_err();
assert_eq!(error.to_string(), "data error: source: category label is empty after whitespace normalization at source row 70");
let numbers = NumericValues::new("value", [3.0, f64::INFINITY]);
assert_eq!(
strict_numeric_at(&numbers, 0, 901, "source")
.unwrap()
.to_bits(),
3.0_f64.to_bits()
);
assert_eq!(
strict_source_f64(&numbers, Some(&rows), "source")
.unwrap_err()
.to_string(),
"data error: source: value \"value\" contains non-finite value inf at source row 901"
);
}
}