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
//! Original caller-supplied significance batches.

use std::sync::Arc;

use super::{Attached, FacetCell, Pairwise, Significance, SignificanceMark, SignificanceTarget};
use crate::{
    data::{KeyValues, RawKey},
    layout::FacetBinding,
    CategoryValues, Error, NumericValues, Result,
};

/// Original target declaration, before scalar broadcast or paired-target construction.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceTargetInput {
    /// A category variable.
    Column(KeyValues),
    /// Aligned categories and positioned series.
    CategorySeries(KeyValues, KeyValues),
    /// One explicitly broadcast target.
    Fixed(SignificanceTarget),
    /// Explicit native targets in supplied order.
    Values(Arc<[SignificanceTarget]>),
}

/// Original supplied result marks and any explicit category mapping.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceMarkInput {
    /// A supplied display p-value variable.
    PValues(NumericValues),
    /// Original categories and the complete ordered authored mapping.
    Categories {
        /// Original category variable.
        values: CategoryValues,
        /// Complete original mapping, including unused declarations.
        mapping: Arc<[(String, SignificanceMark)]>,
    },
    /// One explicitly broadcast mark.
    Fixed(SignificanceMark),
    /// Explicit native marks in supplied order.
    Values(Arc<[SignificanceMark]>),
}

/// The actual facet selection and its original relation to result rows.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SignificanceFacetInput {
    /// No facet restriction.
    Unfaceted,
    /// One explicitly broadcast facet address.
    Fixed(FacetCell),
    /// A native sequence of facet addresses.
    Values(Arc<[FacetCell]>),
    /// Actual per-result source variables selecting the facets.
    Split(FacetBinding),
}

/// An owning batch declaration, shared by its actual generated annotations.
#[derive(Debug, Clone)]
pub struct SignificanceBinding {
    targets: Targets,
    marks: SignificanceMarkInput,
    facets: SignificanceFacetInput,
    count: usize,
    pub(crate) direct_sources: [Option<crate::data::DataSourceInfo>; 4],
}

impl PartialEq for SignificanceBinding {
    fn eq(&self, other: &Self) -> bool {
        self.targets == other.targets && self.marks == other.marks && self.facets == other.facets
    }
}

#[derive(Debug, Clone, PartialEq)]
#[expect(
    clippy::large_enum_variant,
    reason = "one owning batch has one or two original endpoint declarations"
)]
enum Targets {
    Attached(SignificanceTargetInput),
    Pairwise(SignificanceTargetInput, SignificanceTargetInput),
}

impl SignificanceBinding {
    fn new(
        targets: Targets,
        marks: SignificanceMarkInput,
        facets: SignificanceFacetInput,
        count: usize,
    ) -> Self {
        let direct_target = |target: &SignificanceTargetInput| match target {
            SignificanceTargetInput::Values(values) => {
                Some(crate::data::DataSourceInfo::direct(vec![values.len()]))
            }
            _ => None,
        };
        let (left, right) = match &targets {
            Targets::Attached(target) => (direct_target(target), None),
            Targets::Pairwise(left, right) => (direct_target(left), direct_target(right)),
        };
        let marks_source = if let SignificanceMarkInput::Values(values) = &marks {
            Some(crate::data::DataSourceInfo::direct(vec![values.len()]))
        } else {
            None
        };
        let facet_source = if let SignificanceFacetInput::Values(values) = &facets {
            Some(crate::data::DataSourceInfo::direct(vec![values.len()]))
        } else {
            None
        };
        Self {
            targets,
            marks,
            facets,
            count,
            direct_sources: [left, right, marks_source, facet_source],
        }
    }

    pub(crate) fn row_count(&self) -> usize {
        self.count
    }

    /// Original target input of an attached result batch.
    pub fn get_attached(&self) -> Option<&SignificanceTargetInput> {
        match &self.targets {
            Targets::Attached(target) => Some(target),
            Targets::Pairwise(..) => None,
        }
    }

    /// Original endpoints of a pairwise result batch.
    pub fn get_pairwise(&self) -> Option<(&SignificanceTargetInput, &SignificanceTargetInput)> {
        match &self.targets {
            Targets::Pairwise(left, right) => Some((left, right)),
            Targets::Attached(_) => None,
        }
    }

