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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Owning scientific fields and same-operation result records.

use std::sync::Arc;

use crate::{
    data::{
        DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload, DataRole, DataValueType,
        GroupKey, MemberAddress, SourceMembers,
    },
    elements::ElementRef,
    errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
    layout::PanelPath,
    Error, Output, Result,
};

macro_rules! fields {
    ($name:ident { $($variant:ident => $field:literal),+ $(,)? }) => {
        #[doc = concat!("Fields produced by ", stringify!($name), "'s scientific family.")]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        pub enum $name {
            $(#[doc = concat!("Actual ", $field, " field.")] $variant,)+
        }

        impl $name {
            /// Stable field spelling within this scientific family.
            pub const fn name(self) -> &'static str {
                match self { $(Self::$variant => $field,)+ }
            }
            /// Resolve a canonical field spelling for a typed language binding.
            #[doc(hidden)]
            pub fn from_name(name: &str) -> Option<Self> {
                match name { $($field => Some(Self::$variant),)+ _ => None }
            }
        }
    };
}

fields!(BinField {
    Lower => "lower", Upper => "upper", Center => "center", Width => "width",
    Count => "count", Mass => "mass", Probability => "probability",
    Frequency => "frequency", Percent => "percent", Density => "density",
});

fields!(DensityField {
    X => "x", Density => "density", Group => "group", Hue => "hue",
});

fields!(FitField {
    X => "x", Fitted => "fitted", Lower => "lower", Upper => "upper",
});

fields!(SummaryField {
    X => "x", Group => "group", Hue => "hue", Estimate => "estimate", Lower => "lower", Upper => "upper", N => "n",
});

fields!(WaterfallField {
    Category => "category", Delta => "delta", Start => "start", End => "end",
});

/// Kernel of the actual density computation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Kernel {
    /// Gaussian kernel.
    Gaussian,
}

/// A reference to a scientific output field, separate from original input roles.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StatField {
    /// An actual histogram/bin field.
    Bin(BinField),
    /// Actual one-dimensional density field.
    Density(DensityField),
    /// Actual prediction field from one fitted model.
    Fit(FitField),
    /// Actual categorical statistical summary field.
    Summary(SummaryField),
    /// Actual ordered cumulative contribution field.
    Waterfall(WaterfallField),
    /// An explicitly retained original field of this actual preparation.
    Original(DataRole),
}

impl From<DataRole> for StatField {
    fn from(value: DataRole) -> Self {
        Self::Original(value)
    }
}

impl From<BinField> for StatField {
    fn from(value: BinField) -> Self {
        Self::Bin(value)
    }
}

impl From<DensityField> for StatField {
    fn from(value: DensityField) -> Self {
        Self::Density(value)
    }
}

impl From<FitField> for StatField {
    fn from(value: FitField) -> Self {
        Self::Fit(value)
    }
}

impl From<SummaryField> for StatField {
    fn from(value: SummaryField) -> Self {
        Self::Summary(value)
    }
}

impl From<WaterfallField> for StatField {
    fn from(value: WaterfallField) -> Self {
        Self::Waterfall(value)
    }
}

impl StatField {
    /// Field spelling within its own scientific family.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Bin(field) => field.name(),
            Self::Density(field) => field.name(),
            Self::Fit(field) => field.name(),
            Self::Summary(field) => field.name(),
            Self::Waterfall(field) => field.name(),
            Self::Original(role) => role.as_str(),
        }
    }
}

/// An actual field in an owning scientific result.
#[derive(Debug, Clone)]
pub struct StatFieldInfo {
    field: StatField,
    domain: DataDomainRef,
    value_type: DataValueType,
}

impl StatFieldInfo {
    /// Typed producer field.
    pub const fn field(&self) -> StatField {
        self.field
    }
    /// Actual output domain containing this field.
    pub const fn domain(&self) -> &DataDomainRef {
        &self.domain
    }
    /// Canonical field spelling.
    pub fn name(&self) -> &'static str {
        self.field.name()
    }
    /// Actual native values held by the field.
    pub const fn value_type(&self) -> DataValueType {
        self.value_type
    }
}

/// Storage shared by statistical fields and family-specific owning results.
#[derive(Debug, Clone, Default)]
pub(crate) struct ResultDomains {
    infos: Vec<DataDomainInfo>,
    relations: Vec<Arc<[Option<SourceMembers>]>>,
}

