lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Public significance display values.

use super::{binding::SignificanceOrigin, SignificanceBinding, SignificanceFacetInput};
use std::{marker::PhantomData, sync::Arc};

use crate::{data::RawKey, Error};

/// Exact significance text or the p-value used to derive it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SignificanceMark {
    /// Derive `ns` or one through four stars from this exact display p-value.
    PValue(f64),
    /// Render `ns`.
    NotSignificant,
    /// Render `*`.
    OneStar,
    /// Render `**`.
    TwoStars,
    /// Render `***`.
    ThreeStars,
    /// Render `****`.
    FourStars,
}

impl SignificanceMark {
    pub(crate) fn glyph(self) -> Result<&'static str, Error> {
        match self {
            Self::PValue(value) if !value.is_finite() || !(0.0..=1.0).contains(&value) => {
                Err(Error::Data(
                    format!("significance p-value must be finite and in [0, 1]; got {value}")
                        .into(),
                ))
            }
            Self::PValue(value) if value >= 0.05 => Ok("ns"),
            Self::PValue(value) if value < 0.0001 => Ok("****"),
            Self::PValue(value) if value < 0.001 => Ok("***"),
            Self::PValue(value) if value < 0.01 => Ok("**"),
            Self::PValue(_) | Self::OneStar => Ok("*"),
            Self::NotSignificant => Ok("ns"),
            Self::TwoStars => Ok("**"),
            Self::ThreeStars => Ok("***"),
            Self::FourStars => Ok("****"),
        }
    }
}

/// One rendered categorical target for a significance annotation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SignificanceTarget {
    /// A complete categorical axis level or category cluster.
    Category(RawKey),
    /// One positioned series inside a category.
    CategorySeries {
        /// Categorical axis level.
        category: RawKey,
        /// Constructor-owned or configured plot-series level.
        series: RawKey,
    },
}

impl SignificanceTarget {
    /// Target a complete categorical axis level or category cluster.
    #[must_use]
    pub fn category(value: impl Into<RawKey>) -> Self {
        Self::Category(value.into())
    }

    /// Target one positioned series inside a category.
    #[must_use]
    pub fn category_series(category: impl Into<RawKey>, series: impl Into<RawKey>) -> Self {
        Self::CategorySeries {
            category: category.into(),
            series: series.into(),
        }
    }

    /// The supplied category key.
    pub fn get_category(&self) -> &RawKey {
        match self {
            Self::Category(category) | Self::CategorySeries { category, .. } => category,
        }
    }

    /// The supplied positioned series, if present.
    pub fn get_series(&self) -> Option<&RawKey> {
        match self {
            Self::Category(_) => None,
            Self::CategorySeries { series, .. } => Some(series),
        }
    }
}

impl From<String> for SignificanceTarget {
    fn from(value: String) -> Self {
        Self::category(value)
    }
}

impl From<&str> for SignificanceTarget {
    fn from(value: &str) -> Self {
        Self::category(value)
    }
}

impl From<RawKey> for SignificanceTarget {
    fn from(value: RawKey) -> Self {
        Self::category(value)
    }
}

/// One exact panel owned by a faceted significance annotation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FacetCell {
    layout: FacetCellLayout,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum FacetCellLayout {
    Single(RawKey),
    Grid { row: RawKey, column: RawKey },
}

impl FacetCell {
    pub(crate) fn try_copy(&self) -> crate::Result<Self> {
        let copy = |key: &RawKey| match key {
            RawKey::String(level) => {
                crate::data::source::copy_source_string(level).map(RawKey::String)
            }
            _ => Ok(key.clone()),
        };
        match &self.layout {
            FacetCellLayout::Single(level) => Ok(Self::single(copy(level)?)),
            FacetCellLayout::Grid { row, column } => Ok(Self::grid(copy(row)?, copy(column)?)),
        }
    }

    /// Actual original key of a single-dimensional address.
    pub fn get_single(&self) -> Option<&RawKey> {
        match &self.layout {
            FacetCellLayout::Single(level) => Some(level),
            FacetCellLayout::Grid { .. } => None,
        }
    }

    /// Actual original keys of a crossed facet address.
    pub fn get_grid(&self) -> Option<(&RawKey, &RawKey)> {
        match &self.layout {
            FacetCellLayout::Grid { row, column } => Some((row, column)),
            FacetCellLayout::Single(_) => None,
        }
    }

