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)]
61pub struct SignificanceBinding {
62    targets: Targets,
63    marks: SignificanceMarkInput,
64    facets: SignificanceFacetInput,
65    count: usize,
66    pub(crate) direct_sources: [Option<crate::data::DataSourceInfo>; 4],
67}
68
69impl PartialEq for SignificanceBinding {
70    fn eq(&self, other: &Self) -> bool {
71        self.targets == other.targets && self.marks == other.marks && self.facets == other.facets
72    }
73}
74
75#[derive(Debug, Clone, PartialEq)]
76#[expect(
77    clippy::large_enum_variant,
78    reason = "one owning batch has one or two original endpoint declarations"
79)]
80enum Targets {
81    Attached(SignificanceTargetInput),
82    Pairwise(SignificanceTargetInput, SignificanceTargetInput),
83}
84
85impl SignificanceBinding {
86    fn new(
87        targets: Targets,
88        marks: SignificanceMarkInput,
89        facets: SignificanceFacetInput,
90        count: usize,
91    ) -> Self {
92        let direct_target = |target: &SignificanceTargetInput| match target {
93            SignificanceTargetInput::Values(values) => {
94                Some(crate::data::DataSourceInfo::direct(vec![values.len()]))
95            }
96            _ => None,
97        };
98        let (left, right) = match &targets {
99            Targets::Attached(target) => (direct_target(target), None),
100            Targets::Pairwise(left, right) => (direct_target(left), direct_target(right)),
101        };
102        let marks_source = if let SignificanceMarkInput::Values(values) = &marks {
103            Some(crate::data::DataSourceInfo::direct(vec![values.len()]))
104        } else {
105            None
106        };
107        let facet_source = if let SignificanceFacetInput::Values(values) = &facets {
108            Some(crate::data::DataSourceInfo::direct(vec![values.len()]))
109        } else {
110            None
111        };
112        Self {
113            targets,
114            marks,
115            facets,
116            count,
117            direct_sources: [left, right, marks_source, facet_source],
118        }
119    }
120
121    pub(crate) fn row_count(&self) -> usize {
122        self.count
123    }
124
125    /// Original target input of an attached result batch.
126    pub fn get_attached(&self) -> Option<&SignificanceTargetInput> {
127        match &self.targets {
128            Targets::Attached(target) => Some(target),
129            Targets::Pairwise(..) => None,
130        }
131    }
132
133    /// Original endpoints of a pairwise result batch.
134    pub fn get_pairwise(&self) -> Option<(&SignificanceTargetInput, &SignificanceTargetInput)> {
135        match &self.targets {
136            Targets::Pairwise(left, right) => Some((left, right)),
137            Targets::Attached(_) => None,
138        }
139    }
140
141    /// Complete original mark declaration.
142    pub fn marks(&self) -> &SignificanceMarkInput {
143        &self.marks
144    }
145
146    /// Complete original result scope.
147    pub fn facets(&self) -> &SignificanceFacetInput {
148        &self.facets
149    }
150}
151
152#[derive(Debug, Clone, PartialEq)]
153/// Opaque original row relationship of a supplied result annotation.
154#[doc(hidden)]
155pub struct SignificanceOrigin {
156    pub(crate) binding: Arc<SignificanceBinding>,
157    pub(crate) row: usize,
158    pub(crate) facet_overridden: bool,
159}
160
161struct Sequence<T> {
162    values: Vec<T>,
163    scalar: bool,
164}
165
166impl<T: Clone> Sequence<T> {
167    fn fixed(value: &T) -> Self {
168        Self {
169            values: vec![value.clone()],
170            scalar: true,
171        }
172    }
173    fn many(values: Vec<T>) -> Self {
174        Self {
175            values,
176            scalar: false,
177        }
178    }
179    fn shape(&self) -> (usize, bool) {
180        (self.values.len(), self.scalar)
181    }
182    fn at(&self, row: usize) -> T {
183        self.values[if self.scalar { 0 } else { row }].clone()
184    }
185}
186
187fn length(role: &str, expected: usize, actual: usize) -> Result<()> {
188    if expected == actual {
189        Ok(())
190    } else {
191        Err(Error::Data(
192            format!("{role}: expected {expected} result slots, got {actual}").into(),
193        ))
194    }
195}
196
197fn categories(values: &CategoryValues, role: &str) -> Result<Vec<String>> {
198    crate::data::source::collect_source(values.iter().enumerate().map(|(slot, value)| {
199        let value = value.ok_or_else(|| {
200            Error::Data(format!("{role}: missing category at slot {slot}").into())
201        })?;
202        crate::data::source::copy_source_string(value)
203    }))
204}
205
206impl SignificanceTargetInput {
207    fn decode(&self) -> Result<Sequence<SignificanceTarget>> {
208        Ok(match self {
209            Self::Column(values) => Sequence::many(
210                raw_keys(values, "significance target")?
211                    .into_iter()
212                    .map(SignificanceTarget::category)
213                    .collect(),
214            ),
215            Self::CategorySeries(category, series) => {
216                let category = raw_keys(category, "significance category")?;
217                let series = raw_keys(series, "significance series")?;
218                length("significance series", category.len(), series.len())?;
219                Sequence::many(
220                    category
221                        .into_iter()
222                        .zip(series)
223                        .map(|(category, series)| {
224                            SignificanceTarget::category_series(category, series)
225                        })
226                        .collect(),
227                )
228            }
229            Self::Fixed(target) => Sequence::fixed(target),
230            Self::Values(values) => Sequence::many(values.to_vec()),
231        })
232    }
233}
234
235impl SignificanceMarkInput {
236    fn original(self) -> Result<Self> {
237        match self {
238            Self::Categories { values, mapping } => {
239                let KeyValues::Strings(values) = values.key_values() else {
240                    return Err(Error::Data(
241                        "significance mark mapping requires string category keys".into(),
242                    ));
243                };
244                Ok(Self::Categories { values, mapping })
245            }
246            input => Ok(input),
247        }
248    }
249
250    fn decode(&self) -> Result<Sequence<SignificanceMark>> {
251        Ok(match self {
252            Self::PValues(values) => Sequence::many(crate::data::source::collect_source(
253                values.iter().enumerate().map(|(slot, value)| {
254                    value.map(SignificanceMark::PValue).ok_or_else(|| {
255                        Error::Data(
256                            format!("significance p-values: missing value at slot {slot}").into(),
257                        )
258                    })
259                }),
260            )?),
261            Self::Categories { values, mapping } => {
262                let values = categories(values, "significance marks")?;
263                Sequence::many(crate::data::source::collect_source(values.iter().map(
264                    |value| {
265                        let mut matches = mapping.iter().filter(|(key, _)| key == value);
266                        let mark = matches
267                            .next()
268                            .ok_or_else(|| {
269                                Error::Data(
270                                    format!("significance marks: unmapped key {value:?}").into(),
271                                )
272                            })?
273                            .1;
274                        if matches.next().is_some() {
275                            return Err(Error::Data(
276                                format!("significance marks: duplicate map key {value:?}").into(),
277                            ));
278                        }
279                        Ok(mark)
280                    },
281                ))?)
282            }
283            Self::Fixed(mark) => Sequence::fixed(mark),
284            Self::Values(values) => Sequence::many(values.to_vec()),
285        })
286    }
287}
288
289fn raw_keys(values: &KeyValues, role: &str) -> Result<Vec<RawKey>> {
290    crate::data::source::collect_source((0..values.len()).map(|slot| {
291        let key = match values {
292            KeyValues::Strings(values) => values.get(slot).flatten().map(RawKey::from),
293            KeyValues::Raw(values) => values.get(slot).flatten().cloned(),
294        };
295        key.ok_or_else(|| Error::Data(format!("{role}: missing category at slot {slot}").into()))
296    }))
297}
298
299impl SignificanceFacetInput {
300    fn decode(&self) -> Result<Option<Sequence<FacetCell>>> {
301        Ok(Some(match self {
302            Self::Unfaceted => return Ok(None),
303            Self::Fixed(facet) => Sequence::fixed(facet),
304            Self::Values(facets) => Sequence::many(facets.to_vec()),
305            Self::Split(FacetBinding::Wrap(values)) => Sequence::many(
306                raw_keys(values, "significance facet")?
307                    .into_iter()
308                    .map(FacetCell::single)
309                    .collect(),
310            ),
311            Self::Split(FacetBinding::Grid { row, column }) => {
312                let row = raw_keys(row, "significance facet row")?;
313                let column = raw_keys(column, "significance facet column")?;
314                length("significance facet column", row.len(), column.len())?;
315                Sequence::many(
316                    row.into_iter()
317                        .zip(column)
318                        .map(|(row, column)| FacetCell::grid(row, column))
319                        .collect(),
320                )
321            }
322        }))
323    }
324}
325
326fn count(parts: &[(usize, bool)], facets: Option<&Sequence<FacetCell>>) -> Result<usize> {
327    let mut shapes = parts.to_vec();
328    shapes.extend(facets.map(Sequence::shape));
329    let count = shapes
330        .iter()
331        .find(|(_, scalar)| !scalar)
332        .map_or(1, |(length, _)| *length);
333    for (length_value, scalar) in shapes {
334        if !scalar {
335            length("significance", count, length_value)?;
336        }
337    }
338    Ok(count)
339}
340
341/// Bind one actual attached result batch, retaining its original declaration.
342pub fn significance_attached(
343    target: SignificanceTargetInput,
344    marks: SignificanceMarkInput,
345    facets: SignificanceFacetInput,
346) -> Result<Vec<Significance<Attached>>> {
347    // Facet inputs are admitted before endpoint and mark values, as in the original producers.
348    let decoded_facets = facets.decode()?;
349    let decoded_target = target.decode()?;
350    let marks = marks.original()?;
351    let decoded_marks = marks.decode()?;
352    let count = count(
353        &[decoded_target.shape(), decoded_marks.shape()],
354        decoded_facets.as_ref(),
355    )?;
356    let binding = Arc::new(SignificanceBinding::new(
357        Targets::Attached(target),
358        marks,
359        facets,
360        count,
361    ));
362    crate::data::source::collect_source((0..count).map(|row| {
363        let mut value = Significance::at(decoded_target.at(row), decoded_marks.at(row));
364        if let Some(facets) = &decoded_facets {
365            value = value.facet(facets.at(row));
366        }
367        Ok(value.with_origin(binding.clone(), row))
368    }))
369}
370
371/// Bind one actual pairwise result batch, retaining its original declaration.
372pub fn significance_pairwise(
373    left: SignificanceTargetInput,
374    right: SignificanceTargetInput,
375    marks: SignificanceMarkInput,
376    facets: SignificanceFacetInput,
377) -> Result<Vec<Significance<Pairwise>>> {
378    let decoded_facets = facets.decode()?;
379    let decoded_left = left.decode()?;
380    let decoded_right = right.decode()?;
381    let marks = marks.original()?;
382    let decoded_marks = marks.decode()?;
383    let count = count(
384        &[
385            decoded_left.shape(),
386            decoded_right.shape(),
387            decoded_marks.shape(),
388        ],
389        decoded_facets.as_ref(),
390    )?;
391    let binding = Arc::new(SignificanceBinding::new(
392        Targets::Pairwise(left, right),
393        marks,
394        facets,
395        count,
396    ));
397    crate::data::source::collect_source((0..count).map(|row| {
398        let mut value = Significance::between(
399            decoded_left.at(row),
400            decoded_right.at(row),
401            decoded_marks.at(row),
402        );
403        if let Some(facets) = &decoded_facets {
404            value = value.facet(facets.at(row));
405        }
406        Ok(value.with_origin(binding.clone(), row))
407    }))
408}