    /// Complete original mark declaration.
    pub fn marks(&self) -> &SignificanceMarkInput {
        &self.marks
    }

    /// Complete original result scope.
    pub fn facets(&self) -> &SignificanceFacetInput {
        &self.facets
    }
}

#[derive(Debug, Clone, PartialEq)]
/// Opaque original row relationship of a supplied result annotation.
#[doc(hidden)]
pub struct SignificanceOrigin {
    pub(crate) binding: Arc<SignificanceBinding>,
    pub(crate) row: usize,
    pub(crate) facet_overridden: bool,
}

struct Sequence<T> {
    values: Vec<T>,
    scalar: bool,
}

impl<T: Clone> Sequence<T> {
    fn fixed(value: &T) -> Self {
        Self {
            values: vec![value.clone()],
            scalar: true,
        }
    }
    fn many(values: Vec<T>) -> Self {
        Self {
            values,
            scalar: false,
        }
    }
    fn shape(&self) -> (usize, bool) {
        (self.values.len(), self.scalar)
    }
    fn at(&self, row: usize) -> T {
        self.values[if self.scalar { 0 } else { row }].clone()
    }
}

fn length(role: &str, expected: usize, actual: usize) -> Result<()> {
    if expected == actual {
        Ok(())
    } else {
        Err(Error::Data(
            format!("{role}: expected {expected} result slots, got {actual}").into(),
        ))
    }
}

fn categories(values: &CategoryValues, role: &str) -> Result<Vec<String>> {
    crate::data::source::collect_source(values.iter().enumerate().map(|(slot, value)| {
        let value = value.ok_or_else(|| {
            Error::Data(format!("{role}: missing category at slot {slot}").into())
        })?;
        crate::data::source::copy_source_string(value)
    }))
}

impl SignificanceTargetInput {
    fn decode(&self) -> Result<Sequence<SignificanceTarget>> {
        Ok(match self {
            Self::Column(values) => Sequence::many(
                raw_keys(values, "significance target")?
                    .into_iter()
                    .map(SignificanceTarget::category)
                    .collect(),
            ),
            Self::CategorySeries(category, series) => {
                let category = raw_keys(category, "significance category")?;
                let series = raw_keys(series, "significance series")?;
                length("significance series", category.len(), series.len())?;
                Sequence::many(
                    category
                        .into_iter()
                        .zip(series)
                        .map(|(category, series)| {
                            SignificanceTarget::category_series(category, series)
                        })
                        .collect(),
                )
            }
            Self::Fixed(target) => Sequence::fixed(target),
            Self::Values(values) => Sequence::many(values.to_vec()),
        })
    }
}

impl SignificanceMarkInput {
    fn original(self) -> Result<Self> {
        match self {
            Self::Categories { values, mapping } => {
                let KeyValues::Strings(values) = values.key_values() else {
                    return Err(Error::Data(
                        "significance mark mapping requires string category keys".into(),
                    ));
                };
                Ok(Self::Categories { values, mapping })
            }
            input => Ok(input),
        }
    }

    fn decode(&self) -> Result<Sequence<SignificanceMark>> {
        Ok(match self {
            Self::PValues(values) => Sequence::many(crate::data::source::collect_source(
                values.iter().enumerate().map(|(slot, value)| {
                    value.map(SignificanceMark::PValue).ok_or_else(|| {
                        Error::Data(
                            format!("significance p-values: missing value at slot {slot}").into(),
                        )
                    })
                }),
            )?),
            Self::Categories { values, mapping } => {
                let values = categories(values, "significance marks")?;
                Sequence::many(crate::data::source::collect_source(values.iter().map(
                    |value| {
                        let mut matches = mapping.iter().filter(|(key, _)| key == value);
                        let mark = matches
                            .next()
                            .ok_or_else(|| {
                                Error::Data(
                                    format!("significance marks: unmapped key {value:?}").into(),
                                )
                            })?
                            .1;
                        if matches.next().is_some() {
                            return Err(Error::Data(
                                format!("significance marks: duplicate map key {value:?}").into(),
                            ));
                        }
                        Ok(mark)
                    },
                ))?)
            }
            Self::Fixed(mark) => Sequence::fixed(mark),
            Self::Values(values) => Sequence::many(values.to_vec()),
        })
    }
}

