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 native storage admission.
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::memory(values.len() as u128 * std::mem::size_of::<f64>() as u128)?;
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::work(values.len())?;
290    let bitmap = if values.iter().filter(|value| value.is_none()).count() != 0 {
291        values.len().div_ceil(64)
292    } else {
293        0
294    };
295    crate::operation::memory(
296        values.len() as u128
297            * (std::mem::size_of::<f64>()
298                + std::mem::size_of::<Option<f64>>()
299                + std::mem::size_of::<bool>()) as u128
300            + bitmap as u128 * std::mem::size_of::<u64>() as u128,
301    )?;
302    Ok(crate::NumericValues::nullable(name, values))
303}
304
305#[derive(Debug)]
306struct StatData {
307    fields: Vec<StatFieldInfo>,
308    values: Vec<DataPayload>,
309    domains: ResultDomains,
310}
311
312/// An immutable result of one scientific preparation, with real field domains.
313#[derive(Debug, Clone)]
314pub struct StatResult(Arc<StatData>);
315
316pub(crate) struct StatDomainInput {
317    pub(crate) columns: Vec<(StatField, DataPayload)>,
318    pub(crate) members: Vec<Option<SourceMembers>>,
319    pub(crate) group: Option<GroupKey>,
320    pub(crate) keys: Option<crate::data::RawKeyValues>,
321    pub(crate) rows: Option<crate::data::SourceRows>,
322}
323
324/// Actual complete category address of a result row, with a single tuple key
325/// kept distinct from a combination of two or more grouping columns.
326pub(crate) fn result_keys(
327    columns: &[(StatField, DataPayload)],
328    fields: &[StatField],
329) -> Result<crate::data::RawKeyValues> {
330    use crate::data::{KeyValues, RawKey, RawKeyValues};
331    let keys = crate::data::source::collect_source(fields.iter().map(|field| {
332        match columns
333            .iter()
334            .find(|(candidate, _)| candidate == field)
335            .map(|(_, value)| value)
336        {
337            Some(DataPayload::Category(values)) => Ok(values.key_values()),
338            Some(DataPayload::RawKeys(values)) => Ok(KeyValues::Raw(values.clone())),
339            _ => Err(Error::Render(
340                "result member key field is not an actual category column".into(),
341            )),
342        }
343    }))?;
344    let length = keys
345        .first()
346        .ok_or_else(|| Error::Render("result member keys require an actual dimension".into()))?
347        .len();
348    if keys.iter().any(|column| column.len() != length) {
349        return Err(Error::Render(
350            "result member key columns do not align".into(),
351        ));
352    }
353    let values = crate::data::source::collect_source((0..length).map(|slot| {
354        let parts = crate::data::source::collect_source(keys.iter().map(|column| {
355            column
356                .key_at(slot)
357                .ok_or_else(|| Error::Render("result member key is missing".into()))
358        }))?;
359        Ok(match parts.as_slice() {
360            [key] => key.clone(),
361            _ => RawKey::Tuple(parts),
362        })
363    }))?;
364    RawKeyValues::new("group", values)
365}
366
367impl StatResult {
368    pub(crate) fn single_domain(
369        owner: &ElementRef,
370        group: Option<&GroupKey>,
371        columns: Vec<(StatField, DataPayload)>,
372        members: Vec<Option<SourceMembers>>,
373    ) -> Result<Self> {
374        Self::from_domains(
375            owner,
376            [StatDomainInput {
377                columns,
378                members,
379                group: group.cloned(),
380                keys: None,
381                rows: None,
382            }],
383        )
384    }
385
386    pub(crate) fn from_domains(
387        owner: &ElementRef,
388        inputs: impl IntoIterator<Item = StatDomainInput>,
389    ) -> Result<Self> {
390        let mut fields: Vec<StatFieldInfo> = Vec::new();
391        let mut values = Vec::new();
392        let mut domains = ResultDomains::default();
393        for input in inputs {
394            let mut components = Vec::new();
395            crate::data::source::reserve_source(&mut components, input.columns.len())?;
396            crate::data::source::reserve_source(&mut fields, input.columns.len())?;
397            crate::data::source::reserve_source(&mut values, input.columns.len())?;
398            for (field, value) in &input.columns {
399                if fields.iter().any(|candidate| candidate.field == *field)
400                    || input
401                        .columns
402                        .iter()
403                        .filter(|(candidate, _)| candidate == field)
404                        .count()
405                        != 1
406                {
407                    return Err(Error::Render("duplicate field in scientific result".into()));
408                }
409                components.push(DataComponentInfo::scientific_with_members(
410                    field.name(),
411                    value,
412                    &input.members,
413                )?);
414            }
415            let reference = DataDomainRef::scientific(owner, input.group.as_ref());
416            let mut info = DataDomainInfo::bound(
417                reference,
418                input.members.len(),
419                input.rows.as_ref(),
420                components,
421            );
422            if let Some(keys) = &input.keys {
423                if keys.len() != input.members.len() {
424                    return Err(Error::Render(
425                        "scientific member keys do not align with the result".into(),
426                    ));
427                }
428                info = info.with_keys(keys);
429            }
430            let reference = domains.push_info(info, input.members)?;
431            for (field, value) in input.columns {
432                fields.push(StatFieldInfo {
433                    field,
434                    domain: reference.clone(),
435                    value_type: value.value_type(),
436                });
437                values.push(value);
438            }
439        }
440        Ok(Self(crate::data::source::source_arc(StatData {
441            fields,
442            values,
443            domains,
444        })?))
445    }
446
447    pub(crate) fn result_domains(&self) -> &ResultDomains {
448        &self.0.domains
449    }
450
451    /// Actual output field descriptions, in producer order.
452    pub fn fields(&self) -> &[StatFieldInfo] {
453        &self.0.fields
454    }
455
456    /// Actual scientific domains; no domain is inferred from equal lengths.
457    pub fn domains(&self) -> &[DataDomainInfo] {
458        self.0.domains.infos()
459    }
460
461    fn field_index(&self, field: StatField) -> Result<usize> {
462        self.0
463            .fields
464            .iter()
465            .position(|info| info.field == field)
466            .ok_or_else(|| {
467                Error::Data(
468                    Diagnostic::new(
469                        DiagnosticKind::UnknownKey {
470                            key: Some(crate::data::RawKey::from(field.name())),
471                        },
472                        format!("scientific result has no {field:?} field"),
473                    )
474                    .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
475                )
476            })
477    }
478
479    /// Read the actual owning native field, without a scientific calculation.
480    pub fn values(&self, field: impl Into<StatField>) -> Result<&DataPayload> {
481        Ok(&self.0.values[self.field_index(field.into())?])
482    }
483
484    /// Per-member source relations of this field's actual output domain.
485    pub fn get_members(&self, field: impl Into<StatField>) -> Result<&[Option<SourceMembers>]> {
486        let field = &self.0.fields[self.field_index(field.into())?];
487        let index = self.0.domains.index(field.domain())?;
488        Ok(&self.0.domains.relations[index])
489    }
490
491    /// Read a member's source relation within its actual scientific domain.
492    pub fn members_in(
493        &self,
494        domain: &DataDomainRef,
495        address: impl Into<MemberAddress>,
496    ) -> Result<Option<SourceMembers>> {
497        self.0.domains.members_in(domain, &address.into())
498    }
499}
500
501/// The actual scientific value produced by a supported family.
502#[derive(Debug, Clone)]
503#[non_exhaustive]
504pub enum ScientificResult {
505    /// Actual prepared histogram bins and optional auxiliary geometry.
506    Histogram(crate::plots::HistogramResult),
507    /// Actual evaluated one-dimensional density.
508    Density(crate::plots::DensityResult),
509    /// Actual probability-plot quantile pairs.
510    ProbabilityPlot(crate::plots::ProbabilityPlotResult),
511    /// Actual fitted model parameters, predictions and observation diagnostics.
512    Fit(crate::stats::FitResult),
513    /// Actual owning statistical fields.
514    Stat(StatResult),
515    /// Actual box summaries and outlier relations.
516    Box(crate::plots::BoxSummary),
517    /// Actual categorical density profiles and auxiliary domains.
518    Profiles(crate::plots::DensityProfiles),
519    /// Actual raincloud geometry and independent original domains.
520    Raincloud(crate::plots::RaincloudGeometry),
521}
522
523/// A scientific value associated with its actual panel and consuming layers.
524#[derive(Debug, Clone)]
525pub struct ScientificResultEntry {
526    panel: PanelPath,
527    layers: Arc<[ElementRef]>,
528    group: Option<GroupKey>,
529    value: ScientificResult,
530}
531
532impl ScientificResultEntry {
533    pub(crate) fn new(layer: ElementRef, group: Option<GroupKey>, value: ScientificResult) -> Self {
534        Self {
535            panel: layer.panel().clone(),
536            layers: Arc::from([layer]),
537            group,
538            value,
539        }
540    }
541
542    /// Actual panel of this producer.
543    pub const fn panel(&self) -> &PanelPath {
544        &self.panel
545    }
546    /// Actual consuming declarations.
547    pub fn layers(&self) -> &[ElementRef] {
548        &self.layers
549    }
550    /// Actual group key, if a single group is represented.
551    pub const fn group(&self) -> Option<&GroupKey> {
552        self.group.as_ref()
553    }
554    /// The prepared scientific value.
555    pub const fn value(&self) -> &ScientificResult {
556        &self.value
557    }
558}
559
560/// One successful frozen figure and the scientific values from that preparation.
561#[derive(Clone)]
562pub struct RenderWithResults {
563    output: Output,
564    results: Arc<[ScientificResultEntry]>,
565}
566
567impl RenderWithResults {
568    pub(crate) fn new(output: Output, results: Arc<[ScientificResultEntry]>) -> Self {
569        Self { output, results }
570    }
571    /// The ordinary independently reusable frozen output.
572    pub const fn output(&self) -> &Output {
573        &self.output
574    }
575    /// Actual scientific results in occurrence order.
576    pub fn results(&self) -> &[ScientificResultEntry] {
577        &self.results
578    }
579}