Skip to main content

lichtung_plot/data/
variables.rs

1//! Original ordered matrix variables.
2
3use std::sync::Arc;
4
5use super::RawKey;
6use crate::{
7    errors::{Diagnostic, DiagnosticKind, DiagnosticReference, ErrorContext, OperationPhase},
8    Error, NumericValues, Result,
9};
10
11/// One actual variable and its original scientific identity.
12#[derive(Debug, Clone)]
13pub struct NamedNumericValues {
14    /// Complete original variable key.
15    pub key: RawKey,
16    /// Original numeric column.
17    pub values: NumericValues,
18}
19
20/// The actual ordered variable declarations of a matrix.
21#[derive(Debug, Clone)]
22pub struct VariableValues(Arc<[NamedNumericValues]>);
23
24impl VariableValues {
25    pub(crate) fn from_columns(values: Vec<NumericValues>) -> Self {
26        Self(
27            values
28                .into_iter()
29                .map(|values| {
30                    let key = values
31                        .field_key()
32                        .cloned()
33                        .unwrap_or_else(|| RawKey::from(values.name()));
34                    NamedNumericValues { key, values }
35                })
36                .collect(),
37        )
38    }
39
40    /// The actual ordered variables.
41    pub fn variables(&self) -> &[NamedNumericValues] {
42        &self.0
43    }
44
45    /// Read a variable by original key, rejecting duplicate declarations.
46    pub fn get(&self, key: &RawKey) -> Result<&NumericValues> {
47        let matches: Vec<_> = self
48            .0
49            .iter()
50            .enumerate()
51            .filter(|(_, variable)| &variable.key == key)
52            .collect();
53        let context = ErrorContext::new()
54            .with_operation(OperationPhase::Check)
55            .with_binding(key.clone());
56        match matches.as_slice() {
57            [] => Err(Error::Data(
58                Diagnostic::new(
59                    DiagnosticKind::UnknownKey {
60                        key: Some(key.clone()),
61                    },
62                    format!("no matrix variable {key:?}"),
63                )
64                .with_context(context),
65            )),
66            [(_, value)] => Ok(&value.values),
67            _ => Err(Error::Data(
68                Diagnostic::new(
69                    DiagnosticKind::Ambiguous {
70                        candidates: matches
71                            .into_iter()
72                            .map(|(slot, _)| DiagnosticReference::Member {
73                                domain: None,
74                                address: super::MemberAddress::Slot(slot),
75                            })
76                            .collect(),
77                    },
78                    format!("ambiguous matrix variable {key:?}"),
79                )
80                .with_context(context),
81            )),
82        }
83    }
84
85    /// Read a variable by its actual declaration position.
86    pub fn get_at(&self, index: usize) -> Option<&NamedNumericValues> {
87        self.0.get(index)
88    }
89
90    /// Number of variables, independent of observation count.
91    pub fn len(&self) -> usize {
92        self.0.len()
93    }
94
95    /// Whether the declared variable collection is empty.
96    pub fn is_empty(&self) -> bool {
97        self.0.is_empty()
98    }
99
100    pub(crate) fn columns(&self) -> impl ExactSizeIterator<Item = &NumericValues> {
101        self.0.iter().map(|variable| &variable.values)
102    }
103}