fn raw_keys(values: &KeyValues, role: &str) -> Result<Vec<RawKey>> {
    crate::data::source::collect_source((0..values.len()).map(|slot| {
        let key = match values {
            KeyValues::Strings(values) => values.get(slot).flatten().map(RawKey::from),
            KeyValues::Raw(values) => values.get(slot).flatten().cloned(),
        };
        key.ok_or_else(|| Error::Data(format!("{role}: missing category at slot {slot}").into()))
    }))
}

impl SignificanceFacetInput {
    fn decode(&self) -> Result<Option<Sequence<FacetCell>>> {
        Ok(Some(match self {
            Self::Unfaceted => return Ok(None),
            Self::Fixed(facet) => Sequence::fixed(facet),
            Self::Values(facets) => Sequence::many(facets.to_vec()),
            Self::Split(FacetBinding::Wrap(values)) => Sequence::many(
                raw_keys(values, "significance facet")?
                    .into_iter()
                    .map(FacetCell::single)
                    .collect(),
            ),
            Self::Split(FacetBinding::Grid { row, column }) => {
                let row = raw_keys(row, "significance facet row")?;
                let column = raw_keys(column, "significance facet column")?;
                length("significance facet column", row.len(), column.len())?;
                Sequence::many(
                    row.into_iter()
                        .zip(column)
                        .map(|(row, column)| FacetCell::grid(row, column))
                        .collect(),
                )
            }
        }))
    }
}

fn count(parts: &[(usize, bool)], facets: Option<&Sequence<FacetCell>>) -> Result<usize> {
    let mut shapes = parts.to_vec();
    shapes.extend(facets.map(Sequence::shape));
    let count = shapes
        .iter()
        .find(|(_, scalar)| !scalar)
        .map_or(1, |(length, _)| *length);
    for (length_value, scalar) in shapes {
        if !scalar {
            length("significance", count, length_value)?;
        }
    }
    Ok(count)
}

/// Bind one actual attached result batch, retaining its original declaration.
pub fn significance_attached(
    target: SignificanceTargetInput,
    marks: SignificanceMarkInput,
    facets: SignificanceFacetInput,
) -> Result<Vec<Significance<Attached>>> {
    // Facet inputs are admitted before endpoint and mark values, as in the original producers.
    let decoded_facets = facets.decode()?;
    let decoded_target = target.decode()?;
    let marks = marks.original()?;
    let decoded_marks = marks.decode()?;
    let count = count(
        &[decoded_target.shape(), decoded_marks.shape()],
        decoded_facets.as_ref(),
    )?;
    let binding = Arc::new(SignificanceBinding::new(
        Targets::Attached(target),
        marks,
        facets,
        count,
    ));
    crate::data::source::collect_source((0..count).map(|row| {
        let mut value = Significance::at(decoded_target.at(row), decoded_marks.at(row));
        if let Some(facets) = &decoded_facets {
            value = value.facet(facets.at(row));
        }
        Ok(value.with_origin(binding.clone(), row))
    }))
}

/// Bind one actual pairwise result batch, retaining its original declaration.
pub fn significance_pairwise(
    left: SignificanceTargetInput,
    right: SignificanceTargetInput,
    marks: SignificanceMarkInput,
    facets: SignificanceFacetInput,
) -> Result<Vec<Significance<Pairwise>>> {
    let decoded_facets = facets.decode()?;
    let decoded_left = left.decode()?;
    let decoded_right = right.decode()?;
    let marks = marks.original()?;
    let decoded_marks = marks.decode()?;
    let count = count(
        &[
            decoded_left.shape(),
            decoded_right.shape(),
            decoded_marks.shape(),
        ],
        decoded_facets.as_ref(),
    )?;
    let binding = Arc::new(SignificanceBinding::new(
        Targets::Pairwise(left, right),
        marks,
        facets,
        count,
    ));
    crate::data::source::collect_source((0..count).map(|row| {
        let mut value = Significance::between(
            decoded_left.at(row),
            decoded_right.at(row),
            decoded_marks.at(row),
        );
        if let Some(facets) = &decoded_facets {
            value = value.facet(facets.at(row));
        }
        Ok(value.with_origin(binding.clone(), row))
    }))
}