impl ResultDomains {
    pub(crate) fn push(
        &mut self,
        owner: &ElementRef,
        group: Option<&GroupKey>,
        components: Vec<DataComponentInfo>,
        members: Vec<Option<SourceMembers>>,
    ) -> Result<DataDomainRef> {
        let reference = DataDomainRef::scientific(owner, group);
        let info = DataDomainInfo::bound(reference, members.len(), None, components);
        self.push_info(info, members)
    }

    pub(crate) fn push_info(
        &mut self,
        info: DataDomainInfo,
        members: Vec<Option<SourceMembers>>,
    ) -> Result<DataDomainRef> {
        if info.shape() != [members.len()]
            || info
                .components()
                .iter()
                .any(|component| component.shape() != Some(&[members.len()]))
        {
            return Err(Error::Render(
                "scientific result components do not align with their domain".into(),
            ));
        }
        let reference = info.reference().clone();
        crate::data::source::reserve_source(&mut self.infos, 1)?;
        crate::data::source::reserve_source(&mut self.relations, 1)?;
        self.infos.push(info);
        self.relations.push(members.into());
        Ok(reference)
    }

    pub(crate) fn infos(&self) -> &[DataDomainInfo] {
        &self.infos
    }

    fn index(&self, domain: &DataDomainRef) -> Result<usize> {
        self.infos
            .iter()
            .position(|info| info.reference() == domain)
            .ok_or_else(|| {
                use crate::errors::DiagnosticReference;
                Error::Data(
                    Diagnostic::new(
                        DiagnosticKind::StaleReference {
                            reference: Box::new(DiagnosticReference::Domain(domain.clone())),
                            current: None,
                        },
                        "scientific result domain is foreign to this owning result",
                    )
                    .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
                )
            })
    }

    pub(crate) fn relation(&self, domain: &DataDomainRef) -> Result<&[Option<SourceMembers>]> {
        Ok(&self.relations[self.index(domain)?])
    }

    pub(crate) fn extend(&mut self, other: &Self) -> Result<()> {
        crate::data::source::reserve_source(&mut self.infos, other.infos.len())?;
        crate::data::source::reserve_source(&mut self.relations, other.relations.len())?;
        self.infos.extend_from_slice(&other.infos);
        self.relations.extend_from_slice(&other.relations);
        Ok(())
    }

    pub(crate) fn members_in(
        &self,
        domain: &DataDomainRef,
        address: &MemberAddress,
    ) -> Result<Option<SourceMembers>> {
        let index = self.index(domain)?;
        let slot = self.infos[index].resolve(address)?;
        Ok(self.relations[index][slot].clone())
    }

    pub(crate) fn members(&self, address: &MemberAddress) -> Result<Option<SourceMembers>> {
        use crate::errors::DiagnosticReference;
        let [domain] = self.infos.as_slice() else {
            return Err(Error::Data(
                Diagnostic::new(
                    DiagnosticKind::Ambiguous {
                        candidates: self
                            .infos
                            .iter()
                            .map(|info| DiagnosticReference::Domain(info.reference().clone()))
                            .collect(),
                    },
                    "scientific result has no unique domain; select an actual domain",
                )
                .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
            ));
        };
        self.members_in(domain.reference(), address)
    }
}

/// Capture a finite scientific numeric column using fallible source collection.
pub(crate) fn numeric_column(
    name: &str,
    values: impl Iterator<Item = f64>,
) -> Result<crate::NumericValues> {
    let values = crate::data::source::collect_source(values.map(Ok))?;
    crate::operation::check()?;
    Ok(crate::NumericValues::new(name, values))
}

/// Capture a real nullable scientific field, preserving missingness.
pub(crate) fn nullable_column(
    name: &str,
    values: impl Iterator<Item = Option<f64>>,
) -> Result<crate::NumericValues> {
    let values = crate::data::source::collect_source(values.map(Ok))?;
    crate::operation::check()?;
    Ok(crate::NumericValues::nullable(name, values))
}

#[derive(Debug)]
struct StatData {
    fields: Vec<StatFieldInfo>,
    values: Vec<DataPayload>,
    domains: ResultDomains,
}

