Skip to main content

lichtung_plot/stats/
results.rs

1//! Owning scientific fields and same-operation result records.
2
3use std::sync::Arc;
4
5use crate::{
6    data::{
7        DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload, DataRole, DataValueType,
8        GroupKey, MemberAddress, SourceMembers,
9    },
10    elements::ElementRef,
11    errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
12    layout::PanelPath,
13    Error, Output, Result,
14};
15
16macro_rules! fields {
17    ($name:ident { $($variant:ident => $field:literal),+ $(,)? }) => {
18        #[doc = concat!("Fields produced by ", stringify!($name), "'s scientific family.")]
19        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20        #[non_exhaustive]
21        pub enum $name {
22            $(#[doc = concat!("Actual ", $field, " field.")] $variant,)+
23        }
24
25        impl $name {
26            /// Stable field spelling within this scientific family.
27            pub const fn name(self) -> &'static str {
28                match self { $(Self::$variant => $field,)+ }
29            }
30            /// Resolve a canonical field spelling for a typed language binding.
31            #[doc(hidden)]
32            pub fn from_name(name: &str) -> Option<Self> {
33                match name { $($field => Some(Self::$variant),)+ _ => None }
34            }
35        }
36    };
37}
38
39fields!(BinField {
40    Lower => "lower", Upper => "upper", Center => "center", Width => "width",
41    Count => "count", Mass => "mass", Probability => "probability",
42    Frequency => "frequency", Percent => "percent", Density => "density",
43});
44
45fields!(DensityField {
46    X => "x", Density => "density", Group => "group", Hue => "hue",
47});
48
49fields!(FitField {
50    X => "x", Fitted => "fitted", Lower => "lower", Upper => "upper",
51});
52
53fields!(SummaryField {
54    X => "x", Group => "group", Hue => "hue", Estimate => "estimate", Lower => "lower", Upper => "upper", N => "n",
55});
56
57fields!(WaterfallField {
58    Category => "category", Delta => "delta", Start => "start", End => "end",
59});
60
61/// Kernel of the actual density computation.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63#[non_exhaustive]
64pub enum Kernel {
65    /// Gaussian kernel.
66    Gaussian,
67}
68
69/// A reference to a scientific output field, separate from original input roles.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71#[non_exhaustive]
72pub enum StatField {
73    /// An actual histogram/bin field.
74    Bin(BinField),
75    /// Actual one-dimensional density field.
76    Density(DensityField),
77    /// Actual prediction field from one fitted model.
78    Fit(FitField),
79    /// Actual categorical statistical summary field.
80    Summary(SummaryField),
81    /// Actual ordered cumulative contribution field.
82    Waterfall(WaterfallField),
83    /// An explicitly retained original field of this actual preparation.
84    Original(DataRole),
85}
86
87impl From<DataRole> for StatField {
88    fn from(value: DataRole) -> Self {
89        Self::Original(value)
90    }
91}
92
93impl From<BinField> for StatField {
94    fn from(value: BinField) -> Self {
95        Self::Bin(value)
96    }
97}
98
99impl From<DensityField> for StatField {
100    fn from(value: DensityField) -> Self {
101        Self::Density(value)
102    }
103}
104
105impl From<FitField> for StatField {
106    fn from(value: FitField) -> Self {
107        Self::Fit(value)
108    }
109}
110
111impl From<SummaryField> for StatField {
112    fn from(value: SummaryField) -> Self {
113        Self::Summary(value)
114    }
115}
116
117impl From<WaterfallField> for StatField {
118    fn from(value: WaterfallField) -> Self {
119        Self::Waterfall(value)
120    }
121}
122
123impl StatField {
124    /// Field spelling within its own scientific family.
125    pub const fn name(self) -> &'static str {
126        match self {
127            Self::Bin(field) => field.name(),
128            Self::Density(field) => field.name(),
129            Self::Fit(field) => field.name(),
130            Self::Summary(field) => field.name(),
131            Self::Waterfall(field) => field.name(),
132            Self::Original(role) => role.as_str(),
133        }
134    }
135}
136
137/// An actual field in an owning scientific result.
138#[derive(Debug, Clone)]
139pub struct StatFieldInfo {
140    field: StatField,
141    domain: DataDomainRef,
142    value_type: DataValueType,
143}
144
145impl StatFieldInfo {
146    /// Typed producer field.
147    pub const fn field(&self) -> StatField {
148        self.field
149    }
150    /// Actual output domain containing this field.
151    pub const fn domain(&self) -> &DataDomainRef {
152        &self.domain
153    }
154    /// Canonical field spelling.
155    pub fn name(&self) -> &'static str {
156        self.field.name()
157    }
158    /// Actual native values held by the field.
159    pub const fn value_type(&self) -> DataValueType {
160        self.value_type
161    }
162}
163
164/// Storage shared by statistical fields and family-specific owning results.
165#[derive(Debug, Clone, Default)]
166pub(crate) struct ResultDomains {
167    infos: Vec<DataDomainInfo>,
168    relations: Vec<Arc<[Option<SourceMembers>]>>,
169}
170
171impl ResultDomains {
172    pub(crate) fn push(
173        &mut self,
174        owner: &ElementRef,
175        group: Option<&GroupKey>,
176        components: Vec<DataComponentInfo>,
177        members: Vec<Option<SourceMembers>>,
178    ) -> Result<DataDomainRef> {
179        let reference = DataDomainRef::scientific(owner, group);
180        let info = DataDomainInfo::bound(reference, members.len(), None, components);
181        self.push_info(info, members)
182    }
183
184    pub(crate) fn push_info(
185        &mut self,
186        info: DataDomainInfo,
187        members: Vec<Option<SourceMembers>>,
188    ) -> Result<DataDomainRef> {
189        if info.shape() != [members.len()]
190            || info
191                .components()
192                .iter()
193                .any(|component| component.shape() != Some(&[members.len()]))
194        {
195            return Err(Error::Render(
196                "scientific result components do not align with their domain".into(),
197            ));
198        }
199        let reference = info.reference().clone();
200        crate::data::source::reserve_source(&mut self.infos, 1)?;
201        crate::data::source::reserve_source(&mut self.relations, 1)?;
202        self.infos.push(info);
203        self.relations.push(members.into());
204        Ok(reference)
205    }
206
207    pub(crate) fn infos(&self) -> &[DataDomainInfo] {
208        &self.infos
209    }
210
211    fn index(&self, domain: &DataDomainRef) -> Result<usize> {
212        self.infos
213            .iter()
214            .position(|info| info.reference() == domain)
215            .ok_or_else(|| {
216                use crate::errors::DiagnosticReference;
217                Error::Data(
218                    Diagnostic::new(
219                        DiagnosticKind::StaleReference {
220                            reference: Box::new(DiagnosticReference::Domain(domain.clone())),
221                            current: None,
222                        },
223                        "scientific result domain is foreign to this owning result",
224                    )
225                    .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
226                )
227            })
228    }
229
230    pub(crate) fn relation(&self, domain: &DataDomainRef) -> Result<&[Option<SourceMembers>]> {
231        Ok(&self.relations[self.index(domain)?])
232    }
233
234    pub(crate) fn extend(&mut self, other: &Self) -> Result<()> {
235        crate::data::source::reserve_source(&mut self.infos, other.infos.len())?;
236        crate::data::source::reserve_source(&mut self.relations, other.relations.len())?;
237        self.infos.extend_from_slice(&other.infos);
238        self.relations.extend_from_slice(&other.relations);
239        Ok(())
240    }
241
242    pub(crate) fn members_in(
243        &self,
244        domain: &DataDomainRef,
245        address: &MemberAddress,
246    ) -> Result<Option<SourceMembers>> {
247        let index = self.index(domain)?;
248        let slot = self.infos[index].resolve(address)?;
249        Ok(self.relations[index][slot].clone())
250    }
251
252    pub(crate) fn members(&self, address: &MemberAddress) -> Result<Option<SourceMembers>> {
253        use crate::errors::DiagnosticReference;
254        let [domain] = self.infos.as_slice() else {
255            return Err(Error::Data(
256                Diagnostic::new(
257                    DiagnosticKind::Ambiguous {
258                        candidates: self
259                            .infos
260                            .iter()
261                            .map(|info| DiagnosticReference::Domain(info.reference().clone()))
262                            .collect(),
263                    },
264                    "scientific result has no unique domain; select an actual domain",
265                )
266                .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
267            ));
268        };
269        self.members_in(domain.reference(), address)
270    }
271}
272
273/// Capture a finite scientific numeric column using fallible source collection.
274pub(crate) fn numeric_column(
275    name: &str,
276    values: impl Iterator<Item = f64>,
277) -> Result<crate::NumericValues> {
278    let values = crate::data::source::collect_source(values.map(Ok))?;
279    crate::operation::check()?;
280    Ok(crate::NumericValues::new(name, values))
281}
282
283/// Capture a real nullable scientific field, preserving missingness.
284pub(crate) fn nullable_column(
285    name: &str,
286    values: impl Iterator<Item = Option<f64>>,
287) -> Result<crate::NumericValues> {
288    let values = crate::data::source::collect_source(values.map(Ok))?;
289    crate::operation::check()?;
290    Ok(crate::NumericValues::nullable(name, values))
291}
292
293#[derive(Debug)]
294struct StatData {
295    fields: Vec<StatFieldInfo>,
296    values: Vec<DataPayload>,
297    domains: ResultDomains,
298}
299
300/// An immutable result of one scientific preparation, with real field domains.
301#[derive(Debug, Clone)]
302pub struct StatResult(Arc<StatData>);
303
304pub(crate) struct StatDomainInput {
305    pub(crate) columns: Vec<(StatField, DataPayload)>,
306    pub(crate) members: Vec<Option<SourceMembers>>,
307    pub(crate) group: Option<GroupKey>,
308    pub(crate) keys: Option<crate::data::RawKeyValues>,
309    pub(crate) rows: Option<crate::data::SourceRows>,
310}
311
312/// Actual complete category address of a result row, with a single tuple key
313/// kept distinct from a combination of two or more grouping columns.
314pub(crate) fn result_keys(
315    columns: &[(StatField, DataPayload)],
316    fields: &[StatField],
317) -> Result<crate::data::RawKeyValues> {
318    use crate::data::{KeyValues, RawKey, RawKeyValues};
319    let keys = crate::data::source::collect_source(fields.iter().map(|field| {
320        match columns
321            .iter()
322            .find(|(candidate, _)| candidate == field)
323            .map(|(_, value)| value)
324        {
325            Some(DataPayload::Category(values)) => Ok(values.key_values()),
326            Some(DataPayload::RawKeys(values)) => Ok(KeyValues::Raw(values.clone())),
327            _ => Err(Error::Render(
328                "result member key field is not an actual category column".into(),
329            )),
330        }
331    }))?;
332    let length = keys
333        .first()
334        .ok_or_else(|| Error::Render("result member keys require an actual dimension".into()))?
335        .len();
336    if keys.iter().any(|column| column.len() != length) {
337        return Err(Error::Render(
338            "result member key columns do not align".into(),
339        ));
340    }
341    let values = crate::data::source::collect_source((0..length).map(|slot| {
342        let parts = crate::data::source::collect_source(keys.iter().map(|column| {
343            column
344                .key_at(slot)
345                .ok_or_else(|| Error::Render("result member key is missing".into()))
346        }))?;
347        Ok(match parts.as_slice() {
348            [key] => key.clone(),
349            _ => RawKey::Tuple(parts),
350        })
351    }))?;
352    RawKeyValues::new("group", values)
353}
354
355impl StatResult {
356    pub(crate) fn single_domain(
357        owner: &ElementRef,
358        group: Option<&GroupKey>,
359        columns: Vec<(StatField, DataPayload)>,
360        members: Vec<Option<SourceMembers>>,
361    ) -> Result<Self> {
362        Self::from_domains(
363            owner,
364            [StatDomainInput {
365                columns,
366                members,
367                group: group.cloned(),
368                keys: None,
369                rows: None,
370            }],
371        )
372    }
373
374    pub(crate) fn from_domains(
375        owner: &ElementRef,
376        inputs: impl IntoIterator<Item = StatDomainInput>,
377    ) -> Result<Self> {
378        let mut fields: Vec<StatFieldInfo> = Vec::new();
379        let mut values = Vec::new();
380        let mut domains = ResultDomains::default();
381        for input in inputs {
382            let mut components = Vec::new();
383            crate::data::source::reserve_source(&mut components, input.columns.len())?;
384            crate::data::source::reserve_source(&mut fields, input.columns.len())?;
385            crate::data::source::reserve_source(&mut values, input.columns.len())?;
386            for (field, value) in &input.columns {
387                if fields.iter().any(|candidate| candidate.field == *field)
388                    || input
389                        .columns
390                        .iter()
391                        .filter(|(candidate, _)| candidate == field)
392                        .count()
393                        != 1
394                {
395                    return Err(Error::Render("duplicate field in scientific result".into()));
396                }
397                components.push(DataComponentInfo::scientific_with_members(
398                    field.name(),
399                    value,
400                    &input.members,
401                )?);
402            }
403            let reference = DataDomainRef::scientific(owner, input.group.as_ref());
404            let mut info = DataDomainInfo::bound(
405                reference,
406                input.members.len(),
407                input.rows.as_ref(),
408                components,
409            );
410            if let Some(keys) = &input.keys {
411                if keys.len() != input.members.len() {
412                    return Err(Error::Render(
413                        "scientific member keys do not align with the result".into(),
414                    ));
415                }
416                info = info.with_keys(keys);
417            }
418            let reference = domains.push_info(info, input.members)?;
419            for (field, value) in input.columns {
420                fields.push(StatFieldInfo {
421                    field,
422                    domain: reference.clone(),
423                    value_type: value.value_type(),
424                });
425                values.push(value);
426            }
427        }
428        Ok(Self(crate::data::source::source_arc(StatData {
429            fields,
430            values,
431            domains,
432        })?))
433    }
434
435    pub(crate) fn result_domains(&self) -> &ResultDomains {
436        &self.0.domains
437    }
438
439    /// Actual output field descriptions, in producer order.
440    pub fn fields(&self) -> &[StatFieldInfo] {
441        &self.0.fields
442    }
443
444    /// Actual scientific domains; no domain is inferred from equal lengths.
445    pub fn domains(&self) -> &[DataDomainInfo] {
446        self.0.domains.infos()
447    }
448
449    fn field_index(&self, field: StatField) -> Result<usize> {
450        self.0
451            .fields
452            .iter()
453            .position(|info| info.field == field)
454            .ok_or_else(|| {
455                Error::Data(
456                    Diagnostic::new(
457                        DiagnosticKind::UnknownKey {
458                            key: Some(crate::data::RawKey::from(field.name())),
459                        },
460                        format!("scientific result has no {field:?} field"),
461                    )
462                    .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
463                )
464            })
465    }
466
467    /// Read the actual owning native field, without a scientific calculation.
468    pub fn values(&self, field: impl Into<StatField>) -> Result<&DataPayload> {
469        Ok(&self.0.values[self.field_index(field.into())?])
470    }
471
472    /// Per-member source relations of this field's actual output domain.
473    pub fn get_members(&self, field: impl Into<StatField>) -> Result<&[Option<SourceMembers>]> {
474        let field = &self.0.fields[self.field_index(field.into())?];
475        let index = self.0.domains.index(field.domain())?;
476        Ok(&self.0.domains.relations[index])
477    }
478
479    /// Read a member's source relation within its actual scientific domain.
480    pub fn members_in(
481        &self,
482        domain: &DataDomainRef,
483        address: impl Into<MemberAddress>,
484    ) -> Result<Option<SourceMembers>> {
485        self.0.domains.members_in(domain, &address.into())
486    }
487}
488
489/// The actual scientific value produced by a supported family.
490#[derive(Debug, Clone)]
491#[non_exhaustive]
492pub enum ScientificResult {
493    /// Actual prepared histogram bins and optional auxiliary geometry.
494    Histogram(crate::plots::HistogramResult),
495    /// Actual evaluated one-dimensional density.
496    Density(crate::plots::DensityResult),
497    /// Actual probability-plot quantile pairs.
498    ProbabilityPlot(crate::plots::ProbabilityPlotResult),
499    /// Actual fitted model parameters, predictions and observation diagnostics.
500    Fit(crate::stats::FitResult),
501    /// Actual owning statistical fields.
502    Stat(StatResult),
503    /// Actual box summaries and outlier relations.
504    Box(crate::plots::BoxSummary),
505    /// Actual categorical density profiles and auxiliary domains.
506    Profiles(crate::plots::DensityProfiles),
507    /// Actual raincloud geometry and independent original domains.
508    Raincloud(crate::plots::RaincloudGeometry),
509}
510
511/// A scientific value associated with its actual panel and consuming layers.
512#[derive(Debug, Clone)]
513pub struct ScientificResultEntry {
514    panel: PanelPath,
515    layers: Arc<[ElementRef]>,
516    group: Option<GroupKey>,
517    value: ScientificResult,
518}
519
520impl ScientificResultEntry {
521    pub(crate) fn new(layer: ElementRef, group: Option<GroupKey>, value: ScientificResult) -> Self {
522        Self {
523            panel: layer.panel().clone(),
524            layers: Arc::from([layer]),
525            group,
526            value,
527        }
528    }
529
530    /// Actual panel of this producer.
531    pub const fn panel(&self) -> &PanelPath {
532        &self.panel
533    }
534    /// Actual consuming declarations.
535    pub fn layers(&self) -> &[ElementRef] {
536        &self.layers
537    }
538    /// Actual group key, if a single group is represented.
539    pub const fn group(&self) -> Option<&GroupKey> {
540        self.group.as_ref()
541    }
542    /// The prepared scientific value.
543    pub const fn value(&self) -> &ScientificResult {
544        &self.value
545    }
546}
547
548/// One successful frozen figure and the scientific values from that preparation.
549#[derive(Clone)]
550pub struct RenderWithResults {
551    output: Output,
552    results: Arc<[ScientificResultEntry]>,
553}
554
555impl RenderWithResults {
556    pub(crate) fn new(output: Output, results: Arc<[ScientificResultEntry]>) -> Self {
557        Self { output, results }
558    }
559    /// The ordinary independently reusable frozen output.
560    pub const fn output(&self) -> &Output {
561        &self.output
562    }
563    /// Actual scientific results in occurrence order.
564    pub fn results(&self) -> &[ScientificResultEntry] {
565        &self.results
566    }
567}