Skip to main content

lichtung_plot/significance/
spec.rs

1//! Public significance display values.
2
3use std::marker::PhantomData;
4
5use crate::Error;
6
7/// Exact significance text or the p-value used to derive it.
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub enum SignificanceMark {
10    /// Derive `ns` or one through four stars from this exact display p-value.
11    PValue(f64),
12    /// Render `ns`.
13    NotSignificant,
14    /// Render `*`.
15    OneStar,
16    /// Render `**`.
17    TwoStars,
18    /// Render `***`.
19    ThreeStars,
20    /// Render `****`.
21    FourStars,
22}
23
24impl SignificanceMark {
25    pub(crate) fn glyph(self) -> Result<&'static str, Error> {
26        match self {
27            Self::PValue(value) if !value.is_finite() || !(0.0..=1.0).contains(&value) => {
28                Err(Error::Data(format!(
29                    "significance p-value must be finite and in [0, 1]; got {value}"
30                )))
31            }
32            Self::PValue(value) if value >= 0.05 => Ok("ns"),
33            Self::PValue(value) if value < 0.0001 => Ok("****"),
34            Self::PValue(value) if value < 0.001 => Ok("***"),
35            Self::PValue(value) if value < 0.01 => Ok("**"),
36            Self::PValue(_) | Self::OneStar => Ok("*"),
37            Self::NotSignificant => Ok("ns"),
38            Self::TwoStars => Ok("**"),
39            Self::ThreeStars => Ok("***"),
40            Self::FourStars => Ok("****"),
41        }
42    }
43}
44
45/// One rendered categorical target for a significance annotation.
46#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub enum SignificanceTarget {
48    /// A complete categorical axis level or category cluster.
49    Category(String),
50    /// One positioned series inside a category.
51    CategorySeries {
52        /// Categorical axis level.
53        category: String,
54        /// Constructor-owned or configured plot-series level.
55        series: String,
56    },
57}
58
59impl SignificanceTarget {
60    /// Target a complete categorical axis level or category cluster.
61    #[must_use]
62    pub fn category(value: impl Into<String>) -> Self {
63        Self::Category(value.into())
64    }
65
66    /// Target one positioned series inside a category.
67    #[must_use]
68    pub fn category_series(category: impl Into<String>, series: impl Into<String>) -> Self {
69        Self::CategorySeries {
70            category: category.into(),
71            series: series.into(),
72        }
73    }
74
75    pub(crate) fn category_name(&self) -> &str {
76        match self {
77            Self::Category(category) | Self::CategorySeries { category, .. } => category,
78        }
79    }
80
81    pub(crate) fn series_name(&self) -> Option<&str> {
82        match self {
83            Self::Category(_) => None,
84            Self::CategorySeries { series, .. } => Some(series),
85        }
86    }
87}
88
89impl From<String> for SignificanceTarget {
90    fn from(value: String) -> Self {
91        Self::Category(value)
92    }
93}
94
95impl From<&str> for SignificanceTarget {
96    fn from(value: &str) -> Self {
97        Self::Category(value.to_owned())
98    }
99}
100
101/// One exact panel owned by a faceted significance annotation.
102#[derive(Debug, Clone, PartialEq, Eq, Hash)]
103pub struct FacetCell {
104    layout: FacetCellLayout,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Hash)]
108enum FacetCellLayout {
109    Single(String),
110    Grid { row: String, column: String },
111}
112
113impl FacetCell {
114    pub(crate) fn try_copy(&self) -> crate::Result<Self> {
115        match &self.layout {
116            FacetCellLayout::Single(level) => Ok(Self::single(
117                crate::data::source::copy_source_string(level)?,
118            )),
119            FacetCellLayout::Grid { row, column } => Ok(Self::grid(
120                crate::data::source::copy_source_string(row)?,
121                crate::data::source::copy_source_string(column)?,
122            )),
123        }
124    }
125    /// Raw level of a single-dimensional facet address.
126    pub fn single_level(&self) -> Option<&str> {
127        if let FacetCellLayout::Single(level) = &self.layout {
128            Some(level)
129        } else {
130            None
131        }
132    }
133    /// Raw row and column levels of a crossed facet address.
134    pub fn grid_levels(&self) -> Option<(&str, &str)> {
135        if let FacetCellLayout::Grid { row, column } = &self.layout {
136            Some((row, column))
137        } else {
138            None
139        }
140    }
141    /// Select one level of a row, column, or wrapped facet.
142    #[must_use]
143    pub fn single(level: impl Into<String>) -> Self {
144        Self {
145            layout: FacetCellLayout::Single(level.into()),
146        }
147    }
148
149    /// Select one row-by-column facet cell.
150    #[must_use]
151    pub fn grid(row: impl Into<String>, column: impl Into<String>) -> Self {
152        Self {
153            layout: FacetCellLayout::Grid {
154                row: row.into(),
155                column: column.into(),
156            },
157        }
158    }
159
160    pub(crate) const fn dimensions(&self) -> usize {
161        match self.layout {
162            FacetCellLayout::Single(_) => 1,
163            FacetCellLayout::Grid { .. } => 2,
164        }
165    }
166
167    fn validate(&self) -> Result<(), Error> {
168        match &self.layout {
169            FacetCellLayout::Single(level) => validate_text("facet level", level),
170            FacetCellLayout::Grid { row, column } => {
171                validate_text("facet row level", row)?;
172                validate_text("facet column level", column)
173            }
174        }
175    }
176}
177
178/// Marker for a significance mark attached to one rendered target.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
180pub struct Attached;
181
182/// Marker for a pairwise significance bracket between two rendered targets.
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
184pub struct Pairwise;
185
186#[derive(Debug, Clone, PartialEq)]
187pub(crate) enum SignificanceAnnotation {
188    Attached {
189        target: SignificanceTarget,
190        mark: SignificanceMark,
191        facet: Option<FacetCell>,
192    },
193    Pairwise {
194        endpoint_a: SignificanceTarget,
195        endpoint_b: SignificanceTarget,
196        mark: SignificanceMark,
197        facet: Option<FacetCell>,
198    },
199}
200
201/// One caller-owned significance annotation with a compile-time placement.
202#[derive(Debug, Clone, PartialEq)]
203pub struct Significance<P> {
204    annotation: SignificanceAnnotation,
205    placement: PhantomData<P>,
206}
207
208impl Significance<Attached> {
209    /// Place one significance mark at a categorical target.
210    #[must_use]
211    pub fn at(target: impl Into<SignificanceTarget>, mark: SignificanceMark) -> Self {
212        Self {
213            annotation: SignificanceAnnotation::Attached {
214                target: target.into(),
215                mark,
216                facet: None,
217            },
218            placement: PhantomData,
219        }
220    }
221}
222
223impl Significance<Pairwise> {
224    /// Draw one pairwise bracket between two categorical targets.
225    #[must_use]
226    pub fn between(
227        endpoint_a: impl Into<SignificanceTarget>,
228        endpoint_b: impl Into<SignificanceTarget>,
229        mark: SignificanceMark,
230    ) -> Self {
231        Self {
232            annotation: SignificanceAnnotation::Pairwise {
233                endpoint_a: endpoint_a.into(),
234                endpoint_b: endpoint_b.into(),
235                mark,
236                facet: None,
237            },
238            placement: PhantomData,
239        }
240    }
241}
242
243impl<P> Significance<P> {
244    /// Restrict this annotation to one exact configured facet cell.
245    #[must_use]
246    pub fn facet(mut self, cell: FacetCell) -> Self {
247        *self.annotation.facet_mut() = Some(cell);
248        self
249    }
250
251    pub(crate) fn into_annotation(self) -> SignificanceAnnotation {
252        self.annotation
253    }
254}
255
256impl SignificanceAnnotation {
257    pub(crate) const fn mark(&self) -> SignificanceMark {
258        match self {
259            Self::Attached { mark, .. } | Self::Pairwise { mark, .. } => *mark,
260        }
261    }
262
263    pub(crate) fn at_target(&self) -> Option<&SignificanceTarget> {
264        match self {
265            Self::Attached { target, .. } => Some(target),
266            Self::Pairwise { .. } => None,
267        }
268    }
269
270    pub(crate) fn endpoints(&self) -> Option<(&SignificanceTarget, &SignificanceTarget)> {
271        match self {
272            Self::Attached { .. } => None,
273            Self::Pairwise {
274                endpoint_a,
275                endpoint_b,
276                ..
277            } => Some((endpoint_a, endpoint_b)),
278        }
279    }
280
281    pub(crate) const fn facet_cell(&self) -> Option<&FacetCell> {
282        match self {
283            Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet.as_ref(),
284        }
285    }
286
287    pub(crate) fn validate(&self) -> Result<(), Error> {
288        self.mark().glyph()?;
289        match self {
290            Self::Attached { target, .. } => validate_target(target)?,
291            Self::Pairwise {
292                endpoint_a,
293                endpoint_b,
294                ..
295            } => {
296                validate_target(endpoint_a)?;
297                validate_target(endpoint_b)?;
298                if endpoint_a == endpoint_b {
299                    return Err(Error::Data(
300                        "significance comparison endpoints must be different".into(),
301                    ));
302                }
303            }
304        }
305        if let Some(cell) = self.facet_cell() {
306            cell.validate()?;
307        }
308        Ok(())
309    }
310
311    fn facet_mut(&mut self) -> &mut Option<FacetCell> {
312        match self {
313            Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet,
314        }
315    }
316}
317
318fn validate_target(target: &SignificanceTarget) -> Result<(), Error> {
319    validate_text("target category", target.category_name())?;
320    if let Some(series) = target.series_name() {
321        validate_text("target series", series)?;
322    }
323    Ok(())
324}
325
326fn validate_text(role: &str, value: &str) -> Result<(), Error> {
327    if value.trim().is_empty() || value.trim() != value || value.chars().any(char::is_control) {
328        return Err(Error::Data(format!(
329            "significance {role} must be nonempty, trimmed, and free of control characters"
330        )));
331    }
332    Ok(())
333}