/// An immutable result of one scientific preparation, with real field domains.
#[derive(Debug, Clone)]
pub struct StatResult(Arc<StatData>);

pub(crate) struct StatDomainInput {
    pub(crate) columns: Vec<(StatField, DataPayload)>,
    pub(crate) members: Vec<Option<SourceMembers>>,
    pub(crate) group: Option<GroupKey>,
    pub(crate) keys: Option<crate::data::RawKeyValues>,
    pub(crate) rows: Option<crate::data::SourceRows>,
}

/// Actual complete category address of a result row, with a single tuple key
/// kept distinct from a combination of two or more grouping columns.
pub(crate) fn result_keys(
    columns: &[(StatField, DataPayload)],
    fields: &[StatField],
) -> Result<crate::data::RawKeyValues> {
    use crate::data::{KeyValues, RawKey, RawKeyValues};
    let keys = crate::data::source::collect_source(fields.iter().map(|field| {
        match columns
            .iter()
            .find(|(candidate, _)| candidate == field)
            .map(|(_, value)| value)
        {
            Some(DataPayload::Category(values)) => Ok(values.key_values()),
            Some(DataPayload::RawKeys(values)) => Ok(KeyValues::Raw(values.clone())),
            _ => Err(Error::Render(
                "result member key field is not an actual category column".into(),
            )),
        }
    }))?;
    let length = keys
        .first()
        .ok_or_else(|| Error::Render("result member keys require an actual dimension".into()))?
        .len();
    if keys.iter().any(|column| column.len() != length) {
        return Err(Error::Render(
            "result member key columns do not align".into(),
        ));
    }
    let values = crate::data::source::collect_source((0..length).map(|slot| {
        let parts = crate::data::source::collect_source(keys.iter().map(|column| {
            column
                .key_at(slot)
                .ok_or_else(|| Error::Render("result member key is missing".into()))
        }))?;
        Ok(match parts.as_slice() {
            [key] => key.clone(),
            _ => RawKey::Tuple(parts),
        })
    }))?;
    RawKeyValues::new("group", values)
}

impl StatResult {
    pub(crate) fn single_domain(
        owner: &ElementRef,
        group: Option<&GroupKey>,
        columns: Vec<(StatField, DataPayload)>,
        members: Vec<Option<SourceMembers>>,
    ) -> Result<Self> {
        Self::from_domains(
            owner,
            [StatDomainInput {
                columns,
                members,
                group: group.cloned(),
                keys: None,
                rows: None,
            }],
        )
    }

    pub(crate) fn from_domains(
        owner: &ElementRef,
        inputs: impl IntoIterator<Item = StatDomainInput>,
    ) -> Result<Self> {
        let mut fields: Vec<StatFieldInfo> = Vec::new();
        let mut values = Vec::new();
        let mut domains = ResultDomains::default();
        for input in inputs {
            let mut components = Vec::new();
            crate::data::source::reserve_source(&mut components, input.columns.len())?;
            crate::data::source::reserve_source(&mut fields, input.columns.len())?;
            crate::data::source::reserve_source(&mut values, input.columns.len())?;
            for (field, value) in &input.columns {
                if fields.iter().any(|candidate| candidate.field == *field)
                    || input
                        .columns
                        .iter()
                        .filter(|(candidate, _)| candidate == field)
                        .count()
                        != 1
                {
                    return Err(Error::Render("duplicate field in scientific result".into()));
                }
                components.push(DataComponentInfo::scientific_with_members(
                    field.name(),
                    value,
                    &input.members,
                )?);
            }
            let reference = DataDomainRef::scientific(owner, input.group.as_ref());
            let mut info = DataDomainInfo::bound(
                reference,
                input.members.len(),
                input.rows.as_ref(),
                components,
            );
            if let Some(keys) = &input.keys {
                if keys.len() != input.members.len() {
                    return Err(Error::Render(
                        "scientific member keys do not align with the result".into(),
                    ));
                }
                info = info.with_keys(keys);
            }
            let reference = domains.push_info(info, input.members)?;
            for (field, value) in input.columns {
                fields.push(StatFieldInfo {
                    field,
                    domain: reference.clone(),
                    value_type: value.value_type(),
                });
                values.push(value);
            }
        }
        Ok(Self(crate::data::source::source_arc(StatData {
            fields,
            values,
            domains,
        })?))
    }

