Skip to main content

lichtung_plot/data/
status.rs

1//! Original estimate availability and the declaration that produced it.
2
3use std::sync::Arc;
4
5use super::{DataSourceInfo, EstimateStatus};
6use crate::{BooleanValues, CategoryValues, Error, Result};
7
8/// Explicit estimate availability, together with its original input and mapping.
9#[derive(Debug, Clone)]
10pub struct EstimateStatusBinding {
11    statuses: Arc<[EstimateStatus]>,
12    source: StatusSource,
13}
14
15#[derive(Debug, Clone)]
16enum StatusSource {
17    Direct(super::binding::VectorSource),
18    Boolean(BooleanValues),
19    Category {
20        values: CategoryValues,
21        mapping: Arc<[(String, EstimateStatus)]>,
22    },
23}
24
25impl EstimateStatusBinding {
26    pub(crate) fn from_status_names(values: &CategoryValues) -> Result<Self> {
27        let statuses = super::source::collect_source(values.iter().enumerate().map(
28            |(slot, value)| match value {
29                Some("estimated") => Ok(EstimateStatus::Estimated),
30                Some("not_estimable") => Ok(EstimateStatus::NotEstimable),
31                _ => Err(Error::Data(
32                    format!("invalid or missing estimate status at slot {slot}").into(),
33                )),
34            },
35        ))?;
36        Ok(Self {
37            statuses: statuses.into(),
38            source: StatusSource::Direct(values.vector_source().clone()),
39        })
40    }
41    /// Capture explicitly supplied typed statuses.
42    pub fn new(statuses: impl IntoIterator<Item = EstimateStatus>) -> Self {
43        let statuses: Arc<[_]> = statuses.into_iter().collect();
44        let source = StatusSource::Direct(super::binding::VectorSource::direct(statuses.len()));
45        Self { statuses, source }
46    }
47
48    /// Map true to Estimated and false to NotEstimable, preserving the original Boolean input.
49    pub fn boolean(values: BooleanValues) -> Result<Self> {
50        let statuses = super::source::collect_source(values.iter().enumerate().map(
51            |(slot, value)| match value {
52                Some(true) => Ok(EstimateStatus::Estimated),
53                Some(false) => Ok(EstimateStatus::NotEstimable),
54                None => Err(Error::Data(
55                    format!("missing Boolean at slot {slot}").into(),
56                )),
57            },
58        ))?;
59        Ok(Self {
60            statuses: statuses.into(),
61            source: StatusSource::Boolean(values),
62        })
63    }
64
65    /// Map the exact supplied categories with the original ordered declaration.
66    #[expect(
67        clippy::needless_pass_by_value,
68        reason = "the owning category input retains its exact original projection"
69    )]
70    pub fn categorical<S: AsRef<str>>(
71        values: CategoryValues,
72        mapping: impl IntoIterator<Item = (S, EstimateStatus)>,
73    ) -> Result<Self> {
74        let values = match values.key_values() {
75            super::KeyValues::Strings(values) => values,
76            super::KeyValues::Raw(_) => {
77                return Err(Error::Data(
78                    "estimate status mapping requires string category keys".into(),
79                ))
80            }
81        };
82        let mapping =
83            super::source::collect_source(mapping.into_iter().map(|(key, status)| {
84                Ok((super::source::copy_source_string(key.as_ref())?, status))
85            }))?;
86        let statuses =
87            super::source::collect_source(values.iter().enumerate().map(|(slot, value)| {
88                let key = value.ok_or_else(|| {
89                    Error::Data(format!("missing category at slot {slot}").into())
90                })?;
91                let mut matches = mapping.iter().filter(|(raw, _)| raw == key);
92                let status = matches
93                    .next()
94                    .ok_or_else(|| {
95                        Error::Data(format!("unmapped category {key:?} at slot {slot}").into())
96                    })?
97                    .1;
98                if matches.next().is_some() {
99                    return Err(Error::Data(format!("duplicate mapping for {key:?}").into()));
100                }
101                Ok(status)
102            }))?;
103        Ok(Self {
104            statuses: statuses.into(),
105            source: StatusSource::Category {
106                values,
107                mapping: mapping.into(),
108            },
109        })
110    }
111
112    /// Actual mapped or explicitly supplied statuses in original observation order.
113    pub fn statuses(&self) -> &[EstimateStatus] {
114        &self.statuses
115    }
116
117    /// The original Boolean input, when used.
118    pub const fn get_boolean(&self) -> Option<&BooleanValues> {
119        match &self.source {
120            StatusSource::Boolean(values) => Some(values),
121            _ => None,
122        }
123    }
124
125    /// The original categorical input and complete ordered mapping, when used.
126    pub fn get_categorical(&self) -> Option<(&CategoryValues, &[(String, EstimateStatus)])> {
127        match &self.source {
128            StatusSource::Category { values, mapping } => Some((values, mapping)),
129            _ => None,
130        }
131    }
132
133    pub(crate) fn shared_statuses(&self) -> Arc<[EstimateStatus]> {
134        self.statuses.clone()
135    }
136
137    pub(crate) fn vector_source(&self) -> &super::binding::VectorSource {
138        match &self.source {
139            StatusSource::Direct(source) => source,
140            StatusSource::Boolean(values) => values.vector_source(),
141            StatusSource::Category { values, .. } => values.vector_source(),
142        }
143    }
144
145    /// Actual captured source of this declaration.
146    pub fn get_source(&self) -> &DataSourceInfo {
147        match &self.source {
148            StatusSource::Direct(source) => source.info(),
149            StatusSource::Boolean(values) => values.get_source(),
150            StatusSource::Category { values, .. } => values.get_source(),
151        }
152    }
153}