Skip to main content

lichtung_plot/significance/
spec.rs

1//! Public significance display values.
2
3use super::{binding::SignificanceOrigin, SignificanceBinding, SignificanceFacetInput};
4use std::{marker::PhantomData, sync::Arc};
5
6use crate::{data::RawKey, Error};
7
8/// Exact significance text or the p-value used to derive it.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum SignificanceMark {
11    /// Derive `ns` or one through four stars from this exact display p-value.
12    PValue(f64),
13    /// Render `ns`.
14    NotSignificant,
15    /// Render `*`.
16    OneStar,
17    /// Render `**`.
18    TwoStars,
19    /// Render `***`.
20    ThreeStars,
21    /// Render `****`.
22    FourStars,
23}
24
25impl SignificanceMark {
26    pub(crate) fn glyph(self) -> Result<&'static str, Error> {
27        match self {
28            Self::PValue(value) if !value.is_finite() || !(0.0..=1.0).contains(&value) => {
29                Err(Error::Data(
30                    format!("significance p-value must be finite and in [0, 1]; got {value}")
31                        .into(),
32                ))
33            }
34            Self::PValue(value) if value >= 0.05 => Ok("ns"),
35            Self::PValue(value) if value < 0.0001 => Ok("****"),
36            Self::PValue(value) if value < 0.001 => Ok("***"),
37            Self::PValue(value) if value < 0.01 => Ok("**"),
38            Self::PValue(_) | Self::OneStar => Ok("*"),
39            Self::NotSignificant => Ok("ns"),
40            Self::TwoStars => Ok("**"),
41            Self::ThreeStars => Ok("***"),
42            Self::FourStars => Ok("****"),
43        }
44    }
45}
46
47/// One rendered categorical target for a significance annotation.
48#[derive(Debug, Clone, PartialEq, Eq, Hash)]
49pub enum SignificanceTarget {
50    /// A complete categorical axis level or category cluster.
51    Category(RawKey),
52    /// One positioned series inside a category.
53    CategorySeries {
54        /// Categorical axis level.
55        category: RawKey,
56        /// Constructor-owned or configured plot-series level.
57        series: RawKey,
58    },
59}
60
61impl SignificanceTarget {
62    /// Target a complete categorical axis level or category cluster.
63    #[must_use]
64    pub fn category(value: impl Into<RawKey>) -> Self {
65        Self::Category(value.into())
66    }
67
68    /// Target one positioned series inside a category.
69    #[must_use]
70    pub fn category_series(category: impl Into<RawKey>, series: impl Into<RawKey>) -> Self {
71        Self::CategorySeries {
72            category: category.into(),
73            series: series.into(),
74        }
75    }
76
77    /// The supplied category key.
78    pub fn get_category(&self) -> &RawKey {
79        match self {
80            Self::Category(category) | Self::CategorySeries { category, .. } => category,
81        }
82    }
83
84    /// The supplied positioned series, if present.
85    pub fn get_series(&self) -> Option<&RawKey> {
86        match self {
87            Self::Category(_) => None,
88            Self::CategorySeries { series, .. } => Some(series),
89        }
90    }
91}
92
93impl From<String> for SignificanceTarget {
94    fn from(value: String) -> Self {
95        Self::category(value)
96    }
97}
98
99impl From<&str> for SignificanceTarget {
100    fn from(value: &str) -> Self {
101        Self::category(value)
102    }
103}
104
105impl From<RawKey> for SignificanceTarget {
106    fn from(value: RawKey) -> Self {
107        Self::category(value)
108    }
109}
110
111/// One exact panel owned by a faceted significance annotation.
112#[derive(Debug, Clone, PartialEq, Eq, Hash)]
113pub struct FacetCell {
114    layout: FacetCellLayout,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq, Hash)]
118enum FacetCellLayout {
119    Single(RawKey),
120    Grid { row: RawKey, column: RawKey },
121}
122
123impl FacetCell {
124    pub(crate) fn try_copy(&self) -> crate::Result<Self> {
125        let copy = |key: &RawKey| match key {
126            RawKey::String(level) => {
127                crate::data::source::copy_source_string(level).map(RawKey::String)
128            }
129            _ => Ok(key.clone()),
130        };
131        match &self.layout {
132            FacetCellLayout::Single(level) => Ok(Self::single(copy(level)?)),
133            FacetCellLayout::Grid { row, column } => Ok(Self::grid(copy(row)?, copy(column)?)),
134        }
135    }
136
137    /// Actual original key of a single-dimensional address.
138    pub fn get_single(&self) -> Option<&RawKey> {
139        match &self.layout {
140            FacetCellLayout::Single(level) => Some(level),
141            FacetCellLayout::Grid { .. } => None,
142        }
143    }
144
145    /// Actual original keys of a crossed facet address.
146    pub fn get_grid(&self) -> Option<(&RawKey, &RawKey)> {
147        match &self.layout {
148            FacetCellLayout::Grid { row, column } => Some((row, column)),
149            FacetCellLayout::Single(_) => None,
150        }
151    }
152
153    /// String level of a single-dimensional facet address.
154    pub fn single_level(&self) -> Option<&str> {
155        match self.get_single()? {
156            RawKey::String(level) => Some(level),
157            _ => None,
158        }
159    }
160    /// String row and column levels of a crossed facet address.
161    pub fn grid_levels(&self) -> Option<(&str, &str)> {
162        match self.get_grid()? {
163            (RawKey::String(row), RawKey::String(column)) => Some((row, column)),
164            _ => None,
165        }
166    }
167    /// Select one actual level of a row, column, or wrapped facet.
168    #[must_use]
169    pub fn single(level: impl Into<RawKey>) -> Self {
170        Self {
171            layout: FacetCellLayout::Single(level.into()),
172        }
173    }
174
175    /// Select one actual row-by-column facet cell.
176    #[must_use]
177    pub fn grid(row: impl Into<RawKey>, column: impl Into<RawKey>) -> Self {
178        Self {
179            layout: FacetCellLayout::Grid {
180                row: row.into(),
181                column: column.into(),
182            },
183        }
184    }
185
186    pub(crate) const fn dimensions(&self) -> usize {
187        match self.layout {
188            FacetCellLayout::Single(_) => 1,
189            FacetCellLayout::Grid { .. } => 2,
190        }
191    }
192
193    fn validate(&self) -> Result<(), Error> {
194        let key = |role, key: &RawKey| match key {
195            RawKey::String(value) => validate_text(role, value),
196            _ => Ok(()),
197        };
198        match &self.layout {
199            FacetCellLayout::Single(level) => key("facet level", level),
200            FacetCellLayout::Grid { row, column } => {
201                key("facet row level", row)?;
202                key("facet column level", column)
203            }
204        }
205    }
206}
207
208impl From<&str> for FacetCell {
209    fn from(level: &str) -> Self {
210        Self::single(level)
211    }
212}
213impl From<String> for FacetCell {
214    fn from(level: String) -> Self {
215        Self::single(level)
216    }
217}
218impl From<RawKey> for FacetCell {
219    fn from(level: RawKey) -> Self {
220        Self::single(level)
221    }
222}
223impl<R: Into<RawKey>, C: Into<RawKey>> From<(R, C)> for FacetCell {
224    fn from((row, column): (R, C)) -> Self {
225        Self::grid(row, column)
226    }
227}
228
229/// Marker for a significance mark attached to one rendered target.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231pub struct Attached;
232
233/// Marker for a pairwise significance bracket between two rendered targets.
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
235pub struct Pairwise;
236
237/// One actual original significance annotation and its optional supplied batch relation.
238#[derive(Debug, Clone, PartialEq)]
239#[non_exhaustive]
240pub enum SignificanceAnnotation {
241    /// One supplied attached mark.
242    #[non_exhaustive]
243    Attached {
244        /// Original target.
245        target: SignificanceTarget,
246        /// Actual supplied or mapped display mark.
247        mark: SignificanceMark,
248        /// Actual facet restriction.
249        facet: Option<FacetCell>,
250        /// Actual batch relation, if supplied from result variables.
251        origin: Option<SignificanceOrigin>,
252    },
253    /// One supplied pairwise comparison.
254    #[non_exhaustive]
255    Pairwise {
256        /// First supplied endpoint.
257        endpoint_a: SignificanceTarget,
258        /// Second supplied endpoint.
259        endpoint_b: SignificanceTarget,
260        /// Actual supplied or mapped display mark.
261        mark: SignificanceMark,
262        /// Actual facet restriction.
263        facet: Option<FacetCell>,
264        /// Actual batch relation, if supplied from result variables.
265        origin: Option<SignificanceOrigin>,
266    },
267}
268
269/// One caller-owned significance annotation with a compile-time placement.
270#[derive(Debug, Clone, PartialEq)]
271pub struct Significance<P> {
272    annotation: SignificanceAnnotation,
273    placement: PhantomData<P>,
274}
275
276impl Significance<Attached> {
277    /// Place one significance mark at a categorical target.
278    #[must_use]
279    pub fn at(target: impl Into<SignificanceTarget>, mark: SignificanceMark) -> Self {
280        Self {
281            annotation: SignificanceAnnotation::Attached {
282                target: target.into(),
283                mark,
284                facet: None,
285                origin: None,
286            },
287            placement: PhantomData,
288        }
289    }
290}
291
292impl Significance<Pairwise> {
293    /// Draw one pairwise bracket between two categorical targets.
294    #[must_use]
295    pub fn between(
296        endpoint_a: impl Into<SignificanceTarget>,
297        endpoint_b: impl Into<SignificanceTarget>,
298        mark: SignificanceMark,
299    ) -> Self {
300        Self {
301            annotation: SignificanceAnnotation::Pairwise {
302                endpoint_a: endpoint_a.into(),
303                endpoint_b: endpoint_b.into(),
304                mark,
305                facet: None,
306                origin: None,
307            },
308            placement: PhantomData,
309        }
310    }
311}
312
313impl<P> Significance<P> {
314    /// Restrict this annotation to one exact configured facet cell.
315    #[must_use]
316    pub fn facet(mut self, cell: FacetCell) -> Self {
317        *self.annotation.facet_mut() = Some(cell);
318        if let Some(origin) = self.annotation.origin_mut().as_mut() {
319            origin.facet_overridden = true;
320        }
321        self
322    }
323
324    pub(crate) fn with_origin(mut self, binding: Arc<SignificanceBinding>, row: usize) -> Self {
325        *self.annotation.origin_mut() = Some(SignificanceOrigin {
326            binding,
327            row,
328            facet_overridden: false,
329        });
330        self
331    }
332
333    /// Inspect this actual original native annotation before it is attached.
334    pub fn get_annotation(&self) -> &SignificanceAnnotation {
335        &self.annotation
336    }
337
338    pub(crate) fn into_annotation(self) -> SignificanceAnnotation {
339        self.annotation
340    }
341}
342
343impl SignificanceAnnotation {
344    /// Actual supplied or mapped mark, before conversion to a displayed glyph.
345    pub const fn mark(&self) -> SignificanceMark {
346        match self {
347            Self::Attached { mark, .. } | Self::Pairwise { mark, .. } => *mark,
348        }
349    }
350
351    /// Original attached target, if present.
352    pub fn at_target(&self) -> Option<&SignificanceTarget> {
353        match self {
354            Self::Attached { target, .. } => Some(target),
355            Self::Pairwise { .. } => None,
356        }
357    }
358
359    /// Original pairwise endpoints, if present.
360    pub fn endpoints(&self) -> Option<(&SignificanceTarget, &SignificanceTarget)> {
361        match self {
362            Self::Attached { .. } => None,
363            Self::Pairwise {
364                endpoint_a,
365                endpoint_b,
366                ..
367            } => Some((endpoint_a, endpoint_b)),
368        }
369    }
370
371    /// Actual facet restriction.
372    pub const fn facet_cell(&self) -> Option<&FacetCell> {
373        match self {
374            Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet.as_ref(),
375        }
376    }
377
378    /// The owning original source batch, when supplied through result variables.
379    pub fn binding(&self) -> Option<&SignificanceBinding> {
380        self.origin().map(|origin| origin.binding.as_ref())
381    }
382
383    /// The actual row of its original result batch.
384    pub fn binding_row(&self) -> Option<usize> {
385        self.origin().map(|origin| origin.row)
386    }
387
388    /// The active original per-result facet variable declaration, when present.
389    pub fn get_significance_split(&self) -> Option<&crate::layout::FacetBinding> {
390        let origin = self.origin()?;
391        if origin.facet_overridden {
392            return None;
393        }
394        match origin.binding.facets() {
395            SignificanceFacetInput::Split(binding) => Some(binding),
396            _ => None,
397        }
398    }
399
400    fn origin(&self) -> Option<&SignificanceOrigin> {
401        match self {
402            Self::Attached { origin, .. } | Self::Pairwise { origin, .. } => origin.as_ref(),
403        }
404    }
405
406    fn origin_mut(&mut self) -> &mut Option<SignificanceOrigin> {
407        match self {
408            Self::Attached { origin, .. } | Self::Pairwise { origin, .. } => origin,
409        }
410    }
411
412    pub(crate) fn validate(&self) -> Result<(), Error> {
413        self.mark().glyph()?;
414        match self {
415            Self::Attached { target, .. } => validate_target(target)?,
416            Self::Pairwise {
417                endpoint_a,
418                endpoint_b,
419                ..
420            } => {
421                validate_target(endpoint_a)?;
422                validate_target(endpoint_b)?;
423                if endpoint_a == endpoint_b {
424                    return Err(Error::Data(
425                        "significance comparison endpoints must be different".into(),
426                    ));
427                }
428            }
429        }
430        if let Some(cell) = self.facet_cell() {
431            cell.validate()?;
432        }
433        Ok(())
434    }
435
436    fn facet_mut(&mut self) -> &mut Option<FacetCell> {
437        match self {
438            Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet,
439        }
440    }
441}
442
443fn validate_target(target: &SignificanceTarget) -> Result<(), Error> {
444    if let RawKey::String(category) = target.get_category() {
445        validate_text("target category", category)?;
446    }
447    if let Some(RawKey::String(series)) = target.get_series() {
448        validate_text("target series", series)?;
449    }
450    Ok(())
451}
452
453fn validate_text(role: &str, value: &str) -> Result<(), Error> {
454    if value.trim().is_empty() || value.trim() != value || value.chars().any(char::is_control) {
455        return Err(Error::Data(
456            format!(
457                "significance {role} must be nonempty, trimmed, and free of control characters"
458            )
459            .into(),
460        ));
461    }
462    Ok(())
463}