    pub(crate) fn result_domains(&self) -> &ResultDomains {
        &self.0.domains
    }

    /// Actual output field descriptions, in producer order.
    pub fn fields(&self) -> &[StatFieldInfo] {
        &self.0.fields
    }

    /// Actual scientific domains; no domain is inferred from equal lengths.
    pub fn domains(&self) -> &[DataDomainInfo] {
        self.0.domains.infos()
    }

    fn field_index(&self, field: StatField) -> Result<usize> {
        self.0
            .fields
            .iter()
            .position(|info| info.field == field)
            .ok_or_else(|| {
                Error::Data(
                    Diagnostic::new(
                        DiagnosticKind::UnknownKey {
                            key: Some(crate::data::RawKey::from(field.name())),
                        },
                        format!("scientific result has no {field:?} field"),
                    )
                    .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
                )
            })
    }

    /// Read the actual owning native field, without a scientific calculation.
    pub fn values(&self, field: impl Into<StatField>) -> Result<&DataPayload> {
        Ok(&self.0.values[self.field_index(field.into())?])
    }

    /// Per-member source relations of this field's actual output domain.
    pub fn get_members(&self, field: impl Into<StatField>) -> Result<&[Option<SourceMembers>]> {
        let field = &self.0.fields[self.field_index(field.into())?];
        let index = self.0.domains.index(field.domain())?;
        Ok(&self.0.domains.relations[index])
    }

    /// Read a member's source relation within its actual scientific domain.
    pub fn members_in(
        &self,
        domain: &DataDomainRef,
        address: impl Into<MemberAddress>,
    ) -> Result<Option<SourceMembers>> {
        self.0.domains.members_in(domain, &address.into())
    }
}

/// The actual scientific value produced by a supported family.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ScientificResult {
    /// Actual prepared histogram bins and optional auxiliary geometry.
    Histogram(crate::plots::HistogramResult),
    /// Actual evaluated one-dimensional density.
    Density(crate::plots::DensityResult),
    /// Actual probability-plot quantile pairs.
    ProbabilityPlot(crate::plots::ProbabilityPlotResult),
    /// Actual fitted model parameters, predictions and observation diagnostics.
    Fit(crate::stats::FitResult),
    /// Actual owning statistical fields.
    Stat(StatResult),
    /// Actual box summaries and outlier relations.
    Box(crate::plots::BoxSummary),
    /// Actual categorical density profiles and auxiliary domains.
    Profiles(crate::plots::DensityProfiles),
    /// Actual raincloud geometry and independent original domains.
    Raincloud(crate::plots::RaincloudGeometry),
}

/// A scientific value associated with its actual panel and consuming layers.
#[derive(Debug, Clone)]
pub struct ScientificResultEntry {
    panel: PanelPath,
    layers: Arc<[ElementRef]>,
    group: Option<GroupKey>,
    value: ScientificResult,
}

impl ScientificResultEntry {
    pub(crate) fn new(layer: ElementRef, group: Option<GroupKey>, value: ScientificResult) -> Self {
        Self {
            panel: layer.panel().clone(),
            layers: Arc::from([layer]),
            group,
            value,
        }
    }

    /// Actual panel of this producer.
    pub const fn panel(&self) -> &PanelPath {
        &self.panel
    }
    /// Actual consuming declarations.
    pub fn layers(&self) -> &[ElementRef] {
        &self.layers
    }
    /// Actual group key, if a single group is represented.
    pub const fn group(&self) -> Option<&GroupKey> {
        self.group.as_ref()
    }
    /// The prepared scientific value.
    pub const fn value(&self) -> &ScientificResult {
        &self.value
    }
}

/// One successful frozen figure and the scientific values from that preparation.
#[derive(Clone)]
pub struct RenderWithResults {
    output: Output,
    results: Arc<[ScientificResultEntry]>,
}

impl RenderWithResults {
    pub(crate) fn new(output: Output, results: Arc<[ScientificResultEntry]>) -> Self {
        Self { output, results }
    }
    /// The ordinary independently reusable frozen output.
    pub const fn output(&self) -> &Output {
        &self.output
    }
    /// Actual scientific results in occurrence order.
    pub fn results(&self) -> &[ScientificResultEntry] {
        &self.results
    }
}