Skip to main content

lichtung_plot/data/
group_key.rs

1//! Exact group keys, independent of display labels and renderer tokens.
2
3use super::RawKey;
4use std::sync::Arc;
5
6/// An ordered key for an actual scientific group.
7///
8/// A tuple used as a single original key remains distinct from a combination
9/// of multiple original group dimensions.
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct GroupKey(Arc<[RawKey]>);
12
13impl GroupKey {
14    /// One complete original key.
15    pub fn single(key: impl Into<RawKey>) -> Self {
16        Self(Arc::from([key.into()]))
17    }
18
19    /// Ordered keys of the actual group dimensions.
20    pub fn tuple(keys: impl IntoIterator<Item = RawKey>) -> Self {
21        Self(keys.into_iter().collect())
22    }
23
24    /// Original key components, in their dimension order.
25    pub fn keys(&self) -> &[RawKey] {
26        &self.0
27    }
28}
29
30/// Resolved original keys for the two actual collective channels.
31pub(crate) struct CollectiveKeys {
32    pub(crate) group: Option<(String, RawKey)>,
33    pub(crate) hue: Option<(String, RawKey)>,
34    collapsed: bool,
35}
36
37impl CollectiveKeys {
38    pub(crate) fn new(
39        chart: &crate::builder::PlotDescription,
40        identity: &super::CollectivePair,
41    ) -> crate::Result<Self> {
42        let resolve = |values: Option<&crate::CategoryValues>, level: Option<&str>| {
43            values
44                .zip(level)
45                .map(|(values, level)| {
46                    Ok::<_, crate::Error>((
47                        super::source::copy_source_string(values.original_name())?,
48                        values.key_for_level(level).ok_or_else(|| {
49                            crate::Error::Render("collective has no original group key".into())
50                        })?,
51                    ))
52                })
53                .transpose()
54        };
55        Ok(Self {
56            group: resolve(chart.legend_group_values(), identity.group.as_deref())?,
57            hue: resolve(chart.legend_hue_values(), identity.hue.as_deref())?,
58            collapsed: chart.same_group_hue_field(),
59        })
60    }
61
62    pub(crate) fn key(&self) -> Option<GroupKey> {
63        let group = self.group.as_ref().map(|(_, key)| key);
64        let hue = self
65            .hue
66            .as_ref()
67            .map(|(_, key)| key)
68            .filter(|_| !self.collapsed || group.is_none());
69        let keys = group.into_iter().chain(hue).cloned().collect::<Vec<_>>();
70        (!keys.is_empty()).then(|| GroupKey::tuple(keys))
71    }
72}
73
74/// Keep real string categories and non-string original keys in their native payloads.
75pub(crate) fn key_column(
76    name: &str,
77    keys: impl Iterator<Item = RawKey>,
78) -> crate::Result<super::DataPayload> {
79    let keys = super::source::collect_source(keys.map(Ok))?;
80    if keys.iter().all(|key| matches!(key, RawKey::String(_))) {
81        let values = crate::CategoryValues::new(
82            name,
83            keys.into_iter().map(|key| {
84                let RawKey::String(value) = key else {
85                    unreachable!("actual string category")
86                };
87                value
88            }),
89        )?;
90        Ok(super::DataPayload::Category(values))
91    } else {
92        Ok(super::DataPayload::RawKeys(super::RawKeyValues::new(
93            name, keys,
94        )?))
95    }
96}
97
98/// Fixed semantic grouping dimensions, independent of author-supplied names.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100#[non_exhaustive]
101pub enum GroupDimension {
102    /// Actual row-facet dimension.
103    FacetRow,
104    /// Actual column-facet dimension.
105    FacetColumn,
106    /// Actual color grouping dimension.
107    Hue,
108    /// Actual graphical grouping dimension.
109    Group,
110    /// Actual positioned series dimension.
111    Series,
112}
113
114impl GroupDimension {
115    /// Canonical binding spelling.
116    #[doc(hidden)]
117    pub const fn name(self) -> &'static str {
118        match self {
119            Self::FacetRow => "facet_row",
120            Self::FacetColumn => "facet_column",
121            Self::Hue => "hue",
122            Self::Group => "group",
123            Self::Series => "series",
124        }
125    }
126}
127
128/// One actual grouping role or complete original variable key.
129#[derive(Debug, Clone, PartialEq, Eq, Hash)]
130pub enum GroupDimensionRef {
131    /// A fixed group role.
132    Role(GroupDimension),
133    /// An original named grouping variable.
134    Named(RawKey),
135}
136
137impl From<GroupDimension> for GroupDimensionRef {
138    fn from(value: GroupDimension) -> Self {
139        Self::Role(value)
140    }
141}
142
143/// Original ordered key columns and complete group keys in one actual domain.
144#[derive(Debug, Clone)]
145pub struct GroupKeys {
146    dimensions: Arc<[GroupDimensionRef]>,
147    columns: Arc<[super::AxisValues]>,
148    keys: Arc<[GroupKey]>,
149}
150
151impl GroupKeys {
152    /// Capture actual aligned group dimensions and their native columns.
153    pub fn new(
154        dimensions: Vec<GroupDimensionRef>,
155        columns: Vec<super::AxisValues>,
156    ) -> crate::Result<Self> {
157        use super::{AxisValues, KeyValues};
158        if dimensions.len() != columns.len() || columns.is_empty() {
159            return Err(crate::Error::Data(
160                "group keys require one actual column per dimension".into(),
161            ));
162        }
163        if dimensions
164            .iter()
165            .enumerate()
166            .any(|(index, dimension)| dimensions[..index].contains(dimension))
167        {
168            return Err(crate::Error::Data(
169                "group dimensions must be distinct".into(),
170            ));
171        }
172        let columns = super::source::collect_source(columns.into_iter().map(|column| {
173            Ok(match column {
174                AxisValues::Category(values) => match values.key_values() {
175                    KeyValues::Strings(values) => AxisValues::Category(values),
176                    KeyValues::Raw(values) => AxisValues::Keys(values),
177                },
178                column => column,
179            })
180        }))?;
181        let length = columns[0].len();
182        if columns.iter().any(|column| column.len() != length) {
183            return Err(crate::Error::Data(
184                "group key columns must have equal lengths".into(),
185            ));
186        }
187        let keys = super::source::collect_source((0..length).map(|row| {
188            let fields = super::source::collect_source(columns.iter().map(|column| {
189                match column {
190                    AxisValues::Numeric(values) => values.get(row).flatten().map(RawKey::Float),
191                    AxisValues::Category(values) => values.get(row).flatten().map(RawKey::from),
192                    AxisValues::Keys(values) => values.get(row).flatten().cloned(),
193                }
194                .ok_or_else(|| {
195                    crate::Error::Data(
196                        format!(
197                            "group key column {:?} is missing at row {row}",
198                            column.name()
199                        )
200                        .into(),
201                    )
202                })
203            }))?;
204            Ok(GroupKey::tuple(fields))
205        }))?;
206        Ok(Self {
207            dimensions: dimensions.into(),
208            columns: columns.into(),
209            keys: keys.into(),
210        })
211    }
212
213    /// Actual ordered grouping dimensions.
214    pub fn dimensions(&self) -> &[GroupDimensionRef] {
215        &self.dimensions
216    }
217    /// Original key columns in dimension order.
218    pub fn columns(&self) -> &[super::AxisValues] {
219        &self.columns
220    }
221    /// Complete group keys in the actual domain order.
222    pub fn keys(&self) -> &[GroupKey] {
223        &self.keys
224    }
225    /// Number of actual group rows.
226    pub fn len(&self) -> usize {
227        self.keys.len()
228    }
229    /// Whether the domain has no rows.
230    pub fn is_empty(&self) -> bool {
231        self.keys.is_empty()
232    }
233    /// Read a complete group key by its original logical slot.
234    pub fn get(&self, index: usize) -> Option<&GroupKey> {
235        self.keys.get(index)
236    }
237
238    pub(crate) fn components(&self) -> crate::Result<Vec<super::DataComponentInfo>> {
239        super::source::collect_source(self.columns.iter().enumerate().map(|(index, column)| {
240            super::DataComponentInfo::captured_at(
241                vec![
242                    "groups".into(),
243                    "columns".into(),
244                    super::ComponentPathPart::Index(index),
245                ],
246                &super::DataPayload::Axis(column.clone()),
247            )
248        }))
249    }
250
251    pub(crate) fn member_keys(&self) -> crate::Result<super::RawKeyValues> {
252        super::RawKeyValues::new(
253            "group",
254            self.keys.iter().map(|key| match key.keys() {
255                [key] => key.clone(),
256                keys => RawKey::Tuple(keys.to_vec()),
257            }),
258        )
259    }
260}