    /// String level of a single-dimensional facet address.
    pub fn single_level(&self) -> Option<&str> {
        match self.get_single()? {
            RawKey::String(level) => Some(level),
            _ => None,
        }
    }
    /// String row and column levels of a crossed facet address.
    pub fn grid_levels(&self) -> Option<(&str, &str)> {
        match self.get_grid()? {
            (RawKey::String(row), RawKey::String(column)) => Some((row, column)),
            _ => None,
        }
    }
    /// Select one actual level of a row, column, or wrapped facet.
    #[must_use]
    pub fn single(level: impl Into<RawKey>) -> Self {
        Self {
            layout: FacetCellLayout::Single(level.into()),
        }
    }

    /// Select one actual row-by-column facet cell.
    #[must_use]
    pub fn grid(row: impl Into<RawKey>, column: impl Into<RawKey>) -> Self {
        Self {
            layout: FacetCellLayout::Grid {
                row: row.into(),
                column: column.into(),
            },
        }
    }

    pub(crate) const fn dimensions(&self) -> usize {
        match self.layout {
            FacetCellLayout::Single(_) => 1,
            FacetCellLayout::Grid { .. } => 2,
        }
    }

    fn validate(&self) -> Result<(), Error> {
        let key = |role, key: &RawKey| match key {
            RawKey::String(value) => validate_text(role, value),
            _ => Ok(()),
        };
        match &self.layout {
            FacetCellLayout::Single(level) => key("facet level", level),
            FacetCellLayout::Grid { row, column } => {
                key("facet row level", row)?;
                key("facet column level", column)
            }
        }
    }
}

impl From<&str> for FacetCell {
    fn from(level: &str) -> Self {
        Self::single(level)
    }
}
impl From<String> for FacetCell {
    fn from(level: String) -> Self {
        Self::single(level)
    }
}
impl From<RawKey> for FacetCell {
    fn from(level: RawKey) -> Self {
        Self::single(level)
    }
}
impl<R: Into<RawKey>, C: Into<RawKey>> From<(R, C)> for FacetCell {
    fn from((row, column): (R, C)) -> Self {
        Self::grid(row, column)
    }
}

/// Marker for a significance mark attached to one rendered target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Attached;

/// Marker for a pairwise significance bracket between two rendered targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Pairwise;

/// One actual original significance annotation and its optional supplied batch relation.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceAnnotation {
    /// One supplied attached mark.
    #[non_exhaustive]
    Attached {
        /// Original target.
        target: SignificanceTarget,
        /// Actual supplied or mapped display mark.
        mark: SignificanceMark,
        /// Actual facet restriction.
        facet: Option<FacetCell>,
        /// Actual batch relation, if supplied from result variables.
        origin: Option<SignificanceOrigin>,
    },
    /// One supplied pairwise comparison.
    #[non_exhaustive]
    Pairwise {
        /// First supplied endpoint.
        endpoint_a: SignificanceTarget,
        /// Second supplied endpoint.
        endpoint_b: SignificanceTarget,
        /// Actual supplied or mapped display mark.
        mark: SignificanceMark,
        /// Actual facet restriction.
        facet: Option<FacetCell>,
        /// Actual batch relation, if supplied from result variables.
        origin: Option<SignificanceOrigin>,
    },
}

/// One caller-owned significance annotation with a compile-time placement.
#[derive(Debug, Clone, PartialEq)]
pub struct Significance<P> {
    annotation: SignificanceAnnotation,
    placement: PhantomData<P>,
}

impl Significance<Attached> {
    /// Place one significance mark at a categorical target.
    #[must_use]
    pub fn at(target: impl Into<SignificanceTarget>, mark: SignificanceMark) -> Self {
        Self {
            annotation: SignificanceAnnotation::Attached {
                target: target.into(),
                mark,
                facet: None,
                origin: None,
            },
            placement: PhantomData,
        }
    }
}

impl Significance<Pairwise> {
    /// Draw one pairwise bracket between two categorical targets.
    #[must_use]
    pub fn between(
        endpoint_a: impl Into<SignificanceTarget>,
        endpoint_b: impl Into<SignificanceTarget>,
        mark: SignificanceMark,
    ) -> Self {
        Self {
            annotation: SignificanceAnnotation::Pairwise {
                endpoint_a: endpoint_a.into(),
                endpoint_b: endpoint_b.into(),
                mark,
                facet: None,
                origin: None,
            },
            placement: PhantomData,
        }
    }
}

