Skip to main content

lichtung_plot/significance/
binding.rs

1//! Original caller-supplied significance batches.
2
3use std::sync::Arc;
4
5use super::{Attached, FacetCell, Pairwise, Significance, SignificanceMark, SignificanceTarget};
6use crate::{
7    data::{KeyValues, RawKey},
8    layout::FacetBinding,
9    CategoryValues, Error, NumericValues, Result,
10};
11
12/// Original target declaration, before scalar broadcast or paired-target construction.
13#[derive(Debug, Clone, PartialEq)]
14#[non_exhaustive]
15pub enum SignificanceTargetInput {
16    /// A category variable.
17    Column(KeyValues),
18    /// Aligned categories and positioned series.
19    CategorySeries(KeyValues, KeyValues),
20    /// One explicitly broadcast target.
21    Fixed(SignificanceTarget),
22    /// Explicit native targets in supplied order.
23    Values(Arc<[SignificanceTarget]>),
24}
25
26/// Original supplied result marks and any explicit category mapping.
27#[derive(Debug, Clone, PartialEq)]
28#[non_exhaustive]
29pub enum SignificanceMarkInput {
30    /// A supplied display p-value variable.
31    PValues(NumericValues),
32    /// Original categories and the complete ordered authored mapping.
33    Categories {
34        /// Original category variable.
35        values: CategoryValues,
36        /// Complete original mapping, including unused declarations.
37        mapping: Arc<[(String, SignificanceMark)]>,
38    },
39    /// One explicitly broadcast mark.
40    Fixed(SignificanceMark),
41    /// Explicit native marks in supplied order.
42    Values(Arc<[SignificanceMark]>),
43}
44
45/// The actual facet selection and its original relation to result rows.
46#[derive(Debug, Clone, PartialEq)]
47#[non_exhaustive]
48pub enum SignificanceFacetInput {
49    /// No facet restriction.
50    Unfaceted,
51    /// One explicitly broadcast facet address.
52    Fixed(FacetCell),
53    /// A native sequence of facet addresses.
54    Values(Arc<[FacetCell]>),
55    /// Actual per-result source variables selecting the facets.
56    Split(FacetBinding),
57}
58
59/// An owning batch declaration, shared by its actual generated annotations.
60#[derive(Debug, Clone, PartialEq)]
61pub struct SignificanceBinding {
62    targets: Targets,
63    marks: SignificanceMarkInput,
64    facets: SignificanceFacetInput,
65}
66
67#[derive(Debug, Clone, PartialEq)]
68#[expect(
69    clippy::large_enum_variant,
70    reason = "one owning batch has one or two original endpoint declarations"
71)]
72enum Targets {
73    Attached(SignificanceTargetInput),
74    Pairwise(SignificanceTargetInput, SignificanceTargetInput),
75}
76
77impl SignificanceBinding {
78    /// Original target input of an attached result batch.
79    pub fn get_attached(&self) -> Option<&SignificanceTargetInput> {
80        match &self.targets {
81            Targets::Attached(target) => Some(target),
82            Targets::Pairwise(..) => None,
83        }
84    }
85
86    /// Original endpoints of a pairwise result batch.
87    pub fn get_pairwise(&self) -> Option<(&SignificanceTargetInput, &SignificanceTargetInput)> {
88        match &self.targets {
89            Targets::Pairwise(left, right) => Some((left, right)),
90            Targets::Attached(_) => None,
91        }
92    }
93
94    /// Complete original mark declaration.
95    pub fn marks(&self) -> &SignificanceMarkInput {
96        &self.marks
97    }
98
99    /// Complete original result scope.
100    pub fn facets(&self) -> &SignificanceFacetInput {
101        &self.facets
102    }
103}
104
105#[derive(Debug, Clone, PartialEq)]
106/// Opaque original row relationship of a supplied result annotation.
107#[doc(hidden)]
108pub struct SignificanceOrigin {
109    pub(crate) binding: Arc<SignificanceBinding>,
110    pub(crate) row: usize,
111    pub(crate) facet_overridden: bool,
112}
113
114struct Sequence<T> {
115    values: Vec<T>,
116    scalar: bool,
117}
118
119impl<T: Clone> Sequence<T> {
120    fn fixed(value: &T) -> Self {
121        Self {
122            values: vec![value.clone()],
123            scalar: true,
124        }
125    }
126    fn many(values: Vec<T>) -> Self {
127        Self {
128            values,
129            scalar: false,
130        }
131    }
132    fn shape(&self) -> (usize, bool) {
133        (self.values.len(), self.scalar)
134    }
135    fn at(&self, row: usize) -> T {
136        self.values[if self.scalar { 0 } else { row }].clone()
137    }
138}
139
140fn length(role: &str, expected: usize, actual: usize) -> Result<()> {
141    if expected == actual {
142        Ok(())
143    } else {
144        Err(Error::Data(
145            format!("{role}: expected {expected} result slots, got {actual}").into(),
146        ))
147    }
148}
149
150fn categories(values: &CategoryValues, role: &str) -> Result<Vec<String>> {
151    crate::data::source::collect_source(values.iter().enumerate().map(|(slot, value)| {
152        let value = value.ok_or_else(|| {
153            Error::Data(format!("{role}: missing category at slot {slot}").into())
154        })?;
155        crate::data::source::copy_source_string(value)
156    }))
157}
158
159impl SignificanceTargetInput {
160    fn decode(&self) -> Result<Sequence<SignificanceTarget>> {
161        Ok(match self {
162            Self::Column(values) => Sequence::many(
163                raw_keys(values, "significance target")?
164                    .into_iter()
165                    .map(SignificanceTarget::category)
166                    .collect(),
167            ),
168            Self::CategorySeries(category, series) => {
169                let category = raw_keys(category, "significance category")?;
170                let series = raw_keys(series, "significance series")?;
171                length("significance series", category.len(), series.len())?;
172                Sequence::many(
173                    category
174                        .into_iter()
175                        .zip(series)
176                        .map(|(category, series)| {
177                            SignificanceTarget::category_series(category, series)
178                        })
179                        .collect(),
180                )
181            }
182            Self::Fixed(target) => Sequence::fixed(target),
183            Self::Values(values) => Sequence::many(values.to_vec()),
184        })
185    }
186}
187
188impl SignificanceMarkInput {
189    fn original(self) -> Result<Self> {
190        match self {
191            Self::Categories { values, mapping } => {
192                let KeyValues::Strings(values) = values.key_values() else {
193                    return Err(Error::Data(
194                        "significance mark mapping requires string category keys".into(),
195                    ));
196                };
197                Ok(Self::Categories { values, mapping })
198            }
199            input => Ok(input),
200        }
201    }
202
203    fn decode(&self) -> Result<Sequence<SignificanceMark>> {
204        Ok(match self {
205            Self::PValues(values) => Sequence::many(crate::data::source::collect_source(
206                values.iter().enumerate().map(|(slot, value)| {
207                    value.map(SignificanceMark::PValue).ok_or_else(|| {
208                        Error::Data(
209                            format!("significance p-values: missing value at slot {slot}").into(),
210                        )
211                    })
212                }),
213            )?),
214            Self::Categories { values, mapping } => {
215                let values = categories(values, "significance marks")?;
216                Sequence::many(crate::data::source::collect_source(values.iter().map(
217                    |value| {
218                        let mut matches = mapping.iter().filter(|(key, _)| key == value);
219                        let mark = matches
220                            .next()
221                            .ok_or_else(|| {
222                                Error::Data(
223                                    format!("significance marks: unmapped key {value:?}").into(),
224                                )
225                            })?
226                            .1;
227                        if matches.next().is_some() {
228                            return Err(Error::Data(
229                                format!("significance marks: duplicate map key {value:?}").into(),
230                            ));
231                        }
232                        Ok(mark)
233                    },
234                ))?)
235            }
236            Self::Fixed(mark) => Sequence::fixed(mark),
237            Self::Values(values) => Sequence::many(values.to_vec()),
238        })
239    }
240}
241
242fn raw_keys(values: &KeyValues, role: &str) -> Result<Vec<RawKey>> {
243    crate::data::source::collect_source((0..values.len()).map(|slot| {
244        let key = match values {
245            KeyValues::Strings(values) => values.get(slot).flatten().map(RawKey::from),
246            KeyValues::Raw(values) => values.get(slot).flatten().cloned(),
247        };
248        key.ok_or_else(|| Error::Data(format!("{role}: missing category at slot {slot}").into()))
249    }))
250}
251
252impl SignificanceFacetInput {
253    fn decode(&self) -> Result<Option<Sequence<FacetCell>>> {
254        Ok(Some(match self {
255            Self::Unfaceted => return Ok(None),
256            Self::Fixed(facet) => Sequence::fixed(facet),
257            Self::Values(facets) => Sequence::many(facets.to_vec()),
258            Self::Split(FacetBinding::Wrap(values)) => Sequence::many(
259                raw_keys(values, "significance facet")?
260                    .into_iter()
261                    .map(FacetCell::single)
262                    .collect(),
263            ),
264            Self::Split(FacetBinding::Grid { row, column }) => {
265                let row = raw_keys(row, "significance facet row")?;
266                let column = raw_keys(column, "significance facet column")?;
267                length("significance facet column", row.len(), column.len())?;
268                Sequence::many(
269                    row.into_iter()
270                        .zip(column)
271                        .map(|(row, column)| FacetCell::grid(row, column))
272                        .collect(),
273                )
274            }
275        }))
276    }
277}
278
279fn count(parts: &[(usize, bool)], facets: Option<&Sequence<FacetCell>>) -> Result<usize> {
280    let mut shapes = parts.to_vec();
281    shapes.extend(facets.map(Sequence::shape));
282    let count = shapes
283        .iter()
284        .find(|(_, scalar)| !scalar)
285        .map_or(1, |(length, _)| *length);
286    for (length_value, scalar) in shapes {
287        if !scalar {
288            length("significance", count, length_value)?;
289        }
290    }
291    Ok(count)
292}
293
294/// Bind one actual attached result batch, retaining its original declaration.
295pub fn significance_attached(
296    target: SignificanceTargetInput,
297    marks: SignificanceMarkInput,
298    facets: SignificanceFacetInput,
299) -> Result<Vec<Significance<Attached>>> {
300    // Facet inputs are admitted before endpoint and mark values, as in the original producers.
301    let decoded_facets = facets.decode()?;
302    let decoded_target = target.decode()?;
303    let marks = marks.original()?;
304    let decoded_marks = marks.decode()?;
305    let count = count(
306        &[decoded_target.shape(), decoded_marks.shape()],
307        decoded_facets.as_ref(),
308    )?;
309    let binding = Arc::new(SignificanceBinding {
310        targets: Targets::Attached(target),
311        marks,
312        facets,
313    });
314    crate::data::source::collect_source((0..count).map(|row| {
315        let mut value = Significance::at(decoded_target.at(row), decoded_marks.at(row));
316        if let Some(facets) = &decoded_facets {
317            value = value.facet(facets.at(row));
318        }
319        Ok(value.with_origin(binding.clone(), row))
320    }))
321}
322
323/// Bind one actual pairwise result batch, retaining its original declaration.
324pub fn significance_pairwise(
325    left: SignificanceTargetInput,
326    right: SignificanceTargetInput,
327    marks: SignificanceMarkInput,
328    facets: SignificanceFacetInput,
329) -> Result<Vec<Significance<Pairwise>>> {
330    let decoded_facets = facets.decode()?;
331    let decoded_left = left.decode()?;
332    let decoded_right = right.decode()?;
333    let marks = marks.original()?;
334    let decoded_marks = marks.decode()?;
335    let count = count(
336        &[
337            decoded_left.shape(),
338            decoded_right.shape(),
339            decoded_marks.shape(),
340        ],
341        decoded_facets.as_ref(),
342    )?;
343    let binding = Arc::new(SignificanceBinding {
344        targets: Targets::Pairwise(left, right),
345        marks,
346        facets,
347    });
348    crate::data::source::collect_source((0..count).map(|row| {
349        let mut value = Significance::between(
350            decoded_left.at(row),
351            decoded_right.at(row),
352            decoded_marks.at(row),
353        );
354        if let Some(facets) = &decoded_facets {
355            value = value.facet(facets.at(row));
356        }
357        Ok(value.with_origin(binding.clone(), row))
358    }))
359}