lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Original estimate availability and the declaration that produced it.

use std::sync::Arc;

use super::{DataSourceInfo, EstimateStatus};
use crate::{BooleanValues, CategoryValues, Error, Result};

/// Explicit estimate availability, together with its original input and mapping.
#[derive(Debug, Clone)]
pub struct EstimateStatusBinding {
    statuses: Arc<[EstimateStatus]>,
    source: StatusSource,
}

#[derive(Debug, Clone)]
enum StatusSource {
    Direct(super::binding::VectorSource),
    Boolean(BooleanValues),
    Category {
        values: CategoryValues,
        mapping: Arc<[(String, EstimateStatus)]>,
    },
}

impl EstimateStatusBinding {
    pub(crate) fn from_status_names(values: &CategoryValues) -> Result<Self> {
        let statuses = super::source::collect_source(values.iter().enumerate().map(
            |(slot, value)| match value {
                Some("estimated") => Ok(EstimateStatus::Estimated),
                Some("not_estimable") => Ok(EstimateStatus::NotEstimable),
                _ => Err(Error::Data(
                    format!("invalid or missing estimate status at slot {slot}").into(),
                )),
            },
        ))?;
        Ok(Self {
            statuses: statuses.into(),
            source: StatusSource::Direct(values.vector_source().clone()),
        })
    }
    /// Capture explicitly supplied typed statuses.
    pub fn new(statuses: impl IntoIterator<Item = EstimateStatus>) -> Self {
        let statuses: Arc<[_]> = statuses.into_iter().collect();
        let source = StatusSource::Direct(super::binding::VectorSource::direct(statuses.len()));
        Self { statuses, source }
    }

    /// Map true to Estimated and false to NotEstimable, preserving the original Boolean input.
    pub fn boolean(values: BooleanValues) -> Result<Self> {
        let statuses = super::source::collect_source(values.iter().enumerate().map(
            |(slot, value)| match value {
                Some(true) => Ok(EstimateStatus::Estimated),
                Some(false) => Ok(EstimateStatus::NotEstimable),
                None => Err(Error::Data(
                    format!("missing Boolean at slot {slot}").into(),
                )),
            },
        ))?;
        Ok(Self {
            statuses: statuses.into(),
            source: StatusSource::Boolean(values),
        })
    }

    /// Map the exact supplied categories with the original ordered declaration.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "the owning category input retains its exact original projection"
    )]
    pub fn categorical<S: AsRef<str>>(
        values: CategoryValues,
        mapping: impl IntoIterator<Item = (S, EstimateStatus)>,
    ) -> Result<Self> {
        let values = match values.key_values() {
            super::KeyValues::Strings(values) => values,
            super::KeyValues::Raw(_) => {
                return Err(Error::Data(
                    "estimate status mapping requires string category keys".into(),
                ))
            }
        };
        let mapping =
            super::source::collect_source(mapping.into_iter().map(|(key, status)| {
                Ok((super::source::copy_source_string(key.as_ref())?, status))
            }))?;
        let statuses =
            super::source::collect_source(values.iter().enumerate().map(|(slot, value)| {
                let key = value.ok_or_else(|| {
                    Error::Data(format!("missing category at slot {slot}").into())
                })?;
                let mut matches = mapping.iter().filter(|(raw, _)| raw == key);
                let status = matches
                    .next()
                    .ok_or_else(|| {
                        Error::Data(format!("unmapped category {key:?} at slot {slot}").into())
                    })?
                    .1;
                if matches.next().is_some() {
                    return Err(Error::Data(format!("duplicate mapping for {key:?}").into()));
                }
                Ok(status)
            }))?;
        Ok(Self {
            statuses: statuses.into(),
            source: StatusSource::Category {
                values,
                mapping: mapping.into(),
            },
        })
    }

    /// Actual mapped or explicitly supplied statuses in original observation order.
    pub fn statuses(&self) -> &[EstimateStatus] {
        &self.statuses
    }

    /// The original Boolean input, when used.
    pub const fn get_boolean(&self) -> Option<&BooleanValues> {
        match &self.source {
            StatusSource::Boolean(values) => Some(values),
            _ => None,
        }
    }

    /// The original categorical input and complete ordered mapping, when used.
    pub fn get_categorical(&self) -> Option<(&CategoryValues, &[(String, EstimateStatus)])> {
        match &self.source {
            StatusSource::Category { values, mapping } => Some((values, mapping)),
            _ => None,
        }
    }

    pub(crate) fn shared_statuses(&self) -> Arc<[EstimateStatus]> {
        self.statuses.clone()
    }

    pub(crate) fn vector_source(&self) -> &super::binding::VectorSource {
        match &self.source {
            StatusSource::Direct(source) => source,
            StatusSource::Boolean(values) => values.vector_source(),
            StatusSource::Category { values, .. } => values.vector_source(),
        }
    }

    /// Actual captured source of this declaration.
    pub fn get_source(&self) -> &DataSourceInfo {
        match &self.source {
            StatusSource::Direct(source) => source.info(),
            StatusSource::Boolean(values) => values.get_source(),
            StatusSource::Category { values, .. } => values.get_source(),
        }
    }
}