impl<P> Significance<P> {
    /// Restrict this annotation to one exact configured facet cell.
    #[must_use]
    pub fn facet(mut self, cell: FacetCell) -> Self {
        *self.annotation.facet_mut() = Some(cell);
        if let Some(origin) = self.annotation.origin_mut().as_mut() {
            origin.facet_overridden = true;
        }
        self
    }

    pub(crate) fn with_origin(mut self, binding: Arc<SignificanceBinding>, row: usize) -> Self {
        *self.annotation.origin_mut() = Some(SignificanceOrigin {
            binding,
            row,
            facet_overridden: false,
        });
        self
    }

    /// Inspect this actual original native annotation before it is attached.
    pub fn get_annotation(&self) -> &SignificanceAnnotation {
        &self.annotation
    }

    pub(crate) fn into_annotation(self) -> SignificanceAnnotation {
        self.annotation
    }
}

impl SignificanceAnnotation {
    /// Actual supplied or mapped mark, before conversion to a displayed glyph.
    pub const fn mark(&self) -> SignificanceMark {
        match self {
            Self::Attached { mark, .. } | Self::Pairwise { mark, .. } => *mark,
        }
    }

    /// Original attached target, if present.
    pub fn at_target(&self) -> Option<&SignificanceTarget> {
        match self {
            Self::Attached { target, .. } => Some(target),
            Self::Pairwise { .. } => None,
        }
    }

    /// Original pairwise endpoints, if present.
    pub fn endpoints(&self) -> Option<(&SignificanceTarget, &SignificanceTarget)> {
        match self {
            Self::Attached { .. } => None,
            Self::Pairwise {
                endpoint_a,
                endpoint_b,
                ..
            } => Some((endpoint_a, endpoint_b)),
        }
    }

    /// Actual facet restriction.
    pub const fn facet_cell(&self) -> Option<&FacetCell> {
        match self {
            Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet.as_ref(),
        }
    }

    /// The owning original source batch, when supplied through result variables.
    pub fn binding(&self) -> Option<&SignificanceBinding> {
        self.origin().map(|origin| origin.binding.as_ref())
    }

    /// The actual row of its original result batch.
    pub fn binding_row(&self) -> Option<usize> {
        self.origin().map(|origin| origin.row)
    }

    /// The active original per-result facet variable declaration, when present.
    pub fn get_significance_split(&self) -> Option<&crate::layout::FacetBinding> {
        let origin = self.origin()?;
        if origin.facet_overridden {
            return None;
        }
        match origin.binding.facets() {
            SignificanceFacetInput::Split(binding) => Some(binding),
            _ => None,
        }
    }

    fn origin(&self) -> Option<&SignificanceOrigin> {
        match self {
            Self::Attached { origin, .. } | Self::Pairwise { origin, .. } => origin.as_ref(),
        }
    }

    fn origin_mut(&mut self) -> &mut Option<SignificanceOrigin> {
        match self {
            Self::Attached { origin, .. } | Self::Pairwise { origin, .. } => origin,
        }
    }

    pub(crate) fn validate(&self) -> Result<(), Error> {
        self.mark().glyph()?;
        match self {
            Self::Attached { target, .. } => validate_target(target)?,
            Self::Pairwise {
                endpoint_a,
                endpoint_b,
                ..
            } => {
                validate_target(endpoint_a)?;
                validate_target(endpoint_b)?;
                if endpoint_a == endpoint_b {
                    return Err(Error::Data(
                        "significance comparison endpoints must be different".into(),
                    ));
                }
            }
        }
        if let Some(cell) = self.facet_cell() {
            cell.validate()?;
        }
        Ok(())
    }

    fn facet_mut(&mut self) -> &mut Option<FacetCell> {
        match self {
            Self::Attached { facet, .. } | Self::Pairwise { facet, .. } => facet,
        }
    }
}

fn validate_target(target: &SignificanceTarget) -> Result<(), Error> {
    if let RawKey::String(category) = target.get_category() {
        validate_text("target category", category)?;
    }
    if let Some(RawKey::String(series)) = target.get_series() {
        validate_text("target series", series)?;
    }
    Ok(())
}

fn validate_text(role: &str, value: &str) -> Result<(), Error> {
    if value.trim().is_empty() || value.trim() != value || value.chars().any(char::is_control) {
        return Err(Error::Data(
            format!(
                "significance {role} must be nonempty, trimmed, and free of control characters"
            )
            .into(),
        ));
    }
    Ok(())
}